mathhook_core/functions/traits.rs
1//! Function system trait architecture
2//!
3//! Clean trait-based architecture that defines clear boundaries between
4//! different components of the function intelligence system.
5//! Enables perfect modularity with zero coupling between modules.
6
7use crate::core::Expression;
8use crate::functions::properties::FunctionProperties;
9use std::collections::HashMap;
10
11/// Core trait for mathematical function intelligence
12///
13/// This trait defines the essential interface that all function intelligence
14/// modules must implement, ensuring consistent behavior across the system.
15///
16/// ## Design Principles
17/// - **Single Responsibility**: Each implementation handles one function family
18/// - **Interface Segregation**: Minimal, focused interface
19/// - **Dependency Inversion**: Depend on abstractions, not concretions
20/// - **Open/Closed**: Open for extension, closed for modification
21pub trait FunctionIntelligence: Send + Sync {
22 /// Get the name of this function family
23 fn family_name(&self) -> &'static str;
24
25 /// Get all function properties managed by this intelligence
26 fn get_all_properties(&self) -> HashMap<String, FunctionProperties>;
27
28 /// Check if this intelligence manages a specific function
29 fn has_function(&self, name: &str) -> bool;
30
31 /// Get the number of functions managed by this intelligence
32 fn function_count(&self) -> usize {
33 self.get_all_properties().len()
34 }
35
36 /// Get function names managed by this intelligence
37 fn function_names(&self) -> Vec<String> {
38 self.get_all_properties().keys().cloned().collect()
39 }
40}
41
42/// Trait for function educational capabilities
43///
44/// Provides step-by-step explanations and educational content
45/// for mathematical functions, separated from core functionality.
46pub trait FunctionEducator: Send + Sync {
47 /// Generate step-by-step explanation for a function evaluation
48 fn explain_evaluation(&self, name: &str, args: &[Expression]) -> Vec<String>;
49
50 /// Generate LaTeX representation of a function
51 fn to_latex(&self, name: &str, args: &[Expression]) -> String;
52
53 /// Get mathematical background information
54 fn get_background(&self, name: &str) -> Option<String>;
55
56 /// Get related functions and concepts
57 fn get_related_concepts(&self, name: &str) -> Vec<String>;
58}
59
60/// Trait for function optimization capabilities
61///
62/// Handles performance optimizations specific to different function families,
63/// such as SIMD evaluation, caching, and special value detection.
64pub trait FunctionOptimizer: Send + Sync {
65 /// Optimize function evaluation for bulk operations
66 fn optimize_bulk_evaluation(&self, name: &str, values: &[f64]) -> Option<Vec<f64>>;
67
68 /// Check for special values that can be computed exactly
69 fn detect_special_values(&self, name: &str, args: &[Expression]) -> Option<Expression>;
70
71 /// Get optimal evaluation strategy for given input size
72 fn optimal_strategy(&self, name: &str, input_size: usize) -> EvaluationStrategy;
73
74 /// Estimate computational complexity
75 fn complexity_estimate(&self, name: &str, input_size: usize) -> ComplexityEstimate;
76}
77
78/// Evaluation strategy for different scenarios
79#[derive(Debug, Clone, Copy, PartialEq)]
80pub enum EvaluationStrategy {
81 /// Direct evaluation using standard library functions
82 Direct,
83
84 /// SIMD-optimized evaluation for bulk operations
85 SIMD,
86
87 /// Series expansion for high accuracy
88 Series,
89
90 /// Lookup table for frequently used values
91 Lookup,
92
93 /// Recursive evaluation using recurrence relations
94 Recursive,
95}
96
97/// Computational complexity estimate
98#[derive(Debug, Clone)]
99pub struct ComplexityEstimate {
100 /// Time complexity (operations per input)
101 pub time_complexity: f64,
102
103 /// Space complexity (memory per input)
104 pub space_complexity: usize,
105
106 /// Numerical accuracy (relative error)
107 pub accuracy: f64,
108
109 /// Recommended for input sizes up to this limit
110 pub recommended_limit: usize,
111}
112
113/// Trait for function property validation
114///
115/// Ensures mathematical correctness and consistency of function properties
116/// across different implementations and modules.
117pub trait PropertyValidator: Send + Sync {
118 /// Validate mathematical properties of a function
119 fn validate_properties(&self, name: &str, properties: &FunctionProperties) -> ValidationResult;
120
121 /// Check consistency between related functions
122 fn validate_consistency(&self, functions: &[(&str, &FunctionProperties)]) -> ValidationResult;
123
124 /// Validate numerical accuracy against known values
125 fn validate_accuracy(&self, name: &str, test_cases: &[(Vec<f64>, f64)]) -> ValidationResult;
126}
127
128/// Result of property validation
129#[derive(Debug, Clone)]
130pub struct ValidationResult {
131 /// Whether validation passed
132 pub is_valid: bool,
133
134 /// Validation score (0.0 to 1.0)
135 pub score: f64,
136
137 /// Detailed validation report
138 pub report: String,
139
140 /// Issues found during validation
141 pub issues: Vec<ValidationIssue>,
142}
143
144/// Validation issue details
145#[derive(Debug, Clone)]
146pub struct ValidationIssue {
147 /// Severity level of the issue
148 pub severity: IssueSeverity,
149
150 /// Description of the issue
151 pub description: String,
152
153 /// Suggested fix (if available)
154 pub suggested_fix: Option<String>,
155}
156
157/// Severity levels for validation issues
158#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
159pub enum IssueSeverity {
160 /// Informational message
161 Info,
162
163 /// Warning that should be addressed
164 Warning,
165
166 /// Error that must be fixed
167 Error,
168
169 /// Critical error that breaks functionality
170 Critical,
171}
172
173/// Trait for function metadata management
174///
175/// Handles metadata such as references, version information,
176/// and compatibility data for function implementations.
177pub trait MetadataProvider: Send + Sync {
178 /// Get literature references for a function
179 fn get_references(&self, name: &str) -> Vec<Reference>;
180
181 /// Get version information
182 fn get_version(&self, name: &str) -> Option<Version>;
183
184 /// Get compatibility information
185 fn get_compatibility(&self, name: &str) -> CompatibilityInfo;
186
187 /// Get implementation notes
188 fn get_implementation_notes(&self, name: &str) -> Option<String>;
189}
190
191/// Literature reference information
192#[derive(Debug, Clone)]
193pub struct Reference {
194 /// Authors
195 pub authors: Vec<String>,
196
197 /// Title
198 pub title: String,
199
200 /// Publication details
201 pub publication: String,
202
203 /// Year of publication
204 pub year: u32,
205
206 /// DOI or URL (if available)
207 pub identifier: Option<String>,
208}
209
210/// Version information
211#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
212pub struct Version {
213 /// Major version number
214 pub major: u32,
215
216 /// Minor version number
217 pub minor: u32,
218
219 /// Patch version number
220 pub patch: u32,
221}
222
223/// Compatibility information
224#[derive(Debug, Clone)]
225pub struct CompatibilityInfo {
226 /// Minimum required version
227 pub min_version: Version,
228
229 /// Maximum supported version
230 pub max_version: Option<Version>,
231
232 /// Breaking changes in this version
233 pub breaking_changes: Vec<String>,
234
235 /// Deprecated features
236 pub deprecated_features: Vec<String>,
237}
238
239/// Composite trait that combines all function capabilities
240///
241/// This trait provides a unified interface for complete function intelligence
242/// modules that implement all aspects of function management.
243pub trait CompleteFunctionIntelligence:
244 FunctionIntelligence + FunctionEducator + FunctionOptimizer + PropertyValidator + MetadataProvider
245{
246 /// Get a comprehensive report about this function intelligence
247 fn generate_report(&self) -> IntelligenceReport {
248 IntelligenceReport {
249 family_name: self.family_name().to_owned(),
250 function_count: self.function_count(),
251 function_names: self.function_names(),
252 capabilities: vec![
253 "Intelligence".to_owned(),
254 "Evaluation".to_owned(),
255 "Education".to_owned(),
256 "Optimization".to_owned(),
257 "Validation".to_owned(),
258 "Metadata".to_owned(),
259 ],
260 }
261 }
262}
263
264/// Comprehensive report about a function intelligence module
265#[derive(Debug, Clone)]
266pub struct IntelligenceReport {
267 /// Name of the function family
268 pub family_name: String,
269
270 /// Number of functions managed
271 pub function_count: usize,
272
273 /// Names of all managed functions
274 pub function_names: Vec<String>,
275
276 /// Available capabilities
277 pub capabilities: Vec<String>,
278}
279
280/// Factory trait for creating function intelligence modules
281///
282/// Provides a standardized way to create and configure function intelligence
283/// modules with different parameters and options.
284pub trait IntelligenceFactory {
285 /// The type of intelligence this factory creates
286 type Intelligence: FunctionIntelligence;
287
288 /// Create a new intelligence instance with default configuration
289 fn create_default() -> Self::Intelligence;
290
291 /// Create a new intelligence instance with custom configuration
292 fn create_with_config(config: &IntelligenceConfig) -> Self::Intelligence;
293
294 /// Get the default configuration for this intelligence type
295 fn default_config() -> IntelligenceConfig;
296}
297
298/// Configuration for function intelligence modules
299#[derive(Debug, Clone)]
300pub struct IntelligenceConfig {
301 /// Enable high-precision mode
302 pub high_precision: bool,
303
304 /// Enable SIMD optimizations
305 pub enable_simd: bool,
306
307 /// Maximum cache size
308 pub max_cache_size: usize,
309
310 /// Validation level
311 pub validation_level: ValidationLevel,
312
313 /// Custom parameters
314 pub custom_params: HashMap<String, String>,
315}
316
317/// Validation levels for function intelligence
318#[derive(Debug, Clone, Copy, PartialEq)]
319pub enum ValidationLevel {
320 /// No validation
321 None,
322
323 /// Basic validation
324 Basic,
325
326 /// Standard validation
327 Standard,
328
329 /// Strict validation
330 Strict,
331
332 /// Research-grade validation
333 Research,
334}
335
336impl Default for IntelligenceConfig {
337 fn default() -> Self {
338 Self {
339 high_precision: false,
340 enable_simd: true,
341 max_cache_size: 1024,
342 validation_level: ValidationLevel::Standard,
343 custom_params: HashMap::new(),
344 }
345 }
346}
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351
352 #[test]
353 fn test_version_ordering() {
354 let v1 = Version {
355 major: 1,
356 minor: 0,
357 patch: 0,
358 };
359 let v2 = Version {
360 major: 1,
361 minor: 0,
362 patch: 1,
363 };
364 let v3 = Version {
365 major: 1,
366 minor: 1,
367 patch: 0,
368 };
369
370 assert!(v1 < v2);
371 assert!(v2 < v3);
372 assert!(v1 < v3);
373 }
374
375 #[test]
376 fn test_issue_severity_ordering() {
377 assert!(IssueSeverity::Info < IssueSeverity::Warning);
378 assert!(IssueSeverity::Warning < IssueSeverity::Error);
379 assert!(IssueSeverity::Error < IssueSeverity::Critical);
380 }
381
382 #[test]
383 fn test_default_config() {
384 let config = IntelligenceConfig::default();
385 assert!(!config.high_precision);
386 assert!(config.enable_simd);
387 assert_eq!(config.max_cache_size, 1024);
388 assert_eq!(config.validation_level, ValidationLevel::Standard);
389 }
390}