use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use crate::core::{Expression, Number};
use crate::parser::{Parser, syntax::ExpressionParser};
use crate::engine::{ComputeEngine, CachedComputeEngine, EnhancedComputeEngine, RuntimeEnhancedEngine, RuntimeConfig, CacheStats, CacheUsageInfo};
use crate::formatter::{Formatter, FormatOptions, MultiFormatter};
use super::{YufmathError, ComputeConfig, PerformanceMonitor, ComputeProgress};
use super::progress::ProgressCallback;
use super::async_compute::{AsyncComputation, BatchAsyncComputer};
pub struct Yufmath {
parser: Box<dyn Parser>,
engine: Box<dyn ComputeEngine>,
formatter: Arc<Mutex<Box<dyn Formatter>>>,
monitor: Arc<Mutex<PerformanceMonitor>>,
config: ComputeConfig,
cancelled: Arc<AtomicBool>,
async_computer: Arc<BatchAsyncComputer>,
}
impl Yufmath {
pub fn new() -> Self {
let config = ComputeConfig::default();
let async_computer = Arc::new(BatchAsyncComputer::new(config.parallel.max_parallel_tasks));
Self {
parser: Box::new(ExpressionParser::new()),
engine: Box::new(RuntimeEnhancedEngine::new()),
formatter: Arc::new(Mutex::new(Box::new(MultiFormatter::new()))),
monitor: Arc::new(Mutex::new(PerformanceMonitor::new())),
config,
cancelled: Arc::new(AtomicBool::new(false)),
async_computer,
}
}
pub fn with_config(config: ComputeConfig) -> Self {
let async_computer = Arc::new(BatchAsyncComputer::new(config.parallel.max_parallel_tasks));
Self {
parser: Box::new(ExpressionParser::new()),
engine: Box::new(RuntimeEnhancedEngine::new()),
formatter: Arc::new(Mutex::new(Box::new(MultiFormatter::new()))),
monitor: Arc::new(Mutex::new(PerformanceMonitor::new())),
config,
cancelled: Arc::new(AtomicBool::new(false)),
async_computer,
}
}
pub fn compute(&self, input: &str) -> Result<String, YufmathError> {
let expr = self.parser.parse(input)?;
let result = if let Some(runtime_engine) = self.engine.as_any().downcast_ref::<RuntimeEnhancedEngine>() {
runtime_engine.safe_compute(&expr)?
} else {
let vars = HashMap::new();
match self.engine.evaluate(&expr, &vars) {
Ok(number) => Expression::Number(number),
Err(_) => {
self.engine.simplify(&expr)?
}
}
};
let formatter = self.formatter.lock()
.map_err(|_| YufmathError::internal("无法获取格式化器锁"))?;
Ok(formatter.format(&result))
}
pub fn parse(&self, input: &str) -> Result<Expression, YufmathError> {
Ok(self.parser.parse(input)?)
}
pub fn simplify(&self, expr: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.simplify(expr)?)
}
pub fn diff(&self, expr: &Expression, var: &str) -> Result<Expression, YufmathError> {
Ok(self.engine.differentiate(expr, var)?)
}
pub fn differentiate(&self, expr: &Expression, var: &str) -> Result<Expression, YufmathError> {
self.diff(expr, var)
}
pub fn integrate(&self, expr: &Expression, var: &str) -> Result<Expression, YufmathError> {
Ok(self.engine.integrate(expr, var)?)
}
pub fn limit(&self, expr: &Expression, var: &str, point: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.limit(expr, var, point)?)
}
pub fn series(&self, expr: &Expression, var: &str, point: &Expression, order: usize) -> Result<Expression, YufmathError> {
Ok(self.engine.series(expr, var, point, order)?)
}
pub fn numerical_evaluate(&self, expr: &Expression, vars: &std::collections::HashMap<String, f64>) -> Result<f64, YufmathError> {
Ok(self.engine.numerical_evaluate(expr, vars)?)
}
pub fn evaluate(&self, expr: &Expression, vars: &HashMap<String, Number>) -> Result<Number, YufmathError> {
Ok(self.engine.evaluate(expr, vars)?)
}
pub fn set_format_options(&mut self, options: FormatOptions) {
if let Ok(mut formatter) = self.formatter.lock() {
formatter.set_options(options);
}
}
pub fn format(&self, expr: &Expression) -> String {
if let Ok(formatter) = self.formatter.lock() {
formatter.format(expr)
} else {
format!("{:?}", expr) }
}
pub fn set_enhanced_simplify(&mut self, enabled: bool) {
if let Some(enhanced_engine) = self.engine.as_any().downcast_ref::<EnhancedComputeEngine>() {
enhanced_engine.set_auto_simplify(enabled);
}
}
pub fn is_enhanced_simplify_enabled(&self) -> bool {
if let Some(enhanced_engine) = self.engine.as_any().downcast_ref::<EnhancedComputeEngine>() {
enhanced_engine.is_auto_simplify_enabled()
} else {
false
}
}
pub fn set_progress_callback(&mut self, callback: ProgressCallback) {
if let Ok(mut monitor) = self.monitor.lock() {
monitor.set_progress_callback(callback);
}
}
pub fn compute_with_progress(&mut self, input: &str) -> Result<String, YufmathError> {
self.cancelled.store(false, Ordering::Relaxed);
let timer = if let Ok(mut monitor) = self.monitor.lock() {
monitor.start_computation()
} else {
return Err(YufmathError::internal("无法获取性能监控器"));
};
self.update_progress(ComputeProgress::new("解析表达式").with_progress(0.1))?;
let expr = self.parser.parse(input)?;
self.update_progress(ComputeProgress::new("简化表达式").with_progress(0.5))?;
let simplified = self.engine.simplify(&expr)?;
self.update_progress(ComputeProgress::new("格式化结果").with_progress(0.9))?;
let result = {
let formatter = self.formatter.lock()
.map_err(|_| YufmathError::internal("无法获取格式化器锁"))?;
formatter.format(&simplified)
};
if let Ok(mut monitor) = self.monitor.lock() {
monitor.record_computation(timer, true, true);
}
self.update_progress(ComputeProgress::new("计算完成").with_progress(1.0))?;
Ok(result)
}
pub fn simplify_with_progress(&mut self, expr: &Expression) -> Result<Expression, YufmathError> {
self.cancelled.store(false, Ordering::Relaxed);
let timer = if let Ok(mut monitor) = self.monitor.lock() {
monitor.start_computation()
} else {
return Err(YufmathError::internal("无法获取性能监控器"));
};
self.update_progress(ComputeProgress::new("分析表达式结构").with_progress(0.2))?;
let result = self.engine.simplify(expr)?;
if let Ok(mut monitor) = self.monitor.lock() {
monitor.record_computation(timer, true, true);
}
self.update_progress(ComputeProgress::new("简化完成").with_progress(1.0))?;
Ok(result)
}
pub fn integrate_with_progress(&mut self, expr: &Expression, var: &str) -> Result<Expression, YufmathError> {
self.cancelled.store(false, Ordering::Relaxed);
let timer = if let Ok(mut monitor) = self.monitor.lock() {
monitor.start_computation()
} else {
return Err(YufmathError::internal("无法获取性能监控器"));
};
self.update_progress(ComputeProgress::new("分析被积函数").with_progress(0.1))?;
self.update_progress(ComputeProgress::new("应用积分规则").with_progress(0.5))?;
let result = self.engine.integrate(expr, var)?;
if let Ok(mut monitor) = self.monitor.lock() {
monitor.record_computation(timer, true, true);
}
self.update_progress(ComputeProgress::new("积分完成").with_progress(1.0))?;
Ok(result)
}
pub fn cancel_computation(&mut self) {
self.cancelled.store(true, Ordering::Relaxed);
}
pub fn is_cancelled(&self) -> bool {
self.cancelled.load(Ordering::Relaxed)
}
pub fn batch_compute(&self, inputs: &[&str]) -> Vec<Result<String, YufmathError>> {
inputs.iter().map(|input| self.compute(input)).collect()
}
pub fn batch_parse(&self, inputs: &[&str]) -> Vec<Result<Expression, YufmathError>> {
inputs.iter().map(|input| self.parse(input)).collect()
}
pub fn batch_simplify(&self, expressions: &[Expression]) -> Vec<Result<Expression, YufmathError>> {
expressions.iter().map(|expr| self.simplify(expr)).collect()
}
pub fn get_config(&self) -> &ComputeConfig {
&self.config
}
pub fn update_config(&mut self, config: ComputeConfig) {
self.config = config;
}
pub fn get_performance_stats(&self) -> Option<crate::api::PerformanceStats> {
self.monitor.lock().ok().map(|monitor| monitor.get_stats().clone())
}
pub fn reset_performance_stats(&mut self) {
if let Ok(mut monitor) = self.monitor.lock() {
monitor.reset_stats();
}
}
pub fn expand(&self, expr: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.expand(expr)?)
}
pub fn factor(&self, expr: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.factor(expr)?)
}
pub fn collect(&self, expr: &Expression, var: &str) -> Result<Expression, YufmathError> {
Ok(self.engine.collect(expr, var)?)
}
pub fn solve(&self, equation: &Expression, var: &str) -> Result<Vec<Expression>, YufmathError> {
Ok(self.engine.solve(equation, var)?)
}
pub fn solve_system(&self, equations: &[Expression], vars: &[String]) -> Result<Vec<HashMap<String, Expression>>, YufmathError> {
Ok(self.engine.solve_system(equations, vars)?)
}
pub fn matrix_add(&self, a: &Expression, b: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.matrix_add(a, b)?)
}
pub fn matrix_multiply(&self, a: &Expression, b: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.matrix_multiply(a, b)?)
}
pub fn matrix_determinant(&self, matrix: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.matrix_determinant(matrix)?)
}
pub fn matrix_inverse(&self, matrix: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.matrix_inverse(matrix)?)
}
pub fn gcd(&self, a: &Expression, b: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.gcd(a, b)?)
}
pub fn lcm(&self, a: &Expression, b: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.lcm(a, b)?)
}
pub fn is_prime(&self, n: &Expression) -> Result<bool, YufmathError> {
Ok(self.engine.is_prime(n)?)
}
pub fn prime_factors(&self, n: &Expression) -> Result<Vec<Expression>, YufmathError> {
Ok(self.engine.prime_factors(n)?)
}
pub fn binomial(&self, n: &Expression, k: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.binomial(n, k)?)
}
pub fn permutation(&self, n: &Expression, k: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.permutation(n, k)?)
}
pub fn complex_conjugate(&self, expr: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.complex_conjugate(expr)?)
}
pub fn complex_modulus(&self, expr: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.complex_modulus(expr)?)
}
pub fn complex_argument(&self, expr: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.complex_argument(expr)?)
}
pub fn vector_dot(&self, a: &Expression, b: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.vector_dot(a, b)?)
}
pub fn vector_cross(&self, a: &Expression, b: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.vector_cross(a, b)?)
}
pub fn vector_norm(&self, v: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.vector_norm(v)?)
}
pub fn set_union(&self, a: &Expression, b: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.set_union(a, b)?)
}
pub fn set_intersection(&self, a: &Expression, b: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.set_intersection(a, b)?)
}
pub fn set_difference(&self, a: &Expression, b: &Expression) -> Result<Expression, YufmathError> {
Ok(self.engine.set_difference(a, b)?)
}
pub fn mean(&self, values: &[Expression]) -> Result<Expression, YufmathError> {
Ok(self.engine.mean(values)?)
}
pub fn variance(&self, values: &[Expression]) -> Result<Expression, YufmathError> {
Ok(self.engine.variance(values)?)
}
pub fn standard_deviation(&self, values: &[Expression]) -> Result<Expression, YufmathError> {
Ok(self.engine.standard_deviation(values)?)
}
pub fn compute_async(&self, input: &str) -> AsyncComputation<String> {
let expressions = vec![input.to_string()];
let mut computations = self.async_computer.submit_batch(expressions);
computations.pop().unwrap()
}
pub fn batch_compute_async(&self, inputs: &[&str]) -> Vec<AsyncComputation<String>> {
let expressions: Vec<String> = inputs.iter().map(|s| s.to_string()).collect();
self.async_computer.submit_batch(expressions)
}
pub fn active_async_tasks(&self) -> usize {
self.async_computer.active_task_count()
}
pub fn cancel_all_async_tasks(&self) {
self.async_computer.cancel_all();
}
pub fn cleanup_async_tasks(&self) {
self.async_computer.cleanup_completed();
}
pub fn get_cache_stats(&self) -> Option<CacheStats> {
if let Some(cached_engine) = self.engine.as_any().downcast_ref::<CachedComputeEngine>() {
cached_engine.get_cache_stats().ok()
} else {
None
}
}
pub fn get_cache_usage(&self) -> Option<CacheUsageInfo> {
if let Some(cached_engine) = self.engine.as_any().downcast_ref::<CachedComputeEngine>() {
cached_engine.get_cache_usage().ok()
} else {
None
}
}
pub fn cleanup_cache(&self) -> Result<(), YufmathError> {
if let Some(cached_engine) = self.engine.as_any().downcast_ref::<CachedComputeEngine>() {
cached_engine.cleanup_cache().map_err(YufmathError::from)
} else {
Ok(()) }
}
pub fn clear_cache(&self) -> Result<(), YufmathError> {
if let Some(cached_engine) = self.engine.as_any().downcast_ref::<CachedComputeEngine>() {
cached_engine.clear_cache().map_err(YufmathError::from)
} else {
Ok(()) }
}
pub fn set_variable(&self, name: String, value: Expression) -> Result<(), YufmathError> {
if let Some(runtime_engine) = self.engine.as_any().downcast_ref::<RuntimeEnhancedEngine>() {
runtime_engine.set_variable(name, value).map_err(YufmathError::from)
} else {
Err(YufmathError::internal("当前引擎不支持变量管理"))
}
}
pub fn set_variable_from_string(&self, name: String, value_str: &str) -> Result<(), YufmathError> {
let value_expr = self.parse(value_str)?;
self.set_variable(name, value_expr)
}
pub fn get_variable(&self, name: &str) -> Result<Option<Expression>, YufmathError> {
if let Some(runtime_engine) = self.engine.as_any().downcast_ref::<RuntimeEnhancedEngine>() {
runtime_engine.get_variable(name).map_err(YufmathError::from)
} else {
Ok(None)
}
}
pub fn get_all_variables(&self) -> Result<HashMap<String, Expression>, YufmathError> {
if let Some(runtime_engine) = self.engine.as_any().downcast_ref::<RuntimeEnhancedEngine>() {
runtime_engine.get_all_variables().map_err(YufmathError::from)
} else {
Ok(HashMap::new())
}
}
pub fn clear_variables(&self) -> Result<(), YufmathError> {
if let Some(runtime_engine) = self.engine.as_any().downcast_ref::<RuntimeEnhancedEngine>() {
runtime_engine.clear_variables().map_err(YufmathError::from)
} else {
Ok(())
}
}
pub fn remove_variable(&self, name: &str) -> Result<bool, YufmathError> {
if let Some(runtime_engine) = self.engine.as_any().downcast_ref::<RuntimeEnhancedEngine>() {
runtime_engine.remove_variable(name).map_err(YufmathError::from)
} else {
Ok(false)
}
}
pub fn update_runtime_config(&self, config: RuntimeConfig) -> Result<(), YufmathError> {
if let Some(runtime_engine) = self.engine.as_any().downcast_ref::<RuntimeEnhancedEngine>() {
runtime_engine.update_runtime_config(config).map_err(YufmathError::from)
} else {
Err(YufmathError::internal("当前引擎不支持运行时配置"))
}
}
pub fn get_runtime_config(&self) -> Result<RuntimeConfig, YufmathError> {
if let Some(runtime_engine) = self.engine.as_any().downcast_ref::<RuntimeEnhancedEngine>() {
runtime_engine.get_runtime_config().map_err(YufmathError::from)
} else {
Err(YufmathError::internal("当前引擎不支持运行时配置"))
}
}
pub fn safe_compute(&self, expr: &Expression) -> Result<Expression, YufmathError> {
if let Some(runtime_engine) = self.engine.as_any().downcast_ref::<RuntimeEnhancedEngine>() {
runtime_engine.safe_compute(expr).map_err(YufmathError::from)
} else {
self.simplify(expr)
}
}
pub fn compute_with_variables(&self, expr: &Expression) -> Result<Expression, YufmathError> {
if let Some(runtime_engine) = self.engine.as_any().downcast_ref::<RuntimeEnhancedEngine>() {
runtime_engine.compute_with_variables(expr).map_err(YufmathError::from)
} else {
self.simplify(expr)
}
}
fn update_progress(&self, progress: ComputeProgress) -> Result<(), YufmathError> {
if !self.config.enable_progress {
return Ok(());
}
if let Ok(mut monitor) = self.monitor.lock() {
let should_continue = monitor.update_progress(progress);
if !should_continue || self.is_cancelled() {
return Err(YufmathError::internal("计算被用户取消"));
}
}
Ok(())
}
}
impl Default for Yufmath {
fn default() -> Self {
Self::new()
}
}