quantrs2_symengine_pure/scirs2_bridge/
complex.rs1use scirs2_core::Complex64;
7
8use crate::error::{SymEngineError, SymEngineResult};
9use crate::expr::Expression;
10
11pub fn to_complex64(expr: &Expression) -> SymEngineResult<Complex64> {
16 if let Some(re) = expr.to_f64() {
18 return Ok(Complex64::new(re, 0.0));
19 }
20
21 Err(SymEngineError::eval(
25 "Cannot convert symbolic expression to Complex64 - try evaluating with specific values",
26 ))
27}
28
29pub fn from_complex64(c: Complex64) -> Expression {
33 Expression::from_complex64(c)
34}
35
36pub fn eval_complex(
45 expr: &Expression,
46 values: &std::collections::HashMap<String, Complex64>,
47) -> SymEngineResult<Complex64> {
48 let real_values: std::collections::HashMap<String, f64> = values
52 .iter()
53 .filter(|(_, v)| v.im.abs() < 1e-15)
54 .map(|(k, v)| (k.clone(), v.re))
55 .collect();
56
57 if real_values.len() != values.len() {
58 return Err(SymEngineError::not_impl(
59 "Complex variable evaluation not yet implemented",
60 ));
61 }
62
63 let result = expr.eval(&real_values)?;
64 Ok(Complex64::new(result, 0.0))
65}
66
67pub mod complex_ops {
69 use super::*;
70
71 pub fn complex(re: f64, im: f64) -> Expression {
73 Expression::from_complex64(Complex64::new(re, im))
74 }
75
76 pub fn imag(b: f64) -> Expression {
78 Expression::float_unchecked(b) * Expression::i()
79 }
80
81 pub fn polar(r: f64, theta: f64) -> Expression {
83 let c = Complex64::from_polar(r, theta);
84 Expression::from_complex64(c)
85 }
86}
87
88#[cfg(test)]
89mod tests {
90 use super::*;
91
92 #[test]
93 fn test_from_complex64_real() {
94 let c = Complex64::new(2.5, 0.0);
95 let expr = from_complex64(c);
96 assert!(expr.is_number());
97 }
98
99 #[test]
100 fn test_from_complex64_pure_imag() {
101 let c = Complex64::new(0.0, 2.0);
102 let expr = from_complex64(c);
103 assert!(!expr.is_symbol());
105 }
106
107 #[test]
108 fn test_from_complex64_general() {
109 let c = Complex64::new(3.0, 4.0);
110 let expr = from_complex64(c);
111 assert!(!expr.is_symbol());
113 }
114
115 #[test]
116 fn test_complex_ops() {
117 use complex_ops::*;
118
119 let c = complex(1.0, 2.0);
120 let i = imag(3.0);
121 let p = polar(1.0, std::f64::consts::FRAC_PI_2);
122
123 assert!(!c.is_symbol());
124 assert!(!i.is_symbol());
125 assert!(!p.is_symbol());
126 }
127}