Compare commits
63 Commits
d592c74654
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
ac6265eae7
|
|||
|
c70c715126
|
|||
|
f2d0d27345
|
|||
|
41b50eb893
|
|||
|
e497987573
|
|||
|
65ab0c6a1f
|
|||
|
f6a09fe449
|
|||
|
b08a727fe3
|
|||
|
5480522ddb
|
|||
|
07858b229f
|
|||
|
3288752dfb
|
|||
|
3305227ffe
|
|||
|
df05601e26
|
|||
|
48fd49e386
|
|||
|
c7760e2123
|
|||
|
2d7c987f11
|
|||
|
dab002bd15
|
|||
|
f9480fac7c
|
|||
|
44fea82aaa
|
|||
|
e9b8433117
|
|||
|
957c286e59
|
|||
|
63bd73e444
|
|||
|
c9eff77dff
|
|||
|
9677e8f8b4
|
|||
|
8a5d9f1cd5
|
|||
|
53d90b7328
|
|||
|
b59f214c67
|
|||
|
ba2e782af5
|
|||
|
8ee03d953f
|
|||
|
f218ff26c7
|
|||
|
24f99f4cb8
|
|||
|
905820384a
|
|||
|
d6cb0fba1a
|
|||
|
134f11c628
|
|||
|
66f0bd5b02
|
|||
|
abfe5480e5
|
|||
|
31181513d0
|
|||
|
7252d37763
|
|||
|
fe01277f7b
|
|||
|
e96fcdbe99
|
|||
|
9d96977785
|
|||
|
2378f719a7
|
|||
|
7f9a962ff7
|
|||
|
8b7e3b3009
|
|||
|
74813f5f13
|
|||
|
4a4bce90d0
|
|||
|
fabfc6de31
|
|||
|
7dc48f1b33
|
|||
|
c0a05464f3
|
|||
|
84e283f5c2
|
|||
|
faee5488df
|
|||
|
a21fc048ad
|
|||
|
10742d0cc4
|
|||
|
aa07631296
|
|||
|
5a92020dae
|
|||
|
0889f81664
|
|||
|
87de396fc2
|
|||
|
724d705d21
|
|||
|
53cb50316e
|
|||
|
75092e7d9f
|
|||
|
5e01e1762f
|
|||
|
4c9def194e
|
|||
|
0edd1b51a1
|
50
.github/workflows/ci.yml
vendored
50
.github/workflows/ci.yml
vendored
@@ -1,50 +0,0 @@
|
|||||||
on: [push, pull_request]
|
|
||||||
|
|
||||||
name: CI
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
check:
|
|
||||||
name: Check
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout sources
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Install toolchain
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
profile: minimal
|
|
||||||
toolchain: nightly
|
|
||||||
override: true
|
|
||||||
|
|
||||||
- name: Install fonttools
|
|
||||||
run: sudo apt-get install -y fonttools libzstd-dev
|
|
||||||
|
|
||||||
- name: Run cargo check
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: check
|
|
||||||
|
|
||||||
parsing_test:
|
|
||||||
name: Tests
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout sources
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Install toolchain
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
profile: minimal
|
|
||||||
toolchain: nightly
|
|
||||||
override: true
|
|
||||||
|
|
||||||
- name: Install fonttools
|
|
||||||
run: sudo apt-get install -y fonttools libzstd-dev
|
|
||||||
|
|
||||||
- name: Install cargo-all-features
|
|
||||||
uses: actions-rs/install@v0.1
|
|
||||||
with:
|
|
||||||
crate: cargo-all-features
|
|
||||||
version: latest
|
|
||||||
- run: cargo test-all-features
|
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -4,3 +4,4 @@
|
|||||||
/Cargo.lock
|
/Cargo.lock
|
||||||
perf.data
|
perf.data
|
||||||
flamegraph.svg
|
flamegraph.svg
|
||||||
|
result
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
edition = "2021"
|
|
||||||
fn_params_layout = "Compressed"
|
|
||||||
fn_single_line = true
|
|
||||||
hard_tabs = true
|
|
||||||
5
.vscode/settings.json
vendored
5
.vscode/settings.json
vendored
@@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
"files.insertFinalNewline": true,
|
|
||||||
"editor.formatOnSave": true,
|
|
||||||
"files.trimTrailingWhitespace": true,
|
|
||||||
}
|
|
||||||
3176
Cargo.lock
generated
3176
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
47
Cargo.toml
47
Cargo.toml
@@ -1,7 +1,7 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "ytbn_graphing_software"
|
name = "ytbn_graphing_software"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2024"
|
||||||
license = "AGPL-3.0"
|
license = "AGPL-3.0"
|
||||||
repository = "https://github.com/Titaniumtown/YTBN-Graphing-Software"
|
repository = "https://github.com/Titaniumtown/YTBN-Graphing-Software"
|
||||||
description = "Crossplatform (and web-compatible) graphing calculator"
|
description = "Crossplatform (and web-compatible) graphing calculator"
|
||||||
@@ -9,6 +9,9 @@ description = "Crossplatform (and web-compatible) graphing calculator"
|
|||||||
[lib]
|
[lib]
|
||||||
crate-type = ["cdylib", "rlib"]
|
crate-type = ["cdylib", "rlib"]
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["eframe/wayland"]
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
debug = false
|
debug = false
|
||||||
codegen-units = 1
|
codegen-units = 1
|
||||||
@@ -43,25 +46,21 @@ epaint = { git = "https://github.com/titaniumtown/egui.git", default-features =
|
|||||||
"bytemuck",
|
"bytemuck",
|
||||||
] }
|
] }
|
||||||
emath = { git = "https://github.com/titaniumtown/egui.git", default-features = false }
|
emath = { git = "https://github.com/titaniumtown/egui.git", default-features = false }
|
||||||
egui_plot = { git = "https://github.com/titaniumtown/egui.git", default-features = false }
|
egui_plot = { version = "0.34.0", default-features = false }
|
||||||
|
|
||||||
|
ruzstd = "0.8"
|
||||||
|
|
||||||
shadow-rs = { version = "0.12", default-features = false }
|
|
||||||
const_format = { version = "0.2", default-features = false, features = ["fmt"] }
|
|
||||||
cfg-if = "1"
|
|
||||||
ruzstd = "0.5"
|
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
itertools = "0.10"
|
itertools = "0.14"
|
||||||
static_assertions = "1.1"
|
static_assertions = "1.1"
|
||||||
bincode = "1.3"
|
bincode = "1.3"
|
||||||
serde = "1"
|
serde = "1"
|
||||||
|
base64 = "0.22"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
benchmarks = { path = "./benchmarks" }
|
benchmarks = { path = "./benchmarks" }
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
shadow-rs = "0.12"
|
shadow-rs = "1.4"
|
||||||
epaint = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
|
epaint = { git = "https://github.com/titaniumtown/egui.git", default-features = false, features = [
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
] }
|
] }
|
||||||
@@ -71,24 +70,32 @@ egui = { git = "https://github.com/titaniumtown/egui.git", default-features = fa
|
|||||||
bincode = "1.3"
|
bincode = "1.3"
|
||||||
serde = "1"
|
serde = "1"
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
zstd = { version = "0.11", default-features = false, features = ["pkg-config"] }
|
zstd = { version = "0.13", default-features = false, features = ["pkg-config"] }
|
||||||
run_script = "0.9"
|
itertools = "0.14"
|
||||||
json5 = "0.4"
|
allsorts = "0.15"
|
||||||
itertools = "0.10"
|
|
||||||
|
|
||||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||||
instant = "0.1"
|
|
||||||
tracing-subscriber = "0.3"
|
tracing-subscriber = "0.3"
|
||||||
getrandom = { version = "0.2" }
|
|
||||||
|
|
||||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||||
instant = { version = "0.1", features = ["wasm-bindgen"] }
|
lol_alloc = "0.4.1"
|
||||||
lol_alloc = "0.4.0"
|
|
||||||
wasm-bindgen = { version = "0.2", default-features = false, features = ["std"] }
|
wasm-bindgen = { version = "0.2", default-features = false, features = ["std"] }
|
||||||
web-sys = "0.3"
|
web-sys = "0.3"
|
||||||
tracing-wasm = "0.2"
|
tracing-wasm = "0.2"
|
||||||
getrandom = { version = "0.2", features = ["js"] }
|
# pinned to 0.4.54 in order to be compatible with nixos's wasm-bindgen-cli version
|
||||||
wasm-bindgen-futures = "0.4.34"
|
wasm-bindgen-futures = "=0.4.54"
|
||||||
|
|
||||||
[package.metadata.cargo-all-features]
|
[package.metadata.cargo-all-features]
|
||||||
skip_optional_dependencies = true #don't test optional dependencies, only features
|
skip_optional_dependencies = true #don't test optional dependencies, only features
|
||||||
|
|
||||||
|
# various dependency patches fix issues with nix complication such as:
|
||||||
|
# ````
|
||||||
|
# ln: failed to create symbolic link '/nix/store/plh3y4gfxgwcacjccv72f551y1k89x75-cargo-vendor-dir/ecolor-0.33.2/qb43vsx43av6kf4h9y4bsmisvbjlcxd1-ecolor-0.33.2': Permission denied
|
||||||
|
# ````
|
||||||
|
|
||||||
|
[patch.crates-io]
|
||||||
|
egui = { git = "https://github.com/titaniumtown/egui.git" }
|
||||||
|
eframe = { git = "https://github.com/titaniumtown/egui.git" }
|
||||||
|
epaint = { git = "https://github.com/titaniumtown/egui.git" }
|
||||||
|
emath = { git = "https://github.com/titaniumtown/egui.git" }
|
||||||
|
ecolor = { git = "https://github.com/titaniumtown/egui.git" }
|
||||||
|
|||||||
@@ -4,4 +4,4 @@
|
|||||||
<img src="assets/logo.svg" alt="logo" width="200"/>
|
<img src="assets/logo.svg" alt="logo" width="200"/>
|
||||||
|
|
||||||
### What is this?
|
### What is this?
|
||||||
The aim of this project is to provide a [Desmos](https://www.desmos.com/)-like graphing experience. This project is written in [Rust](https://www.rust-lang.org/) and takes advantage of [egui](https://github.com/emilk/egui) as it's graphical backend. Meaning that this program can be compiled targeting either the web, [such as here](https://titaniumtown.github.io), as well as a native application.
|
The aim of this project is to provide a [Desmos](https://www.desmos.com/)-like graphing experience. This project is written in [Rust](https://www.rust-lang.org/) and takes advantage of [egui](https://github.com/emilk/egui) as it's graphical backend. Meaning that this program can be compiled targeting either the web, [such as here](https://graphing.gardling.com), as well as a native application.
|
||||||
|
|||||||
16
TODO.md
16
TODO.md
@@ -1,18 +1,20 @@
|
|||||||
## TODO:
|
## TODO:
|
||||||
1. Function management
|
1. Function management
|
||||||
- Integrals between functions (too hard to implement, maybe will shelve)
|
a. Integrals between functions (too hard to implement, maybe will shelve)
|
||||||
- Display intersection between functions (would have to rewrite a lot of the function plotting handling)
|
b. Display intersection between functions (would have to rewrite a lot of the function plotting handling)
|
||||||
- [Drag and drop support](https://github.com/emilk/egui/discussions/1530) in the UI to re-order functions
|
c. [Drag and drop support](https://github.com/emilk/egui/discussions/1530) in the UI to re-order functions
|
||||||
- Hide/disable functions
|
d. Hide/disable functions
|
||||||
- Prevent user from making too many function entries
|
e. Prevent user from making too many function entries
|
||||||
- Display function errors as tooltips or a warning box (not preventing the display of the graph)
|
f. Display function errors as tooltips or a warning box (not preventing the display of the graph)
|
||||||
- Clone functions
|
g. Clone functions
|
||||||
2. Smart display of graph
|
2. Smart display of graph
|
||||||
- Display of intersections between functions
|
- Display of intersections between functions
|
||||||
3. Allow constants in min/max integral input (like pi or euler's number)
|
3. Allow constants in min/max integral input (like pi or euler's number)
|
||||||
4. Sliding values for functions (like a user-interactable slider that adjusts a variable in the function, like desmos)
|
4. Sliding values for functions (like a user-interactable slider that adjusts a variable in the function, like desmos)
|
||||||
5. Fix integral display
|
5. Fix integral display
|
||||||
6. Better handling of roots and extrema finding
|
6. Better handling of roots and extrema finding
|
||||||
|
a. For instance, persistance, the roots shouldn't be recalculated for each movement of the viewport
|
||||||
|
b. If applicable, the roots/extrema should be expressed in terms of constants such as a root of a number, pi, or something else.
|
||||||
7. Add closing animation for function entry
|
7. Add closing animation for function entry
|
||||||
8. Fix mobile text input
|
8. Fix mobile text input
|
||||||
9. Write custom plotter
|
9. Write custom plotter
|
||||||
|
|||||||
@@ -9,5 +9,4 @@ license = "AGPL-3.0"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
pprof = { version = "0.9", features = ["flamegraph"] }
|
pprof = { version = "0.9", features = ["flamegraph"] }
|
||||||
criterion = "0.3"
|
criterion = "0.3"
|
||||||
criterion-macro = "0.3"
|
|
||||||
parsing = { path = "../parsing" }
|
parsing = { path = "../parsing" }
|
||||||
|
|||||||
@@ -1,105 +1,100 @@
|
|||||||
#![feature(custom_test_frameworks)]
|
use parsing::{split_function_chars, SplitType};
|
||||||
#![test_runner(criterion::runner)]
|
|
||||||
|
|
||||||
#[allow(unused_imports)]
|
|
||||||
use parsing::split_function_chars;
|
|
||||||
|
|
||||||
#[allow(unused_imports)]
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use std::{fs::File, os::raw::c_int, path::Path};
|
use std::{fs::File, os::raw::c_int, path::Path};
|
||||||
|
|
||||||
use criterion::profiler::Profiler;
|
use criterion::profiler::Profiler;
|
||||||
#[allow(unused_imports)]
|
use criterion::{criterion_group, criterion_main, Criterion};
|
||||||
use criterion::{BenchmarkId, Criterion};
|
|
||||||
use criterion_macro::criterion;
|
|
||||||
use pprof::ProfilerGuard;
|
use pprof::ProfilerGuard;
|
||||||
|
|
||||||
pub struct FlamegraphProfiler<'a> {
|
pub struct FlamegraphProfiler<'a> {
|
||||||
frequency: c_int,
|
frequency: c_int,
|
||||||
active_profiler: Option<ProfilerGuard<'a>>,
|
active_profiler: Option<ProfilerGuard<'a>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> FlamegraphProfiler<'a> {
|
impl<'a> FlamegraphProfiler<'a> {
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn new(frequency: c_int) -> Self {
|
pub fn new(frequency: c_int) -> Self {
|
||||||
FlamegraphProfiler {
|
FlamegraphProfiler {
|
||||||
frequency,
|
frequency,
|
||||||
active_profiler: None,
|
active_profiler: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> Profiler for FlamegraphProfiler<'a> {
|
impl<'a> Profiler for FlamegraphProfiler<'a> {
|
||||||
fn start_profiling(&mut self, _benchmark_id: &str, _benchmark_dir: &Path) {
|
fn start_profiling(&mut self, _benchmark_id: &str, _benchmark_dir: &Path) {
|
||||||
self.active_profiler = Some(ProfilerGuard::new(self.frequency).unwrap());
|
self.active_profiler = Some(ProfilerGuard::new(self.frequency).unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
fn stop_profiling(&mut self, _benchmark_id: &str, benchmark_dir: &Path) {
|
fn stop_profiling(&mut self, _benchmark_id: &str, benchmark_dir: &Path) {
|
||||||
std::fs::create_dir_all(benchmark_dir).unwrap();
|
std::fs::create_dir_all(benchmark_dir).unwrap();
|
||||||
let flamegraph_path = benchmark_dir.join("flamegraph.svg");
|
let flamegraph_path = benchmark_dir.join("flamegraph.svg");
|
||||||
let flamegraph_file = File::create(&flamegraph_path)
|
let flamegraph_file = File::create(&flamegraph_path)
|
||||||
.expect("File system error while creating flamegraph.svg");
|
.expect("File system error while creating flamegraph.svg");
|
||||||
if let Some(profiler) = self.active_profiler.take() {
|
if let Some(profiler) = self.active_profiler.take() {
|
||||||
profiler
|
profiler
|
||||||
.report()
|
.report()
|
||||||
.build()
|
.build()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.flamegraph(flamegraph_file)
|
.flamegraph(flamegraph_file)
|
||||||
.expect("Error writing flamegraph");
|
.expect("Error writing flamegraph");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)] // this infact IS used by benchmarks
|
#[allow(dead_code)] // this infact IS used by benchmarks
|
||||||
fn custom_criterion() -> Criterion {
|
fn custom_criterion() -> Criterion {
|
||||||
Criterion::default()
|
Criterion::default()
|
||||||
.warm_up_time(Duration::from_millis(250))
|
.warm_up_time(Duration::from_millis(250))
|
||||||
.sample_size(1000)
|
.sample_size(1000)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)] // this infact IS used by benchmarks
|
#[allow(dead_code)] // this infact IS used by benchmarks
|
||||||
fn custom_criterion_flamegraph() -> Criterion {
|
fn custom_criterion_flamegraph() -> Criterion {
|
||||||
custom_criterion().with_profiler(FlamegraphProfiler::new(100))
|
custom_criterion().with_profiler(FlamegraphProfiler::new(100))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[criterion(custom_criterion())]
|
|
||||||
fn mutli_split_function(c: &mut Criterion) {
|
fn mutli_split_function(c: &mut Criterion) {
|
||||||
let data_chars = vec![
|
let data_chars = vec![
|
||||||
"sin(x)cos(x)",
|
"sin(x)cos(x)",
|
||||||
"x^2",
|
"x^2",
|
||||||
"2x",
|
"2x",
|
||||||
"log10(x)",
|
"log10(x)",
|
||||||
"E^x",
|
"E^x",
|
||||||
"xxxxx",
|
"xxxxx",
|
||||||
"xsin(x)",
|
"xsin(x)",
|
||||||
"(2x+1)(3x+1)",
|
"(2x+1)(3x+1)",
|
||||||
"x**2",
|
"x**2",
|
||||||
"pipipipipipix",
|
"pipipipipipix",
|
||||||
"pi(2x+1)",
|
"pi(2x+1)",
|
||||||
"(2x+1)pi",
|
"(2x+1)pi",
|
||||||
]
|
]
|
||||||
.iter()
|
.iter()
|
||||||
.map(|a| a.chars().collect::<Vec<char>>())
|
.map(|a| a.chars().collect::<Vec<char>>())
|
||||||
.collect::<Vec<Vec<char>>>();
|
.collect::<Vec<Vec<char>>>();
|
||||||
|
|
||||||
let mut group = c.benchmark_group("split_function");
|
let mut group = c.benchmark_group("split_function");
|
||||||
for entry in data_chars {
|
for entry in data_chars {
|
||||||
group.bench_function(entry.iter().collect::<String>(), |b| {
|
group.bench_function(entry.iter().collect::<String>(), |b| {
|
||||||
b.iter(|| {
|
b.iter(|| {
|
||||||
split_function_chars(&entry, parsing::suggestions::SplitType::Multiplication);
|
split_function_chars(&entry, SplitType::Multiplication);
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
group.finish();
|
group.finish();
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[criterion(custom_criterion_flamegraph())]
|
// Uncomment to enable flamegraph profiling
|
||||||
// fn single_split_function(c: &mut Criterion) {
|
// fn single_split_function(c: &mut Criterion) {
|
||||||
// let data_chars = "(2x+1)(3x+1)".chars().collect::<Vec<char>>();
|
// let data_chars = "(2x+1)(3x+1)".chars().collect::<Vec<char>>();
|
||||||
|
//
|
||||||
// c.bench_function("split_function", |b| {
|
// c.bench_function("split_function", |b| {
|
||||||
// b.iter(|| {
|
// b.iter(|| {
|
||||||
// split_function_chars(&data_chars);
|
// split_function_chars(&data_chars, SplitType::Multiplication);
|
||||||
// });
|
// });
|
||||||
// });
|
// });
|
||||||
// }
|
// }
|
||||||
|
|
||||||
|
criterion_group!(benches, mutli_split_function);
|
||||||
|
criterion_main!(benches);
|
||||||
|
|||||||
277
build.rs
277
build.rs
@@ -1,171 +1,166 @@
|
|||||||
use std::{
|
use allsorts::{
|
||||||
collections::BTreeMap,
|
binary::read::ReadScope,
|
||||||
env,
|
font::{Font, MatchingPresentation},
|
||||||
fs::File,
|
font_data::FontData as AllsortsFontData,
|
||||||
io::{BufWriter, Write},
|
subset::subset,
|
||||||
path::Path,
|
tag,
|
||||||
};
|
};
|
||||||
|
|
||||||
use epaint::{
|
use epaint::{
|
||||||
text::{FontData, FontDefinitions, FontTweak},
|
FontFamily,
|
||||||
FontFamily,
|
text::{FontData, FontDefinitions, FontTweak},
|
||||||
|
};
|
||||||
|
use std::{
|
||||||
|
collections::BTreeMap,
|
||||||
|
env,
|
||||||
|
fs::File,
|
||||||
|
io::{BufWriter, Write},
|
||||||
|
path::Path,
|
||||||
|
sync::Arc,
|
||||||
};
|
};
|
||||||
|
|
||||||
use run_script::ScriptOptions;
|
|
||||||
|
|
||||||
include!(concat!(
|
include!(concat!(
|
||||||
env!("CARGO_MANIFEST_DIR"),
|
env!("CARGO_MANIFEST_DIR"),
|
||||||
"/src/unicode_helper.rs"
|
"/src/unicode_helper.rs"
|
||||||
));
|
));
|
||||||
|
|
||||||
fn font_stripper(from: &str, out: &str, unicodes: Vec<char>) -> Result<Vec<u8>, String> {
|
fn font_stripper(from: &str, out: &str, unicodes: Vec<char>) -> Result<Vec<u8>, String> {
|
||||||
let unicodes: Vec<String> = unicodes.iter().map(|c| to_unicode_hash(*c)).collect();
|
let font_path = format!("{}/assets/{}", env!("CARGO_MANIFEST_DIR"), from);
|
||||||
|
let font_data = std::fs::read(&font_path).map_err(|e| e.to_string())?;
|
||||||
|
let scope = ReadScope::new(&font_data);
|
||||||
|
let font_file = scope
|
||||||
|
.read::<AllsortsFontData>()
|
||||||
|
.map_err(|e| format!("Failed to read font data: {}", e))?;
|
||||||
|
let provider = font_file
|
||||||
|
.table_provider(0)
|
||||||
|
.map_err(|e| format!("Failed to get table provider: {}", e))?;
|
||||||
|
let mut font = Font::new(provider).map_err(|e| format!("Failed to create font: {:?}", e))?;
|
||||||
|
|
||||||
let new_path = [&env::var("OUT_DIR").unwrap(), out].concat();
|
let mut glyph_ids = Vec::new();
|
||||||
let unicodes_formatted = unicodes
|
for &ch in &unicodes {
|
||||||
.iter()
|
let mut glyph_ids_curr = font
|
||||||
.map(|u| format!("U+{}", u))
|
.map_glyphs(
|
||||||
.collect::<Vec<String>>()
|
&ch.to_string(),
|
||||||
.join(",");
|
tag::LATN,
|
||||||
|
MatchingPresentation::NotRequired,
|
||||||
|
)
|
||||||
|
.into_iter()
|
||||||
|
.map(|glyph| glyph.glyph_index)
|
||||||
|
.collect();
|
||||||
|
|
||||||
// Test to see if pyftsubset is found
|
glyph_ids.append(&mut glyph_ids_curr);
|
||||||
let pyftsubset_detect = run_script::run("whereis pyftsubset", &(vec![]), &ScriptOptions::new());
|
}
|
||||||
match pyftsubset_detect {
|
// Include .notdef glyph
|
||||||
Ok((_i, s1, _s2)) => {
|
glyph_ids.push(0);
|
||||||
if s1 == "pyftsubset: " {
|
glyph_ids.sort();
|
||||||
return Err(String::from("pyftsubset not found"));
|
glyph_ids.dedup();
|
||||||
}
|
|
||||||
}
|
|
||||||
// It was not, return an error and abort
|
|
||||||
Err(x) => return Err(x.to_string()),
|
|
||||||
}
|
|
||||||
|
|
||||||
let script_result = run_script::run(
|
let subset_data = subset(&font.font_table_provider, &glyph_ids)
|
||||||
&format!(
|
.map_err(|e| format!("Failed to subset font: {}", e))?;
|
||||||
"pyftsubset {}/assets/{} --unicodes={}
|
|
||||||
mv {}/assets/{} {}",
|
|
||||||
env!("CARGO_MANIFEST_DIR"),
|
|
||||||
from,
|
|
||||||
unicodes_formatted,
|
|
||||||
env!("CARGO_MANIFEST_DIR"),
|
|
||||||
from.replace(".ttf", ".subset.ttf"),
|
|
||||||
new_path
|
|
||||||
),
|
|
||||||
&(vec![]),
|
|
||||||
&ScriptOptions::new(),
|
|
||||||
);
|
|
||||||
|
|
||||||
if let Ok((_, _, error)) = script_result {
|
let new_path = [&env::var("OUT_DIR").unwrap(), out].concat();
|
||||||
if error.is_empty() {
|
std::fs::write(&new_path, &subset_data)
|
||||||
return Ok(std::fs::read(new_path).unwrap());
|
.map_err(|e| format!("Failed to write subset font: {}", e))?;
|
||||||
} else {
|
|
||||||
return Err(error);
|
Ok(subset_data)
|
||||||
}
|
|
||||||
} else if let Err(error) = script_result {
|
|
||||||
return Err(error.to_string());
|
|
||||||
}
|
|
||||||
unreachable!()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
// rebuild if new commit or contents of `assets` folder changed
|
// rebuild if contents of `assets` folder changed
|
||||||
println!("cargo:rerun-if-changed=.git/logs/HEAD");
|
println!("cargo:rerun-if-changed=assets/*");
|
||||||
println!("cargo:rerun-if-changed=assets/*");
|
|
||||||
|
|
||||||
shadow_rs::new().expect("Could not initialize shadow_rs");
|
let mut main_chars: Vec<char> =
|
||||||
|
|
||||||
let mut main_chars: Vec<char> =
|
|
||||||
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzsu0123456789?.,!(){}[]-_=+-/<>'\\ :^*`@#$%&|~;"
|
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzsu0123456789?.,!(){}[]-_=+-/<>'\\ :^*`@#$%&|~;"
|
||||||
.iter()
|
.iter()
|
||||||
.map(|c| *c as char)
|
.map(|c| *c as char)
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
main_chars.append(&mut vec!['π', '"']);
|
main_chars.append(&mut vec!['π', '"']);
|
||||||
|
|
||||||
{
|
{
|
||||||
let filtered_chars: Vec<char> = main_chars
|
let filtered_chars: Vec<char> = main_chars
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|c| !c.is_alphanumeric())
|
.filter(|c| !c.is_alphanumeric())
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let chars_array = format!(
|
let chars_array = format!(
|
||||||
"const VALID_EXTRA_CHARS: [char; {}] = {};",
|
"const VALID_EXTRA_CHARS: [char; {}] = {};",
|
||||||
filtered_chars.len(),
|
filtered_chars.len(),
|
||||||
to_chars_array(filtered_chars),
|
to_chars_array(filtered_chars),
|
||||||
);
|
);
|
||||||
let path = Path::new(&env::var("OUT_DIR").unwrap()).join("valid_chars.rs");
|
let path = Path::new(&env::var("OUT_DIR").unwrap()).join("valid_chars.rs");
|
||||||
let mut file = BufWriter::new(File::create(path).expect("Could not save compressed_data"));
|
let mut file = BufWriter::new(File::create(path).expect("Could not save compressed_data"));
|
||||||
|
|
||||||
write!(&mut file, "{}", chars_array).expect("unable to write chars_array");
|
write!(&mut file, "{}", chars_array).expect("unable to write chars_array");
|
||||||
}
|
}
|
||||||
|
|
||||||
let fonts = FontDefinitions {
|
let fonts = FontDefinitions {
|
||||||
font_data: BTreeMap::from([
|
font_data: BTreeMap::from([
|
||||||
(
|
(
|
||||||
"Ubuntu-Light".to_owned(),
|
"Ubuntu-Light".to_owned(),
|
||||||
FontData::from_owned(
|
Arc::new(FontData::from_owned(
|
||||||
font_stripper(
|
font_stripper(
|
||||||
"Ubuntu-Light.ttf",
|
"Ubuntu-Light.ttf",
|
||||||
"ubuntu-light.ttf",
|
"ubuntu-light.ttf",
|
||||||
[main_chars, vec!['∫']].concat(),
|
[main_chars, vec!['∫']].concat(),
|
||||||
)
|
)
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
),
|
)),
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
"NotoEmoji-Regular".to_owned(),
|
"NotoEmoji-Regular".to_owned(),
|
||||||
FontData::from_owned(
|
Arc::new(FontData::from_owned(
|
||||||
font_stripper(
|
font_stripper(
|
||||||
"NotoEmoji-Regular.ttf",
|
"NotoEmoji-Regular.ttf",
|
||||||
"noto-emoji.ttf",
|
"noto-emoji.ttf",
|
||||||
vec!['🌞', '🌙', '✖'],
|
vec!['🌞', '🌙', '✖'],
|
||||||
)
|
)
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
),
|
)),
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
"emoji-icon-font".to_owned(),
|
"emoji-icon-font".to_owned(),
|
||||||
FontData::from_owned(
|
Arc::new(
|
||||||
font_stripper("emoji-icon-font.ttf", "emoji-icon.ttf", vec!['⚙']).unwrap(),
|
FontData::from_owned(
|
||||||
)
|
font_stripper("emoji-icon-font.ttf", "emoji-icon.ttf", vec!['⚙']).unwrap(),
|
||||||
.tweak(FontTweak {
|
)
|
||||||
scale: 0.8,
|
.tweak(FontTweak {
|
||||||
y_offset_factor: 0.07,
|
scale: 0.8,
|
||||||
y_offset: 0.0,
|
y_offset_factor: 0.07,
|
||||||
baseline_offset_factor: -0.0333,
|
y_offset: -0.0333,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
]),
|
),
|
||||||
families: BTreeMap::from([
|
]),
|
||||||
(
|
families: BTreeMap::from([
|
||||||
FontFamily::Monospace,
|
(
|
||||||
vec![
|
FontFamily::Monospace,
|
||||||
"Ubuntu-Light".to_owned(),
|
vec![
|
||||||
"NotoEmoji-Regular".to_owned(),
|
"Ubuntu-Light".to_owned(),
|
||||||
"emoji-icon-font".to_owned(),
|
"NotoEmoji-Regular".to_owned(),
|
||||||
],
|
"emoji-icon-font".to_owned(),
|
||||||
),
|
],
|
||||||
(
|
),
|
||||||
FontFamily::Proportional,
|
(
|
||||||
vec![
|
FontFamily::Proportional,
|
||||||
"Ubuntu-Light".to_owned(),
|
vec![
|
||||||
"NotoEmoji-Regular".to_owned(),
|
"Ubuntu-Light".to_owned(),
|
||||||
"emoji-icon-font".to_owned(),
|
"NotoEmoji-Regular".to_owned(),
|
||||||
],
|
"emoji-icon-font".to_owned(),
|
||||||
),
|
],
|
||||||
]),
|
),
|
||||||
};
|
]),
|
||||||
|
};
|
||||||
|
|
||||||
let data = bincode::serialize(&fonts).unwrap();
|
let data = bincode::serialize(&fonts).unwrap();
|
||||||
|
|
||||||
let zstd_levels = zstd::compression_level_range();
|
let zstd_levels = zstd::compression_level_range();
|
||||||
let data_compressed =
|
let data_compressed =
|
||||||
zstd::encode_all(data.as_slice(), *zstd_levels.end()).expect("Could not compress data");
|
zstd::encode_all(data.as_slice(), *zstd_levels.end()).expect("Could not compress data");
|
||||||
|
|
||||||
let path = Path::new(&env::var("OUT_DIR").unwrap()).join("compressed_data");
|
let path = Path::new(&env::var("OUT_DIR").unwrap()).join("compressed_data");
|
||||||
let mut file = BufWriter::new(File::create(path).expect("Could not save compressed_data"));
|
let mut file = BufWriter::new(File::create(path).expect("Could not save compressed_data"));
|
||||||
|
|
||||||
file.write_all(data_compressed.as_slice())
|
file.write_all(data_compressed.as_slice())
|
||||||
.expect("Failed to save compressed data");
|
.expect("Failed to save compressed data");
|
||||||
}
|
}
|
||||||
|
|||||||
76
build.sh
76
build.sh
@@ -1,76 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
set -e
|
|
||||||
|
|
||||||
rm -fr tmp | true
|
|
||||||
rm -fr pkg | true
|
|
||||||
|
|
||||||
# cargo test
|
|
||||||
|
|
||||||
export RUSTFLAGS="--cfg=web_sys_unstable_apis"
|
|
||||||
|
|
||||||
if test "$1" == "" || test "$1" == "release"; then
|
|
||||||
time cargo build --release --target wasm32-unknown-unknown -Z build-std=core,compiler_builtins,alloc,std,panic_abort,panic_unwind,proc_macro,unwind -Z build-std-features=panic_immediate_abort --lib --timings
|
|
||||||
llvm-strip -s target/wasm32-unknown-unknown/release/ytbn_graphing_software.wasm
|
|
||||||
export TYPE="release"
|
|
||||||
elif test "$1" == "debug"; then
|
|
||||||
time cargo build --target wasm32-unknown-unknown -Z build-std=core,compiler_builtins,alloc,std,panic_abort,panic_unwind,proc_macro,unwind -Z build-std-features=panic-unwind --lib
|
|
||||||
export TYPE="debug"
|
|
||||||
else
|
|
||||||
echo "ERROR: build.sh, argument invalid"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
pre_size=$(du -sb target/wasm32-unknown-unknown/${TYPE}/ytbn_graphing_software.wasm | awk '{ print $1 }')
|
|
||||||
echo "compiled size: $pre_size"
|
|
||||||
|
|
||||||
wasm-bindgen target/wasm32-unknown-unknown/${TYPE}/ytbn_graphing_software.wasm --out-dir pkg --target web --no-typescript
|
|
||||||
|
|
||||||
if test "$TYPE" == "release"; then
|
|
||||||
echo "running wasm-opt..."
|
|
||||||
time wasm-opt --converge -Oz --code-folding --const-hoisting --coalesce-locals-learning --vacuum --merge-locals --merge-blocks --fast-math --precompute --rse --low-memory-unused --once-reduction --optimize-instructions --licm --intrinsic-lowering \
|
|
||||||
--dce --dae-optimizing --inlining-optimizing --strip-debug \
|
|
||||||
-o pkg/ytbn_graphing_software_bg_2.wasm pkg/ytbn_graphing_software_bg.wasm
|
|
||||||
mv pkg/ytbn_graphing_software_bg_2.wasm pkg/ytbn_graphing_software_bg.wasm
|
|
||||||
fi
|
|
||||||
|
|
||||||
mkdir tmp
|
|
||||||
cp -r pkg/ytbn_graphing_software_bg.wasm tmp/
|
|
||||||
|
|
||||||
sed -i 's/fatal: true/fatal: false/g' pkg/ytbn_graphing_software.js
|
|
||||||
|
|
||||||
sed -i "s/TextEncoder('utf-8')/TextEncoder('utf-8', { ignoreBOM: true, fatal: false })/g" pkg/ytbn_graphing_software.js
|
|
||||||
|
|
||||||
#minify pkg/ytbn_graphing_software.js > tmp/ytbn_graphing_software.js
|
|
||||||
|
|
||||||
cp www/* tmp/
|
|
||||||
cp assets/logo.svg tmp/
|
|
||||||
#minify www/index.html > tmp/index.html
|
|
||||||
#minify www/sw.js > tmp/sw.js
|
|
||||||
cp www/index.html www/sw.js pkg/ytbn_graphing_software.js tmp/
|
|
||||||
|
|
||||||
|
|
||||||
wasm_sum=($(md5sum tmp/ytbn_graphing_software_bg.wasm))
|
|
||||||
js_sum=($(md5sum tmp/ytbn_graphing_software.js))
|
|
||||||
sum=($(echo "$wasm_sum $js_sum" | md5sum))
|
|
||||||
|
|
||||||
echo "sum: $sum"
|
|
||||||
|
|
||||||
new_wasm_name="${sum}.wasm"
|
|
||||||
new_js_name="${sum}.js"
|
|
||||||
|
|
||||||
|
|
||||||
mv tmp/ytbn_graphing_software_bg.wasm "tmp/${new_wasm_name}"
|
|
||||||
mv tmp/ytbn_graphing_software.js "tmp/${new_js_name}"
|
|
||||||
|
|
||||||
|
|
||||||
sed -i "s/ytbn_graphing_software_bg.wasm/${new_wasm_name}/g" tmp/*.*
|
|
||||||
|
|
||||||
sed -i "s/ytbn_graphing_software.js/${new_js_name}/g" tmp/*.*
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
new_size=$(du -b tmp/${new_wasm_name} | awk '{ print $1 }')
|
|
||||||
diff=$(echo "scale=5 ; $new_size / $pre_size" | bc)
|
|
||||||
percent=$(echo "scale=5 ; (1-$diff)*100" | bc)
|
|
||||||
echo "Total size: $(du -sb tmp)"
|
|
||||||
echo "Binary size: $new_size reduced: $percent%"
|
|
||||||
82
flake.lock
generated
Normal file
82
flake.lock
generated
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"flake-utils": {
|
||||||
|
"inputs": {
|
||||||
|
"systems": "systems"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1731533236,
|
||||||
|
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1764517877,
|
||||||
|
"narHash": "sha256-pp3uT4hHijIC8JUK5MEqeAWmParJrgBVzHLNfJDZxg4=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "2d293cbfa5a793b4c50d17c05ef9e385b90edf6c",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-utils": "flake-utils",
|
||||||
|
"nixpkgs": "nixpkgs",
|
||||||
|
"rust-overlay": "rust-overlay"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"rust-overlay": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": [
|
||||||
|
"nixpkgs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1764729618,
|
||||||
|
"narHash": "sha256-z4RA80HCWv2los1KD346c+PwNPzMl79qgl7bCVgz8X0=",
|
||||||
|
"owner": "oxalica",
|
||||||
|
"repo": "rust-overlay",
|
||||||
|
"rev": "52764074a85145d5001bf0aa30cb71936e9ad5b8",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "oxalica",
|
||||||
|
"repo": "rust-overlay",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"systems": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1681028828,
|
||||||
|
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
198
flake.nix
Normal file
198
flake.nix
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
{
|
||||||
|
description = "YTBN Graphing Software";
|
||||||
|
|
||||||
|
inputs = {
|
||||||
|
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||||
|
flake-utils.url = "github:numtide/flake-utils";
|
||||||
|
rust-overlay = {
|
||||||
|
url = "github:oxalica/rust-overlay";
|
||||||
|
inputs.nixpkgs.follows = "nixpkgs";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
outputs =
|
||||||
|
{
|
||||||
|
self,
|
||||||
|
nixpkgs,
|
||||||
|
flake-utils,
|
||||||
|
rust-overlay,
|
||||||
|
}:
|
||||||
|
flake-utils.lib.eachDefaultSystem (
|
||||||
|
system:
|
||||||
|
let
|
||||||
|
overlays = [ (import rust-overlay) ];
|
||||||
|
pkgs = import nixpkgs {
|
||||||
|
inherit system overlays;
|
||||||
|
};
|
||||||
|
|
||||||
|
# Use nightly rust with wasm32 target
|
||||||
|
rustToolchain = pkgs.rust-bin.stable.latest.default.override {
|
||||||
|
targets = [ "wasm32-unknown-unknown" ];
|
||||||
|
};
|
||||||
|
|
||||||
|
rustPlatform = pkgs.makeRustPlatform {
|
||||||
|
cargo = rustToolchain;
|
||||||
|
rustc = rustToolchain;
|
||||||
|
};
|
||||||
|
|
||||||
|
# Build the wasm library using rustPlatform
|
||||||
|
wasmLib = rustPlatform.buildRustPackage {
|
||||||
|
pname = "ytbn-graphing-software-wasm";
|
||||||
|
version = "0.1.0";
|
||||||
|
|
||||||
|
src = ./.;
|
||||||
|
|
||||||
|
cargoLock = {
|
||||||
|
lockFile = ./Cargo.lock;
|
||||||
|
outputHashes = {
|
||||||
|
"ecolor-0.33.2" = "sha256-jdQK55yKZptadwosrJXIhoQDGNeELQmPExWRsGc0VG0=";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
nativeBuildInputs = with pkgs; [
|
||||||
|
python3Packages.fonttools
|
||||||
|
pkg-config
|
||||||
|
clang
|
||||||
|
];
|
||||||
|
|
||||||
|
buildInputs = with pkgs; [
|
||||||
|
openssl
|
||||||
|
zstd
|
||||||
|
];
|
||||||
|
|
||||||
|
# Run all tests on native target before building wasm
|
||||||
|
# Note: Tests run without --release because the release profile uses
|
||||||
|
# panic=abort which is incompatible with the test harness.
|
||||||
|
checkPhase =
|
||||||
|
let
|
||||||
|
libPath = pkgs.lib.makeLibraryPath (
|
||||||
|
with pkgs;
|
||||||
|
[
|
||||||
|
libxkbcommon
|
||||||
|
libGL
|
||||||
|
wayland
|
||||||
|
]
|
||||||
|
);
|
||||||
|
in
|
||||||
|
''
|
||||||
|
runHook preCheck
|
||||||
|
export LD_LIBRARY_PATH="${libPath}:$LD_LIBRARY_PATH"
|
||||||
|
cargo test --workspace
|
||||||
|
runHook postCheck
|
||||||
|
'';
|
||||||
|
|
||||||
|
buildPhase = ''
|
||||||
|
runHook preBuild
|
||||||
|
|
||||||
|
cargo build \
|
||||||
|
--release \
|
||||||
|
--lib \
|
||||||
|
--target wasm32-unknown-unknown
|
||||||
|
|
||||||
|
runHook postBuild
|
||||||
|
'';
|
||||||
|
|
||||||
|
installPhase = ''
|
||||||
|
runHook preInstall
|
||||||
|
mkdir -p $out/lib
|
||||||
|
cp target/wasm32-unknown-unknown/release/*.wasm $out/lib/
|
||||||
|
runHook postInstall
|
||||||
|
'';
|
||||||
|
|
||||||
|
doCheck = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
# Final web package with wasm-bindgen processing
|
||||||
|
ytbn-graphing-software-web = pkgs.stdenv.mkDerivation {
|
||||||
|
pname = "ytbn-graphing-software-web";
|
||||||
|
version = "0.1.0";
|
||||||
|
|
||||||
|
src = ./.;
|
||||||
|
|
||||||
|
nativeBuildInputs = with pkgs; [
|
||||||
|
wasm-bindgen-cli
|
||||||
|
binaryen
|
||||||
|
];
|
||||||
|
|
||||||
|
buildPhase = ''
|
||||||
|
runHook preBuild
|
||||||
|
|
||||||
|
# Generate JS bindings
|
||||||
|
wasm-bindgen ${wasmLib}/lib/ytbn_graphing_software.wasm \
|
||||||
|
--out-dir out \
|
||||||
|
--out-name ytbn_graphing_software \
|
||||||
|
--target web \
|
||||||
|
--no-typescript
|
||||||
|
|
||||||
|
# Optimize wasm (enable features used by modern rust wasm targets)
|
||||||
|
wasm-opt out/ytbn_graphing_software_bg.wasm \
|
||||||
|
-Oz \
|
||||||
|
--enable-bulk-memory \
|
||||||
|
--enable-nontrapping-float-to-int \
|
||||||
|
--enable-sign-ext \
|
||||||
|
--enable-mutable-globals \
|
||||||
|
-o out/ytbn_graphing_software_bg.wasm
|
||||||
|
|
||||||
|
runHook postBuild
|
||||||
|
'';
|
||||||
|
|
||||||
|
installPhase = ''
|
||||||
|
runHook preInstall
|
||||||
|
|
||||||
|
mkdir -p $out
|
||||||
|
|
||||||
|
# Copy wasm and js files
|
||||||
|
cp out/ytbn_graphing_software_bg.wasm $out/
|
||||||
|
cp out/ytbn_graphing_software.js $out/
|
||||||
|
|
||||||
|
# Copy static web assets
|
||||||
|
cp www/index.html $out/
|
||||||
|
cp www/manifest.json $out/
|
||||||
|
cp www/sw.js $out/
|
||||||
|
|
||||||
|
# Copy logo
|
||||||
|
cp assets/logo.svg $out/
|
||||||
|
|
||||||
|
runHook postInstall
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
in
|
||||||
|
{
|
||||||
|
packages = {
|
||||||
|
default = ytbn-graphing-software-web;
|
||||||
|
web = ytbn-graphing-software-web;
|
||||||
|
wasm = wasmLib;
|
||||||
|
};
|
||||||
|
|
||||||
|
devShells.default = pkgs.mkShell {
|
||||||
|
nativeBuildInputs = with pkgs; [
|
||||||
|
rustToolchain
|
||||||
|
wasm-bindgen-cli
|
||||||
|
binaryen
|
||||||
|
rust-analyzer
|
||||||
|
pkg-config
|
||||||
|
clang
|
||||||
|
|
||||||
|
# Runtime deps for native builds
|
||||||
|
libxkbcommon
|
||||||
|
libGL
|
||||||
|
wayland
|
||||||
|
];
|
||||||
|
|
||||||
|
buildInputs = with pkgs; [
|
||||||
|
openssl
|
||||||
|
zstd
|
||||||
|
];
|
||||||
|
|
||||||
|
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath (
|
||||||
|
with pkgs;
|
||||||
|
[
|
||||||
|
libxkbcommon
|
||||||
|
libGL
|
||||||
|
wayland
|
||||||
|
]
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -10,11 +10,11 @@ description = "Parsing library for YTBN-Graphing-Software"
|
|||||||
[lib]
|
[lib]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
phf = { version = "0.11" }
|
phf = { version = "0.13" }
|
||||||
exmex = {version = "0.17.5", features = ["partial"]}
|
exmex = {version = "0.20.5", features = ["partial"]}
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
phf_codegen = { version = "0.11" }
|
phf_codegen = { version = "0.13" }
|
||||||
|
|
||||||
[package.metadata.cargo-all-features]
|
[package.metadata.cargo-all-features]
|
||||||
skip_optional_dependencies = true #don't test optional dependencies, only features
|
skip_optional_dependencies = true #don't test optional dependencies, only features
|
||||||
|
|||||||
@@ -5,46 +5,46 @@ use std::path::Path;
|
|||||||
|
|
||||||
/// REMEMBER TO UPDATE THIS IF EXMEX ADDS NEW FUNCTIONS
|
/// REMEMBER TO UPDATE THIS IF EXMEX ADDS NEW FUNCTIONS
|
||||||
const SUPPORTED_FUNCTIONS: [&str; 22] = [
|
const SUPPORTED_FUNCTIONS: [&str; 22] = [
|
||||||
"abs", "signum", "sin", "cos", "tan", "asin", "acos", "atan", "sinh", "cosh", "tanh", "floor",
|
"abs", "signum", "sin", "cos", "tan", "asin", "acos", "atan", "sinh", "cosh", "tanh", "floor",
|
||||||
"round", "ceil", "trunc", "fract", "exp", "sqrt", "cbrt", "ln", "log2", "log10",
|
"round", "ceil", "trunc", "fract", "exp", "sqrt", "cbrt", "ln", "log2", "log10",
|
||||||
];
|
];
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
println!("cargo:rerun-if-changed=src/*");
|
println!("cargo:rerun-if-changed=src/*");
|
||||||
|
|
||||||
generate_hashmap();
|
generate_hashmap();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn generate_hashmap() {
|
fn generate_hashmap() {
|
||||||
let path = Path::new(&env::var("OUT_DIR").unwrap()).join("codegen.rs");
|
let path = Path::new(&env::var("OUT_DIR").unwrap()).join("codegen.rs");
|
||||||
let mut file = BufWriter::new(File::create(path).expect("Could not create file"));
|
let mut file = BufWriter::new(File::create(path).expect("Could not create file"));
|
||||||
|
|
||||||
let string_hashmap =
|
let string_hashmap =
|
||||||
compile_hashmap(SUPPORTED_FUNCTIONS.iter().map(|a| a.to_string()).collect());
|
compile_hashmap(SUPPORTED_FUNCTIONS.iter().map(|a| a.to_string()).collect());
|
||||||
|
|
||||||
let mut hashmap = phf_codegen::Map::new();
|
let mut hashmap = phf_codegen::Map::new();
|
||||||
|
|
||||||
for (key, value) in string_hashmap.iter() {
|
for (key, value) in string_hashmap.iter() {
|
||||||
hashmap.entry(key, value);
|
hashmap.entry(key, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
write!(
|
write!(
|
||||||
&mut file,
|
&mut file,
|
||||||
"static COMPLETION_HASHMAP: phf::Map<&'static str, Hint> = {};",
|
"static COMPLETION_HASHMAP: phf::Map<&'static str, Hint> = {};",
|
||||||
hashmap.build()
|
hashmap.build()
|
||||||
)
|
)
|
||||||
.expect("Could not write to file");
|
.expect("Could not write to file");
|
||||||
|
|
||||||
write!(
|
write!(
|
||||||
&mut file,
|
&mut file,
|
||||||
"#[allow(dead_code)] pub const SUPPORTED_FUNCTIONS: [&str; {}] = {:?};",
|
"#[allow(dead_code)] pub const SUPPORTED_FUNCTIONS: [&str; {}] = {:?};",
|
||||||
SUPPORTED_FUNCTIONS.len(),
|
SUPPORTED_FUNCTIONS.len(),
|
||||||
SUPPORTED_FUNCTIONS.to_vec()
|
SUPPORTED_FUNCTIONS.to_vec()
|
||||||
)
|
)
|
||||||
.expect("Could not write to file");
|
.expect("Could not write to file");
|
||||||
}
|
}
|
||||||
|
|
||||||
include!(concat!(
|
include!(concat!(
|
||||||
env!("CARGO_MANIFEST_DIR"),
|
env!("CARGO_MANIFEST_DIR"),
|
||||||
"/src/autocomplete_hashmap.rs"
|
"/src/autocomplete_hashmap.rs"
|
||||||
));
|
));
|
||||||
|
|||||||
@@ -4,105 +4,113 @@ use crate::{generate_hint, Hint, HINT_EMPTY};
|
|||||||
|
|
||||||
#[derive(PartialEq, Debug)]
|
#[derive(PartialEq, Debug)]
|
||||||
pub enum Movement {
|
pub enum Movement {
|
||||||
Complete,
|
Complete,
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
Down,
|
Down,
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
Up,
|
Up,
|
||||||
None,
|
None,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Movement {
|
impl Movement {
|
||||||
pub const fn is_none(&self) -> bool { matches!(&self, &Self::None) }
|
pub const fn is_none(&self) -> bool {
|
||||||
|
matches!(&self, &Self::None)
|
||||||
|
}
|
||||||
|
|
||||||
pub const fn is_complete(&self) -> bool { matches!(&self, &Self::Complete) }
|
pub const fn is_complete(&self) -> bool {
|
||||||
|
matches!(&self, &Self::Complete)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl const Default for Movement {
|
impl Default for Movement {
|
||||||
fn default() -> Self { Self::None }
|
fn default() -> Self {
|
||||||
|
Self::None
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq)]
|
#[derive(Clone, PartialEq)]
|
||||||
pub struct AutoComplete<'a> {
|
pub struct AutoComplete<'a> {
|
||||||
pub i: usize,
|
pub i: usize,
|
||||||
pub hint: &'a Hint<'a>,
|
pub hint: &'a Hint<'a>,
|
||||||
pub string: String,
|
pub string: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> const Default for AutoComplete<'a> {
|
impl<'a> Default for AutoComplete<'a> {
|
||||||
fn default() -> AutoComplete<'a> { AutoComplete::EMPTY }
|
fn default() -> AutoComplete<'a> {
|
||||||
|
AutoComplete::EMPTY
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> AutoComplete<'a> {
|
impl<'a> AutoComplete<'a> {
|
||||||
pub const EMPTY: AutoComplete<'a> = Self {
|
pub const EMPTY: AutoComplete<'a> = Self {
|
||||||
i: 0,
|
i: 0,
|
||||||
hint: &HINT_EMPTY,
|
hint: &HINT_EMPTY,
|
||||||
string: String::new(),
|
string: String::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn update_string(&mut self, string: &str) {
|
pub fn update_string(&mut self, string: &str) {
|
||||||
if self.string != string {
|
if self.string != string {
|
||||||
// catch empty strings here to avoid call to `generate_hint` and unnecessary logic
|
// catch empty strings here to avoid call to `generate_hint` and unnecessary logic
|
||||||
if string.is_empty() {
|
if string.is_empty() {
|
||||||
*self = Self::EMPTY;
|
*self = Self::EMPTY;
|
||||||
} else {
|
} else {
|
||||||
self.string = string.to_owned();
|
self.string = string.to_owned();
|
||||||
self.do_update_logic();
|
self.do_update_logic();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs update logic assuming that a change to `self.string` has been made
|
/// Runs update logic assuming that a change to `self.string` has been made
|
||||||
fn do_update_logic(&mut self) {
|
fn do_update_logic(&mut self) {
|
||||||
self.i = 0;
|
self.i = 0;
|
||||||
self.hint = generate_hint(&self.string);
|
self.hint = generate_hint(&self.string);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn register_movement(&mut self, movement: &Movement) {
|
pub fn register_movement(&mut self, movement: &Movement) {
|
||||||
if movement.is_none() | self.hint.is_none() {
|
if movement.is_none() | self.hint.is_none() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
match self.hint {
|
match self.hint {
|
||||||
Hint::Many(hints) => {
|
Hint::Many(hints) => {
|
||||||
// Impossible for plural hints to be singular or non-existant
|
// Impossible for plural hints to be singular or non-existant
|
||||||
debug_assert!(hints.len() > 1); // check on debug
|
debug_assert!(hints.len() > 1); // check on debug
|
||||||
|
|
||||||
match movement {
|
match movement {
|
||||||
Movement::Up => {
|
Movement::Up => {
|
||||||
// Wrap self.i to maximum `i` value if needed
|
// Wrap self.i to maximum `i` value if needed
|
||||||
if self.i == 0 {
|
if self.i == 0 {
|
||||||
self.i = hints.len() - 1;
|
self.i = hints.len() - 1;
|
||||||
} else {
|
} else {
|
||||||
self.i -= 1;
|
self.i -= 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Movement::Down => {
|
Movement::Down => {
|
||||||
// Add one, if resulting value is above maximum `i` value, set `i` to 0
|
// Add one, if resulting value is above maximum `i` value, set `i` to 0
|
||||||
self.i += 1;
|
self.i += 1;
|
||||||
if self.i > (hints.len() - 1) {
|
if self.i > (hints.len() - 1) {
|
||||||
self.i = 0;
|
self.i = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Movement::Complete => {
|
Movement::Complete => {
|
||||||
self.apply_hint(unsafe { hints.get_unchecked(self.i) });
|
self.apply_hint(unsafe { hints.get_unchecked(self.i) });
|
||||||
}
|
}
|
||||||
_ => unsafe { unreachable_unchecked() },
|
_ => unsafe { unreachable_unchecked() },
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Hint::Single(hint) => {
|
Hint::Single(hint) => {
|
||||||
if movement.is_complete() {
|
if movement.is_complete() {
|
||||||
self.apply_hint(hint);
|
self.apply_hint(hint);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Hint::None => unsafe { unreachable_unchecked() },
|
Hint::None => unsafe { unreachable_unchecked() },
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn apply_hint(&mut self, hint: &str) {
|
pub fn apply_hint(&mut self, hint: &str) {
|
||||||
self.string.push_str(hint);
|
self.string.push_str(hint);
|
||||||
self.do_update_logic();
|
self.do_update_logic();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,81 +3,82 @@ use std::collections::HashSet;
|
|||||||
|
|
||||||
/// https://www.dotnetperls.com/sort-rust
|
/// https://www.dotnetperls.com/sort-rust
|
||||||
fn compare_len_reverse_alpha(a: &String, b: &String) -> Ordering {
|
fn compare_len_reverse_alpha(a: &String, b: &String) -> Ordering {
|
||||||
match a.len().cmp(&b.len()) {
|
match a.len().cmp(&b.len()) {
|
||||||
Ordering::Equal => b.cmp(a),
|
Ordering::Equal => b.cmp(a),
|
||||||
order => order,
|
order => order,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Generates hashmap (well really a vector of tuple of strings that are then turned into a hashmap by phf)
|
/// Generates hashmap (well really a vector of tuple of strings that are then turned into a hashmap by phf)
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn compile_hashmap(data: Vec<String>) -> Vec<(String, String)> {
|
pub fn compile_hashmap(data: Vec<String>) -> Vec<(String, String)> {
|
||||||
let mut seen = HashSet::new();
|
let mut seen = HashSet::new();
|
||||||
|
|
||||||
let tuple_list_1: Vec<(String, String)> = data
|
let tuple_list_1: Vec<(String, String)> = data
|
||||||
.iter()
|
.iter()
|
||||||
.map(|e| e.to_string() + "(")
|
.map(|e| e.to_string() + "(")
|
||||||
.flat_map(|func| all_possible_splits(func, &mut seen))
|
.flat_map(|func| all_possible_splits(func, &mut seen))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let keys: Vec<&String> = tuple_list_1.iter().map(|(a, _)| a).collect();
|
let keys: Vec<&String> = tuple_list_1.iter().map(|(a, _)| a).collect();
|
||||||
let mut output: Vec<(String, String)> = Vec::new();
|
let mut output: Vec<(String, String)> = Vec::new();
|
||||||
let mut seen_3: HashSet<String> = HashSet::new();
|
let mut seen_3: HashSet<String> = HashSet::new();
|
||||||
|
|
||||||
for (key, value) in tuple_list_1.iter() {
|
for (key, value) in tuple_list_1.iter() {
|
||||||
if seen_3.contains(key) {
|
if seen_3.contains(key) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
seen_3.insert(key.clone());
|
seen_3.insert(key.clone());
|
||||||
|
|
||||||
let count_keys = keys.iter().filter(|a| a == &&key).count();
|
let count_keys = keys.iter().filter(|a| a == &&key).count();
|
||||||
|
|
||||||
match count_keys.cmp(&1usize) {
|
match count_keys.cmp(&1usize) {
|
||||||
Ordering::Less => {
|
Ordering::Less => {
|
||||||
panic!("Number of values for {key} is 0!");
|
panic!("Number of values for {key} is 0!");
|
||||||
}
|
}
|
||||||
Ordering::Greater => {
|
Ordering::Greater => {
|
||||||
let mut multi_data = tuple_list_1
|
let mut multi_data = tuple_list_1
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|(a, _)| a == key)
|
.filter(|(a, _)| a == key)
|
||||||
.map(|(_, b)| b)
|
.map(|(_, b)| b)
|
||||||
.collect::<Vec<&String>>();
|
.collect::<Vec<&String>>();
|
||||||
multi_data.sort_unstable_by(|a, b| compare_len_reverse_alpha(a, b));
|
multi_data.sort_unstable_by(|a, b| compare_len_reverse_alpha(a, b));
|
||||||
output.push((key.clone(), format!("Hint::Many(&{:?})", multi_data)));
|
output.push((key.clone(), format!("Hint::Many(&{:?})", multi_data)));
|
||||||
}
|
}
|
||||||
Ordering::Equal => output.push((key.clone(), format!(r#"Hint::Single("{}")"#, value))),
|
Ordering::Equal => output.push((key.clone(), format!(r#"Hint::Single("{}")"#, value))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// sort
|
// sort
|
||||||
output.sort_unstable_by(|a, b| {
|
output.sort_unstable_by(|a, b| {
|
||||||
let new_a = format!(r#"("{}", {})"#, a.0, a.1);
|
let new_a = format!(r#"("{}", {})"#, a.0, a.1);
|
||||||
let new_b = format!(r#"("{}", {})"#, b.0, b.1);
|
let new_b = format!(r#"("{}", {})"#, b.0, b.1);
|
||||||
|
|
||||||
compare_len_reverse_alpha(&new_b, &new_a)
|
compare_len_reverse_alpha(&new_b, &new_a)
|
||||||
});
|
});
|
||||||
|
|
||||||
output
|
output
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a vector of all possible splitting combinations of a strings
|
/// Returns a vector of all possible splitting combinations of a strings
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
fn all_possible_splits(
|
fn all_possible_splits(
|
||||||
func: String, seen: &mut HashSet<(String, String)>,
|
func: String,
|
||||||
|
seen: &mut HashSet<(String, String)>,
|
||||||
) -> Vec<(String, String)> {
|
) -> Vec<(String, String)> {
|
||||||
(1..func.len())
|
(1..func.len())
|
||||||
.map(|i| {
|
.map(|i| {
|
||||||
let (first, last) = func.split_at(i);
|
let (first, last) = func.split_at(i);
|
||||||
(first.to_string(), last.to_string())
|
(first.to_string(), last.to_string())
|
||||||
})
|
})
|
||||||
.flat_map(|(first, last)| {
|
.flat_map(|(first, last)| {
|
||||||
if seen.contains(&(first.clone(), last.clone())) {
|
if seen.contains(&(first.clone(), last.clone())) {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
seen.insert((first.to_string(), last.to_string()));
|
seen.insert((first.to_string(), last.to_string()));
|
||||||
|
|
||||||
Some((first, last))
|
Some((first, last))
|
||||||
})
|
})
|
||||||
.collect::<Vec<(String, String)>>()
|
.collect::<Vec<(String, String)>>()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
#![feature(const_trait_impl)]
|
|
||||||
#![feature(const_mut_refs)]
|
|
||||||
#![feature(const_for)]
|
|
||||||
mod autocomplete;
|
mod autocomplete;
|
||||||
mod autocomplete_hashmap;
|
mod autocomplete_hashmap;
|
||||||
mod parsing;
|
mod parsing;
|
||||||
@@ -8,9 +5,9 @@ mod splitting;
|
|||||||
mod suggestions;
|
mod suggestions;
|
||||||
|
|
||||||
pub use crate::{
|
pub use crate::{
|
||||||
autocomplete::{AutoComplete, Movement},
|
autocomplete::{AutoComplete, Movement},
|
||||||
autocomplete_hashmap::compile_hashmap,
|
autocomplete_hashmap::compile_hashmap,
|
||||||
parsing::{process_func_str, BackingFunction, FlatExWrapper},
|
parsing::{process_func_str, BackingFunction, FlatExWrapper},
|
||||||
splitting::{split_function, split_function_chars, SplitType},
|
splitting::{split_function, split_function_chars, SplitType},
|
||||||
suggestions::{generate_hint, get_last_term, Hint, HINT_EMPTY, SUPPORTED_FUNCTIONS},
|
suggestions::{generate_hint, get_last_term, Hint, HINT_EMPTY, SUPPORTED_FUNCTIONS},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,184 +3,153 @@ use std::collections::HashMap;
|
|||||||
|
|
||||||
#[derive(Clone, PartialEq)]
|
#[derive(Clone, PartialEq)]
|
||||||
pub struct FlatExWrapper {
|
pub struct FlatExWrapper {
|
||||||
func: Option<FlatEx<f64>>,
|
func: Option<FlatEx<f64>>,
|
||||||
func_str: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FlatExWrapper {
|
impl FlatExWrapper {
|
||||||
const EMPTY: FlatExWrapper = FlatExWrapper {
|
const EMPTY: FlatExWrapper = FlatExWrapper { func: None };
|
||||||
func: None,
|
|
||||||
func_str: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
const fn new(f: FlatEx<f64>) -> Self {
|
const fn new(f: FlatEx<f64>) -> Self {
|
||||||
Self {
|
Self { func: Some(f) }
|
||||||
func: Some(f),
|
}
|
||||||
func_str: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
const fn is_none(&self) -> bool { self.func.is_none() }
|
const fn is_none(&self) -> bool {
|
||||||
|
self.func.is_none()
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn eval(&self, x: &[f64]) -> f64 {
|
pub fn eval(&self, x: &[f64]) -> f64 {
|
||||||
self.func
|
self.func
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|f| f.eval(x).unwrap_or(f64::NAN))
|
.map(|f| f.eval(x).unwrap_or(f64::NAN))
|
||||||
.unwrap_or(f64::NAN)
|
.unwrap_or(f64::NAN)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn partial(&self, x: usize) -> Self {
|
fn partial_iter(&self, n: usize) -> Self {
|
||||||
self.func
|
self.func
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|f| f.clone().partial(x).map(Self::new).unwrap_or(Self::EMPTY))
|
.map(|f| {
|
||||||
.unwrap_or(Self::EMPTY)
|
f.clone()
|
||||||
}
|
.partial_iter((0..n).map(|_| 0))
|
||||||
|
.map(Self::new)
|
||||||
#[inline]
|
.unwrap_or(Self::EMPTY)
|
||||||
fn get_string(&mut self) -> String {
|
})
|
||||||
match self.func_str {
|
.unwrap_or(Self::EMPTY)
|
||||||
Some(ref func_str) => func_str.clone(),
|
}
|
||||||
None => {
|
|
||||||
let calculated = self.func.as_ref().map(|f| f.unparse()).unwrap_or("");
|
|
||||||
self.func_str = Some(calculated.to_owned());
|
|
||||||
calculated.to_owned()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn partial_iter(&self, n: usize) -> Self {
|
|
||||||
self.func
|
|
||||||
.as_ref()
|
|
||||||
.map(|f| {
|
|
||||||
f.clone()
|
|
||||||
.partial_iter((0..=n).map(|_| 0))
|
|
||||||
.map(Self::new)
|
|
||||||
.unwrap_or(Self::EMPTY)
|
|
||||||
})
|
|
||||||
.unwrap_or(Self::EMPTY)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl const Default for FlatExWrapper {
|
impl Default for FlatExWrapper {
|
||||||
fn default() -> FlatExWrapper { FlatExWrapper::EMPTY }
|
fn default() -> FlatExWrapper {
|
||||||
|
FlatExWrapper::EMPTY
|
||||||
|
}
|
||||||
}
|
}
|
||||||
/// Function that includes f(x), f'(x), f'(x)'s string representation, and f''(x)
|
/// Function that includes f(x), f'(x), f'(x)'s string representation, and f''(x)
|
||||||
#[derive(Clone, PartialEq)]
|
#[derive(Clone, PartialEq)]
|
||||||
pub struct BackingFunction {
|
pub struct BackingFunction {
|
||||||
/// f(x)
|
/// f(x)
|
||||||
function: FlatExWrapper,
|
function: FlatExWrapper,
|
||||||
|
|
||||||
/// Temporary cache for nth derivative
|
/// Temporary cache for nth derivative
|
||||||
nth_derivative: HashMap<usize, FlatExWrapper>,
|
nth_derivative: HashMap<usize, FlatExWrapper>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for BackingFunction {
|
impl Default for BackingFunction {
|
||||||
fn default() -> Self { Self::new("").unwrap() }
|
fn default() -> Self {
|
||||||
|
Self::new("").unwrap()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BackingFunction {
|
impl BackingFunction {
|
||||||
pub const fn is_none(&self) -> bool { self.function.is_none() }
|
pub const fn is_none(&self) -> bool {
|
||||||
|
self.function.is_none()
|
||||||
|
}
|
||||||
|
|
||||||
/// Create new [`BackingFunction`] instance
|
/// Create new [`BackingFunction`] instance
|
||||||
pub fn new(func_str: &str) -> Result<Self, String> {
|
pub fn new(func_str: &str) -> Result<Self, String> {
|
||||||
if func_str.is_empty() {
|
if func_str.is_empty() {
|
||||||
return Ok(Self {
|
return Ok(Self {
|
||||||
function: FlatExWrapper::EMPTY,
|
function: FlatExWrapper::EMPTY,
|
||||||
nth_derivative: HashMap::new(),
|
nth_derivative: HashMap::new(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let function = FlatExWrapper::new({
|
let function = FlatExWrapper::new({
|
||||||
let parse_result = exmex::parse::<f64>(func_str);
|
let parse_result = exmex::parse::<f64>(func_str);
|
||||||
|
|
||||||
match &parse_result {
|
match &parse_result {
|
||||||
Err(e) => return Err(e.to_string()),
|
Err(e) => return Err(e.to_string()),
|
||||||
Ok(ok_result) => {
|
Ok(ok_result) => {
|
||||||
let var_names = ok_result.var_names().to_vec();
|
let var_names = ok_result.var_names().to_vec();
|
||||||
|
|
||||||
if var_names != ["x"] {
|
if var_names != ["x"] {
|
||||||
let var_names_not_x: Vec<&String> = var_names
|
let var_names_not_x: Vec<&String> = var_names
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|ele| ele != &"x")
|
.filter(|ele| ele != &"x")
|
||||||
.collect::<Vec<&String>>();
|
.collect::<Vec<&String>>();
|
||||||
|
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"Error: invalid variable{}",
|
"Error: invalid variable{}",
|
||||||
match var_names_not_x.len() {
|
match var_names_not_x.len() {
|
||||||
1 => String::from(": ") + var_names_not_x[0].as_str(),
|
1 => String::from(": ") + var_names_not_x[0].as_str(),
|
||||||
_ => format!("s: {:?}", var_names_not_x),
|
_ => format!("s: {:?}", var_names_not_x),
|
||||||
}
|
}
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
unsafe { parse_result.unwrap_unchecked() }
|
unsafe { parse_result.unwrap_unchecked() }
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
function,
|
function,
|
||||||
|
|
||||||
nth_derivative: HashMap::new(),
|
nth_derivative: HashMap::new(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO rewrite this logic, it's a mess
|
// TODO rewrite this logic, it's a mess
|
||||||
pub fn generate_derivative(&mut self, derivative: usize) {
|
pub fn generate_derivative(&mut self, derivative: usize) {
|
||||||
if derivative == 0 {
|
if derivative == 0 {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if !self.nth_derivative.contains_key(&derivative) {
|
if !self.nth_derivative.contains_key(&derivative) {
|
||||||
let new_func = self.function.partial_iter(derivative);
|
let new_func = self.function.partial_iter(derivative);
|
||||||
self.nth_derivative.insert(derivative, new_func.clone());
|
self.nth_derivative.insert(derivative, new_func.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_function_derivative(&self, derivative: usize) -> &FlatExWrapper {
|
pub fn get_function_derivative(&self, derivative: usize) -> &FlatExWrapper {
|
||||||
if derivative == 0 {
|
if derivative == 0 {
|
||||||
return &self.function;
|
return &self.function;
|
||||||
} else {
|
} else {
|
||||||
return self
|
return self
|
||||||
.nth_derivative
|
.nth_derivative
|
||||||
.get(&derivative)
|
.get(&derivative)
|
||||||
.unwrap_or(&FlatExWrapper::EMPTY);
|
.unwrap_or(&FlatExWrapper::EMPTY);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get(&mut self, derivative: usize, x: f64) -> f64 {
|
pub fn get(&mut self, derivative: usize, x: f64) -> f64 {
|
||||||
self.get_function_derivative(derivative).eval(&[x])
|
self.get_function_derivative(derivative).eval(&[x])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prettyify_function_str(func: &str) -> String {
|
|
||||||
let new_str = func.replace("{x}", "x");
|
|
||||||
|
|
||||||
if &new_str == "0/0" {
|
|
||||||
"Undefined".to_owned()
|
|
||||||
} else {
|
|
||||||
new_str
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// pub const VALID_VARIABLES: [char; 3] = ['x', 'e', 'π'];
|
|
||||||
|
|
||||||
/// Case insensitive checks for if `c` is a character used to represent a variable
|
/// Case insensitive checks for if `c` is a character used to represent a variable
|
||||||
#[inline]
|
#[inline]
|
||||||
pub const fn is_variable(c: &char) -> bool {
|
pub const fn is_variable(c: &char) -> bool {
|
||||||
let c = c.to_ascii_lowercase();
|
let c = c.to_ascii_lowercase();
|
||||||
(c == 'x') | (c == 'e') | (c == 'π')
|
(c == 'x') | (c == 'e') | (c == 'π')
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds asterisks where needed in a function
|
/// Adds asterisks where needed in a function
|
||||||
pub fn process_func_str(function_in: &str) -> String {
|
pub fn process_func_str(function_in: &str) -> String {
|
||||||
if function_in.is_empty() {
|
if function_in.is_empty() {
|
||||||
return String::new();
|
return String::new();
|
||||||
}
|
}
|
||||||
|
|
||||||
crate::split_function(function_in, crate::SplitType::Multiplication).join("*")
|
crate::split_function(function_in, crate::SplitType::Multiplication).join("*")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,204 +1,288 @@
|
|||||||
use crate::parsing::is_variable;
|
use crate::parsing::is_variable;
|
||||||
|
use crate::SUPPORTED_FUNCTIONS;
|
||||||
|
|
||||||
|
/// Protect function names that start with variable characters (like 'e' in 'exp')
|
||||||
|
/// by replacing them with a placeholder during parsing, then restoring them after.
|
||||||
|
/// This prevents incorrect splitting like "exp" -> "e" * "xp".
|
||||||
|
fn protect_function_names(input: &str) -> (String, Vec<(&'static str, String)>) {
|
||||||
|
let mut result = input.to_string();
|
||||||
|
let mut replacements = Vec::new();
|
||||||
|
|
||||||
|
// Only protect functions that start with a variable character
|
||||||
|
// Sort by length descending to replace longer matches first (e.g., "exp" before "e")
|
||||||
|
let mut funcs: Vec<&'static str> = SUPPORTED_FUNCTIONS
|
||||||
|
.iter()
|
||||||
|
.filter(|&&func| {
|
||||||
|
func.chars()
|
||||||
|
.next()
|
||||||
|
.map(|c| is_variable(&c))
|
||||||
|
.unwrap_or(false)
|
||||||
|
})
|
||||||
|
.copied()
|
||||||
|
.collect();
|
||||||
|
funcs.sort_by(|a, b| b.len().cmp(&a.len()));
|
||||||
|
|
||||||
|
for func in funcs {
|
||||||
|
// Use a placeholder made of letters that will be treated as a function name
|
||||||
|
// The placeholder won't be split because it's all letters
|
||||||
|
let placeholder = format!("zzzfn{}", replacements.len());
|
||||||
|
result = result.replace(func, &placeholder);
|
||||||
|
replacements.push((func, placeholder));
|
||||||
|
}
|
||||||
|
|
||||||
|
(result, replacements)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restore protected function names from their placeholders
|
||||||
|
fn restore_function_names(input: &str, replacements: &[(&'static str, String)]) -> String {
|
||||||
|
let mut result = input.to_string();
|
||||||
|
for (func, placeholder) in replacements {
|
||||||
|
result = result.replace(placeholder, func);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
pub fn split_function(input: &str, split: SplitType) -> Vec<String> {
|
pub fn split_function(input: &str, split: SplitType) -> Vec<String> {
|
||||||
split_function_chars(
|
// Protect function names that could be incorrectly split
|
||||||
&input
|
let (protected, replacements) = protect_function_names(input);
|
||||||
.replace("pi", "π") // replace "pi" text with pi symbol
|
|
||||||
.replace("**", "^") // support alternate manner of expressing exponents
|
split_function_chars(
|
||||||
.replace("exp", "\u{1fc93}") // stop-gap solution to fix the `exp` function
|
&protected
|
||||||
.chars()
|
.replace("pi", "π") // replace "pi" text with pi symbol
|
||||||
.collect::<Vec<char>>(),
|
.replace("**", "^") // support alternate manner of expressing exponents
|
||||||
split,
|
.chars()
|
||||||
)
|
.collect::<Vec<char>>(),
|
||||||
.iter()
|
split,
|
||||||
.map(|x| x.replace('\u{1fc93}', "exp")) // Convert back to `exp` text
|
)
|
||||||
.collect::<Vec<String>>()
|
.iter()
|
||||||
|
.map(|x| restore_function_names(x, &replacements))
|
||||||
|
.collect::<Vec<String>>()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Specifies how to split a function
|
// Specifies how to split a function
|
||||||
#[derive(PartialEq, Debug, Copy, Clone)]
|
#[derive(PartialEq, Debug, Copy, Clone)]
|
||||||
pub enum SplitType {
|
pub enum SplitType {
|
||||||
Multiplication,
|
Multiplication,
|
||||||
Term,
|
Term,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Used to store info about a character
|
/// Used to store info about a character
|
||||||
struct BoolSlice {
|
struct BoolSlice {
|
||||||
closing_parens: bool,
|
closing_parens: bool,
|
||||||
open_parens: bool,
|
open_parens: bool,
|
||||||
number: bool,
|
number: bool,
|
||||||
letter: bool,
|
letter: bool,
|
||||||
variable: bool,
|
variable: bool,
|
||||||
masked_num: bool,
|
masked_num: bool,
|
||||||
masked_var: bool,
|
masked_var: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BoolSlice {
|
impl BoolSlice {
|
||||||
const fn from_char(c: &char, prev_masked_num: bool, prev_masked_var: bool) -> Self {
|
const fn from_char(c: &char, prev_masked_num: bool, prev_masked_var: bool) -> Self {
|
||||||
let isnumber = c.is_ascii_digit();
|
let isnumber = c.is_ascii_digit();
|
||||||
let isvariable = is_variable(c);
|
let isvariable = is_variable(c);
|
||||||
Self {
|
Self {
|
||||||
closing_parens: *c == ')',
|
closing_parens: *c == ')',
|
||||||
open_parens: *c == '(',
|
open_parens: *c == '(',
|
||||||
number: isnumber,
|
number: isnumber,
|
||||||
letter: c.is_ascii_alphabetic(),
|
letter: c.is_ascii_alphabetic(),
|
||||||
variable: isvariable,
|
variable: isvariable,
|
||||||
masked_num: match isnumber {
|
masked_num: match isnumber {
|
||||||
true => prev_masked_num,
|
true => prev_masked_num,
|
||||||
false => false,
|
false => false,
|
||||||
},
|
},
|
||||||
masked_var: match isvariable {
|
masked_var: match isvariable {
|
||||||
true => prev_masked_var,
|
true => prev_masked_var,
|
||||||
false => false,
|
false => false,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const fn is_unmasked_variable(&self) -> bool { self.variable && !self.masked_var }
|
const fn is_unmasked_variable(&self) -> bool {
|
||||||
|
self.variable && !self.masked_var
|
||||||
|
}
|
||||||
|
|
||||||
const fn is_unmasked_number(&self) -> bool { self.number && !self.masked_num }
|
const fn is_unmasked_number(&self) -> bool {
|
||||||
|
self.number && !self.masked_num
|
||||||
|
}
|
||||||
|
|
||||||
const fn calculate_mask(&mut self, other: &BoolSlice) {
|
/// Returns true if this char is a function name letter (not a standalone variable)
|
||||||
if other.masked_num && self.number {
|
const fn is_function_letter(&self) -> bool {
|
||||||
// If previous char was a masked number, and current char is a number, mask current char's variable status
|
self.letter && !self.is_unmasked_variable()
|
||||||
self.masked_num = true;
|
}
|
||||||
} else if other.masked_var && self.variable {
|
|
||||||
// If previous char was a masked variable, and current char is a variable, mask current char's variable status
|
|
||||||
self.masked_var = true;
|
|
||||||
} else if other.letter && !other.is_unmasked_variable() {
|
|
||||||
self.masked_num = self.number;
|
|
||||||
self.masked_var = self.variable;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const fn splitable(&self, c: &char, other: &BoolSlice, split: &SplitType) -> bool {
|
/// Returns true if this is a "term" - something that can be multiplied
|
||||||
if (*c == '*') | (matches!(split, &SplitType::Term) && other.open_parens) {
|
const fn is_term(&self) -> bool {
|
||||||
true
|
self.is_unmasked_number() || self.is_unmasked_variable() || self.letter
|
||||||
} else if other.closing_parens {
|
}
|
||||||
// Cases like `)x`, `)2`, and `)(`
|
|
||||||
return (*c == '(')
|
const fn calculate_mask(&mut self, other: &BoolSlice) {
|
||||||
| (self.letter && !self.is_unmasked_variable())
|
if other.masked_num && self.number {
|
||||||
| self.is_unmasked_variable()
|
// Propagate number masking through consecutive digits
|
||||||
| self.is_unmasked_number();
|
self.masked_num = true;
|
||||||
} else if *c == '(' {
|
} else if other.masked_var && self.variable {
|
||||||
// Cases like `x(` and `2(`
|
// Propagate variable masking through consecutive variables
|
||||||
return (other.is_unmasked_variable() | other.is_unmasked_number()) && !other.letter;
|
self.masked_var = true;
|
||||||
} else if other.is_unmasked_number() {
|
} else if other.is_function_letter() {
|
||||||
// Cases like `2x` and `2sin(x)`
|
// After a function letter, mask following numbers/variables as part of function name
|
||||||
return self.is_unmasked_variable() | self.letter;
|
self.masked_num = self.number;
|
||||||
} else if self.is_unmasked_variable() | self.letter {
|
self.masked_var = self.variable;
|
||||||
// Cases like `e2` and `xx`
|
}
|
||||||
return other.is_unmasked_number()
|
}
|
||||||
| (other.is_unmasked_variable() && self.is_unmasked_variable())
|
|
||||||
| other.is_unmasked_variable();
|
/// Determines if we should split (insert implicit multiplication) before current char
|
||||||
} else if (self.is_unmasked_number() | self.letter | self.is_unmasked_variable())
|
const fn splitable(&self, c: &char, prev: &BoolSlice, split: &SplitType) -> bool {
|
||||||
&& (other.is_unmasked_number() | other.letter)
|
// Always split on explicit multiplication
|
||||||
{
|
if *c == '*' {
|
||||||
return true;
|
return true;
|
||||||
} else {
|
}
|
||||||
return self.is_unmasked_number() && other.is_unmasked_variable();
|
|
||||||
}
|
// For Term split type, also split after open parens
|
||||||
}
|
if matches!(split, &SplitType::Term) && prev.open_parens {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// After closing paren: split before `(`, letters, variables, or numbers
|
||||||
|
// e.g., `)x`, `)2`, `)(`, `)sin`
|
||||||
|
if prev.closing_parens {
|
||||||
|
return *c == '(' || self.is_term();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Before open paren: split if previous was a standalone number or variable
|
||||||
|
// e.g., `x(`, `2(` but not `sin(`
|
||||||
|
if *c == '(' {
|
||||||
|
return (prev.is_unmasked_variable() || prev.is_unmasked_number()) && !prev.letter;
|
||||||
|
}
|
||||||
|
|
||||||
|
// After a number: split before variables or function letters
|
||||||
|
// e.g., `2x`, `2sin`
|
||||||
|
if prev.is_unmasked_number() {
|
||||||
|
return self.is_unmasked_variable() || self.letter;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Current is a variable or letter: split if previous was a number or variable
|
||||||
|
// e.g., `e2`, `xx`, `xe`
|
||||||
|
if self.is_unmasked_variable() || self.letter {
|
||||||
|
return prev.is_unmasked_number() || prev.is_unmasked_variable();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Current is a number after a variable
|
||||||
|
// e.g., `x2`
|
||||||
|
if self.is_unmasked_number() && prev.is_unmasked_variable() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Splits a function (which is represented as an array of characters) based off of the value of SplitType
|
// Splits a function (which is represented as an array of characters) based off of the value of SplitType
|
||||||
pub fn split_function_chars(chars: &[char], split: SplitType) -> Vec<String> {
|
pub fn split_function_chars(chars: &[char], split: SplitType) -> Vec<String> {
|
||||||
// Catch some basic cases
|
// Catch some basic cases
|
||||||
match chars.len() {
|
match chars.len() {
|
||||||
0 => return Vec::new(),
|
0 => return Vec::new(),
|
||||||
1 => return vec![chars[0].to_string()],
|
1 => return vec![chars[0].to_string()],
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resulting split-up data
|
// Resulting split-up data
|
||||||
let mut data: Vec<String> = std::vec::from_elem(chars[0].to_string(), 1);
|
let mut data: Vec<String> = std::vec::from_elem(chars[0].to_string(), 1);
|
||||||
|
|
||||||
// Setup first char here
|
// Setup first char here
|
||||||
let mut prev_char: BoolSlice = BoolSlice::from_char(&chars[0], false, false);
|
let mut prev_char: BoolSlice = BoolSlice::from_char(&chars[0], false, false);
|
||||||
|
|
||||||
let mut last = unsafe { data.last_mut().unwrap_unchecked() };
|
let mut last = unsafe { data.last_mut().unwrap_unchecked() };
|
||||||
|
|
||||||
// Iterate through all chars excluding the first one
|
// Iterate through all chars excluding the first one
|
||||||
for c in chars.iter().skip(1) {
|
for c in chars.iter().skip(1) {
|
||||||
// Set data about current character
|
// Set data about current character
|
||||||
let mut curr_c = BoolSlice::from_char(c, prev_char.masked_num, prev_char.masked_var);
|
let mut curr_c = BoolSlice::from_char(c, prev_char.masked_num, prev_char.masked_var);
|
||||||
|
|
||||||
curr_c.calculate_mask(&prev_char);
|
curr_c.calculate_mask(&prev_char);
|
||||||
|
|
||||||
// Append split
|
// Append split
|
||||||
if curr_c.splitable(c, &prev_char, &split) {
|
if curr_c.splitable(c, &prev_char, &split) {
|
||||||
// create new buffer
|
// create new buffer
|
||||||
data.push(String::new());
|
data.push(String::new());
|
||||||
last = unsafe { data.last_mut().unwrap_unchecked() };
|
last = unsafe { data.last_mut().unwrap_unchecked() };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exclude asterisks
|
// Exclude asterisks
|
||||||
if c != &'*' {
|
if c != &'*' {
|
||||||
last.push(*c);
|
last.push(*c);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move current character data to `prev_char`
|
// Move current character data to `prev_char`
|
||||||
prev_char = curr_c;
|
prev_char = curr_c;
|
||||||
}
|
}
|
||||||
|
|
||||||
data
|
data
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
fn assert_test(input: &str, expected: &[&str], split: SplitType) {
|
fn assert_test(input: &str, expected: &[&str], split: SplitType) {
|
||||||
let output = split_function(input, split);
|
let output = split_function(input, split);
|
||||||
let expected_owned = expected
|
let expected_owned = expected
|
||||||
.iter()
|
.iter()
|
||||||
.map(|&x| x.to_owned())
|
.map(|&x| x.to_owned())
|
||||||
.collect::<Vec<String>>();
|
.collect::<Vec<String>>();
|
||||||
if output != expected_owned {
|
if output != expected_owned {
|
||||||
panic!(
|
panic!(
|
||||||
"split type: {:?} of {} resulted in {:?} not {:?}",
|
"split type: {:?} of {} resulted in {:?} not {:?}",
|
||||||
split, input, output, expected
|
split, input, output, expected
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn split_function_test() {
|
fn split_function_test() {
|
||||||
assert_test(
|
assert_test(
|
||||||
"sin(x)cos(x)",
|
"sin(x)cos(x)",
|
||||||
&["sin(x)", "cos(x)"],
|
&["sin(x)", "cos(x)"],
|
||||||
SplitType::Multiplication,
|
SplitType::Multiplication,
|
||||||
);
|
);
|
||||||
|
|
||||||
assert_test(
|
assert_test(
|
||||||
"tanh(cos(x)xx)cos(x)",
|
"tanh(cos(x)xx)cos(x)",
|
||||||
&["tanh(cos(x)", "x", "x)", "cos(x)"],
|
&["tanh(cos(x)", "x", "x)", "cos(x)"],
|
||||||
SplitType::Multiplication,
|
SplitType::Multiplication,
|
||||||
);
|
);
|
||||||
|
|
||||||
assert_test(
|
assert_test(
|
||||||
"tanh(sin(cos(x)xsin(x)))",
|
"tanh(sin(cos(x)xsin(x)))",
|
||||||
&["tanh(sin(cos(x)", "x", "sin(x)))"],
|
&["tanh(sin(cos(x)", "x", "sin(x)))"],
|
||||||
SplitType::Multiplication,
|
SplitType::Multiplication,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Some test cases from https://github.com/GraphiteEditor/Graphite/blob/2515620a77478e57c255cd7d97c13cc7065dd99d/frontend/wasm/src/editor_api.rs#L829-L840
|
// Some test cases from https://github.com/GraphiteEditor/Graphite/blob/2515620a77478e57c255cd7d97c13cc7065dd99d/frontend/wasm/src/editor_api.rs#L829-L840
|
||||||
assert_test("2pi", &["2", "π"], SplitType::Multiplication);
|
assert_test("2pi", &["2", "π"], SplitType::Multiplication);
|
||||||
assert_test("sin(2pi)", &["sin(2", "π)"], SplitType::Multiplication);
|
assert_test("sin(2pi)", &["sin(2", "π)"], SplitType::Multiplication);
|
||||||
assert_test("2sin(pi)", &["2", "sin(π)"], SplitType::Multiplication);
|
assert_test("2sin(pi)", &["2", "sin(π)"], SplitType::Multiplication);
|
||||||
assert_test(
|
assert_test(
|
||||||
"2sin(3(4 + 5))",
|
"2sin(3(4 + 5))",
|
||||||
&["2", "sin(3", "(4 + 5))"],
|
&["2", "sin(3", "(4 + 5))"],
|
||||||
SplitType::Multiplication,
|
SplitType::Multiplication,
|
||||||
);
|
);
|
||||||
assert_test("3abs(-4)", &["3", "abs(-4)"], SplitType::Multiplication);
|
assert_test("3abs(-4)", &["3", "abs(-4)"], SplitType::Multiplication);
|
||||||
assert_test("-1(4)", &["-1", "(4)"], SplitType::Multiplication);
|
assert_test("-1(4)", &["-1", "(4)"], SplitType::Multiplication);
|
||||||
assert_test("(-1)4", &["(-1)", "4"], SplitType::Multiplication);
|
assert_test("(-1)4", &["(-1)", "4"], SplitType::Multiplication);
|
||||||
assert_test(
|
assert_test(
|
||||||
"(((-1)))(4)",
|
"(((-1)))(4)",
|
||||||
&["(((-1)))", "(4)"],
|
&["(((-1)))", "(4)"],
|
||||||
SplitType::Multiplication,
|
SplitType::Multiplication,
|
||||||
);
|
);
|
||||||
assert_test(
|
assert_test(
|
||||||
"2sin(π) + 2cos(tau)",
|
"2sin(π) + 2cos(tau)",
|
||||||
&["2", "sin(π) + 2", "cos(tau)"],
|
&["2", "sin(π) + 2", "cos(tau)"],
|
||||||
SplitType::Multiplication,
|
SplitType::Multiplication,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Test that exp() function is properly handled (not split into e*xp)
|
||||||
|
assert_test("exp(x)", &["exp(x)"], SplitType::Multiplication);
|
||||||
|
assert_test("2exp(x)", &["2", "exp(x)"], SplitType::Multiplication);
|
||||||
|
assert_test(
|
||||||
|
"exp(x)sin(x)",
|
||||||
|
&["exp(x)", "sin(x)"],
|
||||||
|
SplitType::Multiplication,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,106 +14,112 @@ macro_rules! test_print {
|
|||||||
|
|
||||||
/// Generate a hint based on the input `input`, returns an `Option<String>`
|
/// Generate a hint based on the input `input`, returns an `Option<String>`
|
||||||
pub fn generate_hint<'a>(input: &str) -> &'a Hint<'a> {
|
pub fn generate_hint<'a>(input: &str) -> &'a Hint<'a> {
|
||||||
if input.is_empty() {
|
if input.is_empty() {
|
||||||
&HINT_EMPTY
|
&HINT_EMPTY
|
||||||
} else {
|
} else {
|
||||||
let chars: Vec<char> = input.chars().collect::<Vec<char>>();
|
let chars: Vec<char> = input.chars().collect::<Vec<char>>();
|
||||||
|
|
||||||
let key = get_last_term(&chars);
|
let key = get_last_term(&chars);
|
||||||
match key {
|
match key {
|
||||||
Some(key) => {
|
Some(key) => {
|
||||||
if let Some(hint) = COMPLETION_HASHMAP.get(&key) {
|
if let Some(hint) = COMPLETION_HASHMAP.get(&key) {
|
||||||
return hint;
|
return hint;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
return &Hint::None;
|
return &Hint::None;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut open_parens: usize = 0;
|
let mut open_parens: usize = 0;
|
||||||
let mut closed_parens: usize = 0;
|
let mut closed_parens: usize = 0;
|
||||||
chars.iter().for_each(|chr| match *chr {
|
chars.iter().for_each(|chr| match *chr {
|
||||||
'(' => open_parens += 1,
|
'(' => open_parens += 1,
|
||||||
')' => closed_parens += 1,
|
')' => closed_parens += 1,
|
||||||
_ => {}
|
_ => {}
|
||||||
});
|
});
|
||||||
|
|
||||||
if open_parens > closed_parens {
|
if open_parens > closed_parens {
|
||||||
return &HINT_CLOSED_PARENS;
|
return &HINT_CLOSED_PARENS;
|
||||||
}
|
}
|
||||||
|
|
||||||
&Hint::None
|
&Hint::None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_last_term(chars: &[char]) -> Option<String> {
|
pub fn get_last_term(chars: &[char]) -> Option<String> {
|
||||||
if chars.is_empty() {
|
if chars.is_empty() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut result = split_function_chars(chars, SplitType::Term);
|
let mut result = split_function_chars(chars, SplitType::Term);
|
||||||
result.pop()
|
result.pop()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(PartialEq, Clone, Copy)]
|
#[derive(PartialEq, Clone, Copy)]
|
||||||
pub enum Hint<'a> {
|
pub enum Hint<'a> {
|
||||||
Single(&'a str),
|
Single(&'a str),
|
||||||
Many(&'a [&'a str]),
|
Many(&'a [&'a str]),
|
||||||
None,
|
None,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> std::fmt::Display for Hint<'a> {
|
impl<'a> std::fmt::Display for Hint<'a> {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
Hint::Single(single_data) => {
|
Hint::Single(single_data) => {
|
||||||
write!(f, "{}", single_data)
|
write!(f, "{}", single_data)
|
||||||
}
|
}
|
||||||
Hint::Many(multi_data) => {
|
Hint::Many(multi_data) => {
|
||||||
write!(f, "{:?}", multi_data)
|
write!(f, "{:?}", multi_data)
|
||||||
}
|
}
|
||||||
Hint::None => {
|
Hint::None => {
|
||||||
write!(f, "None")
|
write!(f, "None")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> std::fmt::Debug for Hint<'a> {
|
impl<'a> std::fmt::Debug for Hint<'a> {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||||
std::fmt::Display::fmt(self, f)
|
std::fmt::Display::fmt(self, f)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> Hint<'a> {
|
impl<'a> Hint<'a> {
|
||||||
#[inline]
|
#[inline]
|
||||||
pub const fn is_none(&self) -> bool { matches!(&self, &Hint::None) }
|
pub const fn is_none(&self) -> bool {
|
||||||
|
matches!(&self, &Hint::None)
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub const fn is_some(&self) -> bool { !self.is_none() }
|
pub const fn is_some(&self) -> bool {
|
||||||
|
!self.is_none()
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub const fn is_single(&self) -> bool { matches!(&self, &Hint::Single(_)) }
|
pub const fn is_single(&self) -> bool {
|
||||||
|
matches!(&self, &Hint::Single(_))
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub const fn single(&self) -> Option<&str> {
|
pub const fn single(&self) -> Option<&str> {
|
||||||
match self {
|
match self {
|
||||||
Hint::Single(data) => Some(data),
|
Hint::Single(data) => Some(data),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub const fn many(&self) -> Option<&[&str]> {
|
pub const fn many(&self) -> Option<&[&str]> {
|
||||||
match self {
|
match self {
|
||||||
Hint::Many(data) => Some(data),
|
Hint::Many(data) => Some(data),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
include!(concat!(env!("OUT_DIR"), "/codegen.rs"));
|
include!(concat!(env!("OUT_DIR"), "/codegen.rs"));
|
||||||
|
|||||||
15
push.sh
15
push.sh
@@ -1,15 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
set -e #kill script if error occurs
|
|
||||||
|
|
||||||
cargo test
|
|
||||||
|
|
||||||
bash build.sh release
|
|
||||||
|
|
||||||
echo "rsyncing"
|
|
||||||
# rsync -av --delete --info=progress2 tmp/ rpi-public:/mnt/hdd/http_share/ytbn/
|
|
||||||
rsync -av --delete --info=progress2 --exclude=".git" tmp/ ../titaniumtown.github.io/
|
|
||||||
rm -fr tmp
|
|
||||||
cd ../titaniumtown.github.io
|
|
||||||
git add .
|
|
||||||
git commit -m "update" | true
|
|
||||||
git push
|
|
||||||
30
shell.nix
30
shell.nix
@@ -1,30 +0,0 @@
|
|||||||
{
|
|
||||||
pkgs ? import <nixpkgs> { },
|
|
||||||
}:
|
|
||||||
pkgs.mkShell rec {
|
|
||||||
libs = with pkgs; [
|
|
||||||
# wayland
|
|
||||||
libxkbcommon
|
|
||||||
libGL
|
|
||||||
wayland
|
|
||||||
|
|
||||||
libx11
|
|
||||||
libxcursor
|
|
||||||
libxi
|
|
||||||
|
|
||||||
clang
|
|
||||||
];
|
|
||||||
|
|
||||||
nativeBuildInputs =
|
|
||||||
with pkgs;
|
|
||||||
[
|
|
||||||
rustc
|
|
||||||
cargo
|
|
||||||
rust-analyzer
|
|
||||||
python3Packages.fonttools
|
|
||||||
]
|
|
||||||
++ libs;
|
|
||||||
|
|
||||||
# add libs to path
|
|
||||||
LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libs}";
|
|
||||||
}
|
|
||||||
@@ -1,18 +1,4 @@
|
|||||||
use const_format::formatc;
|
|
||||||
use epaint::Color32;
|
use epaint::Color32;
|
||||||
use shadow_rs::shadow;
|
|
||||||
shadow!(build);
|
|
||||||
|
|
||||||
/// Constant string that has a string containing information about the build.
|
|
||||||
pub const BUILD_INFO: &str = formatc!(
|
|
||||||
"Commit: {} ({})\nBuild Date: {}\nPackage Version: {}\nRust Channel: {}\nRust Version: {}",
|
|
||||||
&build::SHORT_COMMIT,
|
|
||||||
&build::BRANCH,
|
|
||||||
&build::BUILD_TIME,
|
|
||||||
&build::PKG_VERSION,
|
|
||||||
&build::RUST_CHANNEL,
|
|
||||||
&build::RUST_VERSION,
|
|
||||||
);
|
|
||||||
|
|
||||||
pub const FONT_SIZE: f32 = 14.0;
|
pub const FONT_SIZE: f32 = 14.0;
|
||||||
|
|
||||||
@@ -31,24 +17,24 @@ pub const DEFAULT_INTEGRAL_NUM: usize = 100;
|
|||||||
/// Colors used for plotting
|
/// Colors used for plotting
|
||||||
// Colors commented out are used elsewhere and are not included here for better user experience
|
// Colors commented out are used elsewhere and are not included here for better user experience
|
||||||
pub const COLORS: [Color32; 13] = [
|
pub const COLORS: [Color32; 13] = [
|
||||||
Color32::RED,
|
Color32::RED,
|
||||||
// Color32::GREEN,
|
// Color32::GREEN,
|
||||||
// Color32::YELLOW,
|
// Color32::YELLOW,
|
||||||
// Color32::BLUE,
|
// Color32::BLUE,
|
||||||
Color32::BROWN,
|
Color32::BROWN,
|
||||||
Color32::GOLD,
|
Color32::GOLD,
|
||||||
Color32::GRAY,
|
Color32::GRAY,
|
||||||
Color32::WHITE,
|
Color32::WHITE,
|
||||||
Color32::LIGHT_YELLOW,
|
Color32::LIGHT_YELLOW,
|
||||||
Color32::LIGHT_GREEN,
|
Color32::LIGHT_GREEN,
|
||||||
// Color32::LIGHT_BLUE,
|
// Color32::LIGHT_BLUE,
|
||||||
Color32::LIGHT_GRAY,
|
Color32::LIGHT_GRAY,
|
||||||
Color32::LIGHT_RED,
|
Color32::LIGHT_RED,
|
||||||
Color32::DARK_GRAY,
|
Color32::DARK_GRAY,
|
||||||
// Color32::DARK_RED,
|
// Color32::DARK_RED,
|
||||||
Color32::KHAKI,
|
Color32::KHAKI,
|
||||||
Color32::DARK_GREEN,
|
Color32::DARK_GREEN,
|
||||||
Color32::DARK_BLUE,
|
Color32::DARK_BLUE,
|
||||||
];
|
];
|
||||||
|
|
||||||
const_assert!(!COLORS.is_empty());
|
const_assert!(!COLORS.is_empty());
|
||||||
|
|||||||
@@ -1,479 +1,571 @@
|
|||||||
use crate::math_app::AppSettings;
|
use crate::math_app::AppSettings;
|
||||||
use crate::misc::{newtons_method_helper, step_helper, EguiHelper};
|
use crate::misc::{EguiHelper, newtons_method_helper, step_helper};
|
||||||
|
use crate::symbolic::try_symbolic;
|
||||||
use egui::{Checkbox, Context};
|
use egui::{Checkbox, Context};
|
||||||
use egui_plot::{Bar, BarChart, PlotPoint, PlotUi};
|
use egui_plot::{Bar, BarChart, PlotPoint, PlotUi, Points};
|
||||||
|
|
||||||
use epaint::Color32;
|
use epaint::Color32;
|
||||||
use parsing::{generate_hint, AutoComplete};
|
use parsing::{AutoComplete, generate_hint};
|
||||||
use parsing::{process_func_str, BackingFunction};
|
use parsing::{BackingFunction, process_func_str};
|
||||||
use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serialize, Serializer};
|
use serde::{Deserialize, Deserializer, Serialize, Serializer, ser::SerializeStruct};
|
||||||
use std::{
|
use std::fmt::{self, Debug};
|
||||||
fmt::{self, Debug},
|
|
||||||
hash::{Hash, Hasher},
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Represents the possible variations of Riemann Sums
|
/// Represents the possible variations of Riemann Sums
|
||||||
#[derive(PartialEq, Eq, Debug, Copy, Clone, Default)]
|
#[derive(PartialEq, Eq, Debug, Copy, Clone, Default)]
|
||||||
pub enum Riemann {
|
pub enum Riemann {
|
||||||
#[default]
|
#[default]
|
||||||
Left,
|
Left,
|
||||||
|
|
||||||
Middle,
|
Middle,
|
||||||
Right,
|
Right,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for Riemann {
|
impl fmt::Display for Riemann {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) }
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
write!(f, "{:?}", self)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `FunctionEntry` is a function that can calculate values, integrals, derivatives, etc etc
|
/// `FunctionEntry` is a function that can calculate values, integrals, derivatives, etc etc
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct FunctionEntry {
|
pub struct FunctionEntry {
|
||||||
/// The `BackingFunction` instance that is used to generate `f(x)`, `f'(x)`, and `f''(x)`
|
/// The `BackingFunction` instance that is used to generate `f(x)`, `f'(x)`, and `f''(x)`
|
||||||
function: BackingFunction,
|
function: BackingFunction,
|
||||||
|
|
||||||
/// Stores a function string (that hasn't been processed via `process_func_str`) to display to the user
|
/// If calculating/displayingintegrals are enabled
|
||||||
pub raw_func_str: String,
|
pub integral: bool,
|
||||||
|
|
||||||
/// If calculating/displayingintegrals are enabled
|
/// If displaying derivatives are enabled (note, they are still calculated for other purposes)
|
||||||
pub integral: bool,
|
pub derivative: bool,
|
||||||
|
|
||||||
/// If displaying derivatives are enabled (note, they are still calculated for other purposes)
|
pub nth_derivative: bool,
|
||||||
pub derivative: bool,
|
|
||||||
|
|
||||||
pub nth_derviative: bool,
|
pub back_data: Vec<PlotPoint>,
|
||||||
|
pub integral_data: Option<(Vec<Bar>, f64)>,
|
||||||
|
pub derivative_data: Vec<PlotPoint>,
|
||||||
|
pub extrema_data: Vec<PlotPoint>,
|
||||||
|
pub root_data: Vec<PlotPoint>,
|
||||||
|
nth_derivative_data: Option<Vec<PlotPoint>>,
|
||||||
|
|
||||||
pub back_data: Vec<PlotPoint>,
|
pub autocomplete: AutoComplete<'static>,
|
||||||
pub integral_data: Option<(Vec<Bar>, f64)>,
|
|
||||||
pub derivative_data: Vec<PlotPoint>,
|
|
||||||
pub extrema_data: Vec<PlotPoint>,
|
|
||||||
pub root_data: Vec<PlotPoint>,
|
|
||||||
nth_derivative_data: Option<Vec<PlotPoint>>,
|
|
||||||
|
|
||||||
pub autocomplete: AutoComplete<'static>,
|
test_result: Option<String>,
|
||||||
|
curr_nth: usize,
|
||||||
|
|
||||||
test_result: Option<String>,
|
pub settings_opened: bool,
|
||||||
curr_nth: usize,
|
|
||||||
|
|
||||||
pub settings_opened: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Hash for FunctionEntry {
|
|
||||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
|
||||||
self.raw_func_str.hash(state);
|
|
||||||
self.integral.hash(state);
|
|
||||||
self.nth_derviative.hash(state);
|
|
||||||
self.curr_nth.hash(state);
|
|
||||||
self.settings_opened.hash(state);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Serialize for FunctionEntry {
|
impl Serialize for FunctionEntry {
|
||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
where
|
where
|
||||||
S: Serializer,
|
S: Serializer,
|
||||||
{
|
{
|
||||||
let mut s = serializer.serialize_struct("FunctionEntry", 4)?;
|
let mut s = serializer.serialize_struct("FunctionEntry", 4)?;
|
||||||
s.serialize_field("raw_func_str", &self.raw_func_str)?;
|
s.serialize_field("raw_func_str", &self.autocomplete.string)?;
|
||||||
s.serialize_field("integral", &self.integral)?;
|
s.serialize_field("integral", &self.integral)?;
|
||||||
s.serialize_field("derivative", &self.derivative)?;
|
s.serialize_field("derivative", &self.derivative)?;
|
||||||
s.serialize_field("curr_nth", &self.curr_nth)?;
|
s.serialize_field("curr_nth", &self.curr_nth)?;
|
||||||
|
|
||||||
s.end()
|
s.end()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'de> Deserialize<'de> for FunctionEntry {
|
impl<'de> Deserialize<'de> for FunctionEntry {
|
||||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||||
where
|
where
|
||||||
D: Deserializer<'de>,
|
D: Deserializer<'de>,
|
||||||
{
|
{
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct Helper {
|
struct Helper {
|
||||||
raw_func_str: String,
|
raw_func_str: String,
|
||||||
integral: bool,
|
integral: bool,
|
||||||
derivative: bool,
|
derivative: bool,
|
||||||
curr_nth: usize,
|
curr_nth: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
let helper = Helper::deserialize(deserializer)?;
|
let helper = Helper::deserialize(deserializer)?;
|
||||||
let mut new_func_entry = FunctionEntry::default();
|
let mut new_func_entry = FunctionEntry::default();
|
||||||
let gen_func = BackingFunction::new(&helper.raw_func_str);
|
let gen_func = BackingFunction::new(&helper.raw_func_str);
|
||||||
match gen_func {
|
match gen_func {
|
||||||
Ok(func) => new_func_entry.function = func,
|
Ok(func) => new_func_entry.function = func,
|
||||||
Err(x) => new_func_entry.test_result = Some(x),
|
Err(x) => new_func_entry.test_result = Some(x),
|
||||||
}
|
}
|
||||||
|
|
||||||
new_func_entry.autocomplete = AutoComplete {
|
new_func_entry.autocomplete = AutoComplete {
|
||||||
i: 0,
|
i: 0,
|
||||||
hint: generate_hint(&helper.raw_func_str),
|
hint: generate_hint(&helper.raw_func_str),
|
||||||
string: helper.raw_func_str,
|
string: helper.raw_func_str,
|
||||||
};
|
};
|
||||||
|
|
||||||
new_func_entry.integral = helper.integral;
|
new_func_entry.integral = helper.integral;
|
||||||
new_func_entry.derivative = helper.derivative;
|
new_func_entry.derivative = helper.derivative;
|
||||||
new_func_entry.curr_nth = helper.curr_nth;
|
new_func_entry.curr_nth = helper.curr_nth;
|
||||||
|
|
||||||
Ok(new_func_entry)
|
Ok(new_func_entry)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl const Default for FunctionEntry {
|
impl Default for FunctionEntry {
|
||||||
/// Creates default FunctionEntry instance (which is empty)
|
/// Creates default FunctionEntry instance (which is empty)
|
||||||
fn default() -> FunctionEntry {
|
fn default() -> FunctionEntry {
|
||||||
FunctionEntry {
|
FunctionEntry {
|
||||||
function: BackingFunction::default(),
|
function: BackingFunction::default(),
|
||||||
raw_func_str: String::new(),
|
integral: false,
|
||||||
integral: false,
|
derivative: false,
|
||||||
derivative: false,
|
nth_derivative: false,
|
||||||
nth_derviative: false,
|
back_data: Vec::new(),
|
||||||
back_data: Vec::new(),
|
integral_data: None,
|
||||||
integral_data: None,
|
derivative_data: Vec::new(),
|
||||||
derivative_data: Vec::new(),
|
extrema_data: Vec::new(),
|
||||||
extrema_data: Vec::new(),
|
root_data: Vec::new(),
|
||||||
root_data: Vec::new(),
|
nth_derivative_data: None,
|
||||||
nth_derivative_data: None,
|
autocomplete: AutoComplete::EMPTY,
|
||||||
autocomplete: AutoComplete::EMPTY,
|
test_result: None,
|
||||||
test_result: None,
|
curr_nth: 3,
|
||||||
curr_nth: 3,
|
settings_opened: false,
|
||||||
settings_opened: false,
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FunctionEntry {
|
impl FunctionEntry {
|
||||||
pub const fn is_some(&self) -> bool { !self.function.is_none() }
|
pub const fn is_some(&self) -> bool {
|
||||||
|
!self.function.is_none()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn settings_window(&mut self, ctx: &Context) {
|
pub fn settings_window(&mut self, ctx: &Context) {
|
||||||
let mut invalidate_nth = false;
|
let mut invalidate_nth = false;
|
||||||
egui::Window::new(format!("Settings: {}", self.raw_func_str))
|
egui::Window::new(format!("Settings: {}", self.func_str()))
|
||||||
.open(&mut self.settings_opened)
|
.open(&mut self.settings_opened)
|
||||||
.default_pos([200.0, 200.0])
|
.default_pos([200.0, 200.0])
|
||||||
.resizable(false)
|
.resizable(false)
|
||||||
.collapsible(false)
|
.collapsible(false)
|
||||||
.show(ctx, |ui| {
|
.show(ctx, |ui| {
|
||||||
ui.add(Checkbox::new(
|
ui.add(Checkbox::new(
|
||||||
&mut self.nth_derviative,
|
&mut self.nth_derivative,
|
||||||
"Display Nth Derivative",
|
"Display Nth Derivative",
|
||||||
));
|
));
|
||||||
|
|
||||||
if ui
|
if ui
|
||||||
.add(egui::Slider::new(&mut self.curr_nth, 3..=5).text("Nth Derivative"))
|
.add(egui::Slider::new(&mut self.curr_nth, 3..=5).text("Nth Derivative"))
|
||||||
.changed()
|
.changed()
|
||||||
{
|
{
|
||||||
invalidate_nth = true;
|
invalidate_nth = true;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if invalidate_nth {
|
if invalidate_nth {
|
||||||
self.function.generate_derivative(self.curr_nth);
|
self.function.generate_derivative(self.curr_nth);
|
||||||
self.clear_nth();
|
self.clear_nth();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get function's cached test result
|
/// Get function's cached test result
|
||||||
pub fn get_test_result(&self) -> &Option<String> { &self.test_result }
|
pub fn get_test_result(&self) -> &Option<String> {
|
||||||
|
&self.test_result
|
||||||
|
}
|
||||||
|
|
||||||
/// Update function string and test it
|
/// Get the raw function string
|
||||||
pub fn update_string(&mut self, raw_func_str: &str) {
|
#[inline]
|
||||||
if raw_func_str == self.raw_func_str {
|
pub fn func_str(&self) -> &str {
|
||||||
return;
|
&self.autocomplete.string
|
||||||
}
|
}
|
||||||
|
|
||||||
self.raw_func_str = raw_func_str.to_owned();
|
/// Update function string and test it
|
||||||
let processed_func = process_func_str(raw_func_str);
|
pub fn update_string(&mut self, raw_func_str: &str) {
|
||||||
let new_func_result = BackingFunction::new(&processed_func);
|
if raw_func_str == self.func_str() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
match new_func_result {
|
// Update the autocomplete string (which is now the source of truth for the raw string)
|
||||||
Ok(new_function) => {
|
self.autocomplete.update_string(raw_func_str);
|
||||||
self.test_result = None;
|
|
||||||
self.function = new_function;
|
|
||||||
self.invalidate_whole();
|
|
||||||
}
|
|
||||||
Err(error) => {
|
|
||||||
self.test_result = Some(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates and does the math for creating all the rectangles under the graph
|
self.reparse_function(raw_func_str);
|
||||||
fn integral_rectangles(
|
}
|
||||||
&mut self, integral_min_x: f64, integral_max_x: f64, sum: Riemann, integral_num: usize,
|
|
||||||
) -> (Vec<(f64, f64)>, f64) {
|
|
||||||
let step = (integral_max_x - integral_min_x) / (integral_num as f64);
|
|
||||||
|
|
||||||
// let sum_func = self.get_sum_func(sum);
|
/// Re-parse the function from the current autocomplete string.
|
||||||
|
/// Call this when the autocomplete string was updated externally (e.g., via hint application).
|
||||||
|
pub fn sync_from_autocomplete(&mut self) {
|
||||||
|
self.reparse_function(&self.autocomplete.string.clone());
|
||||||
|
}
|
||||||
|
|
||||||
let data2: Vec<(f64, f64)> = step_helper(integral_num, integral_min_x, step)
|
/// Internal helper to parse a function string and update internal state
|
||||||
.into_iter()
|
fn reparse_function(&mut self, raw_func_str: &str) {
|
||||||
.map(|x| {
|
let processed_func = process_func_str(raw_func_str);
|
||||||
let step_offset = step.copysign(x); // store the offset here so it doesn't have to be calculated multiple times
|
let new_func_result = BackingFunction::new(&processed_func);
|
||||||
let x2: f64 = x + step_offset;
|
|
||||||
|
|
||||||
let (left_x, right_x) = match x.is_sign_positive() {
|
match new_func_result {
|
||||||
true => (x, x2),
|
Ok(new_function) => {
|
||||||
false => (x2, x),
|
self.test_result = None;
|
||||||
};
|
self.function = new_function;
|
||||||
|
self.invalidate_whole();
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
self.test_result = Some(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let y = match sum {
|
/// Creates and does the math for creating all the rectangles under the graph
|
||||||
Riemann::Left => self.function.get(0, left_x),
|
fn integral_rectangles(
|
||||||
Riemann::Right => self.function.get(0, right_x),
|
&mut self,
|
||||||
Riemann::Middle => {
|
integral_min_x: f64,
|
||||||
(self.function.get(0, left_x) + self.function.get(0, right_x)) / 2.0
|
integral_max_x: f64,
|
||||||
}
|
sum: Riemann,
|
||||||
};
|
integral_num: usize,
|
||||||
|
) -> (Vec<(f64, f64)>, f64) {
|
||||||
|
let step = (integral_max_x - integral_min_x) / (integral_num as f64);
|
||||||
|
|
||||||
(x + (step_offset / 2.0), y)
|
let data: Vec<(f64, f64)> = step_helper(integral_num, integral_min_x, step)
|
||||||
})
|
.into_iter()
|
||||||
.filter(|(_, y)| y.is_finite())
|
.map(|x| {
|
||||||
.collect();
|
let step_offset = step.copysign(x);
|
||||||
|
let x2 = x + step_offset;
|
||||||
|
|
||||||
let area = data2.iter().map(move |(_, y)| y * step).sum();
|
let (left_x, right_x) = if x.is_sign_positive() {
|
||||||
|
(x, x2)
|
||||||
|
} else {
|
||||||
|
(x2, x)
|
||||||
|
};
|
||||||
|
|
||||||
(data2, area)
|
let y = match sum {
|
||||||
}
|
Riemann::Left => self.function.get(0, left_x),
|
||||||
|
Riemann::Right => self.function.get(0, right_x),
|
||||||
|
Riemann::Middle => {
|
||||||
|
(self.function.get(0, left_x) + self.function.get(0, right_x)) / 2.0
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/// Helps with processing newton's method depending on level of derivative
|
(x + (step_offset / 2.0), y)
|
||||||
fn newtons_method_helper(
|
})
|
||||||
&mut self, threshold: f64, derivative_level: usize, range: &std::ops::Range<f64>,
|
.filter(|(_, y)| y.is_finite())
|
||||||
) -> Vec<PlotPoint> {
|
.collect();
|
||||||
self.function.generate_derivative(derivative_level);
|
|
||||||
self.function.generate_derivative(derivative_level + 1);
|
|
||||||
let newtons_method_output: Vec<f64> = match derivative_level {
|
|
||||||
0 => newtons_method_helper(
|
|
||||||
threshold,
|
|
||||||
range,
|
|
||||||
self.back_data.as_slice(),
|
|
||||||
&self.function.get_function_derivative(0),
|
|
||||||
&self.function.get_function_derivative(1),
|
|
||||||
),
|
|
||||||
1 => newtons_method_helper(
|
|
||||||
threshold,
|
|
||||||
range,
|
|
||||||
self.derivative_data.as_slice(),
|
|
||||||
&self.function.get_function_derivative(1),
|
|
||||||
&self.function.get_function_derivative(2),
|
|
||||||
),
|
|
||||||
_ => unreachable!(),
|
|
||||||
};
|
|
||||||
|
|
||||||
newtons_method_output
|
let area = data.iter().map(|(_, y)| y * step).sum();
|
||||||
.into_iter()
|
|
||||||
.map(|x| PlotPoint::new(x, self.function.get(0, x)))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Does the calculations and stores results in `self`
|
(data, area)
|
||||||
pub fn calculate(
|
}
|
||||||
&mut self, width_changed: bool, min_max_changed: bool, did_zoom: bool,
|
|
||||||
settings: AppSettings,
|
|
||||||
) {
|
|
||||||
if self.test_result.is_some() | self.function.is_none() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let resolution = (settings.max_x - settings.min_x) / (settings.plot_width as f64);
|
/// Helps with processing newton's method depending on level of derivative
|
||||||
debug_assert!(resolution > 0.0);
|
fn newtons_method_helper(
|
||||||
let resolution_iter = step_helper(settings.plot_width + 1, settings.min_x, resolution);
|
&mut self,
|
||||||
|
threshold: f64,
|
||||||
|
derivative_level: usize,
|
||||||
|
range: &std::ops::Range<f64>,
|
||||||
|
) -> Vec<PlotPoint> {
|
||||||
|
self.function.generate_derivative(derivative_level);
|
||||||
|
self.function.generate_derivative(derivative_level + 1);
|
||||||
|
|
||||||
// Makes sure proper arguments are passed when integral is enabled
|
let data_source = match derivative_level {
|
||||||
if self.integral && settings.integral_changed {
|
0 => self.back_data.as_slice(),
|
||||||
self.clear_integral();
|
1 => self.derivative_data.as_slice(),
|
||||||
}
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
|
||||||
if width_changed | min_max_changed | did_zoom {
|
newtons_method_helper(
|
||||||
self.clear_back();
|
threshold,
|
||||||
self.clear_derivative();
|
range,
|
||||||
self.clear_nth();
|
data_source,
|
||||||
}
|
self.function.get_function_derivative(derivative_level),
|
||||||
|
self.function.get_function_derivative(derivative_level + 1),
|
||||||
|
)
|
||||||
|
.into_iter()
|
||||||
|
.map(|x| PlotPoint::new(x, self.function.get(0, x)))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
if self.back_data.is_empty() {
|
/// Generates plot data for a given derivative level over the resolution iterator
|
||||||
let data: Vec<PlotPoint> = resolution_iter
|
fn generate_plot_data(&mut self, derivative: usize, resolution_iter: &[f64]) -> Vec<PlotPoint> {
|
||||||
.clone()
|
if derivative > 0 {
|
||||||
.into_iter()
|
self.function.generate_derivative(derivative);
|
||||||
.map(|x| PlotPoint::new(x, self.function.get(0, x)))
|
}
|
||||||
.collect();
|
resolution_iter
|
||||||
debug_assert_eq!(data.len(), settings.plot_width + 1);
|
.iter()
|
||||||
|
.map(|&x| PlotPoint::new(x, self.function.get(derivative, x)))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
self.back_data = data;
|
/// Does the calculations and stores results in `self`
|
||||||
}
|
pub fn calculate(
|
||||||
|
&mut self,
|
||||||
|
width_changed: bool,
|
||||||
|
min_max_changed: bool,
|
||||||
|
did_zoom: bool,
|
||||||
|
settings: AppSettings,
|
||||||
|
) {
|
||||||
|
if self.test_result.is_some() | self.function.is_none() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if self.derivative_data.is_empty() {
|
let resolution = (settings.max_x - settings.min_x) / (settings.plot_width as f64);
|
||||||
self.function.generate_derivative(1);
|
debug_assert!(resolution > 0.0);
|
||||||
let data: Vec<PlotPoint> = resolution_iter
|
let resolution_iter = step_helper(settings.plot_width + 1, settings.min_x, resolution);
|
||||||
.clone()
|
|
||||||
.into_iter()
|
|
||||||
.map(|x| PlotPoint::new(x, self.function.get(1, x)))
|
|
||||||
.collect();
|
|
||||||
debug_assert_eq!(data.len(), settings.plot_width + 1);
|
|
||||||
self.derivative_data = data;
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.nth_derviative && self.nth_derivative_data.is_none() {
|
// Makes sure proper arguments are passed when integral is enabled
|
||||||
let data: Vec<PlotPoint> = resolution_iter
|
if self.integral && settings.integral_changed {
|
||||||
.into_iter()
|
self.clear_integral();
|
||||||
.map(|x| PlotPoint::new(x, self.function.get(self.curr_nth, x)))
|
}
|
||||||
.collect();
|
|
||||||
debug_assert_eq!(data.len(), settings.plot_width + 1);
|
|
||||||
self.nth_derivative_data = Some(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.integral {
|
if width_changed | min_max_changed | did_zoom {
|
||||||
if self.integral_data.is_none() {
|
self.clear_back();
|
||||||
let (data, area) = self.integral_rectangles(
|
self.clear_derivative();
|
||||||
settings.integral_min_x,
|
self.clear_nth();
|
||||||
settings.integral_max_x,
|
}
|
||||||
settings.riemann_sum,
|
|
||||||
settings.integral_num,
|
|
||||||
);
|
|
||||||
|
|
||||||
self.integral_data = Some((
|
if self.back_data.is_empty() {
|
||||||
data.into_iter().map(|(x, y)| Bar::new(x, y)).collect(),
|
self.back_data = self.generate_plot_data(0, &resolution_iter);
|
||||||
area,
|
debug_assert_eq!(self.back_data.len(), settings.plot_width + 1);
|
||||||
));
|
}
|
||||||
}
|
|
||||||
} else {
|
|
||||||
self.clear_integral();
|
|
||||||
}
|
|
||||||
|
|
||||||
let threshold: f64 = resolution / 2.0;
|
if self.derivative_data.is_empty() {
|
||||||
let x_range = settings.min_x..settings.max_x;
|
self.derivative_data = self.generate_plot_data(1, &resolution_iter);
|
||||||
|
debug_assert_eq!(self.derivative_data.len(), settings.plot_width + 1);
|
||||||
|
}
|
||||||
|
|
||||||
// Calculates extrema
|
if self.nth_derivative && self.nth_derivative_data.is_none() {
|
||||||
if settings.do_extrema && (min_max_changed | self.extrema_data.is_empty()) {
|
let data = self.generate_plot_data(self.curr_nth, &resolution_iter);
|
||||||
self.extrema_data = self.newtons_method_helper(threshold, 1, &x_range);
|
debug_assert_eq!(data.len(), settings.plot_width + 1);
|
||||||
}
|
self.nth_derivative_data = Some(data);
|
||||||
|
}
|
||||||
|
|
||||||
// Calculates roots
|
if self.integral {
|
||||||
if settings.do_roots && (min_max_changed | self.root_data.is_empty()) {
|
if self.integral_data.is_none() {
|
||||||
self.root_data = self.newtons_method_helper(threshold, 0, &x_range);
|
let (data, area) = self.integral_rectangles(
|
||||||
}
|
settings.integral_min_x,
|
||||||
}
|
settings.integral_max_x,
|
||||||
|
settings.riemann_sum,
|
||||||
|
settings.integral_num,
|
||||||
|
);
|
||||||
|
|
||||||
/// Displays the function's output on PlotUI `plot_ui` with settings `settings`.
|
self.integral_data = Some((
|
||||||
/// Returns an `Option<f64>` of the calculated integral.
|
data.into_iter().map(|(x, y)| Bar::new(x, y)).collect(),
|
||||||
pub fn display(
|
area,
|
||||||
&self, plot_ui: &mut PlotUi, settings: &AppSettings, main_plot_color: Color32,
|
));
|
||||||
) -> Option<f64> {
|
}
|
||||||
if self.test_result.is_some() | self.function.is_none() {
|
} else {
|
||||||
return None;
|
self.clear_integral();
|
||||||
}
|
}
|
||||||
|
|
||||||
let integral_step =
|
let threshold: f64 = f64::EPSILON;
|
||||||
(settings.integral_max_x - settings.integral_min_x) / (settings.integral_num as f64);
|
let x_range = settings.min_x..settings.max_x;
|
||||||
debug_assert!(integral_step > 0.0);
|
|
||||||
|
|
||||||
let step = (settings.max_x - settings.min_x) / (settings.plot_width as f64);
|
// Calculates extrema
|
||||||
debug_assert!(step > 0.0);
|
if settings.do_extrema && (min_max_changed | self.extrema_data.is_empty()) {
|
||||||
|
self.extrema_data = self.newtons_method_helper(threshold, 1, &x_range);
|
||||||
|
}
|
||||||
|
|
||||||
// Plot back data
|
// Calculates roots
|
||||||
if !self.back_data.is_empty() {
|
if settings.do_roots && (min_max_changed | self.root_data.is_empty()) {
|
||||||
if self.integral && (step >= integral_step) {
|
self.root_data = self.newtons_method_helper(threshold, 0, &x_range);
|
||||||
plot_ui.line(
|
}
|
||||||
self.back_data
|
}
|
||||||
.iter()
|
|
||||||
.filter(|value| {
|
|
||||||
(value.x > settings.integral_min_x)
|
|
||||||
&& (settings.integral_max_x > value.x)
|
|
||||||
})
|
|
||||||
.cloned()
|
|
||||||
.collect::<Vec<PlotPoint>>()
|
|
||||||
.to_line()
|
|
||||||
.stroke(epaint::Stroke::NONE)
|
|
||||||
.color(Color32::from_rgb(4, 4, 255))
|
|
||||||
.fill(0.0),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
plot_ui.line(
|
|
||||||
self.back_data
|
|
||||||
.clone()
|
|
||||||
.to_line()
|
|
||||||
.stroke(egui::Stroke::new(4.0, main_plot_color)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Plot derivative data
|
/// Displays the function's output on PlotUI `plot_ui` with settings `settings`.
|
||||||
if self.derivative && !self.derivative_data.is_empty() {
|
/// Returns an `Option<f64>` of the calculated integral.
|
||||||
plot_ui.line(self.derivative_data.clone().to_line().color(Color32::GREEN));
|
pub fn display(
|
||||||
}
|
&self,
|
||||||
|
plot_ui: &mut PlotUi,
|
||||||
|
settings: &AppSettings,
|
||||||
|
main_plot_color: Color32,
|
||||||
|
) -> Option<f64> {
|
||||||
|
if self.test_result.is_some() | self.function.is_none() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
// Plot extrema points
|
let integral_step =
|
||||||
if settings.do_extrema && !self.extrema_data.is_empty() {
|
(settings.integral_max_x - settings.integral_min_x) / (settings.integral_num as f64);
|
||||||
plot_ui.points(
|
debug_assert!(integral_step > 0.0);
|
||||||
self.extrema_data
|
|
||||||
.clone()
|
|
||||||
.to_points()
|
|
||||||
.color(Color32::YELLOW)
|
|
||||||
.radius(5.0), // Radius of points of Extrema
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Plot roots points
|
let step = (settings.max_x - settings.min_x) / (settings.plot_width as f64);
|
||||||
if settings.do_roots && !self.root_data.is_empty() {
|
debug_assert!(step > 0.0);
|
||||||
plot_ui.points(
|
|
||||||
self.root_data
|
|
||||||
.clone()
|
|
||||||
.to_points()
|
|
||||||
.color(Color32::LIGHT_BLUE)
|
|
||||||
.radius(5.0), // Radius of points of Roots
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.nth_derviative
|
// Check if we have any special points that need exclusion zones
|
||||||
&& let Some(ref nth_derviative) = self.nth_derivative_data
|
let has_special_points = (settings.do_extrema && !self.extrema_data.is_empty())
|
||||||
{
|
|| (settings.do_roots && !self.root_data.is_empty());
|
||||||
plot_ui.line(nth_derviative.clone().to_line().color(Color32::DARK_RED));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Plot integral data
|
// Plot back data, filtering out points near special points for better hover detection
|
||||||
match &self.integral_data {
|
if !self.back_data.is_empty() {
|
||||||
Some(integral_data) => {
|
if self.integral && (step >= integral_step) {
|
||||||
if integral_step > step {
|
plot_ui.line(
|
||||||
plot_ui.bar_chart(
|
self.back_data
|
||||||
BarChart::new(integral_data.0.clone())
|
.iter()
|
||||||
.color(Color32::BLUE)
|
.filter(|value| {
|
||||||
.width(integral_step),
|
(value.x > settings.integral_min_x)
|
||||||
);
|
&& (settings.integral_max_x > value.x)
|
||||||
}
|
})
|
||||||
|
.cloned()
|
||||||
|
.collect::<Vec<PlotPoint>>()
|
||||||
|
.to_line()
|
||||||
|
.stroke(epaint::Stroke::NONE)
|
||||||
|
.color(Color32::from_rgb(4, 4, 255))
|
||||||
|
.fill(0.0),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// return value rounded to 8 decimal places
|
// Only filter when there are special points to avoid
|
||||||
Some(emath::round_to_decimals(integral_data.1, 8))
|
let main_line = if has_special_points {
|
||||||
}
|
let exclusion_radius = step * 3.0;
|
||||||
None => None,
|
let is_near_special = |p: &PlotPoint| {
|
||||||
}
|
(settings.do_extrema
|
||||||
}
|
&& self
|
||||||
|
.extrema_data
|
||||||
|
.iter()
|
||||||
|
.any(|sp| (p.x - sp.x).abs() < exclusion_radius))
|
||||||
|
|| (settings.do_roots
|
||||||
|
&& self
|
||||||
|
.root_data
|
||||||
|
.iter()
|
||||||
|
.any(|sp| (p.x - sp.x).abs() < exclusion_radius))
|
||||||
|
};
|
||||||
|
self.back_data
|
||||||
|
.iter()
|
||||||
|
.filter(|p| !is_near_special(p))
|
||||||
|
.cloned()
|
||||||
|
.collect::<Vec<PlotPoint>>()
|
||||||
|
.to_line()
|
||||||
|
} else {
|
||||||
|
// No filtering needed - use data directly
|
||||||
|
self.back_data.clone().to_line()
|
||||||
|
};
|
||||||
|
|
||||||
/// Invalidate entire cache
|
plot_ui.line(main_line.stroke(egui::Stroke::new(4.0, main_plot_color)));
|
||||||
fn invalidate_whole(&mut self) {
|
}
|
||||||
self.clear_back();
|
|
||||||
self.clear_integral();
|
|
||||||
self.clear_derivative();
|
|
||||||
self.clear_nth();
|
|
||||||
self.clear_extrema();
|
|
||||||
self.clear_roots();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Invalidate `back` data
|
// Plot derivative data
|
||||||
#[inline]
|
if self.derivative && !self.derivative_data.is_empty() {
|
||||||
fn clear_back(&mut self) { self.back_data.clear(); }
|
let derivative_line = if has_special_points {
|
||||||
|
let exclusion_radius = step * 3.0;
|
||||||
|
let is_near_special = |p: &PlotPoint| {
|
||||||
|
(settings.do_extrema
|
||||||
|
&& self
|
||||||
|
.extrema_data
|
||||||
|
.iter()
|
||||||
|
.any(|sp| (p.x - sp.x).abs() < exclusion_radius))
|
||||||
|
|| (settings.do_roots
|
||||||
|
&& self
|
||||||
|
.root_data
|
||||||
|
.iter()
|
||||||
|
.any(|sp| (p.x - sp.x).abs() < exclusion_radius))
|
||||||
|
};
|
||||||
|
self.derivative_data
|
||||||
|
.iter()
|
||||||
|
.filter(|p| !is_near_special(p))
|
||||||
|
.cloned()
|
||||||
|
.collect::<Vec<PlotPoint>>()
|
||||||
|
.to_line()
|
||||||
|
} else {
|
||||||
|
self.derivative_data.clone().to_line()
|
||||||
|
};
|
||||||
|
|
||||||
/// Invalidate Integral data
|
plot_ui.line(derivative_line.color(Color32::GREEN));
|
||||||
#[inline]
|
}
|
||||||
fn clear_integral(&mut self) { self.integral_data = None; }
|
|
||||||
|
|
||||||
/// Invalidate Derivative data
|
// Plot extrema points
|
||||||
#[inline]
|
if settings.do_extrema && !self.extrema_data.is_empty() {
|
||||||
fn clear_derivative(&mut self) { self.derivative_data.clear(); }
|
for point in &self.extrema_data {
|
||||||
|
let name = format!(
|
||||||
|
"({}, {})",
|
||||||
|
try_symbolic(point.x)
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.unwrap_or_else(|| format!("{:.4}", point.x)),
|
||||||
|
try_symbolic(point.y)
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.unwrap_or_else(|| format!("{:.4}", point.y))
|
||||||
|
);
|
||||||
|
plot_ui.points(
|
||||||
|
Points::new(name, vec![[point.x, point.y]])
|
||||||
|
.color(Color32::YELLOW)
|
||||||
|
.radius(5.0),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Invalidates `n`th derivative data
|
// Plot roots points
|
||||||
#[inline]
|
if settings.do_roots && !self.root_data.is_empty() {
|
||||||
fn clear_nth(&mut self) { self.nth_derivative_data = None }
|
for point in &self.root_data {
|
||||||
|
let name = format!(
|
||||||
|
"({}, {})",
|
||||||
|
try_symbolic(point.x)
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.unwrap_or_else(|| format!("{:.4}", point.x)),
|
||||||
|
try_symbolic(point.y)
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.unwrap_or_else(|| format!("{:.4}", point.y))
|
||||||
|
);
|
||||||
|
plot_ui.points(
|
||||||
|
Points::new(name, vec![[point.x, point.y]])
|
||||||
|
.color(Color32::LIGHT_BLUE)
|
||||||
|
.radius(5.0),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Invalidate extrema data
|
if self.nth_derivative
|
||||||
#[inline]
|
&& let Some(ref nth_derivative) = self.nth_derivative_data
|
||||||
fn clear_extrema(&mut self) { self.extrema_data.clear() }
|
{
|
||||||
|
plot_ui.line(nth_derivative.clone().to_line().color(Color32::DARK_RED));
|
||||||
|
}
|
||||||
|
|
||||||
/// Invalidate root data
|
// Plot integral data
|
||||||
#[inline]
|
match &self.integral_data {
|
||||||
fn clear_roots(&mut self) { self.root_data.clear() }
|
Some(integral_data) => {
|
||||||
|
if integral_step > step {
|
||||||
|
plot_ui.bar_chart(
|
||||||
|
BarChart::new("integral bar chart", integral_data.0.clone())
|
||||||
|
.color(Color32::BLUE)
|
||||||
|
.width(integral_step),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// return value rounded to 8 decimal places
|
||||||
|
Some(emath::round_to_decimals(integral_data.1, 8))
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Invalidate entire cache
|
||||||
|
fn invalidate_whole(&mut self) {
|
||||||
|
self.clear_back();
|
||||||
|
self.clear_integral();
|
||||||
|
self.clear_derivative();
|
||||||
|
self.clear_nth();
|
||||||
|
self.clear_extrema();
|
||||||
|
self.clear_roots();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Invalidate `back` data
|
||||||
|
#[inline]
|
||||||
|
fn clear_back(&mut self) {
|
||||||
|
self.back_data.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Invalidate Integral data
|
||||||
|
#[inline]
|
||||||
|
fn clear_integral(&mut self) {
|
||||||
|
self.integral_data = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Invalidate Derivative data
|
||||||
|
#[inline]
|
||||||
|
fn clear_derivative(&mut self) {
|
||||||
|
self.derivative_data.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Invalidates `n`th derivative data
|
||||||
|
#[inline]
|
||||||
|
fn clear_nth(&mut self) {
|
||||||
|
self.nth_derivative_data = None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Invalidate extrema data
|
||||||
|
#[inline]
|
||||||
|
fn clear_extrema(&mut self) {
|
||||||
|
self.extrema_data.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Invalidate root data
|
||||||
|
#[inline]
|
||||||
|
fn clear_roots(&mut self) {
|
||||||
|
self.root_data.clear()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,281 +1,267 @@
|
|||||||
use crate::{
|
use crate::{function_entry::FunctionEntry, widgets::widgets_ontop};
|
||||||
consts::COLORS,
|
use egui::{Button, Id, Key, Modifiers, Popup, PopupCloseBehavior, TextEdit, WidgetText};
|
||||||
function_entry::FunctionEntry,
|
|
||||||
misc::{create_id, get_u64_id, random_u64},
|
|
||||||
widgets::widgets_ontop,
|
|
||||||
};
|
|
||||||
use egui::{Button, Id, Key, Modifiers, TextEdit, WidgetText};
|
|
||||||
use emath::vec2;
|
use emath::vec2;
|
||||||
use parsing::Movement;
|
use parsing::Movement;
|
||||||
use serde::ser::SerializeStruct;
|
use serde::{Deserialize, Serialize};
|
||||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
|
||||||
use std::collections::hash_map::DefaultHasher;
|
|
||||||
use std::hash::{Hash, Hasher};
|
|
||||||
use std::ops::BitXorAssign;
|
use std::ops::BitXorAssign;
|
||||||
|
|
||||||
type Functions = Vec<(Id, FunctionEntry)>;
|
type Functions = Vec<(Id, FunctionEntry)>;
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct FunctionManager {
|
pub struct FunctionManager {
|
||||||
functions: Functions,
|
functions: Functions,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for FunctionManager {
|
impl Default for FunctionManager {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
let mut vec: Functions = Vec::with_capacity(COLORS.len());
|
let mut d = Self::new();
|
||||||
vec.push((
|
d.push_empty();
|
||||||
create_id(11414819524356497634), // Random number here to avoid call to crate::misc::random_u64()
|
d
|
||||||
FunctionEntry::default(),
|
}
|
||||||
));
|
|
||||||
Self { functions: vec }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Serialize for FunctionManager {
|
#[test]
|
||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
fn func_manager_roundtrip_serdes() {
|
||||||
where
|
let mut func_manager = FunctionManager {
|
||||||
S: Serializer,
|
functions: Vec::new(),
|
||||||
{
|
};
|
||||||
let mut s = serializer.serialize_struct("FunctionManager", 1)?;
|
|
||||||
s.serialize_field(
|
|
||||||
"data",
|
|
||||||
&self
|
|
||||||
.functions
|
|
||||||
.iter()
|
|
||||||
.map(|(id, func)| (get_u64_id(*id), func.clone()))
|
|
||||||
.collect::<Vec<(u64, FunctionEntry)>>(),
|
|
||||||
)?;
|
|
||||||
s.end()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'de> Deserialize<'de> for FunctionManager {
|
func_manager.push_empty();
|
||||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
let ser = bincode::serialize(&func_manager).expect("unable to serialize");
|
||||||
where
|
let des: FunctionManager = bincode::deserialize(&ser).expect("unable to deserialize");
|
||||||
D: Deserializer<'de>,
|
assert_eq!(
|
||||||
{
|
func_manager.functions[0].1.func_str(),
|
||||||
#[derive(Deserialize)]
|
des.functions[0].1.func_str()
|
||||||
struct Helper(Vec<(u64, FunctionEntry)>);
|
);
|
||||||
|
|
||||||
let helper = Helper::deserialize(deserializer)?;
|
|
||||||
|
|
||||||
Ok(FunctionManager {
|
|
||||||
functions: helper
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.cloned()
|
|
||||||
.map(|(id, func)| (create_id(id), func))
|
|
||||||
.collect::<Vec<(Id, FunctionEntry)>>(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Function that creates button that's used with the `button_area`
|
/// Function that creates button that's used with the `button_area`
|
||||||
fn button_area_button<'a>(text: impl Into<WidgetText>) -> Button<'a> {
|
fn button_area_button<'a>(text: impl Into<WidgetText>) -> Button<'a> {
|
||||||
Button::new(text).frame(false)
|
Button::new(text).frame(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FunctionManager {
|
impl FunctionManager {
|
||||||
#[inline]
|
pub fn new() -> Self {
|
||||||
fn get_hash(&self) -> u64 {
|
Self {
|
||||||
let mut hasher = DefaultHasher::new();
|
functions: Vec::new(),
|
||||||
self.functions.hash(&mut hasher);
|
}
|
||||||
hasher.finish()
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Displays function entries alongside returning whether or not functions have been modified
|
/// Displays function entries alongside returning whether or not functions have been modified
|
||||||
pub fn display_entries(&mut self, ui: &mut egui::Ui) -> bool {
|
pub fn display_entries(&mut self, ui: &mut egui::Ui) -> bool {
|
||||||
let initial_hash = self.get_hash();
|
let mut changed = false;
|
||||||
|
let can_remove = self.functions.len() > 1;
|
||||||
|
|
||||||
let can_remove = self.functions.len() > 1;
|
let available_width = ui.available_width();
|
||||||
|
let mut remove_i: Option<usize> = None;
|
||||||
|
let target_size = vec2(available_width, crate::consts::FONT_SIZE);
|
||||||
|
for (i, (te_id, function)) in self.functions.iter_mut().map(|(a, b)| (*a, b)).enumerate() {
|
||||||
|
let mut new_string = function.autocomplete.string.clone();
|
||||||
|
|
||||||
let available_width = ui.available_width();
|
let mut movement: Movement = Movement::default();
|
||||||
let mut remove_i: Option<usize> = None;
|
|
||||||
let target_size = vec2(available_width, crate::consts::FONT_SIZE);
|
|
||||||
for (i, (te_id, function)) in self.functions.iter_mut().map(|(a, b)| (*a, b)).enumerate() {
|
|
||||||
let mut new_string = function.autocomplete.string.clone();
|
|
||||||
function.update_string(&new_string);
|
|
||||||
|
|
||||||
let mut movement: Movement = Movement::default();
|
let size_multiplier = vec2(1.0, {
|
||||||
|
let had_focus = ui.memory(|x| x.has_focus(te_id));
|
||||||
|
(ui.ctx().animate_bool(te_id, had_focus) * 1.5) + 1.0
|
||||||
|
});
|
||||||
|
|
||||||
let size_multiplier = vec2(1.0, {
|
let re = ui.add_sized(
|
||||||
let had_focus = ui.memory(|x| x.has_focus(te_id));
|
target_size * size_multiplier,
|
||||||
(ui.ctx().animate_bool(te_id, had_focus) * 1.5) + 1.0
|
egui::TextEdit::singleline(&mut new_string)
|
||||||
});
|
.hint_forward(true) // Make the hint appear after the last text in the textbox
|
||||||
|
.lock_focus(true)
|
||||||
|
.id(te_id) // Set widget's id to `te_id`
|
||||||
|
.hint_text(
|
||||||
|
// If there's a single hint, go ahead and apply the hint here, if not, set the hint to an empty string
|
||||||
|
function.autocomplete.hint.single().unwrap_or(""),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
let re = ui.add_sized(
|
// Only keep valid chars
|
||||||
target_size * size_multiplier,
|
new_string.retain(crate::misc::is_valid_char);
|
||||||
egui::TextEdit::singleline(&mut new_string)
|
|
||||||
.hint_forward(true) // Make the hint appear after the last text in the textbox
|
|
||||||
.lock_focus(true)
|
|
||||||
.id(te_id) // Set widget's id to `te_id`
|
|
||||||
.hint_text(
|
|
||||||
// If there's a single hint, go ahead and apply the hint here, if not, set the hint to an empty string
|
|
||||||
function.autocomplete.hint.single().unwrap_or(""),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Only keep valid chars
|
// Track if function string changed and update the function
|
||||||
new_string.retain(crate::misc::is_valid_char);
|
if new_string != function.autocomplete.string {
|
||||||
|
changed = true;
|
||||||
|
function.update_string(&new_string);
|
||||||
|
}
|
||||||
|
|
||||||
// If not fully open, return here as buttons cannot yet be displayed, therefore the user is inable to mark it for deletion
|
// If not fully open, return here as buttons cannot yet be displayed, therefore the user is inable to mark it for deletion
|
||||||
let animate_bool = ui.ctx().animate_bool(te_id, re.has_focus());
|
let animate_bool = ui.ctx().animate_bool(te_id, re.has_focus());
|
||||||
if animate_bool == 1.0 {
|
if animate_bool == 1.0 {
|
||||||
function.autocomplete.update_string(&new_string);
|
if function.autocomplete.hint.is_some() {
|
||||||
|
// only register up and down arrow movements if hint is type `Hint::Many`
|
||||||
|
if !function.autocomplete.hint.is_single() {
|
||||||
|
let (arrow_down, arrow_up) = ui.input(|x| {
|
||||||
|
(x.key_pressed(Key::ArrowDown), x.key_pressed(Key::ArrowUp))
|
||||||
|
});
|
||||||
|
if arrow_down {
|
||||||
|
movement = Movement::Down;
|
||||||
|
} else if arrow_up {
|
||||||
|
movement = Movement::Up;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if function.autocomplete.hint.is_some() {
|
// Put here so these key presses don't interact with other elements
|
||||||
// only register up and down arrow movements if hint is type `Hint::Many`
|
let movement_complete_action = ui.input_mut(|x| {
|
||||||
if !function.autocomplete.hint.is_single() {
|
x.consume_key(Modifiers::NONE, Key::Enter)
|
||||||
let (arrow_down, arrow_up) = ui.input(|x| {
|
| x.consume_key(Modifiers::NONE, Key::Tab)
|
||||||
(x.key_pressed(Key::ArrowDown), x.key_pressed(Key::ArrowUp))
|
| x.key_pressed(Key::ArrowRight)
|
||||||
});
|
});
|
||||||
if arrow_down {
|
|
||||||
movement = Movement::Down;
|
|
||||||
} else if arrow_up {
|
|
||||||
movement = Movement::Up;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Put here so these key presses don't interact with other elements
|
if movement_complete_action {
|
||||||
let movement_complete_action = ui.input_mut(|x| {
|
movement = Movement::Complete;
|
||||||
x.consume_key(Modifiers::NONE, Key::Enter)
|
}
|
||||||
| x.consume_key(Modifiers::NONE, Key::Tab)
|
|
||||||
| x.key_pressed(Key::ArrowRight)
|
|
||||||
});
|
|
||||||
|
|
||||||
if movement_complete_action {
|
// Remember string before movement to detect changes
|
||||||
movement = Movement::Complete;
|
let string_before = function.autocomplete.string.clone();
|
||||||
}
|
|
||||||
|
|
||||||
// Register movement and apply proper changes
|
// Register movement and apply proper changes
|
||||||
function.autocomplete.register_movement(&movement);
|
function.autocomplete.register_movement(&movement);
|
||||||
|
|
||||||
if movement != Movement::Complete
|
// If the string changed (hint was applied), update the backing function
|
||||||
&& let Some(hints) = function.autocomplete.hint.many()
|
if function.autocomplete.string != string_before {
|
||||||
{
|
function.sync_from_autocomplete();
|
||||||
// Doesn't need to have a number in id as there should only be 1 autocomplete popup in the entire gui
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
// hashed "autocomplete_popup"
|
if movement != Movement::Complete
|
||||||
const POPUP_ID: Id = create_id(7574801616484505465);
|
&& let Some(hints) = function.autocomplete.hint.many()
|
||||||
|
{
|
||||||
|
let mut clicked = false;
|
||||||
|
|
||||||
let mut clicked = false;
|
let autocomplete_popup_id = Id::new("autocomplete popup");
|
||||||
|
|
||||||
egui::popup_below_widget(ui, POPUP_ID, &re, |ui| {
|
Popup::from_response(&re)
|
||||||
hints.iter().enumerate().for_each(|(i, candidate)| {
|
.id(autocomplete_popup_id)
|
||||||
if ui
|
.close_behavior(PopupCloseBehavior::CloseOnClickOutside)
|
||||||
.selectable_label(i == function.autocomplete.i, *candidate)
|
.show(|ui| {
|
||||||
.clicked()
|
hints.iter().enumerate().for_each(|(i, candidate)| {
|
||||||
{
|
if ui
|
||||||
clicked = true;
|
.selectable_label(i == function.autocomplete.i, *candidate)
|
||||||
function.autocomplete.i = i;
|
.clicked()
|
||||||
}
|
{
|
||||||
});
|
clicked = true;
|
||||||
});
|
function.autocomplete.i = i;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
if clicked {
|
if clicked {
|
||||||
function
|
function
|
||||||
.autocomplete
|
.autocomplete
|
||||||
.apply_hint(hints[function.autocomplete.i]);
|
.apply_hint(hints[function.autocomplete.i]);
|
||||||
|
// Update the backing function with the new string after hint was applied
|
||||||
|
function.sync_from_autocomplete();
|
||||||
|
changed = true;
|
||||||
|
|
||||||
// Don't need this here as it simply won't be display next frame
|
movement = Movement::Complete;
|
||||||
// ui.memory_mut().close_popup();
|
} else {
|
||||||
|
Popup::open_id(ui.ctx(), autocomplete_popup_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
movement = Movement::Complete;
|
// Push cursor to end if needed
|
||||||
} else {
|
if movement == Movement::Complete {
|
||||||
ui.memory_mut(|x| x.open_popup(POPUP_ID));
|
// TODO! proper error handling
|
||||||
}
|
let mut state =
|
||||||
}
|
unsafe { TextEdit::load_state(ui.ctx(), te_id).unwrap_unchecked() };
|
||||||
|
let ccursor = egui::text::CCursor::new(function.autocomplete.string.len());
|
||||||
|
state
|
||||||
|
.cursor
|
||||||
|
.set_char_range(Some(egui::text::CCursorRange::one(ccursor)));
|
||||||
|
|
||||||
// Push cursor to end if needed
|
TextEdit::store_state(ui.ctx(), te_id, state);
|
||||||
if movement == Movement::Complete {
|
}
|
||||||
let mut state =
|
}
|
||||||
unsafe { TextEdit::load_state(ui.ctx(), te_id).unwrap_unchecked() };
|
|
||||||
let ccursor = egui::text::CCursor::new(function.autocomplete.string.len());
|
|
||||||
state.set_ccursor_range(Some(egui::text::CCursorRange::one(ccursor)));
|
|
||||||
TextEdit::store_state(ui.ctx(), te_id, state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The y offset multiplier of the `buttons_area` area
|
/// The y offset multiplier of the `buttons_area` area
|
||||||
const BUTTONS_Y_OFFSET: f32 = 1.32;
|
const BUTTONS_Y_OFFSET: f32 = 1.32;
|
||||||
const Y_OFFSET: f32 = crate::consts::FONT_SIZE * BUTTONS_Y_OFFSET;
|
const Y_OFFSET: f32 = crate::consts::FONT_SIZE * BUTTONS_Y_OFFSET;
|
||||||
|
|
||||||
widgets_ontop(ui, create_id(i as u64), &re, Y_OFFSET, |ui| {
|
widgets_ontop(ui, Id::new(i), &re, Y_OFFSET, |ui| {
|
||||||
ui.horizontal(|ui| {
|
ui.horizontal(|ui| {
|
||||||
// There's more than 1 function! Functions can now be deleted
|
// There's more than 1 function! Functions can now be deleted
|
||||||
if ui
|
if ui
|
||||||
.add_enabled(can_remove, button_area_button("✖"))
|
.add_enabled(can_remove, button_area_button("✖"))
|
||||||
.on_hover_text("Delete Function")
|
.on_hover_text("Delete Function")
|
||||||
.clicked()
|
.clicked()
|
||||||
{
|
{
|
||||||
remove_i = Some(i);
|
remove_i = Some(i);
|
||||||
}
|
}
|
||||||
|
|
||||||
ui.add_enabled_ui(function.is_some(), |ui| {
|
ui.add_enabled_ui(function.is_some(), |ui| {
|
||||||
// Toggle integral being enabled or not
|
// Toggle integral being enabled or not
|
||||||
function.integral.bitxor_assign(
|
function.integral.bitxor_assign(
|
||||||
ui.add(button_area_button("∫"))
|
ui.add(button_area_button("∫"))
|
||||||
.on_hover_text(match function.integral {
|
.on_hover_text(match function.integral {
|
||||||
true => "Don't integrate",
|
true => "Don't integrate",
|
||||||
false => "Integrate",
|
false => "Integrate",
|
||||||
})
|
})
|
||||||
.clicked(),
|
.clicked(),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Toggle showing the derivative (even though it's already calculated this option just toggles if it's displayed or not)
|
// Toggle showing the derivative (even though it's already calculated this option just toggles if it's displayed or not)
|
||||||
function.derivative.bitxor_assign(
|
function.derivative.bitxor_assign(
|
||||||
ui.add(button_area_button("d/dx"))
|
ui.add(button_area_button("d/dx"))
|
||||||
.on_hover_text(match function.derivative {
|
.on_hover_text(match function.derivative {
|
||||||
true => "Don't Differentiate",
|
true => "Don't Differentiate",
|
||||||
false => "Differentiate",
|
false => "Differentiate",
|
||||||
})
|
})
|
||||||
.clicked(),
|
.clicked(),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Toggle showing the settings window
|
// Toggle showing the settings window
|
||||||
function.settings_opened.bitxor_assign(
|
function.settings_opened.bitxor_assign(
|
||||||
ui.add(button_area_button("⚙"))
|
ui.add(button_area_button("⚙"))
|
||||||
.on_hover_text(match function.settings_opened {
|
.on_hover_text(match function.settings_opened {
|
||||||
true => "Close Settings",
|
true => "Close Settings",
|
||||||
false => "Open Settings",
|
false => "Open Settings",
|
||||||
})
|
})
|
||||||
.clicked(),
|
.clicked(),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function.settings_window(ui.ctx());
|
function.settings_window(ui.ctx());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove function if the user requests it
|
// Remove function if the user requests it
|
||||||
if let Some(remove_i_unwrap) = remove_i {
|
if let Some(remove_i_unwrap) = remove_i {
|
||||||
self.functions.remove(remove_i_unwrap);
|
self.functions.remove(remove_i_unwrap);
|
||||||
}
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
let final_hash = self.get_hash();
|
changed
|
||||||
|
}
|
||||||
|
|
||||||
initial_hash != final_hash
|
/// Create and push new empty function entry
|
||||||
}
|
pub fn push_empty(&mut self) {
|
||||||
|
self.functions.push((
|
||||||
|
Id::new(format!("function #{}", self.functions.len() + 1)),
|
||||||
|
FunctionEntry::default(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
/// Create and push new empty function entry
|
/// Detect if any functions are using integrals
|
||||||
pub fn push_empty(&mut self) {
|
pub fn any_using_integral(&self) -> bool {
|
||||||
self.functions.push((
|
self.functions.iter().any(|(_, func)| func.integral)
|
||||||
create_id(random_u64().expect("unable to generate random id")),
|
}
|
||||||
FunctionEntry::default(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Detect if any functions are using integrals
|
#[inline]
|
||||||
pub fn any_using_integral(&self) -> bool {
|
pub fn len(&self) -> usize {
|
||||||
self.functions.iter().any(|(_, func)| func.integral)
|
self.functions.len()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn len(&self) -> usize { self.functions.len() }
|
pub fn get_entries_mut(&mut self) -> &mut Functions {
|
||||||
|
&mut self.functions
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn get_entries_mut(&mut self) -> &mut Functions { &mut self.functions }
|
pub fn get_entries(&self) -> &Functions {
|
||||||
|
&self.functions
|
||||||
#[inline]
|
}
|
||||||
pub fn get_entries(&self) -> &Functions { &self.functions }
|
|
||||||
}
|
}
|
||||||
|
|||||||
128
src/lib.rs
128
src/lib.rs
@@ -1,14 +1,3 @@
|
|||||||
#![feature(const_mut_refs)]
|
|
||||||
#![feature(let_chains)]
|
|
||||||
#![feature(const_trait_impl)]
|
|
||||||
#![feature(const_fn_floating_point_arithmetic)]
|
|
||||||
#![feature(const_assume)]
|
|
||||||
#![feature(const_option_ext)]
|
|
||||||
#![feature(const_slice_index)]
|
|
||||||
#![feature(slice_split_at_unchecked)]
|
|
||||||
#![feature(inline_const)]
|
|
||||||
#![feature(const_for)]
|
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate static_assertions;
|
extern crate static_assertions;
|
||||||
|
|
||||||
@@ -17,69 +6,82 @@ mod function_entry;
|
|||||||
mod function_manager;
|
mod function_manager;
|
||||||
mod math_app;
|
mod math_app;
|
||||||
mod misc;
|
mod misc;
|
||||||
|
pub mod symbolic;
|
||||||
mod unicode_helper;
|
mod unicode_helper;
|
||||||
mod widgets;
|
mod widgets;
|
||||||
|
|
||||||
pub use crate::{
|
pub use crate::{
|
||||||
function_entry::{FunctionEntry, Riemann},
|
function_entry::{FunctionEntry, Riemann},
|
||||||
math_app::AppSettings,
|
math_app::{AppSettings, MathApp},
|
||||||
misc::{
|
misc::{EguiHelper, newtons_method, option_vec_printer, step_helper},
|
||||||
hashed_storage_create, hashed_storage_read, newtons_method, option_vec_printer,
|
unicode_helper::{to_chars_array, to_unicode_hash},
|
||||||
step_helper, EguiHelper, HashBytes,
|
|
||||||
},
|
|
||||||
unicode_helper::{to_chars_array, to_unicode_hash},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
cfg_if::cfg_if! {
|
// WASM-specific setup
|
||||||
if #[cfg(target_arch = "wasm32")] {
|
#[cfg(target_arch = "wasm32")]
|
||||||
use wasm_bindgen::prelude::*;
|
mod wasm {
|
||||||
|
use super::math_app;
|
||||||
|
use eframe::WebRunner;
|
||||||
|
use lol_alloc::{FreeListAllocator, LockedAllocator};
|
||||||
|
use wasm_bindgen::prelude::*;
|
||||||
|
use web_sys::HtmlCanvasElement;
|
||||||
|
|
||||||
use lol_alloc::{FreeListAllocator, LockedAllocator};
|
#[global_allocator]
|
||||||
#[global_allocator]
|
static ALLOCATOR: LockedAllocator<FreeListAllocator> =
|
||||||
static ALLOCATOR: LockedAllocator<FreeListAllocator> = LockedAllocator::new(FreeListAllocator::new());
|
LockedAllocator::new(FreeListAllocator::new());
|
||||||
|
|
||||||
use eframe::WebRunner;
|
#[derive(Clone)]
|
||||||
// use tracing::metadata::LevelFilter;
|
#[wasm_bindgen]
|
||||||
#[derive(Clone)]
|
pub struct WebHandle {
|
||||||
#[wasm_bindgen]
|
runner: WebRunner,
|
||||||
pub struct WebHandle {
|
}
|
||||||
runner: WebRunner,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
impl WebHandle {
|
impl WebHandle {
|
||||||
/// Installs a panic hook, then returns.
|
/// Installs a panic hook, then returns.
|
||||||
#[allow(clippy::new_without_default)]
|
#[allow(clippy::new_without_default)]
|
||||||
#[wasm_bindgen(constructor)]
|
#[wasm_bindgen(constructor)]
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
// eframe::WebLogger::init(LevelFilter::Debug).ok();
|
tracing_wasm::set_as_global_default();
|
||||||
tracing_wasm::set_as_global_default();
|
Self {
|
||||||
|
runner: WebRunner::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Self {
|
/// Call this once from JavaScript to start your app.
|
||||||
runner: WebRunner::new(),
|
#[wasm_bindgen]
|
||||||
}
|
pub async fn start(
|
||||||
}
|
&self,
|
||||||
|
canvas_id: HtmlCanvasElement,
|
||||||
|
) -> Result<(), wasm_bindgen::JsValue> {
|
||||||
|
self.runner
|
||||||
|
.start(
|
||||||
|
canvas_id,
|
||||||
|
eframe::WebOptions::default(),
|
||||||
|
Box::new(|cc| Ok(Box::new(math_app::MathApp::new(cc)))),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Call this once from JavaScript to start your app.
|
#[wasm_bindgen(start)]
|
||||||
#[wasm_bindgen]
|
pub async fn start() {
|
||||||
pub async fn start(&self, canvas_id: &str) -> Result<(), wasm_bindgen::JsValue> {
|
tracing::info!("Starting...");
|
||||||
self.runner
|
|
||||||
.start(
|
|
||||||
canvas_id,
|
|
||||||
eframe::WebOptions::default(),
|
|
||||||
Box::new(|cc| Box::new(math_app::MathApp::new(cc))),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[wasm_bindgen(start)]
|
let document = web_sys::window()
|
||||||
pub async fn start() {
|
.expect("no window")
|
||||||
tracing::info!("Starting...");
|
.document()
|
||||||
|
.expect("no document");
|
||||||
|
let canvas = document
|
||||||
|
.get_element_by_id("canvas")
|
||||||
|
.expect("no canvas element")
|
||||||
|
.dyn_into::<HtmlCanvasElement>()
|
||||||
|
.expect("canvas is not an HtmlCanvasElement");
|
||||||
|
|
||||||
|
let web_handle = WebHandle::new();
|
||||||
let web_handle = WebHandle::new();
|
web_handle
|
||||||
web_handle.start("canvas").await.unwrap()
|
.start(canvas)
|
||||||
}
|
.await
|
||||||
}
|
.expect("failed to start web app");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
40
src/main.rs
40
src/main.rs
@@ -1,37 +1,15 @@
|
|||||||
#![feature(const_mut_refs)]
|
|
||||||
#![feature(let_chains)]
|
|
||||||
#![feature(const_trait_impl)]
|
|
||||||
#![feature(const_fn_floating_point_arithmetic)]
|
|
||||||
#![feature(const_assume)]
|
|
||||||
#![feature(const_option_ext)]
|
|
||||||
#![feature(const_slice_index)]
|
|
||||||
#![feature(slice_split_at_unchecked)]
|
|
||||||
#![feature(inline_const)]
|
|
||||||
#![feature(const_for)]
|
|
||||||
|
|
||||||
#[macro_use]
|
|
||||||
extern crate static_assertions;
|
|
||||||
|
|
||||||
mod consts;
|
|
||||||
mod function_entry;
|
|
||||||
mod function_manager;
|
|
||||||
mod math_app;
|
|
||||||
mod misc;
|
|
||||||
mod unicode_helper;
|
|
||||||
mod widgets;
|
|
||||||
|
|
||||||
// For running the program natively! (Because why not?)
|
// For running the program natively! (Because why not?)
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
fn main() -> eframe::Result<()> {
|
fn main() -> eframe::Result<()> {
|
||||||
let subscriber = tracing_subscriber::FmtSubscriber::builder()
|
let subscriber = tracing_subscriber::FmtSubscriber::builder()
|
||||||
.with_max_level(tracing::Level::INFO)
|
.with_max_level(tracing::Level::INFO)
|
||||||
.finish();
|
.finish();
|
||||||
|
|
||||||
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
|
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
|
||||||
|
|
||||||
eframe::run_native(
|
eframe::run_native(
|
||||||
"(Yet-to-be-named) Graphing Software",
|
"(Yet-to-be-named) Graphing Software",
|
||||||
eframe::NativeOptions::default(),
|
eframe::NativeOptions::default(),
|
||||||
Box::new(|cc| Box::new(math_app::MathApp::new(cc))),
|
Box::new(|cc| Ok(Box::new(ytbn_graphing_software::MathApp::new(cc)))),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
876
src/math_app.rs
876
src/math_app.rs
@@ -1,124 +1,122 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
consts::{build, BUILD_INFO, COLORS, DEFAULT_INTEGRAL_NUM, DEFAULT_MAX_X, DEFAULT_MIN_X},
|
consts::{COLORS, DEFAULT_INTEGRAL_NUM, DEFAULT_MAX_X, DEFAULT_MIN_X},
|
||||||
function_entry::Riemann,
|
function_entry::Riemann,
|
||||||
function_manager::FunctionManager,
|
function_manager::FunctionManager,
|
||||||
misc::option_vec_printer,
|
misc::option_vec_printer,
|
||||||
|
widgets::toggle_button,
|
||||||
};
|
};
|
||||||
use eframe::App;
|
use eframe::App;
|
||||||
use egui::{
|
use egui::{
|
||||||
style::Margin, Button, CentralPanel, Color32, ComboBox, Context, DragValue, Frame, Key, Layout,
|
Button, CentralPanel, Color32, ComboBox, Context, CornerRadius, DragValue, Frame, Key, Layout,
|
||||||
SidePanel, TopBottomPanel, Ui, Vec2, Window,
|
SidePanel, TopBottomPanel, Ui, Vec2, Window,
|
||||||
};
|
};
|
||||||
use egui_plot::Plot;
|
use egui_plot::Plot;
|
||||||
|
|
||||||
use emath::{Align, Align2};
|
use emath::{Align, Align2};
|
||||||
use epaint::Rounding;
|
use epaint::Margin;
|
||||||
use instant::Instant;
|
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use std::{io::Read, ops::BitXorAssign};
|
use std::io::Read;
|
||||||
|
|
||||||
/// Stores current settings/state of [`MathApp`]
|
/// Stores current settings/state of [`MathApp`]
|
||||||
#[derive(Copy, Clone)]
|
#[derive(Copy, Clone)]
|
||||||
pub struct AppSettings {
|
pub struct AppSettings {
|
||||||
/// Stores the type of Rienmann sum that should be calculated
|
/// Stores the type of Rienmann sum that should be calculated
|
||||||
pub riemann_sum: Riemann,
|
pub riemann_sum: Riemann,
|
||||||
|
|
||||||
/// Min and Max range for calculating an integral
|
/// Min and Max range for calculating an integral
|
||||||
pub integral_min_x: f64,
|
pub integral_min_x: f64,
|
||||||
|
|
||||||
/// Max value for calculating an
|
/// Max value for calculating an
|
||||||
pub integral_max_x: f64,
|
pub integral_max_x: f64,
|
||||||
|
|
||||||
/// Minimum x bound of plot
|
/// Minimum x bound of plot
|
||||||
pub min_x: f64,
|
pub min_x: f64,
|
||||||
|
|
||||||
/// Maximum x bound of plot
|
/// Maximum x bound of plot
|
||||||
pub max_x: f64,
|
pub max_x: f64,
|
||||||
|
|
||||||
/// Stores whether or not integral settings have changed
|
/// Stores whether or not integral settings have changed
|
||||||
pub integral_changed: bool,
|
pub integral_changed: bool,
|
||||||
|
|
||||||
/// Number of rectangles used to calculate integral
|
/// Number of rectangles used to calculate integral
|
||||||
pub integral_num: usize,
|
pub integral_num: usize,
|
||||||
|
|
||||||
/// Stores whether or not displaying extrema is enabled
|
/// Stores whether or not displaying extrema is enabled
|
||||||
pub do_extrema: bool,
|
pub do_extrema: bool,
|
||||||
|
|
||||||
/// Stores whether or not displaying roots is enabled
|
/// Stores whether or not displaying roots is enabled
|
||||||
pub do_roots: bool,
|
pub do_roots: bool,
|
||||||
|
|
||||||
/// Stores current plot pixel width
|
/// Stores current plot pixel width
|
||||||
pub plot_width: usize,
|
pub plot_width: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl const Default for AppSettings {
|
impl Default for AppSettings {
|
||||||
/// Default implementation of `AppSettings`, this is how the application starts up
|
/// Default implementation of `AppSettings`, this is how the application starts up
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
riemann_sum: Riemann::default(),
|
riemann_sum: Riemann::default(),
|
||||||
integral_min_x: DEFAULT_MIN_X,
|
integral_min_x: DEFAULT_MIN_X,
|
||||||
integral_max_x: DEFAULT_MAX_X,
|
integral_max_x: DEFAULT_MAX_X,
|
||||||
min_x: 0.0,
|
min_x: 0.0,
|
||||||
max_x: 0.0,
|
max_x: 0.0,
|
||||||
integral_changed: true,
|
integral_changed: true,
|
||||||
integral_num: DEFAULT_INTEGRAL_NUM,
|
integral_num: DEFAULT_INTEGRAL_NUM,
|
||||||
do_extrema: true,
|
do_extrema: true,
|
||||||
do_roots: true,
|
do_roots: true,
|
||||||
plot_width: 0,
|
plot_width: 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Used to store the opened of windows/widgets
|
/// Used to store the opened of windows/widgets
|
||||||
struct Opened {
|
struct Opened {
|
||||||
/// Help window
|
/// Help window
|
||||||
pub help: bool,
|
pub help: bool,
|
||||||
|
|
||||||
/// Info window
|
/// Sidepanel
|
||||||
pub info: bool,
|
pub side_panel: bool,
|
||||||
|
|
||||||
/// Sidepanel
|
/// Welcome introduction
|
||||||
pub side_panel: bool,
|
pub welcome: bool,
|
||||||
|
|
||||||
/// Welcome introduction
|
|
||||||
pub welcome: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl const Default for Opened {
|
impl Default for Opened {
|
||||||
fn default() -> Opened {
|
fn default() -> Opened {
|
||||||
Self {
|
Self {
|
||||||
help: false,
|
help: false,
|
||||||
info: false,
|
side_panel: true,
|
||||||
side_panel: true,
|
welcome: true,
|
||||||
welcome: true,
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The actual application
|
/// The actual application
|
||||||
pub struct MathApp {
|
pub struct MathApp {
|
||||||
/// Stores vector of functions
|
/// Stores vector of functions
|
||||||
functions: FunctionManager,
|
functions: FunctionManager,
|
||||||
|
|
||||||
/// Contains the list of Areas calculated (the vector of f64) and time it took for the last frame (the Duration). Stored in a Tuple.
|
/// Contains the list of Areas calculated
|
||||||
last_info: (Option<String>, Option<String>),
|
areas: Option<String>,
|
||||||
|
|
||||||
/// Stores opened windows/elements for later reference
|
/// Stores opened windows/elements for later reference
|
||||||
opened: Opened,
|
opened: Opened,
|
||||||
|
|
||||||
/// Stores settings (pretty self-explanatory)
|
/// Stores settings (pretty self-explanatory)
|
||||||
settings: AppSettings,
|
settings: AppSettings,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
fn get_window() -> web_sys::Window { web_sys::window().expect("Could not get web_sys window") }
|
fn get_window() -> web_sys::Window {
|
||||||
|
web_sys::window().expect("Could not get web_sys window")
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
fn get_localstorage() -> web_sys::Storage {
|
fn get_localstorage() -> web_sys::Storage {
|
||||||
get_window()
|
get_window()
|
||||||
.local_storage()
|
.local_storage()
|
||||||
.expect("failed to get localstorage1")
|
.expect("failed to get localstorage1")
|
||||||
.expect("failed to get localstorage2")
|
.expect("failed to get localstorage2")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
@@ -126,350 +124,260 @@ const DATA_NAME: &str = "YTBN-DECOMPRESSED";
|
|||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
const FUNC_NAME: &str = "YTBN-FUNCTIONS";
|
const FUNC_NAME: &str = "YTBN-FUNCTIONS";
|
||||||
|
|
||||||
|
/// Load functions from localStorage (WASM only)
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
fn load_functions() -> Option<FunctionManager> {
|
||||||
|
let data = get_localstorage().get_item(FUNC_NAME).ok()??;
|
||||||
|
let func_data = crate::misc::hashed_storage_read(&data)?;
|
||||||
|
|
||||||
|
tracing::info!("Reading previous function data");
|
||||||
|
match bincode::deserialize(&func_data) {
|
||||||
|
Ok(Some(function_manager)) => Some(function_manager),
|
||||||
|
_ => {
|
||||||
|
tracing::info!("Unable to load functionManager instance");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decompress_fonts() -> epaint::text::FontDefinitions {
|
||||||
|
let mut data = Vec::new();
|
||||||
|
ruzstd::decoding::StreamingDecoder::new(
|
||||||
|
const { include_bytes!(concat!(env!("OUT_DIR"), "/compressed_data")).as_slice() },
|
||||||
|
)
|
||||||
|
.expect("unable to decode compressed data")
|
||||||
|
.read_to_end(&mut data)
|
||||||
|
.expect("unable to read compressed data");
|
||||||
|
|
||||||
|
bincode::deserialize(data.as_slice()).expect("unable to deserialize bincode")
|
||||||
|
}
|
||||||
|
|
||||||
impl MathApp {
|
impl MathApp {
|
||||||
#[allow(dead_code)] // This is used lol
|
#[allow(dead_code)] // This is used lol
|
||||||
/// Create new instance of [`MathApp`] and return it
|
/// Create new instance of [`MathApp`] and return it
|
||||||
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
|
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
|
||||||
#[cfg(threading)]
|
tracing::info!("Initializing...");
|
||||||
tracing::info!("Threading: Enabled");
|
|
||||||
|
|
||||||
#[cfg(not(threading))]
|
#[cfg(target_arch = "wasm32")]
|
||||||
tracing::info!("Threading: Disabled");
|
tracing::info!("Web Info: {:?}", &cc.integration_info.web_info);
|
||||||
|
|
||||||
tracing::info!("commit: {}", build::SHORT_COMMIT);
|
tracing::info!("Reading fonts...");
|
||||||
|
|
||||||
tracing::info!("Initializing...");
|
// Initialize fonts
|
||||||
let start = Instant::now();
|
// This used to be in the `update` method, but (after a ton of digging) this actually caused OOMs. that was a pain to debug
|
||||||
|
cc.egui_ctx.set_fonts(decompress_fonts());
|
||||||
|
|
||||||
cfg_if::cfg_if! {
|
tracing::info!("Initialized!");
|
||||||
if #[cfg(target_arch = "wasm32")] {
|
|
||||||
|
|
||||||
tracing::info!("Web Info: {:?}", &cc.integration_info.web_info);
|
Self {
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
functions: load_functions().unwrap_or_default(),
|
||||||
|
|
||||||
fn get_storage_decompressed() -> Option<Vec<u8>> {
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
let data = get_localstorage().get_item(DATA_NAME).ok()??;
|
functions: FunctionManager::default(),
|
||||||
let (commit, cached_data) = crate::misc::hashed_storage_read(&data)?;
|
|
||||||
|
|
||||||
|
areas: None,
|
||||||
|
opened: Opened::default(),
|
||||||
|
settings: AppSettings::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if commit == unsafe { std::mem::transmute::<&str, crate::misc::HashBytes>(build::SHORT_COMMIT) } {
|
/// Creates SidePanel which contains configuration options
|
||||||
tracing::info!("Reading decompression cache. Bytes: {}", cached_data.len());
|
fn side_panel(&mut self, ctx: &Context) {
|
||||||
return Some(cached_data.to_vec());
|
// Side Panel which contains vital options to the operation of the application
|
||||||
} else {
|
// (such as adding functions and other options)
|
||||||
None
|
SidePanel::left("side_panel")
|
||||||
}
|
.resizable(false)
|
||||||
}
|
.show(ctx, |ui| {
|
||||||
|
let any_using_integral = self.functions.any_using_integral();
|
||||||
|
let prev_sum = self.settings.riemann_sum;
|
||||||
|
// ComboBox for selecting what Riemann sum type to use
|
||||||
|
ui.add_enabled_ui(any_using_integral, |ui| {
|
||||||
|
let spacing_mut = ui.spacing_mut();
|
||||||
|
|
||||||
fn load_functions() -> Option<FunctionManager> {
|
spacing_mut.item_spacing.x = 1.0;
|
||||||
let data = get_localstorage().get_item(FUNC_NAME).ok()??;
|
spacing_mut.interact_size *= 0.5;
|
||||||
if crate::misc::HASH_LENGTH >= data.len() {
|
ComboBox::from_label("Riemann Sum")
|
||||||
return None;
|
.selected_text(self.settings.riemann_sum.to_string())
|
||||||
}
|
.show_ui(ui, |ui| {
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.settings.riemann_sum,
|
||||||
|
Riemann::Left,
|
||||||
|
"Left",
|
||||||
|
);
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.settings.riemann_sum,
|
||||||
|
Riemann::Middle,
|
||||||
|
"Middle",
|
||||||
|
);
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.settings.riemann_sum,
|
||||||
|
Riemann::Right,
|
||||||
|
"Right",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
// TODO: stabilize FunctionManager serialize so it can persist across builds
|
let riemann_changed = prev_sum != self.settings.riemann_sum;
|
||||||
let (commit, func_data) = crate::misc::hashed_storage_read(&data)?;
|
|
||||||
|
|
||||||
|
let min_x_old = self.settings.integral_min_x;
|
||||||
|
let max_x_old = self.settings.integral_max_x;
|
||||||
|
|
||||||
if commit == unsafe { std::mem::transmute::<&str, &[u8]>(build::SHORT_COMMIT) } {
|
let (min_x_changed, max_x_changed) = ui
|
||||||
tracing::info!("Reading previous function data");
|
.horizontal(|ui: &mut Ui| {
|
||||||
let function_manager: FunctionManager = bincode::deserialize(&func_data).ok()?;
|
// let spacing_mut = ui.spacing_mut();
|
||||||
return Some(function_manager);
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
// spacing_mut.item_spacing = Vec2::new(1.0, 0.0);
|
||||||
}
|
// spacing_mut.interact_size *= 0.5;
|
||||||
|
|
||||||
fn decompress_fonts() -> epaint::text::FontDefinitions {
|
ui.label("Integral: [");
|
||||||
let mut data = Vec::new();
|
let min_x_changed = ui
|
||||||
let _ = ruzstd::StreamingDecoder::new(
|
.add(DragValue::new(&mut self.settings.integral_min_x))
|
||||||
&mut const { include_bytes!(concat!(env!("OUT_DIR"), "/compressed_data")).as_slice() },
|
.changed();
|
||||||
)
|
ui.label(",");
|
||||||
.expect("unable to decode compressed data")
|
let max_x_changed = ui
|
||||||
.read_to_end(&mut data)
|
.add(DragValue::new(&mut self.settings.integral_max_x))
|
||||||
.expect("unable to read compressed data");
|
.changed();
|
||||||
|
ui.label("]");
|
||||||
|
(min_x_changed, max_x_changed)
|
||||||
|
})
|
||||||
|
.inner;
|
||||||
|
|
||||||
#[cfg(target = "wasm32")]
|
// Checks integral bounds, and if they are invalid, fix them
|
||||||
{
|
if self.settings.integral_min_x >= self.settings.integral_max_x {
|
||||||
tracing::info!("Setting decompression cache");
|
if max_x_changed {
|
||||||
let commit: crate::misc::HashBytes = const {
|
self.settings.integral_max_x = max_x_old;
|
||||||
unsafe {
|
} else if min_x_changed {
|
||||||
std::mem::transmute::<&str, crate::misc::HashBytes>(build::SHORT_COMMIT)
|
self.settings.integral_min_x = min_x_old;
|
||||||
}
|
} else {
|
||||||
};
|
// No clue how this would happen, but just in case
|
||||||
let saved_data = commit.hashed_storage_create(data);
|
self.settings.integral_min_x = DEFAULT_MIN_X;
|
||||||
tracing::info!("Bytes: {}", saved_data.len());
|
self.settings.integral_max_x = DEFAULT_MAX_X;
|
||||||
get_localstorage()
|
}
|
||||||
.set_item(DATA_NAME, saved_data)
|
}
|
||||||
.expect("failed to set local storage cache");
|
|
||||||
}
|
|
||||||
|
|
||||||
bincode::deserialize(data.as_slice()).expect("unable to deserialize bincode")
|
// Number of Rectangles for Riemann sum
|
||||||
}
|
let integral_num_changed = ui
|
||||||
|
.horizontal(|ui| {
|
||||||
|
let spacing_mut = ui.spacing_mut();
|
||||||
|
|
||||||
tracing::info!("Reading fonts...");
|
spacing_mut.item_spacing.x = 1.5;
|
||||||
|
ui.label("Interval:");
|
||||||
|
ui.add(DragValue::new(&mut self.settings.integral_num))
|
||||||
|
.changed()
|
||||||
|
})
|
||||||
|
.inner;
|
||||||
|
|
||||||
// Initialize fonts
|
if integral_num_changed {
|
||||||
// This used to be in the `update` method, but (after a ton of digging) this actually caused OOMs. that was a pain to debug
|
self.settings.integral_num = self.settings.integral_num.clamp(0, 500000);
|
||||||
cc.egui_ctx.set_fonts({
|
}
|
||||||
#[cfg(target = "wasm32")]
|
|
||||||
if let Some(Ok(data)) =
|
|
||||||
get_storage_decompressed().map(|data| bincode::deserialize(data.as_slice()))
|
|
||||||
{
|
|
||||||
data
|
|
||||||
} else {
|
|
||||||
decompress_fonts()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target = "wasm32"))]
|
self.settings.integral_changed = any_using_integral
|
||||||
decompress_fonts()
|
&& (max_x_changed | min_x_changed | integral_num_changed | riemann_changed);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Set dark mode by default
|
ui.horizontal(|ui| {
|
||||||
// cc.egui_ctx.set_visuals(crate::style::style());
|
toggle_button(
|
||||||
|
ui,
|
||||||
|
&mut self.settings.do_extrema,
|
||||||
|
"Extrema",
|
||||||
|
"Disable Displaying Extrema",
|
||||||
|
"Display Extrema",
|
||||||
|
);
|
||||||
|
|
||||||
// Set spacing
|
toggle_button(
|
||||||
// cc.egui_ctx.set_spacing(crate::style::SPACING);
|
ui,
|
||||||
|
&mut self.settings.do_roots,
|
||||||
|
"Roots",
|
||||||
|
"Disable Displaying Roots",
|
||||||
|
"Display Roots",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
tracing::info!("Initialized! Took: {:?}", start.elapsed());
|
if self.functions.display_entries(ui) {
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
{
|
||||||
|
tracing::info!("Saving function data");
|
||||||
|
|
||||||
Self {
|
let saved_data = crate::misc::hashed_storage_create(
|
||||||
#[cfg(target_arch = "wasm32")]
|
&bincode::serialize(&self.functions)
|
||||||
functions: load_functions().unwrap_or_default(),
|
.expect("unable to deserialize functions"),
|
||||||
|
);
|
||||||
|
// tracing::info!("Bytes: {}", saved_data.len());
|
||||||
|
get_localstorage()
|
||||||
|
.set_item(FUNC_NAME, &saved_data)
|
||||||
|
.expect("failed to set local function storage");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
// Only render if there's enough space
|
||||||
functions: FunctionManager::default(),
|
if ui.available_height() > crate::consts::FONT_SIZE {
|
||||||
|
ui.with_layout(Layout::bottom_up(Align::Min), |ui| {
|
||||||
|
// Contents put in reverse order from bottom to top due to the 'buttom_up' layout
|
||||||
|
|
||||||
last_info: (None, None),
|
// Hyperlink to project's github
|
||||||
opened: Opened::default(),
|
ui.hyperlink_to(
|
||||||
settings: AppSettings::default(),
|
"I'm Open Source!",
|
||||||
}
|
"https://github.com/Titaniumtown/YTBN-Graphing-Software",
|
||||||
}
|
);
|
||||||
|
});
|
||||||
/// Creates SidePanel which contains configuration options
|
}
|
||||||
fn side_panel(&mut self, ctx: &Context) {
|
});
|
||||||
// Side Panel which contains vital options to the operation of the application
|
}
|
||||||
// (such as adding functions and other options)
|
|
||||||
SidePanel::left("side_panel")
|
|
||||||
.resizable(false)
|
|
||||||
.show(ctx, |ui| {
|
|
||||||
let any_using_integral = self.functions.any_using_integral();
|
|
||||||
let prev_sum = self.settings.riemann_sum;
|
|
||||||
// ComboBox for selecting what Riemann sum type to use
|
|
||||||
ui.add_enabled_ui(any_using_integral, |ui| {
|
|
||||||
let spacing_mut = ui.spacing_mut();
|
|
||||||
|
|
||||||
spacing_mut.item_spacing.x = 1.0;
|
|
||||||
spacing_mut.interact_size *= 0.5;
|
|
||||||
ComboBox::from_label("Riemann Sum")
|
|
||||||
.selected_text(self.settings.riemann_sum.to_string())
|
|
||||||
.show_ui(ui, |ui| {
|
|
||||||
ui.selectable_value(
|
|
||||||
&mut self.settings.riemann_sum,
|
|
||||||
Riemann::Left,
|
|
||||||
"Left",
|
|
||||||
);
|
|
||||||
ui.selectable_value(
|
|
||||||
&mut self.settings.riemann_sum,
|
|
||||||
Riemann::Middle,
|
|
||||||
"Middle",
|
|
||||||
);
|
|
||||||
ui.selectable_value(
|
|
||||||
&mut self.settings.riemann_sum,
|
|
||||||
Riemann::Right,
|
|
||||||
"Right",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
let riemann_changed = prev_sum != self.settings.riemann_sum;
|
|
||||||
|
|
||||||
let min_x_old = self.settings.integral_min_x;
|
|
||||||
let max_x_old = self.settings.integral_max_x;
|
|
||||||
|
|
||||||
let (min_x_changed, max_x_changed) = ui
|
|
||||||
.horizontal(|ui: &mut Ui| {
|
|
||||||
// let spacing_mut = ui.spacing_mut();
|
|
||||||
|
|
||||||
// spacing_mut.item_spacing = Vec2::new(1.0, 0.0);
|
|
||||||
// spacing_mut.interact_size *= 0.5;
|
|
||||||
|
|
||||||
ui.label("Integral: [");
|
|
||||||
let min_x_changed = ui
|
|
||||||
.add(DragValue::new(&mut self.settings.integral_min_x))
|
|
||||||
.changed();
|
|
||||||
ui.label(",");
|
|
||||||
let max_x_changed = ui
|
|
||||||
.add(DragValue::new(&mut self.settings.integral_max_x))
|
|
||||||
.changed();
|
|
||||||
ui.label("]");
|
|
||||||
(min_x_changed, max_x_changed)
|
|
||||||
})
|
|
||||||
.inner;
|
|
||||||
|
|
||||||
// Checks integral bounds, and if they are invalid, fix them
|
|
||||||
if self.settings.integral_min_x >= self.settings.integral_max_x {
|
|
||||||
if max_x_changed {
|
|
||||||
self.settings.integral_max_x = max_x_old;
|
|
||||||
} else if min_x_changed {
|
|
||||||
self.settings.integral_min_x = min_x_old;
|
|
||||||
} else {
|
|
||||||
// No clue how this would happen, but just in case
|
|
||||||
self.settings.integral_min_x = DEFAULT_MIN_X;
|
|
||||||
self.settings.integral_max_x = DEFAULT_MAX_X;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Number of Rectangles for Riemann sum
|
|
||||||
let integral_num_changed = ui
|
|
||||||
.horizontal(|ui| {
|
|
||||||
let spacing_mut = ui.spacing_mut();
|
|
||||||
|
|
||||||
spacing_mut.item_spacing.x = 1.5;
|
|
||||||
ui.label("Interval:");
|
|
||||||
ui.add(DragValue::new(&mut self.settings.integral_num))
|
|
||||||
.changed()
|
|
||||||
})
|
|
||||||
.inner;
|
|
||||||
|
|
||||||
if integral_num_changed {
|
|
||||||
self.settings.integral_num = self.settings.integral_num.clamp(0, 500000);
|
|
||||||
}
|
|
||||||
|
|
||||||
self.settings.integral_changed = any_using_integral
|
|
||||||
&& (max_x_changed | min_x_changed | integral_num_changed | riemann_changed);
|
|
||||||
});
|
|
||||||
|
|
||||||
ui.horizontal(|ui| {
|
|
||||||
self.settings.do_extrema.bitxor_assign(
|
|
||||||
ui.add(Button::new("Extrema"))
|
|
||||||
.on_hover_text(match self.settings.do_extrema {
|
|
||||||
true => "Disable Displaying Extrema",
|
|
||||||
false => "Display Extrema",
|
|
||||||
})
|
|
||||||
.clicked(),
|
|
||||||
);
|
|
||||||
|
|
||||||
self.settings.do_roots.bitxor_assign(
|
|
||||||
ui.add(Button::new("Roots"))
|
|
||||||
.on_hover_text(match self.settings.do_roots {
|
|
||||||
true => "Disable Displaying Roots",
|
|
||||||
false => "Display Roots",
|
|
||||||
})
|
|
||||||
.clicked(),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
if self.functions.display_entries(ui) {
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
{
|
|
||||||
tracing::info!("Saving function data");
|
|
||||||
use crate::misc::{hashed_storage_create, HashBytes};
|
|
||||||
let hash: HashBytes =
|
|
||||||
unsafe { std::mem::transmute::<&str, HashBytes>(build::SHORT_COMMIT) };
|
|
||||||
let saved_data = hashed_storage_create(
|
|
||||||
hash,
|
|
||||||
&bincode::serialize(&self.functions)
|
|
||||||
.expect("unable to deserialize functions"),
|
|
||||||
);
|
|
||||||
// tracing::info!("Bytes: {}", saved_data.len());
|
|
||||||
get_localstorage()
|
|
||||||
.set_item(FUNC_NAME, &saved_data)
|
|
||||||
.expect("failed to set local function storage");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only render if there's enough space
|
|
||||||
if ui.available_height() > crate::consts::FONT_SIZE {
|
|
||||||
ui.with_layout(Layout::bottom_up(Align::Min), |ui| {
|
|
||||||
// Contents put in reverse order from bottom to top due to the 'buttom_up' layout
|
|
||||||
|
|
||||||
// Hyperlink to project's github
|
|
||||||
ui.hyperlink_to(
|
|
||||||
"I'm Open Source!",
|
|
||||||
"https://github.com/Titaniumtown/YTBN-Graphing-Software",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl App for MathApp {
|
impl App for MathApp {
|
||||||
/// Called each time the UI needs repainting.
|
/// Called each time the UI needs repainting.
|
||||||
fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) {
|
fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) {
|
||||||
// start timer
|
// If keyboard input isn't being grabbed, check for key combos
|
||||||
let start = if self.opened.info {
|
if !ctx.wants_keyboard_input() {
|
||||||
Some(instant::Instant::now())
|
// If `H` key is pressed, toggle Side Panel
|
||||||
} else {
|
if ctx.input_mut(|x| x.consume_key(egui::Modifiers::NONE, Key::H)) {
|
||||||
// if disabled, clear the stored formatted time
|
self.opened.side_panel = !self.opened.side_panel;
|
||||||
self.last_info.1 = None;
|
}
|
||||||
|
}
|
||||||
|
|
||||||
None
|
// Creates Top bar that contains some general options
|
||||||
};
|
TopBottomPanel::top("top_bar").show(ctx, |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
// Button in top bar to toggle showing the side panel
|
||||||
|
toggle_button(
|
||||||
|
ui,
|
||||||
|
&mut self.opened.side_panel,
|
||||||
|
"Panel",
|
||||||
|
"Hide Side Panel",
|
||||||
|
"Show Side Panel",
|
||||||
|
);
|
||||||
|
|
||||||
// If keyboard input isn't being grabbed, check for key combos
|
// Button to add a new function
|
||||||
if !ctx.wants_keyboard_input() {
|
if ui
|
||||||
// If `H` key is pressed, toggle Side Panel
|
.add_enabled(
|
||||||
self.opened
|
COLORS.len() > self.functions.len(),
|
||||||
.side_panel
|
Button::new("Add Function"),
|
||||||
.bitxor_assign(ctx.input_mut(|x| x.consume_key(egui::Modifiers::NONE, Key::H)));
|
)
|
||||||
}
|
.on_hover_text("Create and graph new function")
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
self.functions.push_empty();
|
||||||
|
}
|
||||||
|
|
||||||
// Creates Top bar that contains some general options
|
// Toggles opening the Help window
|
||||||
TopBottomPanel::top("top_bar").show(ctx, |ui| {
|
toggle_button(
|
||||||
ui.horizontal(|ui| {
|
ui,
|
||||||
// Button in top bar to toggle showing the side panel
|
&mut self.opened.help,
|
||||||
self.opened.side_panel.bitxor_assign(
|
"Help",
|
||||||
ui.add(Button::new("Panel"))
|
"Close Help Window",
|
||||||
.on_hover_text(match self.opened.side_panel {
|
"Open Help Window",
|
||||||
true => "Hide Side Panel",
|
);
|
||||||
false => "Show Side Panel",
|
|
||||||
})
|
|
||||||
.clicked(),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Button to add a new function
|
// Display Area and time of last frame
|
||||||
if ui
|
if let Some(ref area) = self.areas {
|
||||||
.add_enabled(
|
ui.label(area);
|
||||||
COLORS.len() > self.functions.len(),
|
}
|
||||||
Button::new("Add Function"),
|
});
|
||||||
)
|
});
|
||||||
.on_hover_text("Create and graph new function")
|
|
||||||
.clicked()
|
|
||||||
{
|
|
||||||
self.functions.push_empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Toggles opening the Help window
|
// Help window with information for users
|
||||||
self.opened.help.bitxor_assign(
|
Window::new("Help")
|
||||||
ui.add(Button::new("Help"))
|
|
||||||
.on_hover_text(match self.opened.help {
|
|
||||||
true => "Close Help Window",
|
|
||||||
false => "Open Help Window",
|
|
||||||
})
|
|
||||||
.clicked(),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Toggles opening the Info window
|
|
||||||
self.opened.info.bitxor_assign(
|
|
||||||
ui.add(Button::new("Info"))
|
|
||||||
.on_hover_text(match self.opened.info {
|
|
||||||
true => "Close Info Window",
|
|
||||||
false => "Open Info Window",
|
|
||||||
})
|
|
||||||
.clicked(),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Display Area and time of last frame
|
|
||||||
if let Some(ref area) = self.last_info.0 {
|
|
||||||
ui.label(area);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Help window with information for users
|
|
||||||
Window::new("Help")
|
|
||||||
.open(&mut self.opened.help)
|
.open(&mut self.opened.help)
|
||||||
.default_pos([200.0, 200.0])
|
.default_pos([200.0, 200.0])
|
||||||
.resizable(false)
|
.resizable(false)
|
||||||
@@ -496,9 +404,9 @@ impl App for MathApp {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Welcome window
|
// Welcome window
|
||||||
if self.opened.welcome {
|
if self.opened.welcome {
|
||||||
let welcome_response = Window::new("Welcome")
|
let welcome_response = Window::new("Welcome")
|
||||||
.anchor(Align2::CENTER_CENTER, Vec2::ZERO)
|
.anchor(Align2::CENTER_CENTER, Vec2::ZERO)
|
||||||
.resizable(false)
|
.resizable(false)
|
||||||
.collapsible(false)
|
.collapsible(false)
|
||||||
@@ -507,119 +415,97 @@ impl App for MathApp {
|
|||||||
ui.label("Welcome to the (Yet-to-be-named) Graphing Software!\n\nThis project aims to provide an intuitive experience graphing mathematical functions with features such as Integration, Differentiation, Extrema, Roots, and much more! (see the Help Window for more details)");
|
ui.label("Welcome to the (Yet-to-be-named) Graphing Software!\n\nThis project aims to provide an intuitive experience graphing mathematical functions with features such as Integration, Differentiation, Extrema, Roots, and much more! (see the Help Window for more details)");
|
||||||
});
|
});
|
||||||
|
|
||||||
if let Some(response) = welcome_response {
|
if let Some(response) = welcome_response {
|
||||||
// if user clicks off welcome window, close it
|
// if user clicks off welcome window, close it
|
||||||
if response.response.clicked_elsewhere() {
|
if response.response.clicked_elsewhere() {
|
||||||
self.opened.welcome = false;
|
self.opened.welcome = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Window with information about the build and current commit
|
// If side panel is enabled, show it.
|
||||||
Window::new("Info")
|
if self.opened.side_panel {
|
||||||
.open(&mut self.opened.info)
|
self.side_panel(ctx);
|
||||||
.default_pos([200.0, 200.0])
|
}
|
||||||
.resizable(false)
|
|
||||||
.collapsible(false)
|
|
||||||
.show(ctx, |ui| {
|
|
||||||
ui.add(egui::Label::new(BUILD_INFO));
|
|
||||||
|
|
||||||
if let Some(ref took) = self.last_info.1 {
|
// Central panel which contains the central plot (or an error created when parsing)
|
||||||
ui.label(took);
|
CentralPanel::default()
|
||||||
}
|
.frame(Frame {
|
||||||
});
|
inner_margin: Margin::ZERO,
|
||||||
|
corner_radius: CornerRadius::ZERO,
|
||||||
|
// fill: crate::style::STYLE.window_fill(),
|
||||||
|
fill: Color32::from_gray(27),
|
||||||
|
..Frame::NONE
|
||||||
|
})
|
||||||
|
.show(ctx, |ui| {
|
||||||
|
// Display an error if it exists
|
||||||
|
let errors_formatted: String = self
|
||||||
|
.functions
|
||||||
|
.get_entries()
|
||||||
|
.iter()
|
||||||
|
.map(|(_, func)| func.get_test_result())
|
||||||
|
.enumerate()
|
||||||
|
.filter_map(|(i, error)| error.as_ref().map(|x| (i, x)))
|
||||||
|
.map(|(i, error)| format!("(Function #{}) {}\n", i, error))
|
||||||
|
.join("");
|
||||||
|
|
||||||
// If side panel is enabled, show it.
|
if !errors_formatted.is_empty() {
|
||||||
if self.opened.side_panel {
|
ui.centered_and_justified(|ui| {
|
||||||
self.side_panel(ctx);
|
ui.heading(errors_formatted);
|
||||||
}
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Central panel which contains the central plot (or an error created when parsing)
|
let available_width: usize = (ui.available_width() as usize) + 1; // Used in later logic
|
||||||
CentralPanel::default()
|
let width_changed = available_width != self.settings.plot_width;
|
||||||
.frame(Frame {
|
self.settings.plot_width = available_width;
|
||||||
inner_margin: Margin::symmetric(0.0, 0.0),
|
|
||||||
rounding: Rounding::ZERO,
|
|
||||||
// fill: crate::style::STYLE.window_fill(),
|
|
||||||
fill: Color32::from_gray(27),
|
|
||||||
..Frame::none()
|
|
||||||
})
|
|
||||||
.show(ctx, |ui| {
|
|
||||||
// Display an error if it exists
|
|
||||||
let errors_formatted: String = self
|
|
||||||
.functions
|
|
||||||
.get_entries()
|
|
||||||
.iter()
|
|
||||||
.map(|(_, func)| func.get_test_result())
|
|
||||||
.enumerate()
|
|
||||||
.filter(|(_, error)| error.is_some())
|
|
||||||
.map(|(i, error)| {
|
|
||||||
// use unwrap_unchecked as None Errors are already filtered out
|
|
||||||
unsafe {
|
|
||||||
format!("(Function #{}) {}\n", i, error.as_ref().unwrap_unchecked())
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.join("");
|
|
||||||
|
|
||||||
if !errors_formatted.is_empty() {
|
// Create and setup plot
|
||||||
ui.centered_and_justified(|ui| {
|
Plot::new("plot")
|
||||||
ui.heading(errors_formatted);
|
.set_margin_fraction(Vec2::ZERO)
|
||||||
});
|
.data_aspect(1.0)
|
||||||
return;
|
.include_y(0)
|
||||||
}
|
.show(ui, |plot_ui| {
|
||||||
|
let (min_x, max_x): (f64, f64) = {
|
||||||
|
let bounds = plot_ui.plot_bounds();
|
||||||
|
(bounds.min()[0], bounds.max()[0])
|
||||||
|
};
|
||||||
|
|
||||||
let available_width: usize = (ui.available_width() as usize) + 1; // Used in later logic
|
let min_max_changed =
|
||||||
let width_changed = available_width != self.settings.plot_width;
|
(min_x != self.settings.min_x) | (max_x != self.settings.max_x);
|
||||||
self.settings.plot_width = available_width;
|
let did_zoom = (max_x - min_x).abs()
|
||||||
|
!= (self.settings.max_x - self.settings.min_x).abs();
|
||||||
|
self.settings.min_x = min_x;
|
||||||
|
self.settings.max_x = max_x;
|
||||||
|
|
||||||
// Create and setup plot
|
self.functions
|
||||||
Plot::new("plot")
|
.get_entries_mut()
|
||||||
.set_margin_fraction(Vec2::ZERO)
|
.iter_mut()
|
||||||
.data_aspect(1.0)
|
.for_each(|(_, function)| {
|
||||||
.include_y(0)
|
function.calculate(
|
||||||
.show(ui, |plot_ui| {
|
width_changed,
|
||||||
let (min_x, max_x): (f64, f64) = {
|
min_max_changed,
|
||||||
let bounds = plot_ui.plot_bounds();
|
did_zoom,
|
||||||
(bounds.min()[0], bounds.max()[0])
|
self.settings,
|
||||||
};
|
)
|
||||||
|
});
|
||||||
|
|
||||||
let min_max_changed =
|
let area: Vec<Option<f64>> = self
|
||||||
(min_x != self.settings.min_x) | (max_x != self.settings.max_x);
|
.functions
|
||||||
let did_zoom = (max_x - min_x).abs()
|
.get_entries()
|
||||||
!= (self.settings.max_x - self.settings.min_x).abs();
|
.iter()
|
||||||
self.settings.min_x = min_x;
|
.enumerate()
|
||||||
self.settings.max_x = max_x;
|
.map(|(i, (_, function))| {
|
||||||
|
function.display(plot_ui, &self.settings, COLORS[i])
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
self.functions
|
self.areas = if area.iter().any(|e| e.is_some()) {
|
||||||
.get_entries_mut()
|
Some(format!("Area: {}", option_vec_printer(area.as_slice())))
|
||||||
.iter_mut()
|
} else {
|
||||||
.for_each(|(_, function)| {
|
None
|
||||||
function.calculate(
|
};
|
||||||
width_changed,
|
});
|
||||||
min_max_changed,
|
});
|
||||||
did_zoom,
|
}
|
||||||
self.settings,
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
let area: Vec<Option<f64>> = self
|
|
||||||
.functions
|
|
||||||
.get_entries()
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(i, (_, function))| {
|
|
||||||
function.display(plot_ui, &self.settings, COLORS[i])
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
self.last_info.0 = if area.iter().any(|e| e.is_some()) {
|
|
||||||
Some(format!("Area: {}", option_vec_printer(area.as_slice())))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Calculate and store the last time it took to draw the frame
|
|
||||||
self.last_info.1 = start.map(|a| format!("Took: {}ms", a.elapsed().as_micros()));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
231
src/misc.rs
231
src/misc.rs
@@ -1,75 +1,75 @@
|
|||||||
use egui::Id;
|
use base64::Engine;
|
||||||
|
use base64::engine::general_purpose;
|
||||||
use egui_plot::{Line, PlotPoint, PlotPoints, Points};
|
use egui_plot::{Line, PlotPoint, PlotPoints, Points};
|
||||||
use emath::Pos2;
|
use emath::Pos2;
|
||||||
use getrandom::getrandom;
|
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use parsing::FlatExWrapper;
|
use parsing::FlatExWrapper;
|
||||||
|
|
||||||
/// Implements traits that are useful when dealing with Vectors of egui's `Value`
|
/// Implements traits that are useful when dealing with Vectors of egui's `Value`
|
||||||
pub trait EguiHelper {
|
pub trait EguiHelper {
|
||||||
/// Converts to `egui::plot::Values`
|
/// Converts to `egui::plot::Values`
|
||||||
fn to_values(self) -> PlotPoints;
|
fn to_values(self) -> PlotPoints<'static>;
|
||||||
|
|
||||||
/// Converts to `egui::plot::Line`
|
/// Converts to `egui::plot::Line`
|
||||||
fn to_line(self) -> Line;
|
fn to_line(self) -> Line<'static>;
|
||||||
|
|
||||||
/// Converts to `egui::plot::Points`
|
/// Converts to `egui::plot::Points`
|
||||||
fn to_points(self) -> Points;
|
fn to_points(self) -> Points<'static>;
|
||||||
|
|
||||||
/// Converts Vector of Values into vector of tuples
|
/// Converts Vector of Values into vector of tuples
|
||||||
fn to_tuple(self) -> Vec<(f64, f64)>;
|
fn to_tuple(self) -> Vec<(f64, f64)>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EguiHelper for Vec<PlotPoint> {
|
impl EguiHelper for Vec<PlotPoint> {
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn to_values(self) -> PlotPoints {
|
fn to_values(self) -> PlotPoints<'static> {
|
||||||
PlotPoints::from(unsafe { std::mem::transmute::<Vec<PlotPoint>, Vec<[f64; 2]>>(self) })
|
PlotPoints::from(unsafe { std::mem::transmute::<Vec<PlotPoint>, Vec<[f64; 2]>>(self) })
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn to_line(self) -> Line { Line::new(self.to_values()) }
|
fn to_line(self) -> Line<'static> {
|
||||||
|
Line::new("", self.to_values())
|
||||||
|
}
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn to_points(self) -> Points { Points::new(self.to_values()) }
|
fn to_points(self) -> Points<'static> {
|
||||||
|
Points::new("", self.to_values())
|
||||||
|
}
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn to_tuple(self) -> Vec<(f64, f64)> {
|
fn to_tuple(self) -> Vec<(f64, f64)> {
|
||||||
unsafe { std::mem::transmute::<Vec<PlotPoint>, Vec<(f64, f64)>>(self) }
|
unsafe { std::mem::transmute::<Vec<PlotPoint>, Vec<(f64, f64)>>(self) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait Offset {
|
pub trait Offset {
|
||||||
fn offset_y(self, y_offset: f32) -> Pos2;
|
fn offset_y(self, y_offset: f32) -> Pos2;
|
||||||
fn offset_x(self, x_offset: f32) -> Pos2;
|
fn offset_x(self, x_offset: f32) -> Pos2;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl const Offset for Pos2 {
|
impl Offset for Pos2 {
|
||||||
fn offset_y(self, y_offset: f32) -> Pos2 {
|
fn offset_y(self, y_offset: f32) -> Pos2 {
|
||||||
Pos2 {
|
Pos2 {
|
||||||
x: self.x,
|
x: self.x,
|
||||||
y: self.y + y_offset,
|
y: self.y + y_offset,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn offset_x(self, x_offset: f32) -> Pos2 {
|
fn offset_x(self, x_offset: f32) -> Pos2 {
|
||||||
Pos2 {
|
Pos2 {
|
||||||
x: self.x + x_offset,
|
x: self.x + x_offset,
|
||||||
y: self.y,
|
y: self.y,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const fn create_id(x: u64) -> Id { unsafe { std::mem::transmute::<u64, Id>(x) } }
|
|
||||||
|
|
||||||
pub const fn get_u64_id(id: Id) -> u64 { unsafe { std::mem::transmute::<Id, u64>(id) } }
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
/// Rounds f64 to `n` decimal places
|
/// Rounds f64 to `n` decimal places
|
||||||
pub fn decimal_round(x: f64, n: usize) -> f64 {
|
pub fn decimal_round(x: f64, n: usize) -> f64 {
|
||||||
let large_number: f64 = 10.0_f64.powf(n as f64); // 10^n
|
let large_number: f64 = 10.0_f64.powf(n as f64); // 10^n
|
||||||
|
|
||||||
// round and devide in order to cutoff after the `n`th decimal place
|
// round and devide in order to cutoff after the `n`th decimal place
|
||||||
(x * large_number).round() / large_number
|
(x * large_number).round() / large_number
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -80,18 +80,19 @@ 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: &[PlotPoint], f: &FlatExWrapper,
|
threshold: f64,
|
||||||
f_1: &FlatExWrapper,
|
range: &std::ops::Range<f64>,
|
||||||
|
data: &[PlotPoint],
|
||||||
|
f: &FlatExWrapper,
|
||||||
|
f_1: &FlatExWrapper,
|
||||||
) -> Vec<f64> {
|
) -> Vec<f64> {
|
||||||
data.iter()
|
data.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, _)| start.x)
|
.map(|(start, _)| start.x)
|
||||||
.map(|x| newtons_method(f, f_1, x, range, threshold))
|
.filter_map(|x| newtons_method(f, f_1, x, range, threshold))
|
||||||
.filter(|x| x.is_some())
|
.collect()
|
||||||
.map(|x| unsafe { x.unwrap_unchecked() })
|
|
||||||
.collect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `range` is the range of valid x values (used to stop calculation when
|
/// `range` is the range of valid x values (used to stop calculation when
|
||||||
@@ -99,103 +100,67 @@ 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: &FlatExWrapper, f_1: &FlatExWrapper, start_x: f64, range: &std::ops::Range<f64>,
|
f: &FlatExWrapper,
|
||||||
threshold: f64,
|
f_1: &FlatExWrapper,
|
||||||
|
start_x: f64,
|
||||||
|
range: &std::ops::Range<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 {
|
||||||
derivative = f_1.eval(&[x1]);
|
derivative = f_1.eval(&[x1]);
|
||||||
if !derivative.is_finite() {
|
if !derivative.is_finite() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
x2 = x1 - (f.eval(&[x1]) / derivative);
|
x2 = x1 - (f.eval(&[x1]) / derivative);
|
||||||
if !x2.is_finite() | !range.contains(&x2) {
|
if !x2.is_finite() | !range.contains(&x2) {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If below threshold, break
|
// If below threshold, break
|
||||||
if (x2 - x1).abs() < threshold {
|
if (x2 - x1).abs() < threshold {
|
||||||
return Some(x2);
|
return Some(x2);
|
||||||
}
|
}
|
||||||
|
|
||||||
x1 = x2;
|
x1 = x2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inputs `Vec<Option<T>>` and outputs a `String` containing a pretty representation of the Vector
|
/// Inputs `Vec<Option<T>>` and outputs a `String` containing a pretty representation of the Vector
|
||||||
pub fn option_vec_printer<T: ToString>(data: &[Option<T>]) -> String {
|
pub fn option_vec_printer<T: ToString>(data: &[Option<T>]) -> String {
|
||||||
let formatted: String = data
|
let formatted: String = data
|
||||||
.iter()
|
.iter()
|
||||||
.map(|item| match item {
|
.map(|item| match item {
|
||||||
Some(x) => x.to_string(),
|
Some(x) => x.to_string(),
|
||||||
None => "None".to_owned(),
|
None => "None".to_owned(),
|
||||||
})
|
})
|
||||||
.join(", ");
|
.join(", ");
|
||||||
|
|
||||||
format!("[{}]", formatted)
|
format!("[{}]", formatted)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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)
|
(0..max_i)
|
||||||
.map(move |x: usize| (x as f64 * step) + min_x)
|
.map(move |x: usize| (x as f64 * step) + min_x)
|
||||||
.collect()
|
.collect()
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: use in hovering over points
|
|
||||||
/// Attempts to see what variable `x` is almost
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn almost_variable(x: f64) -> Option<char> {
|
|
||||||
const EPSILON: f32 = f32::EPSILON * 2.0;
|
|
||||||
if emath::almost_equal(x as f32, std::f32::consts::E, EPSILON) {
|
|
||||||
Some('e')
|
|
||||||
} else if emath::almost_equal(x as f32, std::f32::consts::PI, EPSILON) {
|
|
||||||
Some('π')
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const HASH_LENGTH: usize = 8;
|
|
||||||
|
|
||||||
/// Represents bytes used to represent hash info
|
|
||||||
pub type HashBytes = [u8; HASH_LENGTH];
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn hashed_storage_create(hashbytes: HashBytes, data: &[u8]) -> String {
|
|
||||||
unsafe { std::mem::transmute::<Vec<u8>, String>([hashbytes.to_vec(), data.to_vec()].concat()) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn hashed_storage_read(data: &str) -> Option<(HashBytes, &[u8])> {
|
pub fn hashed_storage_create(data: &[u8]) -> String {
|
||||||
// Make sure data is long enough to decode
|
general_purpose::STANDARD.encode(data)
|
||||||
if HASH_LENGTH >= data.len() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transmute data into slice
|
|
||||||
let decoded_1: &[u8] = unsafe { std::mem::transmute::<&str, &[u8]>(data) };
|
|
||||||
|
|
||||||
// Return hash and decoded data
|
|
||||||
Some((
|
|
||||||
unsafe { *(decoded_1[..HASH_LENGTH].as_ptr() as *const HashBytes) },
|
|
||||||
&decoded_1[HASH_LENGTH..],
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates and returns random u64
|
#[allow(dead_code)]
|
||||||
pub fn random_u64() -> Result<u64, getrandom::Error> {
|
pub fn hashed_storage_read(data: &str) -> Option<Vec<u8>> {
|
||||||
// Buffer of 8 `u8`s that are later merged into one u64
|
general_purpose::STANDARD.decode(data).ok()
|
||||||
let mut buf = [0u8; 8];
|
|
||||||
// Populate buffer with random values
|
|
||||||
getrandom(&mut buf)?;
|
|
||||||
// Merge buffer into u64
|
|
||||||
Ok(u64::from_be_bytes(buf))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
include!(concat!(env!("OUT_DIR"), "/valid_chars.rs"));
|
include!(concat!(env!("OUT_DIR"), "/valid_chars.rs"));
|
||||||
|
|
||||||
pub fn is_valid_char(c: char) -> bool { c.is_alphanumeric() | VALID_EXTRA_CHARS.contains(&c) }
|
pub fn is_valid_char(c: char) -> bool {
|
||||||
|
c.is_alphanumeric() | VALID_EXTRA_CHARS.contains(&c)
|
||||||
|
}
|
||||||
|
|||||||
210
src/symbolic.rs
Normal file
210
src/symbolic.rs
Normal file
@@ -0,0 +1,210 @@
|
|||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
/// Maximum denominator to consider when checking for rational approximations.
|
||||||
|
const MAX_DENOMINATOR: i64 = 12;
|
||||||
|
|
||||||
|
/// Maximum coefficient to consider for multiples of special constants.
|
||||||
|
const MAX_COEFFICIENT: i64 = 12;
|
||||||
|
|
||||||
|
/// Represents a symbolic mathematical value.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct SymbolicValue {
|
||||||
|
/// The original numeric value
|
||||||
|
value: f64,
|
||||||
|
/// The symbolic representation
|
||||||
|
repr: SymbolicRepr,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The type of symbolic representation.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
enum SymbolicRepr {
|
||||||
|
/// An integer value
|
||||||
|
Integer(i64),
|
||||||
|
/// A simple fraction: numerator / denominator
|
||||||
|
Fraction { numerator: i64, denominator: i64 },
|
||||||
|
/// A multiple of a constant: (numerator / denominator) * constant
|
||||||
|
ConstantMultiple {
|
||||||
|
numerator: i64,
|
||||||
|
denominator: i64,
|
||||||
|
constant: Constant,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Known mathematical constants.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
|
enum Constant {
|
||||||
|
Pi,
|
||||||
|
E,
|
||||||
|
Sqrt(i64),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Constant {
|
||||||
|
fn value(self) -> f64 {
|
||||||
|
match self {
|
||||||
|
Constant::Pi => std::f64::consts::PI,
|
||||||
|
Constant::E => std::f64::consts::E,
|
||||||
|
Constant::Sqrt(n) => (n as f64).sqrt(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name(self) -> String {
|
||||||
|
match self {
|
||||||
|
Constant::Pi => "pi".to_string(),
|
||||||
|
Constant::E => "e".to_string(),
|
||||||
|
Constant::Sqrt(n) => format!("sqrt({})", n),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All constants to try, in order of priority.
|
||||||
|
const CONSTANTS: &[Constant] = &[
|
||||||
|
Constant::Pi,
|
||||||
|
Constant::E,
|
||||||
|
Constant::Sqrt(2),
|
||||||
|
Constant::Sqrt(3),
|
||||||
|
Constant::Sqrt(5),
|
||||||
|
Constant::Sqrt(6),
|
||||||
|
Constant::Sqrt(7),
|
||||||
|
];
|
||||||
|
|
||||||
|
impl SymbolicValue {
|
||||||
|
/// Returns the original numeric value.
|
||||||
|
pub fn numeric_value(&self) -> f64 {
|
||||||
|
self.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for SymbolicValue {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match &self.repr {
|
||||||
|
SymbolicRepr::Integer(n) => write!(f, "{}", n),
|
||||||
|
SymbolicRepr::Fraction {
|
||||||
|
numerator,
|
||||||
|
denominator,
|
||||||
|
} => write!(f, "{}/{}", numerator, denominator),
|
||||||
|
SymbolicRepr::ConstantMultiple {
|
||||||
|
numerator,
|
||||||
|
denominator,
|
||||||
|
constant,
|
||||||
|
} => format_constant_multiple(f, *numerator, *denominator, &constant.name()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper function to format a constant multiple like "2pi/3" or "-pi/2"
|
||||||
|
fn format_constant_multiple(
|
||||||
|
f: &mut fmt::Formatter<'_>,
|
||||||
|
numerator: i64,
|
||||||
|
denominator: i64,
|
||||||
|
constant: &str,
|
||||||
|
) -> fmt::Result {
|
||||||
|
let sign = if numerator < 0 { "-" } else { "" };
|
||||||
|
let abs_num = numerator.abs();
|
||||||
|
|
||||||
|
match (abs_num, denominator) {
|
||||||
|
(1, 1) => write!(f, "{}{}", sign, constant),
|
||||||
|
(_, 1) => write!(f, "{}{}{}", sign, abs_num, constant),
|
||||||
|
(1, _) => write!(f, "{}{}/{}", sign, constant, denominator),
|
||||||
|
(_, _) => write!(f, "{}{}{}/{}", sign, abs_num, constant, denominator),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attempts to find a symbolic representation for the given numeric value.
|
||||||
|
///
|
||||||
|
/// Returns `Some(SymbolicValue)` if the value can be represented symbolically,
|
||||||
|
/// or `None` if no suitable symbolic representation is found.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use ytbn_graphing_software::symbolic::try_symbolic;
|
||||||
|
/// use std::f64::consts::PI;
|
||||||
|
///
|
||||||
|
/// let sym = try_symbolic(PI).unwrap();
|
||||||
|
/// assert_eq!(sym.to_string(), "pi");
|
||||||
|
///
|
||||||
|
/// let sym = try_symbolic(PI / 2.0).unwrap();
|
||||||
|
/// assert_eq!(sym.to_string(), "pi/2");
|
||||||
|
/// ```
|
||||||
|
pub fn try_symbolic(x: f64) -> Option<SymbolicValue> {
|
||||||
|
if !x.is_finite() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for zero
|
||||||
|
if x.abs() < f64::EPSILON {
|
||||||
|
return Some(SymbolicValue {
|
||||||
|
value: x,
|
||||||
|
repr: SymbolicRepr::Integer(0),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try each constant in order of preference
|
||||||
|
for &constant in CONSTANTS {
|
||||||
|
if let Some(repr) = try_constant_multiple(x, constant) {
|
||||||
|
return Some(SymbolicValue { value: x, repr });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fall back to rational approximation
|
||||||
|
try_rational(x).map(|repr| SymbolicValue { value: x, repr })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Try to represent x as (numerator/denominator) * constant
|
||||||
|
fn try_constant_multiple(x: f64, constant: Constant) -> Option<SymbolicRepr> {
|
||||||
|
let c = constant.value();
|
||||||
|
|
||||||
|
for denom in 1..=MAX_DENOMINATOR {
|
||||||
|
let num_f = x * (denom as f64) / c;
|
||||||
|
let num = num_f.round() as i64;
|
||||||
|
|
||||||
|
// Skip if coefficient is zero or too large
|
||||||
|
if num == 0 || num.abs() > MAX_COEFFICIENT * denom {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let expected = (num as f64) * c / (denom as f64);
|
||||||
|
if (x - expected).abs() < f64::EPSILON {
|
||||||
|
let g = gcd(num.abs(), denom);
|
||||||
|
return Some(SymbolicRepr::ConstantMultiple {
|
||||||
|
numerator: num / g,
|
||||||
|
denominator: denom / g,
|
||||||
|
constant,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Try to represent x as a simple fraction: numerator/denominator
|
||||||
|
fn try_rational(x: f64) -> Option<SymbolicRepr> {
|
||||||
|
for denom in 1..=MAX_DENOMINATOR {
|
||||||
|
let num_f = x * (denom as f64);
|
||||||
|
let num = num_f.round() as i64;
|
||||||
|
|
||||||
|
if (x - (num as f64) / (denom as f64)).abs() < f64::EPSILON {
|
||||||
|
let g = gcd(num.abs(), denom);
|
||||||
|
let (num, denom) = (num / g, denom / g);
|
||||||
|
|
||||||
|
return Some(if denom == 1 {
|
||||||
|
SymbolicRepr::Integer(num)
|
||||||
|
} else {
|
||||||
|
SymbolicRepr::Fraction {
|
||||||
|
numerator: num,
|
||||||
|
denominator: denom,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compute the greatest common divisor using Euclidean algorithm.
|
||||||
|
fn gcd(mut a: i64, mut b: i64) -> i64 {
|
||||||
|
while b != 0 {
|
||||||
|
(a, b) = (b, a % b);
|
||||||
|
}
|
||||||
|
a
|
||||||
|
}
|
||||||
@@ -2,19 +2,19 @@ use itertools::Itertools;
|
|||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn to_unicode_hash(c: char) -> String {
|
pub fn to_unicode_hash(c: char) -> String {
|
||||||
c.escape_unicode()
|
c.escape_unicode()
|
||||||
.to_string()
|
.to_string()
|
||||||
.replace(r"\\u{", "")
|
.replace(r"\\u{", "")
|
||||||
.replace(['{', '}'], "")
|
.replace(['{', '}'], "")
|
||||||
.to_uppercase()
|
.to_uppercase()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn to_chars_array(chars: Vec<char>) -> String {
|
pub fn to_chars_array(chars: Vec<char>) -> String {
|
||||||
"[".to_string()
|
"[".to_string()
|
||||||
+ &chars
|
+ &chars
|
||||||
.iter()
|
.iter()
|
||||||
.map(|c| format!("'{}'", c.escape_unicode()))
|
.map(|c| format!("'{}'", c.escape_unicode()))
|
||||||
.join(", ")
|
.join(", ")
|
||||||
+ "]"
|
+ "]"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,34 @@
|
|||||||
use crate::misc::Offset;
|
use crate::misc::Offset;
|
||||||
use egui::{Id, InnerResponse};
|
use egui::{Button, Id, InnerResponse, Ui};
|
||||||
|
use std::ops::BitXorAssign;
|
||||||
|
|
||||||
/// Creates an area ontop of a widget with an y offset
|
/// Creates an area ontop of a widget with an y offset
|
||||||
pub fn widgets_ontop<R>(
|
pub fn widgets_ontop<R>(
|
||||||
ui: &egui::Ui, id: Id, re: &egui::Response, y_offset: f32,
|
ui: &egui::Ui,
|
||||||
add_contents: impl FnOnce(&mut egui::Ui) -> R,
|
id: Id,
|
||||||
|
re: &egui::Response,
|
||||||
|
y_offset: f32,
|
||||||
|
add_contents: impl FnOnce(&mut egui::Ui) -> R,
|
||||||
) -> InnerResponse<R> {
|
) -> InnerResponse<R> {
|
||||||
let area = egui::Area::new(id)
|
let area = egui::Area::new(id)
|
||||||
.fixed_pos(re.rect.min.offset_y(y_offset))
|
.fixed_pos(re.rect.min.offset_y(y_offset))
|
||||||
.order(egui::Order::Foreground);
|
.order(egui::Order::Foreground);
|
||||||
|
|
||||||
area.show(ui.ctx(), |ui| add_contents(ui))
|
area.show(ui.ctx(), |ui| add_contents(ui))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A toggle button that XORs its state when clicked.
|
||||||
|
/// Shows different hover text based on current state.
|
||||||
|
pub fn toggle_button(
|
||||||
|
ui: &mut Ui,
|
||||||
|
state: &mut bool,
|
||||||
|
label: &str,
|
||||||
|
enabled_tip: &str,
|
||||||
|
disabled_tip: &str,
|
||||||
|
) {
|
||||||
|
state.bitxor_assign(
|
||||||
|
ui.add(Button::new(label))
|
||||||
|
.on_hover_text(if *state { enabled_tip } else { disabled_tip })
|
||||||
|
.clicked(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
set -e
|
|
||||||
|
|
||||||
bash build.sh "$1"
|
|
||||||
|
|
||||||
basic-http-server tmp/
|
|
||||||
@@ -1,159 +1,159 @@
|
|||||||
use parsing::{AutoComplete, Hint, Movement};
|
use parsing::{AutoComplete, Hint, Movement};
|
||||||
|
|
||||||
enum Action<'a> {
|
enum Action<'a> {
|
||||||
AssertIndex(usize),
|
AssertIndex(usize),
|
||||||
AssertString(&'a str),
|
AssertString(&'a str),
|
||||||
AssertHint(&'a str),
|
AssertHint(&'a str),
|
||||||
SetString(&'a str),
|
SetString(&'a str),
|
||||||
Move(Movement),
|
Move(Movement),
|
||||||
}
|
}
|
||||||
use Action::*;
|
use Action::*;
|
||||||
|
|
||||||
fn ac_tester(actions: &[Action]) {
|
fn ac_tester(actions: &[Action]) {
|
||||||
let mut ac = AutoComplete::default();
|
let mut ac = AutoComplete::default();
|
||||||
for action in actions.iter() {
|
for action in actions.iter() {
|
||||||
match action {
|
match action {
|
||||||
AssertIndex(target_i) => {
|
AssertIndex(target_i) => {
|
||||||
if &ac.i != target_i {
|
if &ac.i != target_i {
|
||||||
panic!(
|
panic!(
|
||||||
"AssertIndex failed: Current: '{}' Expected: '{}'",
|
"AssertIndex failed: Current: '{}' Expected: '{}'",
|
||||||
ac.i, target_i
|
ac.i, target_i
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
AssertString(target_string) => {
|
AssertString(target_string) => {
|
||||||
if &ac.string != target_string {
|
if &ac.string != target_string {
|
||||||
panic!(
|
panic!(
|
||||||
"AssertString failed: Current: '{}' Expected: '{}'",
|
"AssertString failed: Current: '{}' Expected: '{}'",
|
||||||
ac.string, target_string
|
ac.string, target_string
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
AssertHint(target_hint) => match ac.hint {
|
AssertHint(target_hint) => match ac.hint {
|
||||||
Hint::None => {
|
Hint::None => {
|
||||||
if !target_hint.is_empty() {
|
if !target_hint.is_empty() {
|
||||||
panic!(
|
panic!(
|
||||||
"AssertHint failed on `Hint::None`: Expected: {}",
|
"AssertHint failed on `Hint::None`: Expected: {}",
|
||||||
target_hint
|
target_hint
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Hint::Many(hints) => {
|
Hint::Many(hints) => {
|
||||||
let hint = hints[ac.i];
|
let hint = hints[ac.i];
|
||||||
if &hint != target_hint {
|
if &hint != target_hint {
|
||||||
panic!(
|
panic!(
|
||||||
"AssertHint failed on `Hint::Many`: Current: '{}' (index: {}) Expected: '{}'",
|
"AssertHint failed on `Hint::Many`: Current: '{}' (index: {}) Expected: '{}'",
|
||||||
hint, ac.i, target_hint
|
hint, ac.i, target_hint
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Hint::Single(hint) => {
|
Hint::Single(hint) => {
|
||||||
if hint != target_hint {
|
if hint != target_hint {
|
||||||
panic!(
|
panic!(
|
||||||
"AssertHint failed on `Hint::Single`: Current: '{}' Expected: '{}'",
|
"AssertHint failed on `Hint::Single`: Current: '{}' Expected: '{}'",
|
||||||
hint, target_hint
|
hint, target_hint
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
SetString(target_string) => {
|
SetString(target_string) => {
|
||||||
ac.update_string(target_string);
|
ac.update_string(target_string);
|
||||||
}
|
}
|
||||||
Move(target_movement) => {
|
Move(target_movement) => {
|
||||||
ac.register_movement(target_movement);
|
ac.register_movement(target_movement);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn single() {
|
fn single() {
|
||||||
ac_tester(&[
|
ac_tester(&[
|
||||||
SetString(""),
|
SetString(""),
|
||||||
AssertHint("x^2"),
|
AssertHint("x^2"),
|
||||||
Move(Movement::Up),
|
Move(Movement::Up),
|
||||||
AssertIndex(0),
|
AssertIndex(0),
|
||||||
AssertString(""),
|
AssertString(""),
|
||||||
AssertHint("x^2"),
|
AssertHint("x^2"),
|
||||||
Move(Movement::Down),
|
Move(Movement::Down),
|
||||||
AssertIndex(0),
|
AssertIndex(0),
|
||||||
AssertString(""),
|
AssertString(""),
|
||||||
AssertHint("x^2"),
|
AssertHint("x^2"),
|
||||||
Move(Movement::Complete),
|
Move(Movement::Complete),
|
||||||
AssertString("x^2"),
|
AssertString("x^2"),
|
||||||
AssertHint(""),
|
AssertHint(""),
|
||||||
AssertIndex(0),
|
AssertIndex(0),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn multi() {
|
fn multi() {
|
||||||
ac_tester(&[
|
ac_tester(&[
|
||||||
SetString("s"),
|
SetString("s"),
|
||||||
AssertHint("in("),
|
AssertHint("in("),
|
||||||
Move(Movement::Up),
|
Move(Movement::Up),
|
||||||
AssertIndex(3),
|
AssertIndex(3),
|
||||||
AssertString("s"),
|
AssertString("s"),
|
||||||
AssertHint("ignum("),
|
AssertHint("ignum("),
|
||||||
Move(Movement::Down),
|
Move(Movement::Down),
|
||||||
AssertIndex(0),
|
AssertIndex(0),
|
||||||
AssertString("s"),
|
AssertString("s"),
|
||||||
AssertHint("in("),
|
AssertHint("in("),
|
||||||
Move(Movement::Down),
|
Move(Movement::Down),
|
||||||
AssertIndex(1),
|
AssertIndex(1),
|
||||||
AssertString("s"),
|
AssertString("s"),
|
||||||
AssertHint("qrt("),
|
AssertHint("qrt("),
|
||||||
Move(Movement::Up),
|
Move(Movement::Up),
|
||||||
AssertIndex(0),
|
AssertIndex(0),
|
||||||
AssertString("s"),
|
AssertString("s"),
|
||||||
AssertHint("in("),
|
AssertHint("in("),
|
||||||
Move(Movement::Complete),
|
Move(Movement::Complete),
|
||||||
AssertString("sin("),
|
AssertString("sin("),
|
||||||
AssertHint(")"),
|
AssertHint(")"),
|
||||||
AssertIndex(0),
|
AssertIndex(0),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn none() {
|
fn none() {
|
||||||
// string that should give no hints
|
// string that should give no hints
|
||||||
let random = "qwert987gybhj";
|
let random = "qwert987gybhj";
|
||||||
assert_eq!(parsing::generate_hint(random), &Hint::None);
|
assert_eq!(parsing::generate_hint(random), &Hint::None);
|
||||||
|
|
||||||
ac_tester(&[
|
ac_tester(&[
|
||||||
SetString(random),
|
SetString(random),
|
||||||
AssertHint(""),
|
AssertHint(""),
|
||||||
Move(Movement::Up),
|
Move(Movement::Up),
|
||||||
AssertIndex(0),
|
AssertIndex(0),
|
||||||
AssertString(random),
|
AssertString(random),
|
||||||
AssertHint(""),
|
AssertHint(""),
|
||||||
Move(Movement::Down),
|
Move(Movement::Down),
|
||||||
AssertIndex(0),
|
AssertIndex(0),
|
||||||
AssertString(random),
|
AssertString(random),
|
||||||
AssertHint(""),
|
AssertHint(""),
|
||||||
Move(Movement::Complete),
|
Move(Movement::Complete),
|
||||||
AssertString(random),
|
AssertString(random),
|
||||||
AssertHint(""),
|
AssertHint(""),
|
||||||
AssertIndex(0),
|
AssertIndex(0),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parens() {
|
fn parens() {
|
||||||
ac_tester(&[
|
ac_tester(&[
|
||||||
SetString("sin(x"),
|
SetString("sin(x"),
|
||||||
AssertHint(")"),
|
AssertHint(")"),
|
||||||
Move(Movement::Up),
|
Move(Movement::Up),
|
||||||
AssertIndex(0),
|
AssertIndex(0),
|
||||||
AssertString("sin(x"),
|
AssertString("sin(x"),
|
||||||
AssertHint(")"),
|
AssertHint(")"),
|
||||||
Move(Movement::Down),
|
Move(Movement::Down),
|
||||||
AssertIndex(0),
|
AssertIndex(0),
|
||||||
AssertString("sin(x"),
|
AssertString("sin(x"),
|
||||||
AssertHint(")"),
|
AssertHint(")"),
|
||||||
Move(Movement::Complete),
|
Move(Movement::Complete),
|
||||||
AssertString("sin(x)"),
|
AssertString("sin(x)"),
|
||||||
AssertHint(""),
|
AssertHint(""),
|
||||||
AssertIndex(0),
|
AssertIndex(0),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,262 +1,530 @@
|
|||||||
use ytbn_graphing_software::{AppSettings, EguiHelper, FunctionEntry, Riemann};
|
use ytbn_graphing_software::{AppSettings, EguiHelper, FunctionEntry, Riemann};
|
||||||
|
|
||||||
fn app_settings_constructor(
|
fn app_settings_constructor(
|
||||||
sum: Riemann, integral_min_x: f64, integral_max_x: f64, pixel_width: usize,
|
sum: Riemann,
|
||||||
integral_num: usize, min_x: f64, max_x: f64,
|
integral_min_x: f64,
|
||||||
|
integral_max_x: f64,
|
||||||
|
pixel_width: usize,
|
||||||
|
integral_num: usize,
|
||||||
|
min_x: f64,
|
||||||
|
max_x: f64,
|
||||||
) -> AppSettings {
|
) -> AppSettings {
|
||||||
AppSettings {
|
AppSettings {
|
||||||
riemann_sum: sum,
|
riemann_sum: sum,
|
||||||
integral_min_x,
|
integral_min_x,
|
||||||
integral_max_x,
|
integral_max_x,
|
||||||
min_x,
|
min_x,
|
||||||
max_x,
|
max_x,
|
||||||
integral_changed: true,
|
integral_changed: true,
|
||||||
integral_num,
|
integral_num,
|
||||||
do_extrema: false,
|
do_extrema: false,
|
||||||
do_roots: false,
|
do_roots: false,
|
||||||
plot_width: pixel_width,
|
plot_width: pixel_width,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static BACK_TARGET: [(f64, f64); 11] = [
|
static BACK_TARGET: [(f64, f64); 11] = [
|
||||||
(-1.0, 1.0),
|
(-1.0, 1.0),
|
||||||
(-0.8, 0.6400000000000001),
|
(-0.8, 0.6400000000000001),
|
||||||
(-0.6, 0.36),
|
(-0.6, 0.36),
|
||||||
(-0.4, 0.16000000000000003),
|
(-0.4, 0.16000000000000003),
|
||||||
(-0.19999999999999996, 0.03999999999999998),
|
(-0.19999999999999996, 0.03999999999999998),
|
||||||
(0.0, 0.0),
|
(0.0, 0.0),
|
||||||
(0.19999999999999996, 0.03999999999999998),
|
(0.19999999999999996, 0.03999999999999998),
|
||||||
(0.3999999999999999, 0.15999999999999992),
|
(0.3999999999999999, 0.15999999999999992),
|
||||||
(0.6000000000000001, 0.3600000000000001),
|
(0.6000000000000001, 0.3600000000000001),
|
||||||
(0.8, 0.6400000000000001),
|
(0.8, 0.6400000000000001),
|
||||||
(1.0, 1.0),
|
(1.0, 1.0),
|
||||||
];
|
];
|
||||||
|
|
||||||
static DERIVATIVE_TARGET: [(f64, f64); 11] = [
|
static DERIVATIVE_TARGET: [(f64, f64); 11] = [
|
||||||
(-1.0, -2.0),
|
(-1.0, -2.0),
|
||||||
(-0.8, -1.6),
|
(-0.8, -1.6),
|
||||||
(-0.6, -1.2),
|
(-0.6, -1.2),
|
||||||
(-0.4, -0.8),
|
(-0.4, -0.8),
|
||||||
(-0.19999999999999996, -0.3999999999999999),
|
(-0.19999999999999996, -0.3999999999999999),
|
||||||
(0.0, 0.0),
|
(0.0, 0.0),
|
||||||
(0.19999999999999996, 0.3999999999999999),
|
(0.19999999999999996, 0.3999999999999999),
|
||||||
(0.3999999999999999, 0.7999999999999998),
|
(0.3999999999999999, 0.7999999999999998),
|
||||||
(0.6000000000000001, 1.2000000000000002),
|
(0.6000000000000001, 1.2000000000000002),
|
||||||
(0.8, 1.6),
|
(0.8, 1.6),
|
||||||
(1.0, 2.0),
|
(1.0, 2.0),
|
||||||
];
|
];
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
fn do_test(sum: Riemann, area_target: f64) {
|
fn do_test(sum: Riemann, area_target: f64) {
|
||||||
let settings = app_settings_constructor(sum, -1.0, 1.0, 10, 10, -1.0, 1.0);
|
let settings = app_settings_constructor(sum, -1.0, 1.0, 10, 10, -1.0, 1.0);
|
||||||
|
|
||||||
let mut function = FunctionEntry::default();
|
let mut function = FunctionEntry::default();
|
||||||
function.update_string("x^2");
|
function.update_string("x^2");
|
||||||
function.integral = true;
|
function.integral = true;
|
||||||
function.derivative = true;
|
function.derivative = true;
|
||||||
|
|
||||||
let mut settings = settings;
|
let mut settings = settings;
|
||||||
{
|
{
|
||||||
function.calculate(true, true, false, settings);
|
function.calculate(true, true, false, settings);
|
||||||
assert!(!function.back_data.is_empty());
|
assert!(!function.back_data.is_empty());
|
||||||
assert_eq!(function.back_data.len(), settings.plot_width + 1);
|
assert_eq!(function.back_data.len(), settings.plot_width + 1);
|
||||||
|
|
||||||
assert!(function.integral);
|
assert!(function.integral);
|
||||||
assert!(function.derivative);
|
assert!(function.derivative);
|
||||||
|
|
||||||
assert_eq!(!function.root_data.is_empty(), settings.do_roots);
|
assert_eq!(!function.root_data.is_empty(), settings.do_roots);
|
||||||
assert_eq!(!function.extrema_data.is_empty(), settings.do_extrema);
|
assert_eq!(!function.extrema_data.is_empty(), settings.do_extrema);
|
||||||
assert!(!function.derivative_data.is_empty());
|
assert!(!function.derivative_data.is_empty());
|
||||||
assert!(function.integral_data.is_some());
|
assert!(function.integral_data.is_some());
|
||||||
|
|
||||||
assert_eq!(function.integral_data.clone().unwrap().1, area_target);
|
assert_eq!(function.integral_data.clone().unwrap().1, area_target);
|
||||||
|
|
||||||
let a = function.derivative_data.clone().to_tuple();
|
let a = function.derivative_data.clone().to_tuple();
|
||||||
|
|
||||||
assert_eq!(a.len(), DERIVATIVE_TARGET.len());
|
assert_eq!(a.len(), DERIVATIVE_TARGET.len());
|
||||||
|
|
||||||
for i in 0..a.len() {
|
for i in 0..a.len() {
|
||||||
if !emath::almost_equal(a[i].0 as f32, DERIVATIVE_TARGET[i].0 as f32, f32::EPSILON)
|
if !emath::almost_equal(a[i].0 as f32, DERIVATIVE_TARGET[i].0 as f32, f32::EPSILON)
|
||||||
| !emath::almost_equal(a[i].1 as f32, DERIVATIVE_TARGET[i].1 as f32, f32::EPSILON)
|
| !emath::almost_equal(a[i].1 as f32, DERIVATIVE_TARGET[i].1 as f32, f32::EPSILON)
|
||||||
{
|
{
|
||||||
panic!("Expected: {:?}\nGot: {:?}", a, DERIVATIVE_TARGET);
|
panic!("Expected: {:?}\nGot: {:?}", DERIVATIVE_TARGET, a);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let a_1 = function.back_data.clone().to_tuple();
|
let a_1 = function.back_data.clone().to_tuple();
|
||||||
|
|
||||||
assert_eq!(a_1.len(), BACK_TARGET.len());
|
assert_eq!(a_1.len(), BACK_TARGET.len());
|
||||||
|
|
||||||
assert_eq!(a.len(), BACK_TARGET.len());
|
assert_eq!(a.len(), BACK_TARGET.len());
|
||||||
|
|
||||||
for i in 0..a.len() {
|
for i in 0..a.len() {
|
||||||
if !emath::almost_equal(a_1[i].0 as f32, BACK_TARGET[i].0 as f32, f32::EPSILON)
|
if !emath::almost_equal(a_1[i].0 as f32, BACK_TARGET[i].0 as f32, f32::EPSILON)
|
||||||
| !emath::almost_equal(a_1[i].1 as f32, BACK_TARGET[i].1 as f32, f32::EPSILON)
|
| !emath::almost_equal(a_1[i].1 as f32, BACK_TARGET[i].1 as f32, f32::EPSILON)
|
||||||
{
|
{
|
||||||
panic!("Expected: {:?}\nGot: {:?}", a_1, BACK_TARGET);
|
panic!("Expected: {:?}\nGot: {:?}", BACK_TARGET, a_1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
settings.min_x += 1.0;
|
settings.min_x += 1.0;
|
||||||
settings.max_x += 1.0;
|
settings.max_x += 1.0;
|
||||||
function.calculate(true, true, false, settings);
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
let a = function
|
let a = function
|
||||||
.derivative_data
|
.derivative_data
|
||||||
.clone()
|
.clone()
|
||||||
.to_tuple()
|
.to_tuple()
|
||||||
.iter()
|
.iter()
|
||||||
.take(6)
|
.take(6)
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect::<Vec<(f64, f64)>>();
|
.collect::<Vec<(f64, f64)>>();
|
||||||
|
|
||||||
let b = DERIVATIVE_TARGET
|
let b = DERIVATIVE_TARGET
|
||||||
.iter()
|
.iter()
|
||||||
.rev()
|
.rev()
|
||||||
.take(6)
|
.take(6)
|
||||||
.rev()
|
.rev()
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect::<Vec<(f64, f64)>>();
|
.collect::<Vec<(f64, f64)>>();
|
||||||
|
|
||||||
assert_eq!(a.len(), b.len());
|
assert_eq!(a.len(), b.len());
|
||||||
|
|
||||||
for i in 0..a.len() {
|
for i in 0..a.len() {
|
||||||
if !emath::almost_equal(a[i].0 as f32, b[i].0 as f32, f32::EPSILON)
|
if !emath::almost_equal(a[i].0 as f32, b[i].0 as f32, f32::EPSILON)
|
||||||
| !emath::almost_equal(a[i].1 as f32, b[i].1 as f32, f32::EPSILON)
|
| !emath::almost_equal(a[i].1 as f32, b[i].1 as f32, f32::EPSILON)
|
||||||
{
|
{
|
||||||
panic!("Expected: {:?}\nGot: {:?}", a, b);
|
panic!("Expected: {:?}\nGot: {:?}", b, a);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let a_1 = function
|
let a_1 = function
|
||||||
.back_data
|
.back_data
|
||||||
.clone()
|
.clone()
|
||||||
.to_tuple()
|
.to_tuple()
|
||||||
.iter()
|
.iter()
|
||||||
.take(6)
|
.take(6)
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect::<Vec<(f64, f64)>>();
|
.collect::<Vec<(f64, f64)>>();
|
||||||
|
|
||||||
let b_1 = BACK_TARGET
|
let b_1 = BACK_TARGET
|
||||||
.iter()
|
.iter()
|
||||||
.rev()
|
.rev()
|
||||||
.take(6)
|
.take(6)
|
||||||
.rev()
|
.rev()
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect::<Vec<(f64, f64)>>();
|
.collect::<Vec<(f64, f64)>>();
|
||||||
|
|
||||||
assert_eq!(a_1.len(), b_1.len());
|
assert_eq!(a_1.len(), b_1.len());
|
||||||
|
|
||||||
assert_eq!(a.len(), b_1.len());
|
assert_eq!(a.len(), b_1.len());
|
||||||
|
|
||||||
for i in 0..a.len() {
|
for i in 0..a.len() {
|
||||||
if !emath::almost_equal(a_1[i].0 as f32, b_1[i].0 as f32, f32::EPSILON)
|
if !emath::almost_equal(a_1[i].0 as f32, b_1[i].0 as f32, f32::EPSILON)
|
||||||
| !emath::almost_equal(a_1[i].1 as f32, b_1[i].1 as f32, f32::EPSILON)
|
| !emath::almost_equal(a_1[i].1 as f32, b_1[i].1 as f32, f32::EPSILON)
|
||||||
{
|
{
|
||||||
panic!("Expected: {:?}\nGot: {:?}", a_1, b_1);
|
panic!("Expected: {:?}\nGot: {:?}", b_1, a_1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
settings.min_x -= 2.0;
|
settings.min_x -= 2.0;
|
||||||
settings.max_x -= 2.0;
|
settings.max_x -= 2.0;
|
||||||
function.calculate(true, true, false, settings);
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
let a = function
|
let a = function
|
||||||
.derivative_data
|
.derivative_data
|
||||||
.clone()
|
.clone()
|
||||||
.to_tuple()
|
.to_tuple()
|
||||||
.iter()
|
.iter()
|
||||||
.rev()
|
.rev()
|
||||||
.take(6)
|
.take(6)
|
||||||
.rev()
|
.rev()
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect::<Vec<(f64, f64)>>();
|
.collect::<Vec<(f64, f64)>>();
|
||||||
|
|
||||||
let b = DERIVATIVE_TARGET
|
let b = DERIVATIVE_TARGET
|
||||||
.iter()
|
.iter()
|
||||||
.take(6)
|
.take(6)
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect::<Vec<(f64, f64)>>();
|
.collect::<Vec<(f64, f64)>>();
|
||||||
|
|
||||||
assert_eq!(a.len(), b.len());
|
assert_eq!(a.len(), b.len());
|
||||||
|
|
||||||
for i in 0..a.len() {
|
for i in 0..a.len() {
|
||||||
if !emath::almost_equal(a[i].0 as f32, b[i].0 as f32, f32::EPSILON)
|
if !emath::almost_equal(a[i].0 as f32, b[i].0 as f32, f32::EPSILON)
|
||||||
| !emath::almost_equal(a[i].1 as f32, b[i].1 as f32, f32::EPSILON)
|
| !emath::almost_equal(a[i].1 as f32, b[i].1 as f32, f32::EPSILON)
|
||||||
{
|
{
|
||||||
panic!("Expected: {:?}\nGot: {:?}", a, b);
|
panic!("Expected: {:?}\nGot: {:?}", b, a);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let a_1 = function
|
let a_1 = function
|
||||||
.back_data
|
.back_data
|
||||||
.clone()
|
.clone()
|
||||||
.to_tuple()
|
.to_tuple()
|
||||||
.iter()
|
.iter()
|
||||||
.rev()
|
.rev()
|
||||||
.take(6)
|
.take(6)
|
||||||
.rev()
|
.rev()
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect::<Vec<(f64, f64)>>();
|
.collect::<Vec<(f64, f64)>>();
|
||||||
|
|
||||||
let b_1 = BACK_TARGET
|
let b_1 = BACK_TARGET
|
||||||
.iter()
|
.iter()
|
||||||
.take(6)
|
.take(6)
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect::<Vec<(f64, f64)>>();
|
.collect::<Vec<(f64, f64)>>();
|
||||||
|
|
||||||
assert_eq!(a_1.len(), b_1.len());
|
assert_eq!(a_1.len(), b_1.len());
|
||||||
|
|
||||||
assert_eq!(a.len(), b_1.len());
|
assert_eq!(a.len(), b_1.len());
|
||||||
|
|
||||||
for i in 0..a.len() {
|
for i in 0..a.len() {
|
||||||
if !emath::almost_equal(a_1[i].0 as f32, b_1[i].0 as f32, f32::EPSILON)
|
if !emath::almost_equal(a_1[i].0 as f32, b_1[i].0 as f32, f32::EPSILON)
|
||||||
| !emath::almost_equal(a_1[i].1 as f32, b_1[i].1 as f32, f32::EPSILON)
|
| !emath::almost_equal(a_1[i].1 as f32, b_1[i].1 as f32, f32::EPSILON)
|
||||||
{
|
{
|
||||||
panic!("Expected: {:?}\nGot: {:?}", a_1, b_1);
|
panic!("Expected: {:?}\nGot: {:?}", b_1, a_1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
function.update_string("sin(x)");
|
function.update_string("sin(x)");
|
||||||
assert!(function.get_test_result().is_none());
|
assert!(function.get_test_result().is_none());
|
||||||
assert_eq!(&function.raw_func_str, "sin(x)");
|
assert_eq!(function.func_str(), "sin(x)");
|
||||||
|
|
||||||
function.integral = false;
|
function.integral = false;
|
||||||
function.derivative = false;
|
function.derivative = false;
|
||||||
|
|
||||||
assert!(!function.integral);
|
assert!(!function.integral);
|
||||||
assert!(!function.derivative);
|
assert!(!function.derivative);
|
||||||
|
|
||||||
assert!(function.back_data.is_empty());
|
assert!(function.back_data.is_empty());
|
||||||
assert!(function.integral_data.is_none());
|
assert!(function.integral_data.is_none());
|
||||||
assert!(function.root_data.is_empty());
|
assert!(function.root_data.is_empty());
|
||||||
assert!(function.extrema_data.is_empty());
|
assert!(function.extrema_data.is_empty());
|
||||||
assert!(function.derivative_data.is_empty());
|
assert!(function.derivative_data.is_empty());
|
||||||
|
|
||||||
settings.min_x -= 1.0;
|
settings.min_x -= 1.0;
|
||||||
settings.max_x -= 1.0;
|
settings.max_x -= 1.0;
|
||||||
|
|
||||||
function.calculate(true, true, false, settings);
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
assert!(!function.back_data.is_empty());
|
assert!(!function.back_data.is_empty());
|
||||||
assert!(function.integral_data.is_none());
|
assert!(function.integral_data.is_none());
|
||||||
assert!(function.root_data.is_empty());
|
assert!(function.root_data.is_empty());
|
||||||
assert!(function.extrema_data.is_empty());
|
assert!(function.extrema_data.is_empty());
|
||||||
assert!(!function.derivative_data.is_empty());
|
assert!(!function.derivative_data.is_empty());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn left_function() { do_test(Riemann::Left, 0.9600000000000001); }
|
fn left_function() {
|
||||||
|
do_test(Riemann::Left, 0.9600000000000001);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn middle_function() { do_test(Riemann::Middle, 0.92); }
|
fn middle_function() {
|
||||||
|
do_test(Riemann::Middle, 0.92);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn right_function() { do_test(Riemann::Right, 0.8800000000000001); }
|
fn right_function() {
|
||||||
|
do_test(Riemann::Right, 0.8800000000000001);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_extrema() {
|
||||||
|
let mut settings = app_settings_constructor(Riemann::Middle, -2.0, 2.0, 100, 100, -2.0, 2.0);
|
||||||
|
settings.do_extrema = true;
|
||||||
|
|
||||||
|
let mut function = FunctionEntry::default();
|
||||||
|
function.update_string("x^2 - 4"); // Parabola with vertex at (0, -4)
|
||||||
|
function.integral = false;
|
||||||
|
function.derivative = false;
|
||||||
|
|
||||||
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
|
// For f(x) = x^2 - 4, f'(x) = 2x
|
||||||
|
// Extrema occurs where f'(x) = 0, so at x = 0
|
||||||
|
assert!(!function.extrema_data.is_empty());
|
||||||
|
|
||||||
|
// Should have exactly one extremum at x = 0
|
||||||
|
assert_eq!(function.extrema_data.len(), 1);
|
||||||
|
|
||||||
|
let extremum = function.extrema_data[0];
|
||||||
|
assert!(emath::almost_equal(extremum.x as f32, 0.0, f32::EPSILON));
|
||||||
|
assert!(emath::almost_equal(extremum.y as f32, -4.0, f32::EPSILON));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_extrema_multiple() {
|
||||||
|
let mut settings = app_settings_constructor(Riemann::Middle, -3.0, 3.0, 200, 200, -3.0, 3.0);
|
||||||
|
settings.do_extrema = true;
|
||||||
|
|
||||||
|
let mut function = FunctionEntry::default();
|
||||||
|
function.update_string("x^3 - 3*x"); // Cubic with local max and min
|
||||||
|
function.integral = false;
|
||||||
|
function.derivative = false;
|
||||||
|
|
||||||
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
|
// For f(x) = x^3 - 3x, f'(x) = 3x^2 - 3
|
||||||
|
// Extrema occur where f'(x) = 0, so at x = ±1
|
||||||
|
assert!(!function.extrema_data.is_empty());
|
||||||
|
|
||||||
|
// Should have exactly two extrema
|
||||||
|
assert_eq!(function.extrema_data.len(), 2);
|
||||||
|
|
||||||
|
// Sort by x coordinate for consistent testing
|
||||||
|
let mut extrema = function.extrema_data.clone();
|
||||||
|
extrema.sort_by(|a, b| a.x.partial_cmp(&b.x).unwrap());
|
||||||
|
|
||||||
|
// First extremum at x = -1, f(-1) = -1 + 3 = 2
|
||||||
|
assert!(emath::almost_equal(extrema[0].x as f32, -1.0, 0.01));
|
||||||
|
assert!(emath::almost_equal(extrema[0].y as f32, 2.0, 0.01));
|
||||||
|
|
||||||
|
// Second extremum at x = 1, f(1) = 1 - 3 = -2
|
||||||
|
assert!(emath::almost_equal(extrema[1].x as f32, 1.0, 0.01));
|
||||||
|
assert!(emath::almost_equal(extrema[1].y as f32, -2.0, 0.01));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_extrema_disabled() {
|
||||||
|
let mut settings = app_settings_constructor(Riemann::Middle, -2.0, 2.0, 100, 100, -2.0, 2.0);
|
||||||
|
settings.do_extrema = false; // Disable extrema
|
||||||
|
|
||||||
|
let mut function = FunctionEntry::default();
|
||||||
|
function.update_string("x^2 - 4");
|
||||||
|
function.integral = false;
|
||||||
|
function.derivative = false;
|
||||||
|
|
||||||
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
|
// Extrema data should be empty when disabled
|
||||||
|
assert!(function.extrema_data.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_roots() {
|
||||||
|
let mut settings = app_settings_constructor(Riemann::Middle, -3.0, 3.0, 200, 200, -3.0, 3.0);
|
||||||
|
settings.do_roots = true;
|
||||||
|
|
||||||
|
let mut function = FunctionEntry::default();
|
||||||
|
function.update_string("x^2 - 4"); // Parabola crossing x-axis at ±2
|
||||||
|
function.integral = false;
|
||||||
|
function.derivative = false;
|
||||||
|
|
||||||
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
|
// For f(x) = x^2 - 4, roots occur where x^2 = 4, so at x = ±2
|
||||||
|
assert!(!function.root_data.is_empty());
|
||||||
|
|
||||||
|
// Should have exactly two roots
|
||||||
|
assert_eq!(function.root_data.len(), 2);
|
||||||
|
|
||||||
|
// Sort by x coordinate for consistent testing
|
||||||
|
let mut roots = function.root_data.clone();
|
||||||
|
roots.sort_by(|a, b| a.x.partial_cmp(&b.x).unwrap());
|
||||||
|
|
||||||
|
// First root at x = -2
|
||||||
|
assert!(emath::almost_equal(roots[0].x as f32, -2.0, 0.01));
|
||||||
|
assert!(emath::almost_equal(roots[0].y as f32, 0.0, 0.001));
|
||||||
|
|
||||||
|
// Second root at x = 2
|
||||||
|
assert!(emath::almost_equal(roots[1].x as f32, 2.0, 0.01));
|
||||||
|
assert!(emath::almost_equal(roots[1].y as f32, 0.0, 0.001));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_roots_single() {
|
||||||
|
let mut settings = app_settings_constructor(Riemann::Middle, -2.0, 2.0, 100, 100, -2.0, 2.0);
|
||||||
|
settings.do_roots = true;
|
||||||
|
|
||||||
|
let mut function = FunctionEntry::default();
|
||||||
|
function.update_string("x - 1"); // Linear function crossing x-axis at x = 1
|
||||||
|
function.integral = false;
|
||||||
|
function.derivative = false;
|
||||||
|
|
||||||
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
|
// For f(x) = x - 1, root occurs at x = 1
|
||||||
|
assert!(!function.root_data.is_empty());
|
||||||
|
|
||||||
|
// Should have exactly one root
|
||||||
|
assert_eq!(function.root_data.len(), 1);
|
||||||
|
|
||||||
|
let root = function.root_data[0];
|
||||||
|
assert!(emath::almost_equal(root.x as f32, 1.0, 0.01));
|
||||||
|
assert!(emath::almost_equal(root.y as f32, 0.0, f32::EPSILON));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_roots_disabled() {
|
||||||
|
let mut settings = app_settings_constructor(Riemann::Middle, -3.0, 3.0, 200, 200, -3.0, 3.0);
|
||||||
|
settings.do_roots = false; // Disable roots
|
||||||
|
|
||||||
|
let mut function = FunctionEntry::default();
|
||||||
|
function.update_string("x^2 - 4");
|
||||||
|
function.integral = false;
|
||||||
|
function.derivative = false;
|
||||||
|
|
||||||
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
|
// Root data should be empty when disabled
|
||||||
|
assert!(function.root_data.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_extrema_and_roots_together() {
|
||||||
|
let mut settings = app_settings_constructor(Riemann::Middle, -3.0, 3.0, 200, 200, -3.0, 3.0);
|
||||||
|
settings.do_extrema = true;
|
||||||
|
settings.do_roots = true;
|
||||||
|
|
||||||
|
let mut function = FunctionEntry::default();
|
||||||
|
function.update_string("x^2 - 1"); // Parabola with vertex at (0, -1) and roots at ±1
|
||||||
|
function.integral = false;
|
||||||
|
function.derivative = false;
|
||||||
|
|
||||||
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
|
// Should have one extremum at x = 0
|
||||||
|
assert!(!function.extrema_data.is_empty());
|
||||||
|
assert_eq!(function.extrema_data.len(), 1);
|
||||||
|
let extremum = function.extrema_data[0];
|
||||||
|
assert!(emath::almost_equal(extremum.x as f32, 0.0, 0.01));
|
||||||
|
assert!(emath::almost_equal(extremum.y as f32, -1.0, 0.01));
|
||||||
|
|
||||||
|
// Should have two roots at x = ±1
|
||||||
|
assert!(!function.root_data.is_empty());
|
||||||
|
assert_eq!(function.root_data.len(), 2);
|
||||||
|
|
||||||
|
let mut roots = function.root_data.clone();
|
||||||
|
roots.sort_by(|a, b| a.x.partial_cmp(&b.x).unwrap());
|
||||||
|
|
||||||
|
assert!(emath::almost_equal(roots[0].x as f32, -1.0, 0.01));
|
||||||
|
assert!(emath::almost_equal(roots[1].x as f32, 1.0, 0.01));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_extrema_no_extrema() {
|
||||||
|
let mut settings = app_settings_constructor(Riemann::Middle, -2.0, 2.0, 100, 100, -2.0, 2.0);
|
||||||
|
settings.do_extrema = true;
|
||||||
|
|
||||||
|
let mut function = FunctionEntry::default();
|
||||||
|
function.update_string("x"); // Linear function has no extrema
|
||||||
|
function.integral = false;
|
||||||
|
function.derivative = false;
|
||||||
|
|
||||||
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
|
// Linear function should have no extrema
|
||||||
|
assert!(function.extrema_data.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_roots_no_roots() {
|
||||||
|
let mut settings = app_settings_constructor(Riemann::Middle, -2.0, 2.0, 100, 100, -2.0, 2.0);
|
||||||
|
settings.do_roots = true;
|
||||||
|
|
||||||
|
let mut function = FunctionEntry::default();
|
||||||
|
function.update_string("x^2 + 1"); // Parabola that never crosses x-axis
|
||||||
|
function.integral = false;
|
||||||
|
function.derivative = false;
|
||||||
|
|
||||||
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
|
// Function that never crosses x-axis should have no roots
|
||||||
|
assert!(function.root_data.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_extrema_and_roots_with_trig() {
|
||||||
|
let mut settings = app_settings_constructor(Riemann::Middle, -4.0, 4.0, 300, 300, -4.0, 4.0);
|
||||||
|
settings.do_extrema = true;
|
||||||
|
settings.do_roots = true;
|
||||||
|
|
||||||
|
let mut function = FunctionEntry::default();
|
||||||
|
function.update_string("sin(x)"); // Sine function has extrema at odd multiples of π/2
|
||||||
|
function.integral = false;
|
||||||
|
function.derivative = false;
|
||||||
|
|
||||||
|
function.calculate(true, true, false, settings);
|
||||||
|
|
||||||
|
// Sine function should have extrema in the given range
|
||||||
|
assert!(!function.extrema_data.is_empty());
|
||||||
|
|
||||||
|
// Should have multiple extrema (local max/min)
|
||||||
|
assert!(function.extrema_data.len() >= 2);
|
||||||
|
|
||||||
|
// Check that extrema are at approximately the right locations
|
||||||
|
// Local max at π/2 ≈ 1.57, local min at 3π/2 ≈ 4.71 (outside range)
|
||||||
|
// Local min at -π/2 ≈ -1.57, local max at -3π/2 ≈ -4.71 (outside range)
|
||||||
|
let extrema_x: Vec<f32> = function.extrema_data.iter().map(|p| p.x as f32).collect();
|
||||||
|
|
||||||
|
// Should have extrema near ±π/2
|
||||||
|
assert!(
|
||||||
|
extrema_x
|
||||||
|
.iter()
|
||||||
|
.any(|&x| emath::almost_equal(x, std::f32::consts::PI / 2.0, 0.1))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
extrema_x
|
||||||
|
.iter()
|
||||||
|
.any(|&x| emath::almost_equal(x, -std::f32::consts::PI / 2.0, 0.1))
|
||||||
|
);
|
||||||
|
|
||||||
|
let roots_x: Vec<f32> = function.root_data.iter().map(|p| p.x as f32).collect();
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
roots_x
|
||||||
|
.iter()
|
||||||
|
.any(|&x| emath::almost_equal(x, std::f32::consts::PI, 0.1))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
roots_x
|
||||||
|
.iter()
|
||||||
|
.any(|&x| emath::almost_equal(x, -std::f32::consts::PI, 0.1))
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(roots_x.iter().any(|&x| emath::almost_equal(x, 0.0, 0.1)));
|
||||||
|
}
|
||||||
|
|||||||
164
tests/misc.rs
164
tests/misc.rs
@@ -2,90 +2,62 @@
|
|||||||
/// Ensures [`decimal_round`] returns correct values
|
/// Ensures [`decimal_round`] returns correct values
|
||||||
#[test]
|
#[test]
|
||||||
fn decimal_round() {
|
fn decimal_round() {
|
||||||
use ytbn_graphing_software::decimal_round;
|
use ytbn_graphing_software::decimal_round;
|
||||||
|
|
||||||
assert_eq!(decimal_round(0.00001, 1), 0.0);
|
assert_eq!(decimal_round(0.00001, 1), 0.0);
|
||||||
assert_eq!(decimal_round(0.00001, 2), 0.0);
|
assert_eq!(decimal_round(0.00001, 2), 0.0);
|
||||||
assert_eq!(decimal_round(0.00001, 3), 0.0);
|
assert_eq!(decimal_round(0.00001, 3), 0.0);
|
||||||
assert_eq!(decimal_round(0.00001, 4), 0.0);
|
assert_eq!(decimal_round(0.00001, 4), 0.0);
|
||||||
assert_eq!(decimal_round(0.00001, 5), 0.00001);
|
assert_eq!(decimal_round(0.00001, 5), 0.00001);
|
||||||
|
|
||||||
assert_eq!(decimal_round(0.12345, 1), 0.1);
|
assert_eq!(decimal_round(0.12345, 1), 0.1);
|
||||||
assert_eq!(decimal_round(0.12345, 2), 0.12);
|
assert_eq!(decimal_round(0.12345, 2), 0.12);
|
||||||
assert_eq!(decimal_round(0.12345, 3), 0.123);
|
assert_eq!(decimal_round(0.12345, 3), 0.123);
|
||||||
assert_eq!(decimal_round(0.12345, 4), 0.1235); // rounds up
|
assert_eq!(decimal_round(0.12345, 4), 0.1235); // rounds up
|
||||||
assert_eq!(decimal_round(0.12345, 5), 0.12345);
|
assert_eq!(decimal_round(0.12345, 5), 0.12345);
|
||||||
|
|
||||||
assert_eq!(decimal_round(1.9, 0), 2.0);
|
assert_eq!(decimal_round(1.9, 0), 2.0);
|
||||||
assert_eq!(decimal_round(1.9, 1), 1.9);
|
assert_eq!(decimal_round(1.9, 1), 1.9);
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn step_helper() {
|
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]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tests [`option_vec_printer`]
|
/// Tests [`option_vec_printer`]
|
||||||
#[test]
|
#[test]
|
||||||
fn option_vec_printer() {
|
fn option_vec_printer() {
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use ytbn_graphing_software::option_vec_printer;
|
use ytbn_graphing_software::option_vec_printer;
|
||||||
|
|
||||||
let values_strings: HashMap<Vec<Option<&str>>, &str> = HashMap::from([
|
let values_strings: HashMap<Vec<Option<&str>>, &str> = HashMap::from([
|
||||||
(vec![None], "[None]"),
|
(vec![None], "[None]"),
|
||||||
(vec![Some("text"), None], "[text, None]"),
|
(vec![Some("text"), None], "[text, None]"),
|
||||||
(vec![None, None], "[None, None]"),
|
(vec![None, None], "[None, None]"),
|
||||||
(vec![Some("text1"), Some("text2")], "[text1, text2]"),
|
(vec![Some("text1"), Some("text2")], "[text1, text2]"),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
for (key, value) in values_strings {
|
for (key, value) in values_strings {
|
||||||
assert_eq!(option_vec_printer(&key), value);
|
assert_eq!(option_vec_printer(&key), value);
|
||||||
}
|
}
|
||||||
|
|
||||||
let values_nums = HashMap::from([
|
let values_nums = HashMap::from([
|
||||||
(vec![Some(10)], "[10]"),
|
(vec![Some(10)], "[10]"),
|
||||||
(vec![Some(10), None], "[10, None]"),
|
(vec![Some(10), None], "[10, None]"),
|
||||||
(vec![None, Some(10)], "[None, 10]"),
|
(vec![None, Some(10)], "[None, 10]"),
|
||||||
(vec![Some(10), Some(100)], "[10, 100]"),
|
(vec![Some(10), Some(100)], "[10, 100]"),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
for (key, value) in values_nums {
|
for (key, value) in values_nums {
|
||||||
assert_eq!(option_vec_printer(&key), value);
|
assert_eq!(option_vec_printer(&key), value);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn hashed_storage() {
|
|
||||||
use ytbn_graphing_software::{hashed_storage_create, hashed_storage_read};
|
|
||||||
|
|
||||||
let commit = "abcdefeg".chars().map(|c| c as u8).collect::<Vec<u8>>();
|
|
||||||
let data = "really cool data"
|
|
||||||
.chars()
|
|
||||||
.map(|c| c as u8)
|
|
||||||
.collect::<Vec<u8>>();
|
|
||||||
let storage_tmp: [u8; 8] = commit
|
|
||||||
.as_slice()
|
|
||||||
.try_into()
|
|
||||||
.expect("cannot turn into [u8; 8]");
|
|
||||||
let storage = hashed_storage_create(storage_tmp, data.as_slice());
|
|
||||||
|
|
||||||
let read = hashed_storage_read(&storage);
|
|
||||||
assert_eq!(
|
|
||||||
read.map(|(a, b)| (a.to_vec(), b.to_vec())),
|
|
||||||
Some((commit.to_vec(), data.to_vec()))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn invalid_hashed_storage() {
|
|
||||||
use ytbn_graphing_software::hashed_storage_read;
|
|
||||||
assert_eq!(hashed_storage_read("aaaa"), None);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[test]
|
// #[test]
|
||||||
@@ -141,45 +113,45 @@ fn invalid_hashed_storage() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn newtons_method() {
|
fn newtons_method() {
|
||||||
use parsing::BackingFunction;
|
use parsing::BackingFunction;
|
||||||
use parsing::FlatExWrapper;
|
use parsing::FlatExWrapper;
|
||||||
fn get_flatexwrapper(func: &str) -> FlatExWrapper {
|
fn get_flatexwrapper(func: &str) -> FlatExWrapper {
|
||||||
let mut backing_func = BackingFunction::new(func).unwrap();
|
let mut backing_func = BackingFunction::new(func).unwrap();
|
||||||
backing_func.get_function_derivative(0).clone()
|
backing_func.get_function_derivative(0).clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
use ytbn_graphing_software::newtons_method;
|
use ytbn_graphing_software::newtons_method;
|
||||||
|
|
||||||
let data = newtons_method(
|
let data = newtons_method(
|
||||||
&get_flatexwrapper("x^2 -1"),
|
&get_flatexwrapper("x^2 -1"),
|
||||||
&get_flatexwrapper("2x"),
|
&get_flatexwrapper("2*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(
|
||||||
&get_flatexwrapper("sin(x)"),
|
&get_flatexwrapper("sin(x)"),
|
||||||
&get_flatexwrapper("cos(x)"),
|
&get_flatexwrapper("cos(x)"),
|
||||||
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));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn to_unicode_hash() {
|
fn to_unicode_hash() {
|
||||||
use ytbn_graphing_software::to_unicode_hash;
|
use ytbn_graphing_software::to_unicode_hash;
|
||||||
assert_eq!(to_unicode_hash('\u{1f31e}'), "\\U1F31E");
|
assert_eq!(to_unicode_hash('\u{1f31e}'), "\\U1F31E");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn to_chars_array() {
|
fn to_chars_array() {
|
||||||
use ytbn_graphing_software::to_chars_array;
|
use ytbn_graphing_software::to_chars_array;
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
to_chars_array(vec!['\u{1f31e}', '\u{2d12c}']),
|
to_chars_array(vec!['\u{1f31e}', '\u{2d12c}']),
|
||||||
r"['\u{1f31e}', '\u{2d12c}']"
|
r"['\u{1f31e}', '\u{2d12c}']"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
428
tests/parsing.rs
428
tests/parsing.rs
@@ -3,292 +3,292 @@ use std::collections::HashMap;
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn hashmap_gen_test() {
|
fn hashmap_gen_test() {
|
||||||
let data = ["time", "text", "test"];
|
let data = ["time", "text", "test"];
|
||||||
let expect = vec![
|
let expect = vec![
|
||||||
("t", "Hint::Many(&[\"ime(\", \"ext(\", \"est(\"])"),
|
("t", "Hint::Many(&[\"ime(\", \"ext(\", \"est(\"])"),
|
||||||
("te", "Hint::Many(&[\"xt(\", \"st(\"])"),
|
("te", "Hint::Many(&[\"xt(\", \"st(\"])"),
|
||||||
("tes", "Hint::Single(\"t(\")"),
|
("tes", "Hint::Single(\"t(\")"),
|
||||||
("test", "Hint::Single(\"(\")"),
|
("test", "Hint::Single(\"(\")"),
|
||||||
("tex", "Hint::Single(\"t(\")"),
|
("tex", "Hint::Single(\"t(\")"),
|
||||||
("text", "Hint::Single(\"(\")"),
|
("text", "Hint::Single(\"(\")"),
|
||||||
("ti", "Hint::Single(\"me(\")"),
|
("ti", "Hint::Single(\"me(\")"),
|
||||||
("tim", "Hint::Single(\"e(\")"),
|
("tim", "Hint::Single(\"e(\")"),
|
||||||
("time", "Hint::Single(\"(\")"),
|
("time", "Hint::Single(\"(\")"),
|
||||||
];
|
];
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
parsing::compile_hashmap(data.iter().map(|e| e.to_string()).collect()),
|
parsing::compile_hashmap(data.iter().map(|e| e.to_string()).collect()),
|
||||||
expect
|
expect
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(a, b)| (a.to_string(), b.to_string()))
|
.map(|(a, b)| (a.to_string(), b.to_string()))
|
||||||
.collect::<Vec<(String, String)>>()
|
.collect::<Vec<(String, String)>>()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns if function with string `func_str` is valid after processing through [`process_func_str`]
|
/// Returns if function with string `func_str` is valid after processing through [`process_func_str`]
|
||||||
fn func_is_valid(func_str: &str) -> bool {
|
fn func_is_valid(func_str: &str) -> bool {
|
||||||
parsing::BackingFunction::new(&parsing::process_func_str(func_str)).is_ok()
|
parsing::BackingFunction::new(&parsing::process_func_str(func_str)).is_ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Used for testing: passes function to [`process_func_str`] before running [`test_func`]. if `expect_valid` == `true`, it expects no errors to be created.
|
/// Used for testing: passes function to [`process_func_str`] before running [`test_func`]. if `expect_valid` == `true`, it expects no errors to be created.
|
||||||
fn test_func_helper(func_str: &str, expect_valid: bool) {
|
fn test_func_helper(func_str: &str, expect_valid: bool) {
|
||||||
let is_valid = func_is_valid(func_str);
|
let is_valid = func_is_valid(func_str);
|
||||||
let string = format!(
|
let string = format!(
|
||||||
"function: {} (expected: {}, got: {})",
|
"function: {} (expected: {}, got: {})",
|
||||||
func_str, expect_valid, is_valid
|
func_str, expect_valid, is_valid
|
||||||
);
|
);
|
||||||
|
|
||||||
if is_valid == expect_valid {
|
if is_valid == expect_valid {
|
||||||
println!("{}", string);
|
println!("{}", string);
|
||||||
} else {
|
} else {
|
||||||
panic!("{}", string);
|
panic!("{}", string);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tests to make sure functions that are expected to succeed, succeed.
|
/// Tests to make sure functions that are expected to succeed, succeed.
|
||||||
#[test]
|
#[test]
|
||||||
fn test_expected() {
|
fn test_expected() {
|
||||||
let values = HashMap::from([
|
let values = HashMap::from([
|
||||||
("", true),
|
("", true),
|
||||||
("x^2", true),
|
("x^2", true),
|
||||||
("2x", true),
|
("2x", true),
|
||||||
("E^x", true),
|
("E^x", true),
|
||||||
("log10(x)", true),
|
("log10(x)", true),
|
||||||
("xxxxx", true),
|
("xxxxx", true),
|
||||||
("sin(x)", true),
|
("sin(x)", true),
|
||||||
("xsin(x)", true),
|
("xsin(x)", true),
|
||||||
("sin(x)cos(x)", true),
|
("sin(x)cos(x)", true),
|
||||||
("x/0", true),
|
("x/0", true),
|
||||||
("(x+1)(x-3)", true),
|
("(x+1)(x-3)", true),
|
||||||
("cos(xsin(x)x)", true),
|
("cos(xsin(x)x)", true),
|
||||||
("(2x+1)x", true),
|
("(2x+1)x", true),
|
||||||
("(2x+1)pi", true),
|
("(2x+1)pi", true),
|
||||||
("pi(2x+1)", true),
|
("pi(2x+1)", true),
|
||||||
("pipipipipipix", true),
|
("pipipipipipix", true),
|
||||||
("e^sin(x)", true),
|
("e^sin(x)", true),
|
||||||
("E^sin(x)", true),
|
("E^sin(x)", true),
|
||||||
("e^x", true),
|
("e^x", true),
|
||||||
("x**2", true),
|
("x**2", true),
|
||||||
("a", false),
|
("a", false),
|
||||||
("log222(x)", false),
|
("log222(x)", false),
|
||||||
("abcdef", false),
|
("abcdef", false),
|
||||||
("log10(x", false),
|
("log10(x", false),
|
||||||
("x^a", false),
|
("x^a", false),
|
||||||
("sin(cos(x)))", false),
|
("sin(cos(x)))", false),
|
||||||
("0/0", false),
|
("0/0", false),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
for (key, value) in values {
|
for (key, value) in values {
|
||||||
test_func_helper(key, value);
|
test_func_helper(key, value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Helps with tests of [`process_func_str`]
|
/// Helps with tests of [`process_func_str`]
|
||||||
fn test_process_helper(input: &str, expected: &str) {
|
fn test_process_helper(input: &str, expected: &str) {
|
||||||
assert_eq!(&parsing::process_func_str(input), expected);
|
assert_eq!(&parsing::process_func_str(input), expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tests to make sure my cursed function works as intended
|
/// Tests to make sure my cursed function works as intended
|
||||||
#[test]
|
#[test]
|
||||||
fn func_process_test() {
|
fn func_process_test() {
|
||||||
let values = HashMap::from([
|
let values = HashMap::from([
|
||||||
("2x", "2*x"),
|
("2x", "2*x"),
|
||||||
(")(", ")*("),
|
(")(", ")*("),
|
||||||
("(2", "(2"),
|
("(2", "(2"),
|
||||||
("log10(x)", "log10(x)"),
|
("log10(x)", "log10(x)"),
|
||||||
("log2(x)", "log2(x)"),
|
("log2(x)", "log2(x)"),
|
||||||
("pipipipipipi", "π*π*π*π*π*π"),
|
("pipipipipipi", "π*π*π*π*π*π"),
|
||||||
("10pi", "10*π"),
|
("10pi", "10*π"),
|
||||||
("pi10", "π*10"),
|
("pi10", "π*10"),
|
||||||
("10pi10", "10*π*10"),
|
("10pi10", "10*π*10"),
|
||||||
("emax(x)", "e*max(x)"),
|
("emax(x)", "e*max(x)"),
|
||||||
("pisin(x)", "π*sin(x)"),
|
("pisin(x)", "π*sin(x)"),
|
||||||
("e^sin(x)", "e^sin(x)"),
|
("e^sin(x)", "e^sin(x)"),
|
||||||
("x**2", "x^2"),
|
("x**2", "x^2"),
|
||||||
("(x+1)(x-3)", "(x+1)*(x-3)"),
|
("(x+1)(x-3)", "(x+1)*(x-3)"),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
for (key, value) in values {
|
for (key, value) in values {
|
||||||
test_process_helper(key, value);
|
test_process_helper(key, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
for func in SUPPORTED_FUNCTIONS.iter() {
|
for func in SUPPORTED_FUNCTIONS.iter() {
|
||||||
let func_new = format!("{}(x)", func);
|
let func_new = format!("{}(x)", func);
|
||||||
test_process_helper(&func_new, &func_new);
|
test_process_helper(&func_new, &func_new);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tests to make sure hints are properly outputed based on input
|
/// Tests to make sure hints are properly outputed based on input
|
||||||
#[test]
|
#[test]
|
||||||
fn hints() {
|
fn hints() {
|
||||||
let values = HashMap::from([
|
let values = HashMap::from([
|
||||||
("", Hint::Single("x^2")),
|
("", Hint::Single("x^2")),
|
||||||
("si", Hint::Many(&["n(", "nh(", "gnum("])),
|
("si", Hint::Many(&["n(", "nh(", "gnum("])),
|
||||||
("log", Hint::Many(&["2(", "10("])),
|
("log", Hint::Many(&["2(", "10("])),
|
||||||
("cos", Hint::Many(&["(", "h("])),
|
("cos", Hint::Many(&["(", "h("])),
|
||||||
("sin(", Hint::Single(")")),
|
("sin(", Hint::Single(")")),
|
||||||
("sqrt", Hint::Single("(")),
|
("sqrt", Hint::Single("(")),
|
||||||
("ln(x)", Hint::None),
|
("ln(x)", Hint::None),
|
||||||
("ln(x)cos", Hint::Many(&["(", "h("])),
|
("ln(x)cos", Hint::Many(&["(", "h("])),
|
||||||
("ln(x)*cos", Hint::Many(&["(", "h("])),
|
("ln(x)*cos", Hint::Many(&["(", "h("])),
|
||||||
("sin(cos", Hint::Many(&["(", "h("])),
|
("sin(cos", Hint::Many(&["(", "h("])),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
for (key, value) in values {
|
for (key, value) in values {
|
||||||
println!("{} + {:?}", key, value);
|
println!("{} + {:?}", key, value);
|
||||||
assert_eq!(parsing::generate_hint(key), &value);
|
assert_eq!(parsing::generate_hint(key), &value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn hint_to_string() {
|
fn hint_to_string() {
|
||||||
let values = HashMap::from([
|
let values = HashMap::from([
|
||||||
("x^2", Hint::Single("x^2")),
|
("x^2", Hint::Single("x^2")),
|
||||||
(
|
(
|
||||||
r#"["n(", "nh(", "gnum("]"#,
|
r#"["n(", "nh(", "gnum("]"#,
|
||||||
Hint::Many(&["n(", "nh(", "gnum("]),
|
Hint::Many(&["n(", "nh(", "gnum("]),
|
||||||
),
|
),
|
||||||
(r#"["n("]"#, Hint::Many(&["n("])),
|
(r#"["n("]"#, Hint::Many(&["n("])),
|
||||||
("None", Hint::None),
|
("None", Hint::None),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
for (key, value) in values {
|
for (key, value) in values {
|
||||||
assert_eq!(value.to_string(), key);
|
assert_eq!(value.to_string(), key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn invalid_function() {
|
fn invalid_function() {
|
||||||
use parsing::SplitType;
|
use parsing::SplitType;
|
||||||
|
|
||||||
SUPPORTED_FUNCTIONS
|
SUPPORTED_FUNCTIONS
|
||||||
.iter()
|
.iter()
|
||||||
.flat_map(|func1| {
|
.flat_map(|func1| {
|
||||||
SUPPORTED_FUNCTIONS
|
SUPPORTED_FUNCTIONS
|
||||||
.iter()
|
.iter()
|
||||||
.map(|func2| func1.to_string() + func2)
|
.map(|func2| func1.to_string() + func2)
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
})
|
})
|
||||||
.filter(|func| !SUPPORTED_FUNCTIONS.contains(&func.as_str()))
|
.filter(|func| !SUPPORTED_FUNCTIONS.contains(&func.as_str()))
|
||||||
.for_each(|key| {
|
.for_each(|key| {
|
||||||
let split = parsing::split_function(&key, SplitType::Multiplication);
|
let split = parsing::split_function(&key, SplitType::Multiplication);
|
||||||
|
|
||||||
if split.len() != 1 {
|
if split.len() != 1 {
|
||||||
panic!("failed: {} (len: {}, split: {:?})", key, split.len(), split);
|
panic!("failed: {} (len: {}, split: {:?})", key, split.len(), split);
|
||||||
}
|
}
|
||||||
|
|
||||||
let generated_hint = parsing::generate_hint(&key);
|
let generated_hint = parsing::generate_hint(&key);
|
||||||
if generated_hint.is_none() {
|
if generated_hint.is_none() {
|
||||||
println!("success: {}", key);
|
println!("success: {}", key);
|
||||||
} else {
|
} else {
|
||||||
panic!("failed: {} (Hint: '{}')", key, generated_hint);
|
panic!("failed: {} (Hint: '{}')", key, generated_hint);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn split_function_multiplication() {
|
fn split_function_multiplication() {
|
||||||
use parsing::SplitType;
|
use parsing::SplitType;
|
||||||
|
|
||||||
let values = HashMap::from([
|
let values = HashMap::from([
|
||||||
("cos(x)", vec!["cos(x)"]),
|
("cos(x)", vec!["cos(x)"]),
|
||||||
("cos(", vec!["cos("]),
|
("cos(", vec!["cos("]),
|
||||||
("cos(x)sin(x)", vec!["cos(x)", "sin(x)"]),
|
("cos(x)sin(x)", vec!["cos(x)", "sin(x)"]),
|
||||||
("aaaaaaaaaaa", vec!["aaaaaaaaaaa"]),
|
("aaaaaaaaaaa", vec!["aaaaaaaaaaa"]),
|
||||||
("emax(x)", vec!["e", "max(x)"]),
|
("emax(x)", vec!["e", "max(x)"]),
|
||||||
("x", vec!["x"]),
|
("x", vec!["x"]),
|
||||||
("xxx", vec!["x", "x", "x"]),
|
("xxx", vec!["x", "x", "x"]),
|
||||||
("sin(cos(x)x)", vec!["sin(cos(x)", "x)"]),
|
("sin(cos(x)x)", vec!["sin(cos(x)", "x)"]),
|
||||||
("sin(x)*cos(x)", vec!["sin(x)", "cos(x)"]),
|
("sin(x)*cos(x)", vec!["sin(x)", "cos(x)"]),
|
||||||
("x*x", vec!["x", "x"]),
|
("x*x", vec!["x", "x"]),
|
||||||
("10*10", vec!["10", "10"]),
|
("10*10", vec!["10", "10"]),
|
||||||
("a1b2c3d4", vec!["a1b2c3d4"]),
|
("a1b2c3d4", vec!["a1b2c3d4"]),
|
||||||
("cos(sin(x)cos(x))", vec!["cos(sin(x)", "cos(x))"]),
|
("cos(sin(x)cos(x))", vec!["cos(sin(x)", "cos(x))"]),
|
||||||
("", Vec::new()),
|
("", Vec::new()),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
for (key, value) in values {
|
for (key, value) in values {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
parsing::split_function(key, SplitType::Multiplication),
|
parsing::split_function(key, SplitType::Multiplication),
|
||||||
value
|
value
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn split_function_terms() {
|
fn split_function_terms() {
|
||||||
use parsing::SplitType;
|
use parsing::SplitType;
|
||||||
|
|
||||||
let values = HashMap::from([
|
let values = HashMap::from([
|
||||||
(
|
(
|
||||||
"cos(sin(x)cos(x))",
|
"cos(sin(x)cos(x))",
|
||||||
vec!["cos(", "sin(", "x)", "cos(", "x))"],
|
vec!["cos(", "sin(", "x)", "cos(", "x))"],
|
||||||
),
|
),
|
||||||
("", Vec::new()),
|
("", Vec::new()),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
for (key, value) in values {
|
for (key, value) in values {
|
||||||
assert_eq!(parsing::split_function(key, SplitType::Term), value);
|
assert_eq!(parsing::split_function(key, SplitType::Term), value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn hint_tests() {
|
fn hint_tests() {
|
||||||
{
|
{
|
||||||
let hint = Hint::None;
|
let hint = Hint::None;
|
||||||
assert!(hint.is_none());
|
assert!(hint.is_none());
|
||||||
assert!(!hint.is_some());
|
assert!(!hint.is_some());
|
||||||
assert!(!hint.is_single());
|
assert!(!hint.is_single());
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
let hint = Hint::Single("");
|
let hint = Hint::Single("");
|
||||||
assert!(!hint.is_none());
|
assert!(!hint.is_none());
|
||||||
assert!(hint.is_some());
|
assert!(hint.is_some());
|
||||||
assert!(hint.is_single());
|
assert!(hint.is_single());
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
let hint = Hint::Many(&[""]);
|
let hint = Hint::Many(&[""]);
|
||||||
assert!(!hint.is_none());
|
assert!(!hint.is_none());
|
||||||
assert!(hint.is_some());
|
assert!(hint.is_some());
|
||||||
assert!(!hint.is_single());
|
assert!(!hint.is_single());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn get_last_term() {
|
fn get_last_term() {
|
||||||
let values = HashMap::from([
|
let values = HashMap::from([
|
||||||
("cos(x)", "x)"),
|
("cos(x)", "x)"),
|
||||||
("cos(", "cos("),
|
("cos(", "cos("),
|
||||||
("aaaaaaaaaaa", "aaaaaaaaaaa"),
|
("aaaaaaaaaaa", "aaaaaaaaaaa"),
|
||||||
("x", "x"),
|
("x", "x"),
|
||||||
("xxx", "x"),
|
("xxx", "x"),
|
||||||
("x*x", "x"),
|
("x*x", "x"),
|
||||||
("10*10", "10"),
|
("10*10", "10"),
|
||||||
("sin(cos", "cos"),
|
("sin(cos", "cos"),
|
||||||
("exp(cos(exp(sin", "sin"),
|
("exp(cos(exp(sin", "sin"),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
for (key, value) in values {
|
for (key, value) in values {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
parsing::get_last_term(key.chars().collect::<Vec<char>>().as_slice()),
|
parsing::get_last_term(key.chars().collect::<Vec<char>>().as_slice()),
|
||||||
Some(value.to_owned())
|
Some(value.to_owned())
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn hint_accessor() {
|
fn hint_accessor() {
|
||||||
assert_eq!(Hint::Single("hint").many(), None);
|
assert_eq!(Hint::Single("hint").many(), None);
|
||||||
assert_eq!(Hint::Single("hint").single(), Some("hint"));
|
assert_eq!(Hint::Single("hint").single(), Some("hint"));
|
||||||
|
|
||||||
assert_eq!(Hint::Many(&["hint", "hint2"]).single(), None);
|
assert_eq!(Hint::Many(&["hint", "hint2"]).single(), None);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Hint::Many(&["hint", "hint2"]).many(),
|
Hint::Many(&["hint", "hint2"]).many(),
|
||||||
Some(["hint", "hint2"].as_slice())
|
Some(["hint", "hint2"].as_slice())
|
||||||
);
|
);
|
||||||
|
|
||||||
assert_eq!(Hint::None.single(), None);
|
assert_eq!(Hint::None.single(), None);
|
||||||
assert_eq!(Hint::None.many(), None);
|
assert_eq!(Hint::None.many(), None);
|
||||||
}
|
}
|
||||||
|
|||||||
229
tests/symbolic.rs
Normal file
229
tests/symbolic.rs
Normal file
@@ -0,0 +1,229 @@
|
|||||||
|
use std::f64::consts::{E, PI, SQRT_2};
|
||||||
|
use ytbn_graphing_software::symbolic::try_symbolic;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn exact_pi() {
|
||||||
|
let result = try_symbolic(PI);
|
||||||
|
assert!(result.is_some());
|
||||||
|
let sym = result.unwrap();
|
||||||
|
assert_eq!(sym.to_string(), "pi");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn multiples_of_pi() {
|
||||||
|
// 2*pi
|
||||||
|
let result = try_symbolic(2.0 * PI);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "2pi");
|
||||||
|
|
||||||
|
// 3*pi
|
||||||
|
let result = try_symbolic(3.0 * PI);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "3pi");
|
||||||
|
|
||||||
|
// -pi
|
||||||
|
let result = try_symbolic(-PI);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "-pi");
|
||||||
|
|
||||||
|
// -2*pi
|
||||||
|
let result = try_symbolic(-2.0 * PI);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "-2pi");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fractions_of_pi() {
|
||||||
|
// pi/2
|
||||||
|
let result = try_symbolic(PI / 2.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "pi/2");
|
||||||
|
|
||||||
|
// pi/3
|
||||||
|
let result = try_symbolic(PI / 3.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "pi/3");
|
||||||
|
|
||||||
|
// pi/4
|
||||||
|
let result = try_symbolic(PI / 4.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "pi/4");
|
||||||
|
|
||||||
|
// pi/6
|
||||||
|
let result = try_symbolic(PI / 6.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "pi/6");
|
||||||
|
|
||||||
|
// 2pi/3
|
||||||
|
let result = try_symbolic(2.0 * PI / 3.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "2pi/3");
|
||||||
|
|
||||||
|
// 3pi/4
|
||||||
|
let result = try_symbolic(3.0 * PI / 4.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "3pi/4");
|
||||||
|
|
||||||
|
// 5pi/6
|
||||||
|
let result = try_symbolic(5.0 * PI / 6.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "5pi/6");
|
||||||
|
|
||||||
|
// -pi/2
|
||||||
|
let result = try_symbolic(-PI / 2.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "-pi/2");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn exact_e() {
|
||||||
|
let result = try_symbolic(E);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "e");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn multiples_of_e() {
|
||||||
|
// 2e
|
||||||
|
let result = try_symbolic(2.0 * E);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "2e");
|
||||||
|
|
||||||
|
// -e
|
||||||
|
let result = try_symbolic(-E);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "-e");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sqrt_2() {
|
||||||
|
let result = try_symbolic(SQRT_2);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "sqrt(2)");
|
||||||
|
|
||||||
|
// -sqrt(2)
|
||||||
|
let result = try_symbolic(-SQRT_2);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "-sqrt(2)");
|
||||||
|
|
||||||
|
// 2*sqrt(2)
|
||||||
|
let result = try_symbolic(2.0 * SQRT_2);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "2sqrt(2)");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sqrt_3() {
|
||||||
|
let sqrt_3 = 3.0_f64.sqrt();
|
||||||
|
let result = try_symbolic(sqrt_3);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "sqrt(3)");
|
||||||
|
|
||||||
|
// sqrt(3)/2 - common in trigonometry
|
||||||
|
let result = try_symbolic(sqrt_3 / 2.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "sqrt(3)/2");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn simple_fractions() {
|
||||||
|
// 1/2
|
||||||
|
let result = try_symbolic(0.5);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "1/2");
|
||||||
|
|
||||||
|
// 1/3
|
||||||
|
let result = try_symbolic(1.0 / 3.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "1/3");
|
||||||
|
|
||||||
|
// 2/3
|
||||||
|
let result = try_symbolic(2.0 / 3.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "2/3");
|
||||||
|
|
||||||
|
// 1/4
|
||||||
|
let result = try_symbolic(0.25);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "1/4");
|
||||||
|
|
||||||
|
// 3/4
|
||||||
|
let result = try_symbolic(0.75);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "3/4");
|
||||||
|
|
||||||
|
// -1/2
|
||||||
|
let result = try_symbolic(-0.5);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "-1/2");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn integers() {
|
||||||
|
// 0
|
||||||
|
let result = try_symbolic(0.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "0");
|
||||||
|
|
||||||
|
// 1
|
||||||
|
let result = try_symbolic(1.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "1");
|
||||||
|
|
||||||
|
// -1
|
||||||
|
let result = try_symbolic(-1.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "-1");
|
||||||
|
|
||||||
|
// 5
|
||||||
|
let result = try_symbolic(5.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "5");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn non_symbolic_values() {
|
||||||
|
// Some arbitrary irrational number that isn't special
|
||||||
|
let result = try_symbolic(1.234567890123);
|
||||||
|
assert!(result.is_none());
|
||||||
|
|
||||||
|
// A number that's close to but not quite pi
|
||||||
|
let result = try_symbolic(3.15);
|
||||||
|
assert!(result.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numeric_value() {
|
||||||
|
// SymbolicValue should provide the original numeric value
|
||||||
|
let sym = try_symbolic(PI).unwrap();
|
||||||
|
assert!((sym.numeric_value() - PI).abs() < 1e-10);
|
||||||
|
|
||||||
|
let sym = try_symbolic(PI / 2.0).unwrap();
|
||||||
|
assert!((sym.numeric_value() - PI / 2.0).abs() < 1e-10);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn zero() {
|
||||||
|
let result = try_symbolic(0.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "0");
|
||||||
|
|
||||||
|
// Also test -0.0
|
||||||
|
let result = try_symbolic(-0.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn special_trig_values() {
|
||||||
|
// Common values that appear in trigonometry
|
||||||
|
// sin(pi/4) = cos(pi/4) = sqrt(2)/2
|
||||||
|
let result = try_symbolic(SQRT_2 / 2.0);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "sqrt(2)/2");
|
||||||
|
|
||||||
|
// sin(pi/6) = cos(pi/3) = 1/2
|
||||||
|
let result = try_symbolic(0.5);
|
||||||
|
assert!(result.is_some());
|
||||||
|
assert_eq!(result.unwrap().to_string(), "1/2");
|
||||||
|
}
|
||||||
@@ -56,9 +56,10 @@
|
|||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
display: block;
|
display: block;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 0%;
|
top: 0;
|
||||||
left: 50%;
|
left: 0;
|
||||||
transform: translate(-50%, 0%);
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
Reference in New Issue
Block a user