use crate::core::types::{AstNode, EvalResult};
use num_traits::Signed;
pub fn format_latex_scalar(v: f64) -> String {
if v.is_nan() {
return "\\text{NaN}".to_string();
}
if v.is_infinite() {
return if v > 0.0 {
"\\infty".to_string()
} else {
"-\\infty".to_string()
};
}
if v.fract() == 0.0 && v.abs() < 9e15 {
format!("{}", v as i64)
} else {
format!("{}", v)
}
}
pub fn format_latex_complex(re: f64, im: f64) -> String {
let re_s = format_latex_scalar(re);
if im >= 0.0 {
format!("{} + {}i", re_s, format_latex_scalar(im))
} else {
format!("{} - {}i", re_s, format_latex_scalar(-im))
}
}
pub fn format_latex_matrix(m: &[Vec<f64>]) -> String {
let rows: Vec<String> = m
.iter()
.map(|row| {
let elems: Vec<String> = row.iter().map(|v| format_latex_scalar(*v)).collect();
elems.join(" & ")
})
.collect();
format!("\\begin{{pmatrix}}{}\\end{{pmatrix}}", rows.join(" \\\\ "))
}
pub fn format_latex_vector(v: &[f64]) -> String {
let elems: Vec<String> = v.iter().map(|x| format_latex_scalar(*x)).collect();
format!("\\left[{}\\right]", elems.join(", "))
}
pub fn format_latex_polynomial(p: &[f64]) -> String {
if p.is_empty() {
return "0".to_string();
}
let mut terms: Vec<String> = Vec::new();
for (i, &coef) in p.iter().enumerate().rev() {
if coef == 0.0 {
continue;
}
let term = match i {
0 => format_latex_scalar(coef),
1 => {
if coef == 1.0 {
"x".to_string()
} else if coef == -1.0 {
"-x".to_string()
} else {
format!("{}x", format_latex_scalar(coef))
}
}
_ => {
if coef == 1.0 {
format!("x^{{{}}}", i)
} else if coef == -1.0 {
format!("-x^{{{}}}", i)
} else {
format!("{}x^{{{}}}", format_latex_scalar(coef), i)
}
}
};
terms.push(term);
}
if terms.is_empty() {
return "0".to_string();
}
let mut result = terms[0].clone();
for term in &terms[1..] {
if term.starts_with('-') {
result.push_str(term);
} else {
result.push_str(" + ");
result.push_str(term);
}
}
result
}
pub fn format_latex_bigint(b: &num_bigint::BigInt) -> String {
b.to_string()
}
pub fn format_latex_bigrational(r: &num_rational::BigRational, fmt_prec: Option<usize>) -> String {
if let Some(prec) = fmt_prec {
let neg = r.is_negative();
let abs = r.abs();
let numer = abs.numer();
let denom = abs.denom();
let int_part = numer / denom;
let remainder = numer % denom;
let mut scale = num_bigint::BigInt::from(1);
let ten = num_bigint::BigInt::from(10);
for _ in 0..prec {
scale *= &ten;
}
let scaled = remainder * &scale;
let frac_digits = scaled / denom;
let int_str = int_part.to_string();
let frac_str = format!("{:0>width$}", frac_digits.to_string(), width = prec);
let sign = if neg { "-" } else { "" };
if prec == 0 {
format!("{}{}", sign, int_str)
} else {
format!("{}{}.{}", sign, int_str, frac_str)
}
} else {
format!("\\frac{{{}}}{{{}}}", r.numer(), r.denom())
}
}
pub fn format_latex_complex_list(c: &[(f64, f64)]) -> String {
let elems: Vec<String> = c
.iter()
.map(|(re, im)| format_latex_complex(*re, *im))
.collect();
format!("\\left[{}\\right]", elems.join(", "))
}
pub fn format_latex_symbolic(op_name: &str, ast: &AstNode, result_str: &str) -> String {
let result_latex = symbolic_str_to_latex(result_str);
let args = match ast {
AstNode::FunctionCall(_, args) => args,
_ => return result_latex,
};
match op_name {
"diff" => {
let var = args
.get(1)
.and_then(ast_to_latex_expr)
.unwrap_or_else(|| "x".to_string());
let body = args
.first()
.and_then(ast_to_latex_expr)
.unwrap_or_else(|| result_latex.clone());
format!(
"\\frac{{d}}{{d{var}}}\\left({body}\\right) = {result_latex}",
var = var,
body = body,
result_latex = result_latex
)
}
"integrate" => {
let var = args
.get(1)
.and_then(ast_to_latex_expr)
.unwrap_or_else(|| "x".to_string());
let body = args
.first()
.and_then(ast_to_latex_expr)
.unwrap_or_else(|| "".to_string());
format!(
"\\int {body} \\, d{var} = {result_latex}",
body = body,
var = var,
result_latex = result_latex
)
}
"limit" => {
let var = args
.get(1)
.and_then(ast_to_latex_expr)
.unwrap_or_else(|| "x".to_string());
let point = args
.get(2)
.and_then(ast_to_latex_expr)
.unwrap_or_else(|| "0".to_string());
let body = args
.first()
.and_then(ast_to_latex_expr)
.unwrap_or_else(|| "".to_string());
format!(
"\\lim_{{{var} \\to {point}}} {body} = {result_latex}",
var = var,
point = point,
body = body,
result_latex = result_latex
)
}
"series" | "taylor" => {
let body = args
.first()
.and_then(ast_to_latex_expr)
.unwrap_or_else(|| "".to_string());
format!(
"\\text{{Taylor series of}} {body} = {result_latex}",
body = body,
result_latex = result_latex
)
}
_ => result_latex,
}
}
fn ast_to_latex_expr(node: &AstNode) -> Option<String> {
match node {
AstNode::Number(n) => Some(format_latex_scalar(*n)),
AstNode::BigNumber(s) => Some(s.clone()),
AstNode::Variable(name) => Some(name.clone()),
AstNode::BinaryOp(op, lhs, rhs) => {
let l = ast_to_latex_expr(lhs)?;
let r = ast_to_latex_expr(rhs)?;
let op_str = match op {
crate::core::types::BinaryOp::Add => format!("{} + {}", l, r),
crate::core::types::BinaryOp::Sub => format!("{} - {}", l, r),
crate::core::types::BinaryOp::Mul => format!("{} \\cdot {}", l, r),
crate::core::types::BinaryOp::Div => format!("\\frac{{{}}}{{{}}}", l, r),
crate::core::types::BinaryOp::Pow => format!("{}^{{{}}}", l, r),
crate::core::types::BinaryOp::Mod => format!("{} \\bmod {}", l, r),
};
Some(op_str)
}
AstNode::UnaryOp(op, expr) => {
let e = ast_to_latex_expr(expr)?;
Some(match op {
crate::core::types::UnaryOp::Neg => format!("-{}", e),
crate::core::types::UnaryOp::Factorial => format!("{}!", e),
crate::core::types::UnaryOp::Abs => format!("\\left|{}\\right|", e),
})
}
AstNode::FunctionCall(name, args) => {
let args_latex: Vec<String> = args.iter().filter_map(ast_to_latex_expr).collect();
Some(format!("{}({})", name, args_latex.join(", ")))
}
_ => None,
}
}
fn symbolic_str_to_latex(s: &str) -> String {
s.replace('*', " \\cdot ")
}
pub fn format_latex(
result: &EvalResult,
ast: &AstNode,
_expr: &str,
fmt_prec: Option<usize>,
) -> String {
match result {
EvalResult::Scalar(v) => format_latex_scalar(*v),
EvalResult::Complex(re, im) => format_latex_complex(*re, *im),
EvalResult::Matrix(m) => format_latex_matrix(m),
EvalResult::BigInt(b) => format_latex_bigint(b),
EvalResult::BigRational(r) => format_latex_bigrational(r, fmt_prec),
EvalResult::Vector(v) => format_latex_vector(v),
EvalResult::Polynomial(p) => format_latex_polynomial(p),
EvalResult::ComplexList(c) => format_latex_complex_list(c),
EvalResult::Symbolic(s) => {
if let AstNode::FunctionCall(name, _) = ast {
if matches!(
name.as_str(),
"diff" | "integrate" | "limit" | "series" | "taylor"
) {
return format_latex_symbolic(name, ast, s);
}
}
symbolic_str_to_latex(s)
}
EvalResult::LaTeX(s) => s.clone(),
EvalResult::Steps(v) => v.join(" \\to "),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::types::{BinaryOp, UnaryOp};
#[test]
fn latex_scalar_integer() {
assert_eq!(format_latex_scalar(42.0), "42");
assert_eq!(format_latex_scalar(-7.0), "-7");
}
#[test]
fn latex_scalar_decimal() {
assert_eq!(format_latex_scalar(3.14), "3.14");
}
#[test]
fn latex_scalar_nan_inf() {
assert_eq!(format_latex_scalar(f64::NAN), "\\text{NaN}");
assert_eq!(format_latex_scalar(f64::INFINITY), "\\infty");
assert_eq!(format_latex_scalar(f64::NEG_INFINITY), "-\\infty");
}
#[test]
fn latex_complex_positive_im() {
assert_eq!(format_latex_complex(3.0, 4.0), "3 + 4i");
}
#[test]
fn latex_complex_negative_im() {
assert_eq!(format_latex_complex(3.0, -4.0), "3 - 4i");
}
#[test]
fn latex_matrix_2x2() {
let m = vec![vec![1.0, 2.0], vec![3.0, 4.0]];
assert_eq!(
format_latex_matrix(&m),
"\\begin{pmatrix}1 & 2 \\\\ 3 & 4\\end{pmatrix}"
);
}
#[test]
fn latex_vector() {
assert_eq!(
format_latex_vector(&[1.0, 2.0, 3.0]),
"\\left[1, 2, 3\\right]"
);
}
#[test]
fn latex_polynomial_simple() {
assert_eq!(format_latex_polynomial(&[1.0, 2.0, 1.0]), "x^{2} + 2x + 1");
}
#[test]
fn latex_polynomial_negative_coef() {
assert_eq!(format_latex_polynomial(&[1.0, -1.0]), "-x + 1");
}
#[test]
fn latex_polynomial_zero() {
assert_eq!(format_latex_polynomial(&[]), "0");
assert_eq!(format_latex_polynomial(&[0.0, 0.0]), "0");
}
#[test]
fn latex_bigint() {
let b = num_bigint::BigInt::from(123456789);
assert_eq!(format_latex_bigint(&b), "123456789");
}
#[test]
fn latex_bigrational_fraction() {
let r = num_rational::BigRational::new(
num_bigint::BigInt::from(1),
num_bigint::BigInt::from(3),
);
assert_eq!(format_latex_bigrational(&r, None), "\\frac{1}{3}");
}
#[test]
fn latex_bigrational_decimal() {
let r = num_rational::BigRational::new(
num_bigint::BigInt::from(1),
num_bigint::BigInt::from(2),
);
assert_eq!(format_latex_bigrational(&r, Some(3)), "0.500");
}
#[test]
fn latex_complex_list() {
let c = vec![(1.0, 2.0), (3.0, -4.0)];
assert_eq!(
format_latex_complex_list(&c),
"\\left[1 + 2i, 3 - 4i\\right]"
);
}
#[test]
fn latex_symbolic_diff() {
let ast = AstNode::FunctionCall(
"diff".to_string(),
vec![
AstNode::BinaryOp(
BinaryOp::Pow,
Box::new(AstNode::Variable("x".to_string())),
Box::new(AstNode::Number(2.0)),
),
AstNode::Variable("x".to_string()),
],
);
let s = format_latex_symbolic("diff", &ast, "2*x");
assert_eq!(s, "\\frac{d}{dx}\\left(x^{2}\\right) = 2 \\cdot x");
}
#[test]
fn latex_symbolic_integrate() {
let ast = AstNode::FunctionCall(
"integrate".to_string(),
vec![
AstNode::Variable("x".to_string()),
AstNode::Variable("x".to_string()),
],
);
let s = format_latex_symbolic("integrate", &ast, "x^2/2");
assert!(s.contains("\\int"));
assert!(s.contains("\\, dx"));
}
#[test]
fn latex_symbolic_limit() {
let ast = AstNode::FunctionCall(
"limit".to_string(),
vec![
AstNode::Variable("x".to_string()),
AstNode::Variable("x".to_string()),
AstNode::Number(0.0),
],
);
let s = format_latex_symbolic("limit", &ast, "1");
assert!(s.contains("\\lim_{x \\to 0}"));
}
#[test]
fn latex_top_level_scalar() {
let r = EvalResult::Scalar(5.0);
let ast = AstNode::Number(5.0);
assert_eq!(format_latex(&r, &ast, "2+3", None), "5");
}
#[test]
fn latex_top_level_matrix() {
let r = EvalResult::Matrix(vec![vec![1.0, 2.0], vec![3.0, 4.0]]);
let ast = AstNode::Number(0.0); assert_eq!(
format_latex(&r, &ast, "[[1,2],[3,4]]", None),
"\\begin{pmatrix}1 & 2 \\\\ 3 & 4\\end{pmatrix}"
);
}
#[test]
fn latex_top_level_symbolic_diff() {
let r = EvalResult::Symbolic("2*x".to_string());
let ast = AstNode::FunctionCall(
"diff".to_string(),
vec![
AstNode::BinaryOp(
BinaryOp::Pow,
Box::new(AstNode::Variable("x".to_string())),
Box::new(AstNode::Number(2.0)),
),
AstNode::Variable("x".to_string()),
],
);
let s = format_latex(&r, &ast, "diff(x^2,x)", None);
assert_eq!(s, "\\frac{d}{dx}\\left(x^{2}\\right) = 2 \\cdot x");
}
#[test]
fn latex_top_level_latex_passthrough() {
let r = EvalResult::LaTeX("\\alpha".to_string());
let ast = AstNode::Number(0.0);
assert_eq!(format_latex(&r, &ast, "", None), "\\alpha");
}
#[test]
fn latex_top_level_steps_join() {
let r = EvalResult::Steps(vec!["2+9=11".to_string(), "11*7=77".to_string()]);
let ast = AstNode::Number(0.0);
assert_eq!(format_latex(&r, &ast, "", None), "2+9=11 \\to 11*7=77");
}
#[test]
fn latex_symbolic_str_to_latex_multiplies() {
assert_eq!(symbolic_str_to_latex("2*x*y"), "2 \\cdot x \\cdot y");
}
#[test]
fn latex_ast_to_latex_expr_pow() {
let node = AstNode::BinaryOp(
BinaryOp::Pow,
Box::new(AstNode::Variable("x".to_string())),
Box::new(AstNode::Number(2.0)),
);
assert_eq!(ast_to_latex_expr(&node), Some("x^{2}".to_string()));
}
#[test]
fn latex_ast_to_latex_expr_div() {
let node = AstNode::BinaryOp(
BinaryOp::Div,
Box::new(AstNode::Number(1.0)),
Box::new(AstNode::Number(2.0)),
);
assert_eq!(ast_to_latex_expr(&node), Some("\\frac{1}{2}".to_string()));
}
#[test]
fn latex_ast_to_latex_expr_unary_neg() {
let node = AstNode::UnaryOp(UnaryOp::Neg, Box::new(AstNode::Variable("x".to_string())));
assert_eq!(ast_to_latex_expr(&node), Some("-x".to_string()));
}
#[test]
fn latex_ast_to_latex_expr_factorial() {
let node = AstNode::UnaryOp(UnaryOp::Factorial, Box::new(AstNode::Number(5.0)));
assert_eq!(ast_to_latex_expr(&node), Some("5!".to_string()));
}
#[test]
fn latex_polynomial_leading_coef_one_x() {
assert_eq!(format_latex_polynomial(&[5.0, 1.0]), "x + 5");
}
#[test]
fn latex_polynomial_high_degree_neg_one_coef() {
assert_eq!(format_latex_polynomial(&[0.0, 0.0, -1.0]), "-x^{2}");
}
#[test]
fn latex_polynomial_high_degree_general_coef() {
assert_eq!(format_latex_polynomial(&[0.0, 0.0, 3.0]), "3x^{2}");
}
#[test]
fn latex_polynomial_negative_term_concatenation() {
assert_eq!(format_latex_polynomial(&[1.0, -2.0, 1.0]), "x^{2}-2x + 1");
}
#[test]
fn latex_bigrational_zero_precision() {
let r = num_rational::BigRational::new(
num_bigint::BigInt::from(7),
num_bigint::BigInt::from(2),
);
assert_eq!(format_latex_bigrational(&r, Some(0)), "3");
}
#[test]
fn latex_symbolic_non_functioncall_ast() {
let ast = AstNode::Number(0.0);
let s = format_latex_symbolic("diff", &ast, "2*x");
assert_eq!(s, "2 \\cdot x");
}
#[test]
fn latex_symbolic_series_branch() {
let ast = AstNode::FunctionCall(
"series".to_string(),
vec![AstNode::Variable("x".to_string())],
);
let s = format_latex_symbolic("series", &ast, "1+x+x^2");
assert!(s.contains("\\text{Taylor series of}"));
assert!(s.contains("x"));
}
#[test]
fn latex_symbolic_taylor_branch() {
let ast = AstNode::FunctionCall(
"taylor".to_string(),
vec![AstNode::Variable("x".to_string())],
);
let s = format_latex_symbolic("taylor", &ast, "1+x");
assert!(s.contains("\\text{Taylor series of}"));
}
#[test]
fn latex_symbolic_unknown_op() {
let ast = AstNode::FunctionCall(
"unknown".to_string(),
vec![AstNode::Variable("x".to_string())],
);
let s = format_latex_symbolic("unknown", &ast, "42");
assert_eq!(s, "42");
}
#[test]
fn latex_ast_to_latex_expr_bignumber() {
let node = AstNode::BigNumber("1234567890123456".to_string());
assert_eq!(
ast_to_latex_expr(&node),
Some("1234567890123456".to_string())
);
}
#[test]
fn latex_ast_to_latex_expr_add_sub_mul_mod() {
let add = AstNode::BinaryOp(
BinaryOp::Add,
Box::new(AstNode::Variable("a".to_string())),
Box::new(AstNode::Variable("b".to_string())),
);
assert_eq!(ast_to_latex_expr(&add), Some("a + b".to_string()));
let sub = AstNode::BinaryOp(
BinaryOp::Sub,
Box::new(AstNode::Variable("a".to_string())),
Box::new(AstNode::Variable("b".to_string())),
);
assert_eq!(ast_to_latex_expr(&sub), Some("a - b".to_string()));
let mul = AstNode::BinaryOp(
BinaryOp::Mul,
Box::new(AstNode::Variable("a".to_string())),
Box::new(AstNode::Variable("b".to_string())),
);
assert_eq!(ast_to_latex_expr(&mul), Some("a \\cdot b".to_string()));
let modulo = AstNode::BinaryOp(
BinaryOp::Mod,
Box::new(AstNode::Variable("a".to_string())),
Box::new(AstNode::Variable("b".to_string())),
);
assert_eq!(ast_to_latex_expr(&modulo), Some("a \\bmod b".to_string()));
}
#[test]
fn latex_ast_to_latex_expr_abs() {
let node = AstNode::UnaryOp(UnaryOp::Abs, Box::new(AstNode::Variable("x".to_string())));
assert_eq!(
ast_to_latex_expr(&node),
Some("\\left|x\\right|".to_string())
);
}
#[test]
fn latex_ast_to_latex_expr_function_call() {
let node = AstNode::FunctionCall(
"sin".to_string(),
vec![AstNode::Number(0.0), AstNode::Variable("x".to_string())],
);
assert_eq!(ast_to_latex_expr(&node), Some("sin(0, x)".to_string()));
}
#[test]
fn latex_ast_to_latex_expr_unsupported_returns_none() {
let node = AstNode::Complex(1.0, 2.0);
assert_eq!(ast_to_latex_expr(&node), None);
let node = AstNode::Matrix(vec![vec![AstNode::Number(1.0)]]);
assert_eq!(ast_to_latex_expr(&node), None);
let node = AstNode::List(vec![AstNode::Number(1.0)]);
assert_eq!(ast_to_latex_expr(&node), None);
}
#[test]
fn latex_top_level_complex() {
let r = EvalResult::Complex(3.0, 4.0);
let ast = AstNode::Number(0.0);
assert_eq!(format_latex(&r, &ast, "", None), "3 + 4i");
}
#[test]
fn latex_top_level_bigint() {
let r = EvalResult::BigInt(num_bigint::BigInt::from(42));
let ast = AstNode::Number(0.0);
assert_eq!(format_latex(&r, &ast, "", None), "42");
}
#[test]
fn latex_top_level_bigrational() {
let r = EvalResult::BigRational(num_rational::BigRational::new(
num_bigint::BigInt::from(1),
num_bigint::BigInt::from(3),
));
let ast = AstNode::Number(0.0);
assert_eq!(format_latex(&r, &ast, "", None), "\\frac{1}{3}");
}
#[test]
fn latex_top_level_vector() {
let r = EvalResult::Vector(vec![1.0, 2.0, 3.0]);
let ast = AstNode::Number(0.0);
assert_eq!(format_latex(&r, &ast, "", None), "\\left[1, 2, 3\\right]");
}
#[test]
fn latex_top_level_polynomial() {
let r = EvalResult::Polynomial(vec![1.0, 2.0, 1.0]);
let ast = AstNode::Number(0.0);
assert_eq!(format_latex(&r, &ast, "", None), "x^{2} + 2x + 1");
}
#[test]
fn latex_top_level_complex_list() {
let r = EvalResult::ComplexList(vec![(1.0, 2.0), (3.0, -4.0)]);
let ast = AstNode::Number(0.0);
assert_eq!(
format_latex(&r, &ast, "", None),
"\\left[1 + 2i, 3 - 4i\\right]"
);
}
#[test]
fn latex_top_level_symbolic_non_matching_function() {
let r = EvalResult::Symbolic("2*x".to_string());
let ast = AstNode::FunctionCall("foo".to_string(), vec![]);
assert_eq!(format_latex(&r, &ast, "", None), "2 \\cdot x");
}
#[test]
fn latex_top_level_symbolic_non_function() {
let r = EvalResult::Symbolic("2*x".to_string());
let ast = AstNode::Number(0.0);
assert_eq!(format_latex(&r, &ast, "", None), "2 \\cdot x");
}
}