use super::common::{
ensure_math_constants, resolve_variable, unsupported_function_error, unsupported_node_error,
};
use crate::core::CalculationDomain;
use crate::core::{AstNode, BinaryOp, CalcError, EvalContext, EvalResult, UnaryOp};
use num_complex::Complex64;
use crate::math::complex as math_complex;
pub(crate) const COMPLEX_FUNCTIONS: &[&str] = &["complex", "conj", "arg"];
pub struct ComplexDomain;
impl CalculationDomain for ComplexDomain {
fn domain_name(&self) -> &str {
"complex"
}
fn priority(&self) -> u8 {
30
}
fn supports(&self, ast: &AstNode) -> bool {
contains_complex(ast)
}
fn evaluate(&self, ast: &AstNode, ctx: &EvalContext) -> Result<EvalResult, CalcError> {
let ctx = ensure_math_constants(ctx);
let value = self.eval(ast, &ctx)?;
match value {
ComplexValue::Scalar(v) => {
if !v.is_finite() {
return Err(CalcError::nan_or_inf());
}
Ok(EvalResult::Scalar(v))
}
ComplexValue::Complex(c) => {
if !c.re.is_finite() || !c.im.is_finite() {
return Err(CalcError::nan_or_inf());
}
Ok(EvalResult::Complex(c.re, c.im))
}
}
}
}
impl ComplexDomain {
fn eval(&self, ast: &AstNode, ctx: &EvalContext) -> Result<ComplexValue, CalcError> {
match ast {
AstNode::Number(n) => Ok(ComplexValue::Scalar(*n)),
AstNode::Complex(re, im) => Ok(ComplexValue::Complex(Complex64::new(*re, *im))),
AstNode::Variable(name) => {
if name == "i" {
return Ok(ComplexValue::Complex(Complex64::new(0.0, 1.0)));
}
resolve_variable(ctx, name).map(ComplexValue::Scalar)
}
AstNode::BinaryOp(op, l, r) => {
let a = self.eval(l, ctx)?;
let b = self.eval(r, ctx)?;
self.eval_binary(*op, a, b)
}
AstNode::UnaryOp(op, e) => {
let v = self.eval(e, ctx)?;
match op {
UnaryOp::Neg => match v {
ComplexValue::Scalar(s) => Ok(ComplexValue::Scalar(-s)),
ComplexValue::Complex(c) => Ok(ComplexValue::Complex(-c)),
},
UnaryOp::Abs => Ok(ComplexValue::Scalar(v.to_complex().norm())),
UnaryOp::Factorial => Err(CalcError::domain(
"factorial not supported in complex domain".to_string(),
)
.with_i18n("msg.complex.factorial_not_supported", vec![])),
}
}
AstNode::FunctionCall(name, args) => self.eval_function(name, args, ctx),
AstNode::Matrix(_) | AstNode::List(_) | AstNode::BigNumber(_) | AstNode::Str(_) => {
Err(unsupported_node_error("complex", ast))
}
}
}
fn eval_binary(
&self,
op: BinaryOp,
a: ComplexValue,
b: ComplexValue,
) -> Result<ComplexValue, CalcError> {
if let (ComplexValue::Scalar(av), ComplexValue::Scalar(bv)) = (&a, &b) {
let result = match op {
BinaryOp::Add => av + bv,
BinaryOp::Sub => av - bv,
BinaryOp::Mul => av * bv,
BinaryOp::Div => {
if *bv == 0.0 {
return Err(CalcError::division_by_zero());
}
av / bv
}
BinaryOp::Pow => {
if *av == 0.0 && *bv == 0.0 {
return Ok(ComplexValue::Scalar(1.0));
}
let r = av.powf(*bv);
if !r.is_finite() {
return Err(CalcError::nan_or_inf());
}
r
}
BinaryOp::Mod => {
return Err(CalcError::domain(
"mod not supported in complex domain".to_string(),
)
.with_i18n("msg.complex.mod_not_supported_scalar", vec![]));
}
};
return Ok(ComplexValue::Scalar(result));
}
let ac = a.to_complex();
let bc = b.to_complex();
let result = match op {
BinaryOp::Add => math_complex::add(ac, bc),
BinaryOp::Sub => math_complex::sub(ac, bc),
BinaryOp::Mul => math_complex::mul(ac, bc),
BinaryOp::Div => math_complex::div(ac, bc)?,
BinaryOp::Pow => {
if ac.re == 0.0 && ac.im == 0.0 && bc.re == 0.0 && bc.im == 0.0 {
return Ok(ComplexValue::Scalar(1.0));
}
math_complex::pow(ac, bc)?
}
BinaryOp::Mod => {
return Err(
CalcError::domain("mod not supported for complex numbers".to_string())
.with_i18n("msg.complex.mod_not_supported_complex", vec![]),
);
}
};
Ok(ComplexValue::Complex(result))
}
fn eval_function(
&self,
name: &str,
args: &[AstNode],
ctx: &EvalContext,
) -> Result<ComplexValue, CalcError> {
match name {
"complex" => {
if args.len() != 2 {
return Err(CalcError::domain(format!(
"complex() requires exactly 2 arguments, got {}",
args.len()
))
.with_i18n(
"msg.complex.complex_arg_count",
vec![("actual".to_string(), args.len().to_string())],
));
}
let re = match self.eval(&args[0], ctx)? {
ComplexValue::Scalar(v) => v,
_ => {
return Err(CalcError::domain(
"complex() requires scalar arguments".to_string(),
)
.with_i18n(
"msg.output.requires_scalar",
vec![("name".to_string(), "complex()".to_string())],
));
}
};
let im = match self.eval(&args[1], ctx)? {
ComplexValue::Scalar(v) => v,
_ => {
return Err(CalcError::domain(
"complex() requires scalar arguments".to_string(),
)
.with_i18n(
"msg.output.requires_scalar",
vec![("name".to_string(), "complex()".to_string())],
));
}
};
Ok(ComplexValue::Complex(Complex64::new(re, im)))
}
"conj" => {
let c = self.expect_one_arg(name, args, ctx)?;
Ok(ComplexValue::Complex(math_complex::conj(c)))
}
"arg" => {
let c = self.expect_one_arg(name, args, ctx)?;
Ok(ComplexValue::Scalar(math_complex::arg(c)?))
}
"abs" => {
let c = self.expect_one_arg(name, args, ctx)?;
Ok(ComplexValue::Scalar(math_complex::norm(c)))
}
"exp" => {
let c = self.expect_one_arg(name, args, ctx)?;
Ok(ComplexValue::Complex(math_complex::exp(c)))
}
"ln" => {
let c = self.expect_one_arg(name, args, ctx)?;
Ok(ComplexValue::Complex(math_complex::ln(c)))
}
_ => Err(unsupported_function_error("complex", name)),
}
}
fn expect_one_arg(
&self,
name: &str,
args: &[AstNode],
ctx: &EvalContext,
) -> Result<Complex64, CalcError> {
if args.len() != 1 {
return Err(CalcError::domain(format!(
"{}() requires exactly 1 argument, got {}",
name,
args.len()
))
.with_i18n(
"msg.complex.arg_count_1",
vec![
("name".to_string(), name.to_string()),
("actual".to_string(), args.len().to_string()),
],
));
}
Ok(self.eval(&args[0], ctx)?.to_complex())
}
}
enum ComplexValue {
Scalar(f64),
Complex(Complex64),
}
impl ComplexValue {
fn to_complex(&self) -> Complex64 {
match self {
ComplexValue::Scalar(v) => Complex64::new(*v, 0.0),
ComplexValue::Complex(c) => *c,
}
}
}
fn contains_complex(ast: &AstNode) -> bool {
match ast {
AstNode::Complex(_, _) => true,
AstNode::FunctionCall(name, args) => {
if COMPLEX_FUNCTIONS.contains(&name.as_str()) {
return true;
}
if matches!(name.as_str(), "abs" | "exp" | "ln") {
return args.iter().any(contains_complex);
}
args.iter().any(contains_complex)
}
AstNode::BinaryOp(_, l, r) => contains_complex(l) || contains_complex(r),
AstNode::UnaryOp(_, e) => contains_complex(e),
AstNode::Matrix(rows) => rows.iter().flatten().any(contains_complex),
AstNode::List(elements) => elements.iter().any(contains_complex),
AstNode::Number(_) | AstNode::Variable(_) | AstNode::BigNumber(_) | AstNode::Str(_) => {
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::ErrorKind;
use crate::core::parse;
fn assert_approx(actual: f64, expected: f64) {
assert!(
(actual - expected).abs() < 1e-10,
"expected {} but got {}",
expected,
actual
);
}
fn assert_complex_approx(actual: &EvalResult, expected_re: f64, expected_im: f64) {
match actual {
EvalResult::Complex(re, im) => {
assert_approx(*re, expected_re);
assert_approx(*im, expected_im);
}
other => panic!("expected Complex result, got {:?}", other),
}
}
fn assert_scalar(actual: &EvalResult, expected: f64) {
match actual {
EvalResult::Scalar(v) => assert_approx(*v, expected),
other => panic!("expected Scalar({}), got {:?}", expected, other),
}
}
fn default_ctx() -> EvalContext {
EvalContext::new()
.with_var("pi", std::f64::consts::PI)
.with_var("e", std::f64::consts::E)
}
#[test]
fn test_complex_literal_standard() {
let ast = parse("3+4i").unwrap();
assert_eq!(ast, AstNode::Complex(3.0, 4.0));
}
#[test]
fn test_complex_literal_pure_imaginary() {
let ast = parse("2i").unwrap();
assert_eq!(ast, AstNode::Complex(0.0, 2.0));
}
#[test]
fn test_real_number_not_route_to_complex() {
let ast = parse("5").unwrap();
assert_eq!(ast, AstNode::Number(5.0));
let domain = ComplexDomain;
assert!(!domain.supports(&ast));
}
#[test]
fn test_complex_addition() {
let ast = parse("(1+2i) + (3+4i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, 4.0, 6.0);
}
#[test]
fn test_complex_subtraction() {
let ast = parse("(1+2i) - (3+4i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, -2.0, -2.0);
}
#[test]
fn test_complex_multiplication() {
let ast = parse("(1+2i) * (3+4i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, -5.0, 10.0);
}
#[test]
fn test_complex_division() {
let ast = parse("(1+2i) / (3+4i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, 0.44, 0.08);
}
#[test]
fn test_complex_abs_standard() {
let ast = parse("abs(3+4i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_scalar(&result, 5.0);
}
#[test]
fn test_complex_abs_pure_imaginary() {
let ast = parse("abs(0+3i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_scalar(&result, 3.0);
}
#[test]
fn test_complex_arg_first_quadrant() {
let ast = parse("arg(1+1i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_scalar(&result, std::f64::consts::FRAC_PI_4);
}
#[test]
fn test_complex_arg_positive_real() {
let ast = parse("arg(2+0i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_scalar(&result, 0.0);
}
#[test]
fn test_complex_conjugate_standard() {
let ast = parse("conj(3+4i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, 3.0, -4.0);
}
#[test]
fn test_complex_conjugate_pure_real() {
let ast = parse("conj(5+0i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, 5.0, 0.0);
}
#[test]
fn test_complex_exp_euler_identity() {
let ast = parse("exp(complex(0,1)*pi)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, -1.0, 0.0);
}
#[test]
fn test_complex_exp_general() {
let ast = parse("exp(1+1i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
let expected_re = std::f64::consts::E * 1.0_f64.cos();
let expected_im = std::f64::consts::E * 1.0_f64.sin();
assert_complex_approx(&result, expected_re, expected_im);
}
#[test]
fn test_complex_ln_one_plus_i() {
let ast = parse("ln(1+1i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
let c = Complex64::new(1.0, 1.0);
let expected = c.ln();
assert_complex_approx(&result, expected.re, expected.im);
}
#[test]
fn test_complex_ln_positive_real() {
let ast = parse("ln(2+0i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, std::f64::consts::LN_2, 0.0);
}
#[test]
fn test_route_complex_node() {
let ast = parse("3+4i + 1").unwrap();
let domain = ComplexDomain;
assert!(domain.supports(&ast));
}
#[test]
fn test_route_complex_function() {
let ast = parse("conj(2+3i)").unwrap();
let domain = ComplexDomain;
assert!(domain.supports(&ast));
}
#[test]
fn test_mixed_abs_complex_plus_real() {
let ast = parse("abs(3+4i) + 2").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_scalar(&result, 7.0);
}
#[test]
fn test_mixed_complex_plus_real() {
let ast = parse("(1+2i) + 3").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, 4.0, 2.0);
}
#[test]
fn test_unsupported_matrix_node() {
let ast = AstNode::Matrix(vec![vec![AstNode::Number(1.0)]]);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
let e = result.unwrap_err();
assert!(
e.kind == ErrorKind::Domain,
"expected DomainError, got {:?}",
e
);
}
#[test]
fn test_invalid_complex_literal_parse_error() {
let result = parse("3+*4i");
let e = result.unwrap_err();
assert!(
e.kind == ErrorKind::Parse,
"expected ParseError, got {:?}",
e
);
}
#[test]
fn test_complex_domain_priority() {
let domain = ComplexDomain;
assert_eq!(domain.priority(), 30);
assert_eq!(domain.domain_name(), "complex");
}
#[test]
fn test_complex_priority_higher_than_scientific() {
let complex = ComplexDomain;
let scientific = crate::ScientificDomain;
assert!(complex.priority() > scientific.priority());
}
#[test]
fn test_complex_division_by_zero() {
let ast = parse("(1+2i) / 0").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(matches!(result, Err(e) if e.kind == ErrorKind::DivisionByZero));
}
#[test]
fn test_complex_unsupported_function() {
let ast = parse("unknown_func(1+2i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn test_complex_factorial_unsupported() {
let ast = AstNode::UnaryOp(UnaryOp::Factorial, Box::new(AstNode::Complex(1.0, 2.0)));
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn test_complex_list_unsupported() {
let ast = AstNode::List(vec![AstNode::Number(1.0)]);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn test_complex_wrong_arg_count() {
let ast = AstNode::FunctionCall("conj".to_string(), vec![]);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn test_complex_pow() {
let ast = parse("(1+1i)^2").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, 0.0, 2.0);
}
#[test]
fn test_complex_pow_zero_zero_returns_scalar_one() {
let ast = AstNode::BinaryOp(
BinaryOp::Pow,
Box::new(AstNode::Complex(0.0, 0.0)),
Box::new(AstNode::Complex(0.0, 0.0)),
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_scalar(&result, 1.0);
}
#[test]
fn test_complex_pow_overflow_returns_nan_or_inf() {
let ast = AstNode::BinaryOp(
BinaryOp::Pow,
Box::new(AstNode::Complex(1e308, 1e308)),
Box::new(AstNode::Complex(1e308, 1e308)),
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(
matches!(result, Err(ref e) if e.kind == ErrorKind::NaNOrInf),
"expected NaNOrInf error, got {:?}",
result
);
}
#[test]
fn test_complex_neg() {
let ast = parse("-(1+2i)").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, -1.0, -2.0);
}
#[test]
fn test_complex_abs_unary_op() {
let ast = AstNode::UnaryOp(UnaryOp::Abs, Box::new(AstNode::Complex(3.0, 4.0)));
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_scalar(&result, 5.0);
}
#[test]
fn test_complex_function_call_abs_with_real_arg() {
let ast = parse("abs(5)").unwrap();
let domain = ComplexDomain;
assert!(!domain.supports(&ast));
}
#[test]
fn test_complex_i_variable() {
let ast = AstNode::Variable("i".to_string());
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, 0.0, 1.0);
}
#[test]
fn test_complex_nan_detection() {
let ast = parse("(0+0i) / 0").unwrap();
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(matches!(result, Err(e) if e.kind == ErrorKind::DivisionByZero));
}
#[test]
fn test_pi_e_auto_binding() {
let ast = parse("conj(3+4i)").unwrap();
let domain = ComplexDomain;
let ctx = EvalContext::new();
let result = domain.evaluate(&ast, &ctx).unwrap();
assert_complex_approx(&result, 3.0, -4.0);
}
#[test]
fn test_scalar_nan_or_inf() {
let ast = AstNode::BinaryOp(
BinaryOp::Pow,
Box::new(AstNode::FunctionCall(
"abs".to_string(),
vec![AstNode::Complex(3.0, 4.0)],
)),
Box::new(AstNode::Number(1000.0)),
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(matches!(result, Err(e) if e.kind == ErrorKind::NaNOrInf));
}
#[test]
fn test_complex_nan_or_inf() {
let ast = AstNode::FunctionCall("exp".to_string(), vec![AstNode::Complex(1000.0, 0.0)]);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(matches!(result, Err(e) if e.kind == ErrorKind::NaNOrInf));
}
#[test]
fn test_neg_on_scalar_in_complex() {
let ast = AstNode::BinaryOp(
BinaryOp::Add,
Box::new(AstNode::Complex(1.0, 2.0)),
Box::new(AstNode::UnaryOp(
UnaryOp::Neg,
Box::new(AstNode::Number(3.0)),
)),
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, -2.0, 2.0);
}
#[test]
fn test_scalar_sub_in_complex() {
let ast = AstNode::BinaryOp(
BinaryOp::Sub,
Box::new(AstNode::FunctionCall(
"abs".to_string(),
vec![AstNode::Complex(3.0, 4.0)],
)),
Box::new(AstNode::Number(1.0)),
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_scalar(&result, 4.0);
}
#[test]
fn test_scalar_mul_in_complex() {
let ast = AstNode::BinaryOp(
BinaryOp::Mul,
Box::new(AstNode::FunctionCall(
"abs".to_string(),
vec![AstNode::Complex(3.0, 4.0)],
)),
Box::new(AstNode::Number(2.0)),
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_scalar(&result, 10.0);
}
#[test]
fn test_scalar_div_in_complex() {
let ast = AstNode::BinaryOp(
BinaryOp::Div,
Box::new(AstNode::FunctionCall(
"abs".to_string(),
vec![AstNode::Complex(3.0, 4.0)],
)),
Box::new(AstNode::Number(2.0)),
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_scalar(&result, 2.5);
}
#[test]
fn test_scalar_div_by_zero_in_complex() {
let ast = AstNode::BinaryOp(
BinaryOp::Div,
Box::new(AstNode::FunctionCall(
"abs".to_string(),
vec![AstNode::Complex(3.0, 4.0)],
)),
Box::new(AstNode::Number(0.0)),
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(matches!(result, Err(e) if e.kind == ErrorKind::DivisionByZero));
}
#[test]
fn test_scalar_pow_in_complex() {
let ast = AstNode::BinaryOp(
BinaryOp::Pow,
Box::new(AstNode::FunctionCall(
"abs".to_string(),
vec![AstNode::Complex(3.0, 4.0)],
)),
Box::new(AstNode::Number(2.0)),
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_scalar(&result, 25.0);
}
#[test]
fn test_scalar_mod_in_complex() {
let ast = AstNode::BinaryOp(
BinaryOp::Mod,
Box::new(AstNode::FunctionCall(
"abs".to_string(),
vec![AstNode::Complex(3.0, 4.0)],
)),
Box::new(AstNode::Number(2.0)),
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn test_complex_mod_unsupported() {
let ast = AstNode::BinaryOp(
BinaryOp::Mod,
Box::new(AstNode::Complex(1.0, 2.0)),
Box::new(AstNode::Complex(3.0, 4.0)),
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn test_complex_function_normal() {
let ast = AstNode::FunctionCall(
"complex".to_string(),
vec![AstNode::Number(1.0), AstNode::Number(2.0)],
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
assert_complex_approx(&result, 1.0, 2.0);
}
#[test]
fn test_complex_function_wrong_arg_count() {
let ast = AstNode::FunctionCall("complex".to_string(), vec![AstNode::Number(1.0)]);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx());
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn test_complex_function_rejects_complex_argument() {
let ast_re_complex = AstNode::FunctionCall(
"complex".to_string(),
vec![AstNode::Complex(1.0, 2.0), AstNode::Number(3.0)],
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast_re_complex, &default_ctx());
assert!(matches!(result, Err(ref e) if e.kind == ErrorKind::Domain));
if let Err(ref e) = result {
assert_eq!(
e.i18n_key,
Some("msg.output.requires_scalar"),
"expected i18n key msg.output.requires_scalar"
);
}
let ast_im_complex = AstNode::FunctionCall(
"complex".to_string(),
vec![AstNode::Number(1.0), AstNode::Complex(3.0, 4.0)],
);
let result = domain.evaluate(&ast_im_complex, &default_ctx());
assert!(matches!(result, Err(ref e) if e.kind == ErrorKind::Domain));
}
#[test]
fn test_supports_unary_op_with_complex() {
let ast = AstNode::UnaryOp(UnaryOp::Neg, Box::new(AstNode::Complex(3.0, 4.0)));
let domain = ComplexDomain;
assert!(domain.supports(&ast));
}
#[test]
fn test_supports_matrix_with_complex() {
let ast = AstNode::Matrix(vec![vec![AstNode::Complex(1.0, 2.0)]]);
let domain = ComplexDomain;
assert!(domain.supports(&ast));
}
#[test]
fn test_supports_list_with_complex() {
let ast = AstNode::List(vec![AstNode::Complex(1.0, 2.0)]);
let domain = ComplexDomain;
assert!(domain.supports(&ast));
}
#[test]
#[should_panic(expected = "expected Complex result")]
fn test_assert_complex_approx_panics_on_non_complex() {
assert_complex_approx(&EvalResult::Scalar(1.0), 1.0, 0.0);
}
#[test]
#[should_panic(expected = "expected Scalar")]
fn test_assert_scalar_panics_on_non_scalar() {
assert_scalar(&EvalResult::Complex(1.0, 2.0), 1.0);
}
use proptest::prelude::*;
proptest! {
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
#[test]
fn prop_double_conjugate_identity(re in -1e6f64..1e6, im in -1e6f64..1e6) {
let ast = AstNode::FunctionCall(
"conj".to_string(),
vec![AstNode::FunctionCall(
"conj".to_string(),
vec![AstNode::Complex(re, im)],
)],
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
match result {
EvalResult::Complex(r, i) => {
prop_assert!((r - re).abs() < 1e-6);
prop_assert!((i - im).abs() < 1e-6);
}
_ => panic!("expected Complex result"),
}
}
#[test]
fn prop_abs_non_negative(re in -1e6f64..1e6, im in -1e6f64..1e6) {
let ast = AstNode::FunctionCall(
"abs".to_string(),
vec![AstNode::Complex(re, im)],
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
match result {
EvalResult::Scalar(v) => prop_assert!(v >= 0.0),
_ => panic!("expected Scalar result"),
}
}
#[test]
fn prop_euler_formula_unit_modulus(theta in -10.0f64..10.0) {
let ast = AstNode::FunctionCall(
"exp".to_string(),
vec![AstNode::Complex(0.0, theta)],
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
match result {
EvalResult::Complex(re, im) => {
let modulus = (re * re + im * im).sqrt();
prop_assert!((modulus - 1.0).abs() < 1e-9);
}
_ => panic!("expected Complex result"),
}
}
#[test]
fn prop_addition_commutative(
ar in -1e3f64..1e3, ai in -1e3f64..1e3,
br in -1e3f64..1e3, bi in -1e3f64..1e3
) {
let domain = ComplexDomain;
let ctx = default_ctx();
let ast_ab = AstNode::BinaryOp(
BinaryOp::Add,
Box::new(AstNode::Complex(ar, ai)),
Box::new(AstNode::Complex(br, bi)),
);
let ast_ba = AstNode::BinaryOp(
BinaryOp::Add,
Box::new(AstNode::Complex(br, bi)),
Box::new(AstNode::Complex(ar, ai)),
);
let r_ab = domain.evaluate(&ast_ab, &ctx).unwrap();
let r_ba = domain.evaluate(&ast_ba, &ctx).unwrap();
match (&r_ab, &r_ba) {
(EvalResult::Complex(r1, i1), EvalResult::Complex(r2, i2)) => {
prop_assert!((r1 - r2).abs() < 1e-9);
prop_assert!((i1 - i2).abs() < 1e-9);
}
_ => panic!("expected Complex results"),
}
}
#[test]
fn prop_conjugate_sum_is_real(re in -1e6f64..1e6, im in -1e6f64..1e6) {
let ast = AstNode::BinaryOp(
BinaryOp::Add,
Box::new(AstNode::Complex(re, im)),
Box::new(AstNode::FunctionCall(
"conj".to_string(),
vec![AstNode::Complex(re, im)],
)),
);
let domain = ComplexDomain;
let result = domain.evaluate(&ast, &default_ctx()).unwrap();
match result {
EvalResult::Complex(r, i) => {
prop_assert!((r - 2.0 * re).abs() < 1e-6);
prop_assert!(i.abs() < 1e-6);
}
_ => panic!("expected Complex result"),
}
}
}
}