micro cleanups

This commit is contained in:
Simon Gardling 2022-05-20 14:17:30 -04:00
parent 685ff25631
commit 4b0e758d33
4 changed files with 74 additions and 97 deletions

View File

@ -17,9 +17,6 @@ use std::{
}; };
use unzip_n::unzip_n; use unzip_n::unzip_n;
#[cfg(threading)]
use rayon::iter::ParallelIterator;
/// Represents the possible variations of Riemann Sums /// Represents the possible variations of Riemann Sums
#[derive(PartialEq, Debug, Copy, Clone)] #[derive(PartialEq, Debug, Copy, Clone)]
pub enum Riemann { pub enum Riemann {
@ -195,6 +192,7 @@ impl FunctionEntry {
} }
} }
/*
/// Get function that can be used to calculate integral based on Riemann Sum type /// Get function that can be used to calculate integral based on Riemann Sum type
fn get_sum_func(&self, sum: Riemann) -> FunctionHelper { fn get_sum_func(&self, sum: Riemann) -> FunctionHelper {
match sum { match sum {
@ -209,19 +207,20 @@ impl FunctionEntry {
}), }),
} }
} }
*/
/// Creates and does the math for creating all the rectangles under the graph /// Creates and does the math for creating all the rectangles under the graph
fn integral_rectangles( fn integral_rectangles(
&self, integral_min_x: &f64, integral_max_x: &f64, sum: &Riemann, integral_num: &usize, &self, integral_min_x: f64, integral_max_x: f64, sum: Riemann, integral_num: usize,
) -> (Vec<(f64, f64)>, f64) { ) -> (Vec<(f64, f64)>, f64) {
let step = (integral_max_x - integral_min_x) / (*integral_num as f64); let step = (integral_max_x - integral_min_x) / (integral_num as f64);
let sum_func = self.get_sum_func(*sum); // let sum_func = self.get_sum_func(sum);
let data2: Vec<(f64, f64)> = step_helper(*integral_num, integral_min_x, &step) let data2: Vec<(f64, f64)> = step_helper(integral_num, integral_min_x, step)
.into_iter() .into_iter()
.map(|x| { .map(|x| {
let step_offset = step * x.signum(); // store the offset here so it doesn't have to be calculated multiple times let step_offset = step.copysign(x); // store the offset here so it doesn't have to be calculated multiple times
let x2: f64 = x + step_offset; let x2: f64 = x + step_offset;
let (left_x, right_x) = match x.is_sign_positive() { let (left_x, right_x) = match x.is_sign_positive() {
@ -229,21 +228,27 @@ impl FunctionEntry {
false => (x2, x), false => (x2, x),
}; };
let y = sum_func.get(left_x, right_x); let y = match sum {
Riemann::Left => self.function.get(left_x),
Riemann::Right => self.function.get(right_x),
Riemann::Middle => {
(self.function.get(left_x) + self.function.get(right_x)) / 2.0
}
};
(x + (step_offset / 2.0), y) (x + (step_offset / 2.0), y)
}) })
.filter(|(_, y)| y.is_finite()) .filter(|(_, y)| y.is_finite())
.collect(); .collect();
let area = data2.iter().map(|(_, y)| y * step).sum(); let area = data2.iter().map(move |(_, y)| y * step).sum();
(data2, area) (data2, area)
} }
/// Helps with processing newton's method depending on level of derivative /// Helps with processing newton's method depending on level of derivative
fn newtons_method_helper( fn newtons_method_helper(
&self, threshold: &f64, derivative_level: usize, range: &std::ops::Range<f64>, &self, threshold: f64, derivative_level: usize, range: &std::ops::Range<f64>,
) -> Vec<Value> { ) -> Vec<Value> {
let newtons_method_output: Vec<f64> = match derivative_level { let newtons_method_output: Vec<f64> = match derivative_level {
0 => newtons_method_helper( 0 => newtons_method_helper(
@ -279,7 +284,7 @@ impl FunctionEntry {
let resolution = (settings.max_x - settings.min_x) / (settings.plot_width as f64); let resolution = (settings.max_x - settings.min_x) / (settings.plot_width as f64);
debug_assert!(resolution > 0.0); debug_assert!(resolution > 0.0);
let resolution_iter = step_helper(&settings.plot_width + 1, &settings.min_x, &resolution); let resolution_iter = step_helper(settings.plot_width + 1, settings.min_x, resolution);
unsafe { assume(!resolution_iter.is_empty()) } unsafe { assume(!resolution_iter.is_empty()) }
@ -308,9 +313,11 @@ impl FunctionEntry {
Vec<Value>, Vec<Value>,
Vec<Option<Value>>, Vec<Option<Value>>,
Vec<Option<Value>>, Vec<Option<Value>>,
) = dyn_iter(&resolution_iter) ) = resolution_iter
.clone()
.into_iter()
.map(|x| { .map(|x| {
if let Some(i) = x_data.get_index(*x) { if let Some(i) = x_data.get_index(x) {
( (
self.back_data[i], self.back_data[i],
derivative_required.then(|| self.derivative_data[i]), derivative_required.then(|| self.derivative_data[i]),
@ -320,11 +327,11 @@ impl FunctionEntry {
) )
} else { } else {
( (
Value::new(*x, self.function.get(*x)), Value::new(x, self.function.get(x)),
derivative_required derivative_required
.then(|| Value::new(*x, self.function.get_derivative_1(*x))), .then(|| Value::new(x, self.function.get_derivative_1(x))),
do_nth_derivative.then(|| { do_nth_derivative.then(|| {
Value::new(*x, self.function.get_nth_derivative(self.curr_nth, *x)) Value::new(x, self.function.get_nth_derivative(self.curr_nth, x))
}), }),
) )
} }
@ -376,8 +383,10 @@ impl FunctionEntry {
if !partial_regen { if !partial_regen {
if self.back_data.is_empty() { if self.back_data.is_empty() {
let data: Vec<Value> = dyn_iter(&resolution_iter) let data: Vec<Value> = resolution_iter
.map(|x| Value::new(*x, self.function.get(*x))) .clone()
.into_iter()
.map(|x| Value::new(x, self.function.get(x)))
.collect(); .collect();
debug_assert_eq!(data.len(), settings.plot_width + 1); debug_assert_eq!(data.len(), settings.plot_width + 1);
@ -385,16 +394,19 @@ impl FunctionEntry {
} }
if derivative_required && self.derivative_data.is_empty() { if derivative_required && self.derivative_data.is_empty() {
let data: Vec<Value> = dyn_iter(&resolution_iter) let data: Vec<Value> = resolution_iter
.map(|x| Value::new(*x, self.function.get_derivative_1(*x))) .clone()
.into_iter()
.map(|x| Value::new(x, self.function.get_derivative_1(x)))
.collect(); .collect();
debug_assert_eq!(data.len(), settings.plot_width + 1); debug_assert_eq!(data.len(), settings.plot_width + 1);
self.derivative_data = data; self.derivative_data = data;
} }
if self.nth_derviative && self.nth_derivative_data.is_none() { if self.nth_derviative && self.nth_derivative_data.is_none() {
let data: Vec<Value> = dyn_iter(&resolution_iter) let data: Vec<Value> = resolution_iter
.map(|x| Value::new(*x, self.function.get_nth_derivative(self.curr_nth, *x))) .into_iter()
.map(|x| Value::new(x, self.function.get_nth_derivative(self.curr_nth, x)))
.collect(); .collect();
debug_assert_eq!(data.len(), settings.plot_width + 1); debug_assert_eq!(data.len(), settings.plot_width + 1);
self.nth_derivative_data = Some(data); self.nth_derivative_data = Some(data);
@ -404,10 +416,10 @@ impl FunctionEntry {
if self.integral { if self.integral {
if self.integral_data.is_none() { if self.integral_data.is_none() {
let (data, area) = self.integral_rectangles( let (data, area) = self.integral_rectangles(
&settings.integral_min_x, settings.integral_min_x,
&settings.integral_max_x, settings.integral_max_x,
&settings.riemann_sum, settings.riemann_sum,
&settings.integral_num, settings.integral_num,
); );
self.integral_data = Some(( self.integral_data = Some((
@ -424,12 +436,12 @@ impl FunctionEntry {
// Calculates extrema // Calculates extrema
if settings.do_extrema && (min_max_changed | self.extrema_data.is_empty()) { if settings.do_extrema && (min_max_changed | self.extrema_data.is_empty()) {
self.extrema_data = self.newtons_method_helper(&threshold, 1, &x_range); self.extrema_data = self.newtons_method_helper(threshold, 1, &x_range);
} }
// Calculates roots // Calculates roots
if settings.do_roots && (min_max_changed | self.root_data.is_empty()) { if settings.do_roots && (min_max_changed | self.root_data.is_empty()) {
self.root_data = self.newtons_method_helper(&threshold, 0, &x_range); self.root_data = self.newtons_method_helper(threshold, 0, &x_range);
} }
} }

View File

@ -2,7 +2,7 @@ use crate::consts::*;
use crate::data::TextData; use crate::data::TextData;
use crate::function_entry::Riemann; use crate::function_entry::Riemann;
use crate::function_manager::FunctionManager; use crate::function_manager::FunctionManager;
use crate::misc::{dyn_mut_iter, option_vec_printer}; use crate::misc::option_vec_printer;
use eframe::App; use eframe::App;
use egui::{ use egui::{
plot::Plot, style::Margin, Button, CentralPanel, ComboBox, Context, Frame, Key, Layout, plot::Plot, style::Margin, Button, CentralPanel, ComboBox, Context, Frame, Key, Layout,
@ -14,9 +14,6 @@ use epaint::Rounding;
use instant::Instant; use instant::Instant;
use std::{io::Read, ops::BitXorAssign}; use std::{io::Read, ops::BitXorAssign};
#[cfg(threading)]
use rayon::iter::{IndexedParallelIterator, ParallelIterator};
/// Stores current settings/state of [`MathApp`] /// Stores current settings/state of [`MathApp`]
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct AppSettings { pub struct AppSettings {
@ -591,9 +588,12 @@ impl App for MathApp {
self.settings.min_x = min_x; self.settings.min_x = min_x;
self.settings.max_x = max_x; self.settings.max_x = max_x;
dyn_mut_iter(self.functions.get_entries_mut()).for_each(|(_, function)| { self.functions
function.calculate(width_changed, min_max_changed, &self.settings) .get_entries_mut()
}); .iter_mut()
.for_each(|(_, function)| {
function.calculate(width_changed, min_max_changed, &self.settings)
});
let area: Vec<Option<f64>> = self let area: Vec<Option<f64>> = self
.functions .functions

View File

@ -3,45 +3,7 @@ use std::intrinsics::assume;
use egui::plot::{Line, Points, Value, Values}; use egui::plot::{Line, Points, Value, Values};
use itertools::Itertools; use itertools::Itertools;
#[cfg(not(threading))] /*
#[inline]
pub fn dyn_iter<'a, T>(input: &'a [T]) -> impl Iterator<Item = &'a T>
where
&'a [T]: IntoIterator,
{
input.iter()
}
#[cfg(threading)]
#[inline]
pub fn dyn_iter<'a, I>(input: &'a I) -> <&'a I as IntoParallelIterator>::Iter
where
&'a I: IntoParallelIterator,
{
use rayon::prelude::*;
input.par_iter()
}
#[cfg(not(threading))]
#[inline]
pub fn dyn_mut_iter<'a, T>(input: &'a mut [T]) -> impl Iterator<Item = &'a mut T>
where
&'a mut [T]: IntoIterator,
{
input.iter_mut()
}
#[cfg(threading)]
#[inline]
pub fn dyn_mut_iter<'a, I>(input: &'a mut I) -> <&'a mut I as IntoParallelIterator>::Iter
where
&'a mut I: IntoParallelIterator,
{
use rayon::prelude::*;
input.par_iter_mut()
}
pub struct FunctionHelper<'a> { pub struct FunctionHelper<'a> {
#[cfg(threading)] #[cfg(threading)]
f: async_lock::Mutex<Box<dyn Fn(f64, f64) -> f64 + 'a + Sync + Send>>, f: async_lock::Mutex<Box<dyn Fn(f64, f64) -> f64 + 'a + Sync + Send>>,
@ -69,6 +31,7 @@ impl<'a> FunctionHelper<'a> {
#[cfg(not(threading))] #[cfg(not(threading))]
pub fn get(&self, x: f64, x1: f64) -> f64 { (self.f)(x, x1) } pub fn get(&self, x: f64, x1: f64) -> f64 { (self.f)(x, x1) }
} }
*/
/// [`SteppedVector`] is used in order to efficiently sort through an ordered /// [`SteppedVector`] is used in order to efficiently sort through an ordered
/// `Vec<f64>` Used in order to speedup the processing of cached data when /// `Vec<f64>` Used in order to speedup the processing of cached data when
@ -230,14 +193,14 @@ pub fn decimal_round(x: f64, n: usize) -> f64 {
/// `f_1` is f'(x) aka the derivative of f(x) /// `f_1` is f'(x) aka the derivative of f(x)
/// The function returns a Vector of `x` values where roots occur /// The function returns a Vector of `x` values where roots occur
pub fn newtons_method_helper( pub fn newtons_method_helper(
threshold: &f64, range: &std::ops::Range<f64>, data: &[Value], f: &dyn Fn(f64) -> f64, threshold: f64, range: &std::ops::Range<f64>, data: &[Value], f: &dyn Fn(f64) -> f64,
f_1: &dyn Fn(f64) -> f64, f_1: &dyn Fn(f64) -> f64,
) -> Vec<f64> { ) -> Vec<f64> {
data.into_iter() data.into_iter()
.tuple_windows() .tuple_windows()
.filter(|(prev, curr)| prev.y.is_finite() && curr.y.is_finite()) .filter(|(prev, curr)| prev.y.is_finite() && curr.y.is_finite())
.filter(|(prev, curr)| prev.y.signum() != curr.y.signum()) .filter(|(prev, curr)| prev.y.signum() != curr.y.signum())
.map(|(start, _)| newtons_method(f, f_1, &start.x, range, threshold)) .map(|(start, _)| newtons_method(f, f_1, start.x, range, threshold))
.filter(|x| x.is_some()) .filter(|x| x.is_some())
.map(|x| unsafe { x.unwrap_unchecked() }) .map(|x| unsafe { x.unwrap_unchecked() })
.collect() .collect()
@ -248,10 +211,10 @@ pub fn newtons_method_helper(
/// `f_1` is f'(x) aka the derivative of f(x) /// `f_1` is f'(x) aka the derivative of f(x)
/// The function returns an `Option<f64>` of the x value at which a root occurs /// The function returns an `Option<f64>` of the x value at which a root occurs
pub fn newtons_method( pub fn newtons_method(
f: &dyn Fn(f64) -> f64, f_1: &dyn Fn(f64) -> f64, start_x: &f64, range: &std::ops::Range<f64>, f: &dyn Fn(f64) -> f64, f_1: &dyn Fn(f64) -> f64, start_x: f64, range: &std::ops::Range<f64>,
threshold: &f64, threshold: f64,
) -> Option<f64> { ) -> Option<f64> {
let mut x1: f64 = *start_x; let mut x1: f64 = start_x;
let mut x2: f64; let mut x2: f64;
let mut derivative: f64; let mut derivative: f64;
loop { loop {
@ -266,7 +229,7 @@ pub fn newtons_method(
} }
// If below threshold, break // If below threshold, break
if (x2 - x1).abs() < *threshold { if (x2 - x1).abs() < threshold {
break; break;
} }
@ -287,7 +250,7 @@ where
"[", "[",
&data &data
.iter() .iter()
.map(|x| { .map(move |x| {
x.as_ref() x.as_ref()
.map(|x_1| x_1.to_string()) .map(|x_1| x_1.to_string())
.unwrap_or_else(|| "None".to_owned()) .unwrap_or_else(|| "None".to_owned())
@ -308,8 +271,10 @@ where
} }
/// Returns a vector of length `max_i` starting at value `min_x` with step of `step` /// Returns a vector of length `max_i` starting at value `min_x` with step of `step`
pub fn step_helper(max_i: usize, min_x: &f64, step: &f64) -> Vec<f64> { pub fn step_helper(max_i: usize, min_x: f64, step: f64) -> Vec<f64> {
(0..max_i).map(|x| (x as f64 * step) + min_x).collect() (0..max_i)
.map(move |x: usize| (x as f64 * step) + min_x)
.collect()
} }
// TODO: use in hovering over points // TODO: use in hovering over points

View File

@ -54,7 +54,7 @@ fn step_helper() {
use ytbn_graphing_software::step_helper; use ytbn_graphing_software::step_helper;
assert_eq!( assert_eq!(
step_helper(10, &2.0, &3.0), step_helper(10, 2.0, 3.0),
vec![2.0, 5.0, 8.0, 11.0, 14.0, 17.0, 20.0, 23.0, 26.0, 29.0] vec![2.0, 5.0, 8.0, 11.0, 14.0, 17.0, 20.0, 23.0, 26.0, 29.0]
); );
} }
@ -172,54 +172,54 @@ fn newtons_method() {
let data = newtons_method( let data = newtons_method(
&|x: f64| x.powf(2.0) - 1.0, &|x: f64| x.powf(2.0) - 1.0,
&|x: f64| 2.0 * x, &|x: f64| 2.0 * x,
&3.0, 3.0,
&(0.0..5.0), &(0.0..5.0),
&f64::EPSILON, f64::EPSILON,
); );
assert_eq!(data, Some(1.0)); assert_eq!(data, Some(1.0));
let data = newtons_method( let data = newtons_method(
&|x: f64| x.sin(), &|x: f64| x.sin(),
&|x: f64| x.cos(), &|x: f64| x.cos(),
&3.0, 3.0,
&(2.95..3.18), &(2.95..3.18),
&f64::EPSILON, f64::EPSILON,
); );
assert_eq!(data, Some(std::f64::consts::PI)); assert_eq!(data, Some(std::f64::consts::PI));
let data = newtons_method( let data = newtons_method(
&|x: f64| x.sin(), &|x: f64| x.sin(),
&|_: f64| f64::NAN, &|_: f64| f64::NAN,
&0.0, 0.0,
&(-10.0..10.0), &(-10.0..10.0),
&f64::EPSILON, f64::EPSILON,
); );
assert_eq!(data, None); assert_eq!(data, None);
let data = newtons_method( let data = newtons_method(
&|_: f64| f64::NAN, &|_: f64| f64::NAN,
&|x: f64| x.sin(), &|x: f64| x.sin(),
&0.0, 0.0,
&(-10.0..10.0), &(-10.0..10.0),
&f64::EPSILON, f64::EPSILON,
); );
assert_eq!(data, None); assert_eq!(data, None);
let data = newtons_method( let data = newtons_method(
&|_: f64| f64::INFINITY, &|_: f64| f64::INFINITY,
&|x: f64| x.sin(), &|x: f64| x.sin(),
&0.0, 0.0,
&(-10.0..10.0), &(-10.0..10.0),
&f64::EPSILON, f64::EPSILON,
); );
assert_eq!(data, None); assert_eq!(data, None);
let data = newtons_method( let data = newtons_method(
&|x: f64| x.sin(), &|x: f64| x.sin(),
&|_: f64| f64::INFINITY, &|_: f64| f64::INFINITY,
&0.0, 0.0,
&(-10.0..10.0), &(-10.0..10.0),
&f64::EPSILON, f64::EPSILON,
); );
assert_eq!(data, None); assert_eq!(data, None);
} }