Add math stdlib with formulas/plots and polish the docs view.
Ship Num/Formula runtime, bilingual math libs, SVG plots with axes/grid, and view UX for collapsible folders plus centered plots. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
a53ebb65ee
commit
dcd0cdb8f7
40 files changed
+3553
-276
No files matched your search
@@ -0,0 +1,961 @@
|
||||
//! High-school formula AST: parse, simplify, diff, eval, solve, plot helpers.
|
||||
|
||||
mod plot;
|
||||
|
||||
pub use plot::{plot_conic_svg, plot_function_svg, plot_points_svg, PlotStyle};
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
/// Expression tree for `Value::Formula`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Expr {
|
||||
Num(f64),
|
||||
Var(String),
|
||||
UnaryNeg(Box<Expr>),
|
||||
Bin {
|
||||
op: BinOp,
|
||||
left: Box<Expr>,
|
||||
right: Box<Expr>,
|
||||
},
|
||||
Call {
|
||||
name: String,
|
||||
args: Vec<Expr>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BinOp {
|
||||
Add,
|
||||
Sub,
|
||||
Mul,
|
||||
Div,
|
||||
Pow,
|
||||
}
|
||||
|
||||
impl Expr {
|
||||
pub fn num(n: f64) -> Self {
|
||||
Expr::Num(n)
|
||||
}
|
||||
|
||||
pub fn var(name: impl Into<String>) -> Self {
|
||||
Expr::Var(name.into())
|
||||
}
|
||||
|
||||
pub fn as_display(&self) -> String {
|
||||
self.fmt_prec(0)
|
||||
}
|
||||
|
||||
fn fmt_prec(&self, parent_prec: u8) -> String {
|
||||
match self {
|
||||
Expr::Num(n) => format_num(*n),
|
||||
Expr::Var(v) => v.clone(),
|
||||
Expr::UnaryNeg(e) => {
|
||||
let inner = e.fmt_prec(3);
|
||||
let s = format!("-{inner}");
|
||||
if parent_prec > 2 {
|
||||
format!("({s})")
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
Expr::Bin { op, left, right } => {
|
||||
let prec = op.prec();
|
||||
let ls = left.fmt_prec(prec);
|
||||
let rs = right.fmt_prec(if matches!(op, BinOp::Sub | BinOp::Div) {
|
||||
prec + 1
|
||||
} else if matches!(op, BinOp::Pow) {
|
||||
prec
|
||||
} else {
|
||||
prec
|
||||
});
|
||||
let s = format!("{ls}{}{rs}", op.sym());
|
||||
if prec < parent_prec {
|
||||
format!("({s})")
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
Expr::Call { name, args } => {
|
||||
let joined: Vec<String> = args.iter().map(|a| a.as_display()).collect();
|
||||
format!("{name}({})", joined.join(", "))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Expr {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.as_display())
|
||||
}
|
||||
}
|
||||
|
||||
impl BinOp {
|
||||
fn prec(self) -> u8 {
|
||||
match self {
|
||||
BinOp::Add | BinOp::Sub => 1,
|
||||
BinOp::Mul | BinOp::Div => 2,
|
||||
BinOp::Pow => 3,
|
||||
}
|
||||
}
|
||||
|
||||
fn sym(self) -> &'static str {
|
||||
match self {
|
||||
BinOp::Add => " + ",
|
||||
BinOp::Sub => " - ",
|
||||
BinOp::Mul => "*",
|
||||
BinOp::Div => "/",
|
||||
BinOp::Pow => "^",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format_num(n: f64) -> String {
|
||||
if n.is_nan() {
|
||||
return "nan".into();
|
||||
}
|
||||
if n.is_infinite() {
|
||||
return if n.is_sign_positive() {
|
||||
"inf".into()
|
||||
} else {
|
||||
"-inf".into()
|
||||
};
|
||||
}
|
||||
if n.fract() == 0.0 && n.abs() < 1e15 {
|
||||
return format!("{}", n as i64);
|
||||
}
|
||||
let s = format!("{n:.10}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s.is_empty() || s == "-" {
|
||||
"0".into()
|
||||
} else {
|
||||
s.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse ASCII formula text (`sin(x) + x^2`, optional simple `y = …` left strip).
|
||||
pub fn parse(input: &str) -> Result<Expr, String> {
|
||||
let t = input.trim();
|
||||
if t.is_empty() {
|
||||
return Err("empty formula".into());
|
||||
}
|
||||
let body = if let Some((lhs, rhs)) = t.split_once('=') {
|
||||
let lhs = lhs.trim();
|
||||
if lhs.chars().all(|c| c.is_ascii_alphabetic() || c == '_') && !rhs.trim().is_empty() {
|
||||
rhs.trim()
|
||||
} else {
|
||||
t
|
||||
}
|
||||
} else {
|
||||
t
|
||||
};
|
||||
let mut p = Parser {
|
||||
src: body.chars().collect(),
|
||||
i: 0,
|
||||
};
|
||||
let e = p.parse_expr()?;
|
||||
p.skip_ws();
|
||||
if p.i < p.src.len() {
|
||||
return Err(format!(
|
||||
"unexpected trailing input near `{}`",
|
||||
p.src[p.i..].iter().collect::<String>()
|
||||
));
|
||||
}
|
||||
Ok(e)
|
||||
}
|
||||
|
||||
struct Parser {
|
||||
src: Vec<char>,
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
fn skip_ws(&mut self) {
|
||||
while self.i < self.src.len() && self.src[self.i].is_whitespace() {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn peek(&mut self) -> Option<char> {
|
||||
self.skip_ws();
|
||||
self.src.get(self.i).copied()
|
||||
}
|
||||
|
||||
fn bump(&mut self) -> Option<char> {
|
||||
self.skip_ws();
|
||||
let c = self.src.get(self.i).copied()?;
|
||||
self.i += 1;
|
||||
Some(c)
|
||||
}
|
||||
|
||||
fn parse_expr(&mut self) -> Result<Expr, String> {
|
||||
self.parse_add()
|
||||
}
|
||||
|
||||
fn parse_add(&mut self) -> Result<Expr, String> {
|
||||
let mut left = self.parse_mul()?;
|
||||
loop {
|
||||
match self.peek() {
|
||||
Some('+') => {
|
||||
self.bump();
|
||||
let right = self.parse_mul()?;
|
||||
left = Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
};
|
||||
}
|
||||
Some('-') => {
|
||||
self.bump();
|
||||
let right = self.parse_mul()?;
|
||||
left = Expr::Bin {
|
||||
op: BinOp::Sub,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
};
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
Ok(left)
|
||||
}
|
||||
|
||||
fn parse_mul(&mut self) -> Result<Expr, String> {
|
||||
let mut left = self.parse_pow()?;
|
||||
loop {
|
||||
match self.peek() {
|
||||
Some('*') => {
|
||||
self.bump();
|
||||
let right = self.parse_pow()?;
|
||||
left = Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
};
|
||||
}
|
||||
Some('/') => {
|
||||
self.bump();
|
||||
let right = self.parse_pow()?;
|
||||
left = Expr::Bin {
|
||||
op: BinOp::Div,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
};
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
Ok(left)
|
||||
}
|
||||
|
||||
fn parse_pow(&mut self) -> Result<Expr, String> {
|
||||
let left = self.parse_unary()?;
|
||||
if self.peek() == Some('^') {
|
||||
self.bump();
|
||||
let right = self.parse_pow()?; // right-assoc
|
||||
Ok(Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
})
|
||||
} else {
|
||||
Ok(left)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_unary(&mut self) -> Result<Expr, String> {
|
||||
match self.peek() {
|
||||
Some('+') => {
|
||||
self.bump();
|
||||
self.parse_unary()
|
||||
}
|
||||
Some('-') => {
|
||||
self.bump();
|
||||
Ok(Expr::UnaryNeg(Box::new(self.parse_unary()?)))
|
||||
}
|
||||
_ => self.parse_primary(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_primary(&mut self) -> Result<Expr, String> {
|
||||
match self.peek() {
|
||||
Some('(') => {
|
||||
self.bump();
|
||||
let e = self.parse_expr()?;
|
||||
if self.bump() != Some(')') {
|
||||
return Err("expected `)`".into());
|
||||
}
|
||||
Ok(e)
|
||||
}
|
||||
Some(c) if c.is_ascii_digit() || c == '.' => self.parse_number(),
|
||||
Some(c) if c.is_ascii_alphabetic() || c == '_' => {
|
||||
let name = self.parse_ident()?;
|
||||
if self.peek() == Some('(') {
|
||||
self.bump();
|
||||
let mut args = Vec::new();
|
||||
if self.peek() != Some(')') {
|
||||
loop {
|
||||
args.push(self.parse_expr()?);
|
||||
match self.peek() {
|
||||
Some(',') => {
|
||||
self.bump();
|
||||
}
|
||||
Some(')') => break,
|
||||
_ => return Err("expected `,` or `)` in call".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.bump() != Some(')') {
|
||||
return Err("expected `)` after call args".into());
|
||||
}
|
||||
Ok(Expr::Call { name, args })
|
||||
} else {
|
||||
Ok(Expr::Var(name))
|
||||
}
|
||||
}
|
||||
Some(c) => Err(format!("unexpected `{c}` in formula")),
|
||||
None => Err("unexpected end of formula".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_number(&mut self) -> Result<Expr, String> {
|
||||
self.skip_ws();
|
||||
let start = self.i;
|
||||
while self.i < self.src.len()
|
||||
&& (self.src[self.i].is_ascii_digit() || self.src[self.i] == '.')
|
||||
{
|
||||
self.i += 1;
|
||||
}
|
||||
let s: String = self.src[start..self.i].iter().collect();
|
||||
let n: f64 = s
|
||||
.parse()
|
||||
.map_err(|_| format!("invalid number `{s}`"))?;
|
||||
Ok(Expr::Num(n))
|
||||
}
|
||||
|
||||
fn parse_ident(&mut self) -> Result<String, String> {
|
||||
self.skip_ws();
|
||||
let start = self.i;
|
||||
while self.i < self.src.len() {
|
||||
let c = self.src[self.i];
|
||||
if c.is_ascii_alphanumeric() || c == '_' {
|
||||
self.i += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if start == self.i {
|
||||
return Err("expected identifier".into());
|
||||
}
|
||||
Ok(self.src[start..self.i].iter().collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Constant-fold + light algebraic cleanup.
|
||||
pub fn simplify(e: &Expr) -> Expr {
|
||||
match e {
|
||||
Expr::Num(n) => Expr::Num(*n),
|
||||
Expr::Var(v) => Expr::Var(v.clone()),
|
||||
Expr::UnaryNeg(inner) => {
|
||||
let i = simplify(inner);
|
||||
match i {
|
||||
Expr::Num(n) => Expr::Num(-n),
|
||||
Expr::UnaryNeg(x) => *x,
|
||||
other => Expr::UnaryNeg(Box::new(other)),
|
||||
}
|
||||
}
|
||||
Expr::Bin { op, left, right } => {
|
||||
let l = simplify(left);
|
||||
let r = simplify(right);
|
||||
fold_bin(*op, l, r)
|
||||
}
|
||||
Expr::Call { name, args } => {
|
||||
let args: Vec<Expr> = args.iter().map(simplify).collect();
|
||||
if args.len() == 1 {
|
||||
if let Expr::Num(n) = &args[0] {
|
||||
if let Some(v) = eval_call_f64(name, &[*n]) {
|
||||
return Expr::Num(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
Expr::Call {
|
||||
name: name.clone(),
|
||||
args,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fold_bin(op: BinOp, l: Expr, r: Expr) -> Expr {
|
||||
match (op, &l, &r) {
|
||||
(BinOp::Add, Expr::Num(a), Expr::Num(b)) => Expr::Num(a + b),
|
||||
(BinOp::Sub, Expr::Num(a), Expr::Num(b)) => Expr::Num(a - b),
|
||||
(BinOp::Mul, Expr::Num(a), Expr::Num(b)) => Expr::Num(a * b),
|
||||
(BinOp::Div, Expr::Num(a), Expr::Num(b)) if *b != 0.0 => Expr::Num(a / b),
|
||||
(BinOp::Pow, Expr::Num(a), Expr::Num(b)) => Expr::Num(a.powf(*b)),
|
||||
(BinOp::Add, _, Expr::Num(0.0)) => l,
|
||||
(BinOp::Add, Expr::Num(0.0), _) => r,
|
||||
(BinOp::Sub, _, Expr::Num(0.0)) => l,
|
||||
(BinOp::Mul, _, Expr::Num(1.0)) => l,
|
||||
(BinOp::Mul, Expr::Num(1.0), _) => r,
|
||||
(BinOp::Mul, _, Expr::Num(0.0)) | (BinOp::Mul, Expr::Num(0.0), _) => Expr::Num(0.0),
|
||||
(BinOp::Pow, _, Expr::Num(1.0)) => l,
|
||||
(BinOp::Pow, _, Expr::Num(0.0)) => Expr::Num(1.0),
|
||||
(BinOp::Div, _, Expr::Num(1.0)) => l,
|
||||
_ => Expr::Bin {
|
||||
op,
|
||||
left: Box::new(l),
|
||||
right: Box::new(r),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Lightweight expand: distribute multiplication over addition one level.
|
||||
pub fn expand(e: &Expr) -> Expr {
|
||||
let e = simplify(e);
|
||||
match e {
|
||||
Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left,
|
||||
right,
|
||||
} => {
|
||||
let l = expand(&left);
|
||||
let r = expand(&right);
|
||||
match (l, r) {
|
||||
(
|
||||
Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: a,
|
||||
right: b,
|
||||
},
|
||||
r,
|
||||
) => simplify(&Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: a,
|
||||
right: Box::new(r.clone()),
|
||||
}),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: b,
|
||||
right: Box::new(r),
|
||||
}),
|
||||
}),
|
||||
(
|
||||
l,
|
||||
Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: a,
|
||||
right: b,
|
||||
},
|
||||
) => simplify(&Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(l.clone()),
|
||||
right: a,
|
||||
}),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(l),
|
||||
right: b,
|
||||
}),
|
||||
}),
|
||||
(l, r) => simplify(&Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(l),
|
||||
right: Box::new(r),
|
||||
}),
|
||||
}
|
||||
}
|
||||
Expr::Bin { op, left, right } => simplify(&Expr::Bin {
|
||||
op,
|
||||
left: Box::new(expand(&left)),
|
||||
right: Box::new(expand(&right)),
|
||||
}),
|
||||
Expr::UnaryNeg(x) => simplify(&Expr::UnaryNeg(Box::new(expand(&x)))),
|
||||
Expr::Call { name, args } => Expr::Call {
|
||||
name,
|
||||
args: args.iter().map(expand).collect(),
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn diff(e: &Expr, var: &str) -> Expr {
|
||||
simplify(&diff_raw(e, var))
|
||||
}
|
||||
|
||||
fn diff_raw(e: &Expr, var: &str) -> Expr {
|
||||
match e {
|
||||
Expr::Num(_) => Expr::Num(0.0),
|
||||
Expr::Var(v) => {
|
||||
if v == var {
|
||||
Expr::Num(1.0)
|
||||
} else {
|
||||
Expr::Num(0.0)
|
||||
}
|
||||
}
|
||||
Expr::UnaryNeg(x) => Expr::UnaryNeg(Box::new(diff_raw(x, var))),
|
||||
Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left,
|
||||
right,
|
||||
} => Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: Box::new(diff_raw(left, var)),
|
||||
right: Box::new(diff_raw(right, var)),
|
||||
},
|
||||
Expr::Bin {
|
||||
op: BinOp::Sub,
|
||||
left,
|
||||
right,
|
||||
} => Expr::Bin {
|
||||
op: BinOp::Sub,
|
||||
left: Box::new(diff_raw(left, var)),
|
||||
right: Box::new(diff_raw(right, var)),
|
||||
},
|
||||
Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left,
|
||||
right,
|
||||
} => {
|
||||
// product rule
|
||||
Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(diff_raw(left, var)),
|
||||
right: right.clone(),
|
||||
}),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: left.clone(),
|
||||
right: Box::new(diff_raw(right, var)),
|
||||
}),
|
||||
}
|
||||
}
|
||||
Expr::Bin {
|
||||
op: BinOp::Div,
|
||||
left,
|
||||
right,
|
||||
} => {
|
||||
// (u'v - uv') / v^2
|
||||
let num = Expr::Bin {
|
||||
op: BinOp::Sub,
|
||||
left: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(diff_raw(left, var)),
|
||||
right: right.clone(),
|
||||
}),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: left.clone(),
|
||||
right: Box::new(diff_raw(right, var)),
|
||||
}),
|
||||
};
|
||||
Expr::Bin {
|
||||
op: BinOp::Div,
|
||||
left: Box::new(num),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left: right.clone(),
|
||||
right: Box::new(Expr::Num(2.0)),
|
||||
}),
|
||||
}
|
||||
}
|
||||
Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left,
|
||||
right,
|
||||
} => {
|
||||
// d/dx [u^n] when n constant: n*u^(n-1)*u'
|
||||
if let Expr::Num(n) = right.as_ref() {
|
||||
Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(Expr::Num(*n)),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left: left.clone(),
|
||||
right: Box::new(Expr::Num(n - 1.0)),
|
||||
}),
|
||||
}),
|
||||
right: Box::new(diff_raw(left, var)),
|
||||
}
|
||||
} else {
|
||||
// a^u → a^u * ln(a) * u' when a constant
|
||||
if let Expr::Num(a) = left.as_ref() {
|
||||
Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(e.clone()),
|
||||
right: Box::new(Expr::Call {
|
||||
name: "ln".into(),
|
||||
args: vec![Expr::Num(*a)],
|
||||
}),
|
||||
}),
|
||||
right: Box::new(diff_raw(right, var)),
|
||||
}
|
||||
} else {
|
||||
// fallback: treat as exp(v*ln(u))
|
||||
Expr::Num(0.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
Expr::Call { name, args } => {
|
||||
if args.len() != 1 {
|
||||
return Expr::Num(0.0);
|
||||
}
|
||||
let u = &args[0];
|
||||
let du = diff_raw(u, var);
|
||||
let chain = |outer: Expr| {
|
||||
Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(outer),
|
||||
right: Box::new(du.clone()),
|
||||
}
|
||||
};
|
||||
match name.as_str() {
|
||||
"sin" => chain(Expr::Call {
|
||||
name: "cos".into(),
|
||||
args: vec![u.clone()],
|
||||
}),
|
||||
"cos" => chain(Expr::UnaryNeg(Box::new(Expr::Call {
|
||||
name: "sin".into(),
|
||||
args: vec![u.clone()],
|
||||
}))),
|
||||
"tan" => chain(Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left: Box::new(Expr::Call {
|
||||
name: "cos".into(),
|
||||
args: vec![u.clone()],
|
||||
}),
|
||||
right: Box::new(Expr::Num(-2.0)),
|
||||
}),
|
||||
"sqrt" => chain(Expr::Bin {
|
||||
op: BinOp::Div,
|
||||
left: Box::new(Expr::Num(1.0)),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(Expr::Num(2.0)),
|
||||
right: Box::new(Expr::Call {
|
||||
name: "sqrt".into(),
|
||||
args: vec![u.clone()],
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
"ln" | "log" => chain(Expr::Bin {
|
||||
op: BinOp::Div,
|
||||
left: Box::new(Expr::Num(1.0)),
|
||||
right: Box::new(u.clone()),
|
||||
}),
|
||||
"exp" => chain(Expr::Call {
|
||||
name: "exp".into(),
|
||||
args: vec![u.clone()],
|
||||
}),
|
||||
"abs" => {
|
||||
// sign(u)*u' — use u/abs(u) when u≠0
|
||||
chain(Expr::Bin {
|
||||
op: BinOp::Div,
|
||||
left: Box::new(u.clone()),
|
||||
right: Box::new(Expr::Call {
|
||||
name: "abs".into(),
|
||||
args: vec![u.clone()],
|
||||
}),
|
||||
})
|
||||
}
|
||||
_ => Expr::Num(0.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subs(e: &Expr, var: &str, value: &Expr) -> Expr {
|
||||
simplify(&subs_raw(e, var, value))
|
||||
}
|
||||
|
||||
fn subs_raw(e: &Expr, var: &str, value: &Expr) -> Expr {
|
||||
match e {
|
||||
Expr::Num(n) => Expr::Num(*n),
|
||||
Expr::Var(v) => {
|
||||
if v == var {
|
||||
value.clone()
|
||||
} else {
|
||||
Expr::Var(v.clone())
|
||||
}
|
||||
}
|
||||
Expr::UnaryNeg(x) => Expr::UnaryNeg(Box::new(subs_raw(x, var, value))),
|
||||
Expr::Bin { op, left, right } => Expr::Bin {
|
||||
op: *op,
|
||||
left: Box::new(subs_raw(left, var, value)),
|
||||
right: Box::new(subs_raw(right, var, value)),
|
||||
},
|
||||
Expr::Call { name, args } => Expr::Call {
|
||||
name: name.clone(),
|
||||
args: args.iter().map(|a| subs_raw(a, var, value)).collect(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn eval_f64(e: &Expr, env: &HashMap<String, f64>) -> Result<f64, String> {
|
||||
match e {
|
||||
Expr::Num(n) => Ok(*n),
|
||||
Expr::Var(v) => env
|
||||
.get(v)
|
||||
.copied()
|
||||
.ok_or_else(|| format!("unbound variable `{v}`")),
|
||||
Expr::UnaryNeg(x) => Ok(-eval_f64(x, env)?),
|
||||
Expr::Bin { op, left, right } => {
|
||||
let a = eval_f64(left, env)?;
|
||||
let b = eval_f64(right, env)?;
|
||||
Ok(match op {
|
||||
BinOp::Add => a + b,
|
||||
BinOp::Sub => a - b,
|
||||
BinOp::Mul => a * b,
|
||||
BinOp::Div => {
|
||||
if b == 0.0 {
|
||||
return Err("division by zero".into());
|
||||
}
|
||||
a / b
|
||||
}
|
||||
BinOp::Pow => a.powf(b),
|
||||
})
|
||||
}
|
||||
Expr::Call { name, args } => {
|
||||
let mut xs = Vec::with_capacity(args.len());
|
||||
for a in args {
|
||||
xs.push(eval_f64(a, env)?);
|
||||
}
|
||||
eval_call_f64(name, &xs).ok_or_else(|| format!("unknown or arity-mismatch function `{name}`"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_call_f64(name: &str, args: &[f64]) -> Option<f64> {
|
||||
match (name, args) {
|
||||
("sin", [x]) => Some(x.sin()),
|
||||
("cos", [x]) => Some(x.cos()),
|
||||
("tan", [x]) => Some(x.tan()),
|
||||
("asin", [x]) => Some(x.asin()),
|
||||
("acos", [x]) => Some(x.acos()),
|
||||
("atan", [x]) => Some(x.atan()),
|
||||
("sqrt", [x]) => Some(x.sqrt()),
|
||||
("abs", [x]) => Some(x.abs()),
|
||||
("ln" | "log", [x]) => Some(x.ln()),
|
||||
("exp", [x]) => Some(x.exp()),
|
||||
("floor", [x]) => Some(x.floor()),
|
||||
("ceil", [x]) => Some(x.ceil()),
|
||||
("pow", [a, b]) => Some(a.powf(*b)),
|
||||
("min", [a, b]) => Some(a.min(*b)),
|
||||
("max", [a, b]) => Some(a.max(*b)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Solve `e = 0` for `var`. Quadratic/linear closed form; else numeric scan.
|
||||
pub fn solve(e: &Expr, var: &str, xmin: f64, xmax: f64) -> Result<Vec<f64>, String> {
|
||||
let e = expand(&simplify(e));
|
||||
if let Some(roots) = try_polynomial_solve(&e, var) {
|
||||
return Ok(roots);
|
||||
}
|
||||
numeric_roots(&e, var, xmin, xmax)
|
||||
}
|
||||
|
||||
fn try_polynomial_solve(e: &Expr, var: &str) -> Option<Vec<f64>> {
|
||||
let (a, b, c) = poly_coeffs_quadratic(e, var)?;
|
||||
if a.abs() < 1e-12 {
|
||||
if b.abs() < 1e-12 {
|
||||
return if c.abs() < 1e-12 {
|
||||
None // identity
|
||||
} else {
|
||||
Some(vec![])
|
||||
};
|
||||
}
|
||||
return Some(vec![-c / b]);
|
||||
}
|
||||
let disc = b * b - 4.0 * a * c;
|
||||
if disc < -1e-12 {
|
||||
return Some(vec![]);
|
||||
}
|
||||
if disc.abs() <= 1e-12 {
|
||||
return Some(vec![-b / (2.0 * a)]);
|
||||
}
|
||||
let s = disc.sqrt();
|
||||
let mut roots = vec![(-b - s) / (2.0 * a), (-b + s) / (2.0 * a)];
|
||||
roots.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal));
|
||||
Some(roots)
|
||||
}
|
||||
|
||||
/// Collect ax^2+bx+c if expression is a polynomial of degree ≤ 2 in `var`.
|
||||
fn poly_coeffs_quadratic(e: &Expr, var: &str) -> Option<(f64, f64, f64)> {
|
||||
let mut a = 0.0;
|
||||
let mut b = 0.0;
|
||||
let mut c = 0.0;
|
||||
if !accum_poly(e, var, 1.0, &mut a, &mut b, &mut c) {
|
||||
return None;
|
||||
}
|
||||
Some((a, b, c))
|
||||
}
|
||||
|
||||
fn accum_poly(e: &Expr, var: &str, scale: f64, a: &mut f64, b: &mut f64, c: &mut f64) -> bool {
|
||||
match e {
|
||||
Expr::Num(n) => {
|
||||
*c += scale * n;
|
||||
true
|
||||
}
|
||||
Expr::Var(v) if v == var => {
|
||||
*b += scale;
|
||||
true
|
||||
}
|
||||
Expr::Var(_) => false,
|
||||
Expr::UnaryNeg(x) => accum_poly(x, var, -scale, a, b, c),
|
||||
Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left,
|
||||
right,
|
||||
} => accum_poly(left, var, scale, a, b, c) && accum_poly(right, var, scale, a, b, c),
|
||||
Expr::Bin {
|
||||
op: BinOp::Sub,
|
||||
left,
|
||||
right,
|
||||
} => accum_poly(left, var, scale, a, b, c) && accum_poly(right, var, -scale, a, b, c),
|
||||
Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left,
|
||||
right,
|
||||
} => match (left.as_ref(), right.as_ref()) {
|
||||
(Expr::Num(n), r) => accum_poly(r, var, scale * n, a, b, c),
|
||||
(l, Expr::Num(n)) => accum_poly(l, var, scale * n, a, b, c),
|
||||
(Expr::Var(v), Expr::Var(w)) if v == var && w == var => {
|
||||
*a += scale;
|
||||
true
|
||||
}
|
||||
(
|
||||
Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left: base,
|
||||
right: exp,
|
||||
},
|
||||
other,
|
||||
)
|
||||
| (
|
||||
other,
|
||||
Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left: base,
|
||||
right: exp,
|
||||
},
|
||||
) => {
|
||||
if let (Expr::Var(v), Expr::Num(2.0)) = (base.as_ref(), exp.as_ref()) {
|
||||
if v == var {
|
||||
if let Expr::Num(n) = other {
|
||||
*a += scale * n;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left,
|
||||
right,
|
||||
} => match (left.as_ref(), right.as_ref()) {
|
||||
(Expr::Var(v), Expr::Num(2.0)) if v == var => {
|
||||
*a += scale;
|
||||
true
|
||||
}
|
||||
(Expr::Var(v), Expr::Num(1.0)) if v == var => {
|
||||
*b += scale;
|
||||
true
|
||||
}
|
||||
(Expr::Var(v), Expr::Num(0.0)) if v == var => {
|
||||
*c += scale;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn numeric_roots(e: &Expr, var: &str, xmin: f64, xmax: f64) -> Result<Vec<f64>, String> {
|
||||
const STEPS: usize = 200;
|
||||
let mut roots = Vec::new();
|
||||
let mut env = HashMap::new();
|
||||
let dx = (xmax - xmin) / STEPS as f64;
|
||||
let mut x0 = xmin;
|
||||
env.insert(var.to_string(), x0);
|
||||
let mut y0 = eval_f64(e, &env)?;
|
||||
for i in 1..=STEPS {
|
||||
let x1 = xmin + dx * i as f64;
|
||||
env.insert(var.to_string(), x1);
|
||||
let y1 = eval_f64(e, &env)?;
|
||||
if y0 == 0.0 {
|
||||
push_unique(&mut roots, x0);
|
||||
} else if y0.signum() != y1.signum() && y1 != 0.0 {
|
||||
// bisection
|
||||
let mut lo = x0;
|
||||
let mut hi = x1;
|
||||
let mut flo = y0;
|
||||
for _ in 0..40 {
|
||||
let mid = 0.5 * (lo + hi);
|
||||
env.insert(var.to_string(), mid);
|
||||
let fm = eval_f64(e, &env)?;
|
||||
if fm == 0.0 || (hi - lo).abs() < 1e-10 {
|
||||
push_unique(&mut roots, mid);
|
||||
break;
|
||||
}
|
||||
if flo.signum() == fm.signum() {
|
||||
lo = mid;
|
||||
flo = fm;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
if i == STEPS && y1 == 0.0 {
|
||||
push_unique(&mut roots, x1);
|
||||
}
|
||||
x0 = x1;
|
||||
y0 = y1;
|
||||
}
|
||||
Ok(roots)
|
||||
}
|
||||
|
||||
fn push_unique(xs: &mut Vec<f64>, x: f64) {
|
||||
if xs.iter().any(|y| (y - x).abs() < 1e-6) {
|
||||
return;
|
||||
}
|
||||
xs.push(x);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_and_diff_quadratic() {
|
||||
let e = parse("x^2 - 2").unwrap();
|
||||
let d = diff(&e, "x");
|
||||
assert_eq!(d.as_display(), "2*x");
|
||||
let roots = solve(&e, "x", -10.0, 10.0).unwrap();
|
||||
assert_eq!(roots.len(), 2);
|
||||
assert!((roots[0] + 2f64.sqrt()).abs() < 1e-6);
|
||||
assert!((roots[1] - 2f64.sqrt()).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_sin() {
|
||||
let e = parse("sin(x)").unwrap();
|
||||
let mut env = HashMap::new();
|
||||
env.insert("x".into(), 0.0);
|
||||
assert!((eval_f64(&e, &env).unwrap()).abs() < 1e-12);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
//! SVG plot helpers for high-school graphs.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::{eval_f64, Expr};
|
||||
|
||||
const MAX_STEPS: usize = 2000;
|
||||
const DEFAULT_STEPS: usize = 200;
|
||||
const SVG_W: f64 = 520.0;
|
||||
const SVG_H: f64 = 360.0;
|
||||
const PAD: f64 = 36.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct PlotStyle {
|
||||
pub grid: bool,
|
||||
}
|
||||
|
||||
impl Default for PlotStyle {
|
||||
fn default() -> Self {
|
||||
Self { grid: true }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn plot_function_svg(
|
||||
expr: &Expr,
|
||||
var: &str,
|
||||
xmin: f64,
|
||||
xmax: f64,
|
||||
steps: usize,
|
||||
style: PlotStyle,
|
||||
) -> Result<String, String> {
|
||||
if !(xmin.is_finite() && xmax.is_finite()) || xmax <= xmin {
|
||||
return Err("plot needs finite min < max".into());
|
||||
}
|
||||
let steps = steps.clamp(2, MAX_STEPS);
|
||||
let mut env = HashMap::new();
|
||||
let mut pts: Vec<(f64, f64)> = Vec::with_capacity(steps + 1);
|
||||
let mut ymin = f64::INFINITY;
|
||||
let mut ymax = f64::NEG_INFINITY;
|
||||
for i in 0..=steps {
|
||||
let x = xmin + (xmax - xmin) * (i as f64) / (steps as f64);
|
||||
env.insert(var.to_string(), x);
|
||||
match eval_f64(expr, &env) {
|
||||
Ok(y) if y.is_finite() => {
|
||||
ymin = ymin.min(y);
|
||||
ymax = ymax.max(y);
|
||||
pts.push((x, y));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if pts.is_empty() {
|
||||
return Err("plot produced no finite points".into());
|
||||
}
|
||||
if (ymax - ymin).abs() < 1e-12 {
|
||||
ymin -= 1.0;
|
||||
ymax += 1.0;
|
||||
}
|
||||
let pad_y = 0.05 * (ymax - ymin);
|
||||
ymin -= pad_y;
|
||||
ymax += pad_y;
|
||||
|
||||
let mut path = String::new();
|
||||
for (i, (x, y)) in pts.iter().enumerate() {
|
||||
let (sx, sy) = map_xy(*x, *y, xmin, xmax, ymin, ymax);
|
||||
if i == 0 {
|
||||
path.push_str(&format!("M {sx:.2} {sy:.2}"));
|
||||
} else {
|
||||
path.push_str(&format!(" L {sx:.2} {sy:.2}"));
|
||||
}
|
||||
}
|
||||
|
||||
let frame = draw_frame(xmin, xmax, ymin, ymax, style);
|
||||
Ok(svg_wrap(
|
||||
&format!(r#"{frame}<path d="{path}" class="curve"/>"#),
|
||||
"function plot",
|
||||
))
|
||||
}
|
||||
|
||||
pub fn plot_points_svg(xs: &[f64], ys: &[f64], style: PlotStyle) -> Result<String, String> {
|
||||
if xs.len() != ys.len() {
|
||||
return Err("plot_points: xs and ys length mismatch".into());
|
||||
}
|
||||
if xs.is_empty() {
|
||||
return Err("plot_points: empty series".into());
|
||||
}
|
||||
let xmin = xs.iter().cloned().fold(f64::INFINITY, f64::min);
|
||||
let xmax = xs.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
|
||||
let ymin = ys.iter().cloned().fold(f64::INFINITY, f64::min);
|
||||
let ymax = ys.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
|
||||
let (xmin, xmax) = pad_range(xmin, xmax);
|
||||
let (ymin, ymax) = pad_range(ymin, ymax);
|
||||
let mut dots = String::new();
|
||||
for (x, y) in xs.iter().zip(ys.iter()) {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let (sx, sy) = map_xy(*x, *y, xmin, xmax, ymin, ymax);
|
||||
dots.push_str(&format!(
|
||||
r#"<circle cx="{sx:.2}" cy="{sy:.2}" r="3" class="pt"/>"#
|
||||
));
|
||||
}
|
||||
let frame = draw_frame(xmin, xmax, ymin, ymax, style);
|
||||
Ok(svg_wrap(&format!("{frame}{dots}"), "points plot"))
|
||||
}
|
||||
|
||||
/// Standard conics via parametric sampling.
|
||||
/// kind: circle | ellipse | hyperbola | parabola
|
||||
pub fn plot_conic_svg(
|
||||
kind: &str,
|
||||
a: f64,
|
||||
b: f64,
|
||||
h: f64,
|
||||
k: f64,
|
||||
style: PlotStyle,
|
||||
) -> Result<String, String> {
|
||||
let steps = DEFAULT_STEPS;
|
||||
let mut pts: Vec<(f64, f64)> = Vec::new();
|
||||
match kind {
|
||||
"circle" => {
|
||||
let r = if a > 0.0 { a } else { b };
|
||||
if r <= 0.0 {
|
||||
return Err("circle needs positive radius (a)".into());
|
||||
}
|
||||
for i in 0..=steps {
|
||||
let t = std::f64::consts::TAU * (i as f64) / (steps as f64);
|
||||
pts.push((h + r * t.cos(), k + r * t.sin()));
|
||||
}
|
||||
}
|
||||
"ellipse" => {
|
||||
if a <= 0.0 || b <= 0.0 {
|
||||
return Err("ellipse needs a>0, b>0".into());
|
||||
}
|
||||
for i in 0..=steps {
|
||||
let t = std::f64::consts::TAU * (i as f64) / (steps as f64);
|
||||
pts.push((h + a * t.cos(), k + b * t.sin()));
|
||||
}
|
||||
}
|
||||
"hyperbola" => {
|
||||
if a <= 0.0 || b <= 0.0 {
|
||||
return Err("hyperbola needs a>0, b>0".into());
|
||||
}
|
||||
for branch in [-1.0_f64, 1.0] {
|
||||
for i in 0..=steps {
|
||||
let t = -2.0 + 4.0 * (i as f64) / (steps as f64);
|
||||
pts.push((h + branch * a * t.cosh(), k + b * t.sinh()));
|
||||
}
|
||||
}
|
||||
let mid = pts.len() / 2;
|
||||
let (left, right) = pts.split_at(mid);
|
||||
let xmin = pts.iter().map(|p| p.0).fold(f64::INFINITY, f64::min);
|
||||
let xmax = pts.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max);
|
||||
let ymin = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
|
||||
let ymax = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max);
|
||||
let (xmin, xmax) = pad_range(xmin, xmax);
|
||||
let (ymin, ymax) = pad_range(ymin, ymax);
|
||||
let p1 = polyline_path(left, xmin, xmax, ymin, ymax);
|
||||
let p2 = polyline_path(right, xmin, xmax, ymin, ymax);
|
||||
let frame = draw_frame(xmin, xmax, ymin, ymax, style);
|
||||
return Ok(svg_wrap(
|
||||
&format!(
|
||||
r#"{frame}<path d="{p1}" class="curve"/><path d="{p2}" class="curve"/>"#
|
||||
),
|
||||
"hyperbola",
|
||||
));
|
||||
}
|
||||
"parabola" => {
|
||||
let scale = if a.abs() > 1e-12 { a } else { 1.0 };
|
||||
for i in 0..=steps {
|
||||
let t = -3.0 + 6.0 * (i as f64) / (steps as f64);
|
||||
let x = h + t;
|
||||
let y = k + (t * t) / (4.0 * scale.abs()) * scale.signum();
|
||||
pts.push((x, y));
|
||||
}
|
||||
}
|
||||
other => return Err(format!("unknown conic kind `{other}`")),
|
||||
}
|
||||
|
||||
let xmin = pts.iter().map(|p| p.0).fold(f64::INFINITY, f64::min);
|
||||
let xmax = pts.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max);
|
||||
let ymin = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
|
||||
let ymax = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max);
|
||||
let (xmin, xmax) = pad_range(xmin, xmax);
|
||||
let (ymin, ymax) = pad_range(ymin, ymax);
|
||||
let path = polyline_path(&pts, xmin, xmax, ymin, ymax);
|
||||
let frame = draw_frame(xmin, xmax, ymin, ymax, style);
|
||||
Ok(svg_wrap(
|
||||
&format!(r#"{frame}<path d="{path}" class="curve"/>"#),
|
||||
kind,
|
||||
))
|
||||
}
|
||||
|
||||
fn pad_range(lo: f64, hi: f64) -> (f64, f64) {
|
||||
if (hi - lo).abs() < 1e-12 {
|
||||
(lo - 1.0, hi + 1.0)
|
||||
} else {
|
||||
let pad = 0.05 * (hi - lo);
|
||||
(lo - pad, hi + pad)
|
||||
}
|
||||
}
|
||||
|
||||
fn polyline_path(pts: &[(f64, f64)], xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> String {
|
||||
let mut path = String::new();
|
||||
for (i, (x, y)) in pts.iter().enumerate() {
|
||||
let (sx, sy) = map_xy(*x, *y, xmin, xmax, ymin, ymax);
|
||||
if i == 0 {
|
||||
path.push_str(&format!("M {sx:.2} {sy:.2}"));
|
||||
} else {
|
||||
path.push_str(&format!(" L {sx:.2} {sy:.2}"));
|
||||
}
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
fn map_xy(x: f64, y: f64, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> (f64, f64) {
|
||||
let w = SVG_W - 2.0 * PAD;
|
||||
let h = SVG_H - 2.0 * PAD;
|
||||
let sx = PAD + (x - xmin) / (xmax - xmin) * w;
|
||||
let sy = PAD + (ymax - y) / (ymax - ymin) * h;
|
||||
(sx, sy)
|
||||
}
|
||||
|
||||
fn nice_step(span: f64, target: usize) -> f64 {
|
||||
let target = target.max(2) as f64;
|
||||
let raw = (span / target).abs().max(1e-12);
|
||||
let exp = raw.log10().floor();
|
||||
let mag = 10f64.powf(exp);
|
||||
let norm = raw / mag;
|
||||
let nice = if norm <= 1.5 {
|
||||
1.0
|
||||
} else if norm <= 3.0 {
|
||||
2.0
|
||||
} else if norm <= 7.0 {
|
||||
5.0
|
||||
} else {
|
||||
10.0
|
||||
};
|
||||
nice * mag
|
||||
}
|
||||
|
||||
fn tick_values(lo: f64, hi: f64, step: f64) -> Vec<f64> {
|
||||
if step <= 0.0 || !step.is_finite() {
|
||||
return Vec::new();
|
||||
}
|
||||
let start = (lo / step).ceil() * step;
|
||||
let mut out = Vec::new();
|
||||
let mut v = start;
|
||||
let mut guard = 0;
|
||||
while v <= hi + step * 1e-9 && guard < 200 {
|
||||
if v >= lo - step * 1e-9 && v <= hi + step * 1e-9 {
|
||||
if v.abs() < step * 1e-9 {
|
||||
out.push(0.0);
|
||||
} else {
|
||||
out.push(v);
|
||||
}
|
||||
}
|
||||
v += step;
|
||||
guard += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn draw_frame(xmin: f64, xmax: f64, ymin: f64, ymax: f64, style: PlotStyle) -> String {
|
||||
let left = PAD;
|
||||
let right = SVG_W - PAD;
|
||||
let top = PAD;
|
||||
let bottom = SVG_H - PAD;
|
||||
|
||||
let (ox, _) = map_xy(0.0, 0.0, xmin, xmax, ymin, ymax);
|
||||
let (_, oy) = map_xy(0.0, 0.0, xmin, xmax, ymin, ymax);
|
||||
let axis_x_y = if ymin <= 0.0 && ymax >= 0.0 {
|
||||
oy.clamp(top, bottom)
|
||||
} else if ymax < 0.0 {
|
||||
top
|
||||
} else {
|
||||
bottom
|
||||
};
|
||||
let axis_y_x = if xmin <= 0.0 && xmax >= 0.0 {
|
||||
ox.clamp(left, right)
|
||||
} else if xmax < 0.0 {
|
||||
right
|
||||
} else {
|
||||
left
|
||||
};
|
||||
|
||||
let mut s = String::new();
|
||||
let x_step = nice_step(xmax - xmin, 8);
|
||||
let y_step = nice_step(ymax - ymin, 6);
|
||||
|
||||
if style.grid {
|
||||
for x in tick_values(xmin, xmax, x_step) {
|
||||
let (sx, _) = map_xy(x, 0.0, xmin, xmax, ymin, ymax);
|
||||
if sx < left - 0.5 || sx > right + 0.5 {
|
||||
continue;
|
||||
}
|
||||
s.push_str(&format!(
|
||||
r#"<line x1="{sx:.2}" y1="{top}" x2="{sx:.2}" y2="{bottom}" class="grid"/>"#
|
||||
));
|
||||
}
|
||||
for y in tick_values(ymin, ymax, y_step) {
|
||||
let (_, sy) = map_xy(0.0, y, xmin, xmax, ymin, ymax);
|
||||
if sy < top - 0.5 || sy > bottom + 0.5 {
|
||||
continue;
|
||||
}
|
||||
s.push_str(&format!(
|
||||
r#"<line x1="{left}" y1="{sy:.2}" x2="{right}" y2="{sy:.2}" class="grid"/>"#
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Axes with arrowheads (positive direction).
|
||||
s.push_str(&format!(
|
||||
r#"<line x1="{left}" y1="{axis_x_y:.2}" x2="{right}" y2="{axis_x_y:.2}" class="axis" marker-end="url(#arrow)"/>"#
|
||||
));
|
||||
s.push_str(&format!(
|
||||
r#"<line x1="{axis_y_x:.2}" y1="{bottom}" x2="{axis_y_x:.2}" y2="{top}" class="axis" marker-end="url(#arrow)"/>"#
|
||||
));
|
||||
|
||||
// Axis end labels
|
||||
s.push_str(&format!(
|
||||
r#"<text x="{x:.2}" y="{y:.2}" class="axis-label">x</text>"#,
|
||||
x = right + 4.0,
|
||||
y = axis_x_y + 4.0,
|
||||
));
|
||||
s.push_str(&format!(
|
||||
r#"<text x="{x:.2}" y="{y:.2}" class="axis-label">y</text>"#,
|
||||
x = axis_y_x + 6.0,
|
||||
y = top + 4.0,
|
||||
));
|
||||
|
||||
// Tick labels along axes (skip 0 clutter when both axes cross).
|
||||
for x in tick_values(xmin, xmax, x_step) {
|
||||
if x.abs() < x_step * 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let (sx, _) = map_xy(x, 0.0, xmin, xmax, ymin, ymax);
|
||||
if sx < left || sx > right {
|
||||
continue;
|
||||
}
|
||||
s.push_str(&format!(
|
||||
r#"<line x1="{sx:.2}" y1="{y1:.2}" x2="{sx:.2}" y2="{y2:.2}" class="tick"/>"#,
|
||||
y1 = axis_x_y - 4.0,
|
||||
y2 = axis_x_y + 4.0,
|
||||
));
|
||||
s.push_str(&format!(
|
||||
r#"<text x="{sx:.2}" y="{ty:.2}" text-anchor="middle" class="tick-label">{label}</text>"#,
|
||||
ty = (axis_x_y + 14.0).min(bottom + 14.0),
|
||||
label = super::format_num(x),
|
||||
));
|
||||
}
|
||||
for y in tick_values(ymin, ymax, y_step) {
|
||||
if y.abs() < y_step * 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let (_, sy) = map_xy(0.0, y, xmin, xmax, ymin, ymax);
|
||||
if sy < top || sy > bottom {
|
||||
continue;
|
||||
}
|
||||
s.push_str(&format!(
|
||||
r#"<line x1="{x1:.2}" y1="{sy:.2}" x2="{x2:.2}" y2="{sy:.2}" class="tick"/>"#,
|
||||
x1 = axis_y_x - 4.0,
|
||||
x2 = axis_y_x + 4.0,
|
||||
));
|
||||
s.push_str(&format!(
|
||||
r#"<text x="{tx:.2}" y="{sy:.2}" text-anchor="end" dominant-baseline="middle" class="tick-label">{label}</text>"#,
|
||||
tx = (axis_y_x - 8.0).max(4.0),
|
||||
label = super::format_num(y),
|
||||
));
|
||||
}
|
||||
|
||||
// Origin mark when visible
|
||||
if xmin <= 0.0 && xmax >= 0.0 && ymin <= 0.0 && ymax >= 0.0 {
|
||||
s.push_str(&format!(
|
||||
r#"<text x="{x:.2}" y="{y:.2}" class="tick-label">0</text>"#,
|
||||
x = axis_y_x - 8.0,
|
||||
y = axis_x_y + 14.0,
|
||||
));
|
||||
}
|
||||
|
||||
s
|
||||
}
|
||||
|
||||
fn svg_wrap(body: &str, title: &str) -> String {
|
||||
// r## so fill="#…" does not terminate the raw string at "#
|
||||
format!(
|
||||
r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" width="{w}" height="{h}" role="img" aria-label="{title}">
|
||||
<defs>
|
||||
<marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#4b5563"/>
|
||||
</marker>
|
||||
</defs>
|
||||
<style>
|
||||
.grid {{ stroke: #e5e7eb; stroke-width: 1; }}
|
||||
.axis {{ stroke: #4b5563; stroke-width: 1.5; }}
|
||||
.tick {{ stroke: #4b5563; stroke-width: 1; }}
|
||||
.curve {{ fill: none; stroke: #1f6feb; stroke-width: 2; }}
|
||||
.pt {{ fill: #1f6feb; }}
|
||||
.axis-label {{ font: 12px ui-sans-serif, system-ui, sans-serif; fill: #374151; font-weight: 600; }}
|
||||
.tick-label {{ font: 10px ui-sans-serif, system-ui, sans-serif; fill: #6b7280; }}
|
||||
</style>
|
||||
{body}
|
||||
</svg>"##,
|
||||
w = SVG_W,
|
||||
h = SVG_H,
|
||||
title = title,
|
||||
body = body,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::formula::parse;
|
||||
|
||||
#[test]
|
||||
fn plot_has_arrows_and_grid_by_default() {
|
||||
let e = parse("x^2").unwrap();
|
||||
let svg = plot_function_svg(&e, "x", -2.0, 2.0, 40, PlotStyle::default()).unwrap();
|
||||
assert!(svg.contains("marker-end=\"url(#arrow)\""));
|
||||
assert!(svg.contains("class=\"grid\""));
|
||||
assert!(svg.contains(">x</text>"));
|
||||
assert!(svg.contains(">y</text>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plot_can_disable_grid() {
|
||||
let e = parse("x").unwrap();
|
||||
let svg = plot_function_svg(&e, "x", -1.0, 1.0, 20, PlotStyle { grid: false }).unwrap();
|
||||
assert!(!svg.contains("class=\"grid\""));
|
||||
assert!(svg.contains("marker-end=\"url(#arrow)\""));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user