# Calculator MAV - Hybrid CAS Application Logic *** ## Overview This document describes the operational logic of the Calculator MAV (Hybrid Computer Algebra System), focusing on the semantic flow from user input to result display. The application implements a distributed tokenization system with automatic type discovery, pure algebraic evaluation, and hybrid symbolic-numeric computation. ## Architecture Components ### 1. Application Entry Point (calc.py) The launcher serves as the system bootstrap, handling: - **Logging Infrastructure**: Establishes comprehensive error tracking with automatic log rotation - **System Verification**: Validates dependencies and environment setup - **Error Recovery**: Provides detailed error reporting with context-aware debugging information - **Application Lifecycle**: Manages startup, execution, and graceful shutdown ### 2. Main Application Interface (main_calc_app.py) The GUI application provides: - **Dual-Pane Interface**: Synchronized input and output panels with smart resizing - **Real-time Evaluation**: Debounced input processing with automatic width adjustment - **Interactive Results**: Clickable elements for plots, matrices, and complex data structures - **Dynamic Help System**: Context-aware assistance using registered type helpers ### 3. Type Discovery System (type_registry.py) The core innovation implementing: - **Automatic Class Detection**: Scans custom_types directory for *_type.py files - **Dynamic Registration**: Loads classes and their capabilities without code modification - **Tokenization Pattern Collection**: Aggregates parsing rules from individual types - **Context Building**: Creates unified namespace for evaluation engine ## Computation Flow ### Phase 1: Input Processing When a user types in the input panel, the system triggers a processing cycle: **Input Capture**: The text widget captures keystrokes and triggers debounced evaluation after 300ms of inactivity. Special handling occurs for dot notation (triggering autocomplete) and real-time content analysis. **Content Parsing**: The entire input content is split into lines, with each line processed independently. Empty lines and comments (starting with #) are preserved but bypassed during evaluation. **Context Reset**: Before each full evaluation cycle, the algebraic engine clears its internal state, ensuring consistent results regardless of previous computations. ### Phase 2: Distributed Tokenization The tokenization system operates on a priority-based pattern matching approach: **Pattern Discovery**: Each registered type contributes tokenization patterns with priority levels. Higher priority patterns (more specific) are applied first, preventing conflicts between similar syntaxes. **Expression Transformation**: The universal tokenizer applies transformations in priority order: - Base number patterns (16#FF, 2#1010) are converted to IntBase constructor calls - Four-element patterns (192.168.1.1, 10.x.y.z) become FourBytes instances - Specialized prefixes (0x, 0b) are handled by specific type patterns **Bracket Parser Integration**: After tokenization, the bracket parser handles the simplified syntax transformation from Type[value] to Type("value") constructor calls. ### Phase 3: Line Classification The pure algebraic engine analyzes each processed line to determine its semantic type: **Assignment Detection**: Lines matching "variable = expression" where the left side is a valid Python identifier are classified as assignments. These create symbol bindings and optionally add implicit equations if undefined symbols are present. **Equation Recognition**: Lines containing equals signs that aren't simple assignments become equations. The system distinguishes between algebraic equations (=) and SymPy comparisons (==, <=, >=, !=). **Solve Shortcuts**: The pattern "variable=?" is recognized as shorthand for solve(variable), providing quick variable resolution. **Expression Evaluation**: All other lines are treated as mathematical expressions for symbolic or numeric evaluation. ### Phase 4: Symbolic Evaluation The evaluation engine operates in pure algebraic mode: **SymPy Integration**: All mathematical operations prioritize symbolic representation, maintaining exact forms (fractions, radicals, symbolic expressions) whenever possible. **Dynamic Context**: The evaluation context combines: - Base mathematical functions (sin, cos, integrate, solve, etc.) - Dynamically registered custom types from the type discovery system - User-defined variables from previous assignments - Automatic symbol creation for undefined variables **Hybrid Object Handling**: Custom types (IP4, IntBase, FourBytes, etc.) maintain their native operations while integrating seamlessly with SymPy algebra through the SympyClassBase inheritance pattern. ### Phase 5: Smart Solving The equation system implements intelligent resolution: **System Building**: Each equation is added to a persistent equation list, with variable extraction and dependency tracking. **Variable Resolution**: The solve shortcut (variable=?) triggers sophisticated resolution logic: - Single-variable equations are solved directly - Multi-variable systems use SymPy's constraint solver - Underdetermined systems provide parametric solutions - Overdetermined systems report conflicts with context **Automatic Substitution**: Known variable values are automatically substituted into symbolic expressions, providing immediate numeric evaluation when all symbols are resolved. ### Phase 6: Result Processing The evaluation results undergo format optimization: **Display Selection**: The system determines the most informative representation: - Symbolic form is preserved for exact mathematical expressions - Numeric approximations are provided when significantly different from symbolic form - Custom type representations use their native display methods **Interactive Enhancement**: Complex results (plots, matrices, large lists) are converted to interactive placeholders that open detailed views when clicked. **Error Context**: Failed evaluations trigger contextual help suggestions from registered type helpers, providing guidance based on input patterns. ### Phase 7: Output Synchronization The GUI updates reflect the complete evaluation state: **Parallel Display**: Input and output panels maintain line-by-line correspondence, with synchronized scrolling and visual alignment. **Color Coding**: Results are tagged with semantic colors: - Symbolic expressions in blue - Numeric results in green - Equations in purple - Errors in red - Helper suggestions in gold **Layout Adaptation**: The input panel automatically resizes based on content width, maintaining optimal visibility for both mathematical expressions and code. ## Key Semantic Principles ### Pure Algebraic Approach Unlike traditional calculators, this system treats every assignment as a potential equation. Variables maintain their symbolic nature until explicitly evaluated, enabling sophisticated algebraic manipulation. ### Distributed Extensibility The type system allows seamless addition of new mathematical objects without modifying core engine code. Each type contributes its own tokenization patterns, helper functions, and algebraic integration. ### Context Preservation The evaluation engine maintains a persistent mathematical context across all input lines, enabling complex multi-step calculations and equation system building. ### Smart Automation The system automatically: - Creates symbols for undefined variables - Applies substitutions when variables are resolved - Provides numeric approximations when helpful - Suggests corrections for invalid input patterns ### Hybrid Integration Custom types (networking, programming, engineering) integrate seamlessly with pure mathematical operations, enabling domain-specific calculations within a unified algebraic framework. This architecture enables the calculator to function as both a powerful symbolic mathematics tool and a specialized computational environment for technical domains, with the flexibility to expand into new areas through the distributed type system. ```plantuml @startuml Calculator_MAV_Flow !define RECTANGLE class title Calculator MAV - Hybrid CAS Processing Flow start :User types in input panel; note right: GUI captures keystrokes\nwith 300ms debounce :Input Processing Phase; partition "Input Capture" { :Split content into lines; :Preserve comments and empty lines; :Clear engine context for fresh evaluation; } :Distributed Tokenization Phase; partition "Pattern Matching" { :Discover tokenization patterns from registered types; note left: Type registry auto-discovers\npatterns from custom_types/* :Apply high-priority patterns first; note right: 16#FF → IntBase("FF", 16)\n2#1010 → IntBase("1010", 2) :Apply medium-priority patterns; note right: 192.168.1.1 → FourBytes("192.168.1.1") :Apply bracket parser transformations; note right: Type[value] → Type("value") } :Line Classification Phase; partition "Semantic Analysis" { if (Line contains "=?") then (yes) :Classify as Solve Shortcut; elseif (Simple assignment pattern?) then (yes) :Classify as Assignment; note right: variable = expression\nwhere left side is valid identifier elseif (Contains = but not assignment?) then (yes) :Classify as Equation; note right: x**2 + 2*x = 8\na + b == 10 else (no) :Classify as Expression; endif } :Symbolic Evaluation Phase; partition "Algebraic Processing" { if (Assignment type?) then (yes) :Create symbol binding; :Check for undefined symbols; if (Has undefined symbols?) then (yes) :Add implicit equation to system; endif elseif (Equation type?) then (yes) :Parse left and right sides; :Create SymPy Eq object; :Add to equation system; elseif (Solve shortcut?) then (yes) :Extract variable name; :Trigger smart solving; else (Expression) :Evaluate with SymPy priority; :Maintain symbolic form; :Auto-create undefined symbols; endif } :Smart Solving Phase; partition "Equation Resolution" { if (Solve shortcut triggered?) then (yes) :Find equations containing variable; if (Single variable equations?) then (yes) :Solve directly; elseif (Multi-variable system?) then (yes) :Use SymPy constraint solver; :Handle parametric solutions; else (no equations) :Return current symbol value; endif endif :Apply automatic substitutions; note right: Substitute known values\ninto symbolic expressions } :Result Processing Phase; partition "Output Formatting" { :Determine optimal representation; if (Complex result?) then (yes) :Create interactive placeholder; note right: Plots, matrices, large lists\nbecome clickable elements endif :Generate numeric approximation if helpful; :Apply semantic color coding; note right: Symbolic: blue\nNumeric: green\nEquations: purple\nErrors: red } :Output Synchronization Phase; partition "GUI Updates" { :Update output panel with line correspondence; :Apply synchronized scrolling; :Auto-resize input panel based on content; :Enable interactive result clicking; } if (Error occurred?) then (yes) :Trigger contextual help from type helpers; note right: Dynamic help based on\ninput patterns and registered types endif stop @enduml ``` ```plantuml @startuml Calculator_MAV_Flow_Corrected !define RECTANGLE class title Calculator MAV - Pure Algebraic Engine Processing Flow start :User types in input panel; note right: GUI captures keystrokes\nwith 300ms debounce :Input Processing Phase; partition "Input Capture" { :Split content into lines; :Preserve comments and empty lines; :Clear engine context for fresh evaluation; note right: PureAlgebraicEngine.clear_context() } :Distributed Tokenization Phase; partition "Pattern Matching" { :Apply dynamic tokenization patterns; note left: From get_registered_tokenization_patterns() :Transform expressions in priority order; note right: 16#FF → IntBase("FF", 16)\n192.168.1.1 → FourBytes("192.168.1.1") :Apply bracket parser processing; } :Line Classification Phase; partition "Pure Algebraic Analysis" { if (Line ends with "=?") then (yes) :Classify as Solve Shortcut; note right: x=? becomes solve(x) elseif (Contains "=" and not comparison?) then (yes) :Classify as Equation; note right: ALL assignments become equations\nin pure algebraic mode else (no) :Classify as Expression; endif } :Pure Algebraic Evaluation; partition "SymPy-First Processing" { if (Equation type?) then (yes) :Split on "=" sign; :Create SymPy Eq() object; :Add to equations list; :Extract and track variables; elseif (Solve shortcut?) then (yes) :Extract variable name; :Call _solve_variable_in_system(); else (Expression) :Evaluate with sympify() first; :Maintain symbolic form; :Apply simplify if configured; endif } :Smart Variable Resolution; partition "Equation System Solving" { if (Solve triggered?) then (yes) :Find relevant equations for variable; if (Multi-variable system?) then (yes) :Solve complete system with SymPy; :Extract specific variable; else (simple case) :Solve single variable directly; endif :Update symbol_table with result; endif } :Result Processing Phase; partition "Output Formatting" { :Generate symbolic result; :Create numeric approximation if different; :Format as single-line output; note right: Concise format:\n"x = 5 ≈ 5.000000" } :Output Synchronization Phase; partition "GUI Updates" { :Update output panel; :Apply color coding for result type; :Auto-resize input panel; } if (Error occurred?) then (yes) :Get help from registered helpers; :Display error with context; endif stop note bottom : **Pure Algebraic Principle**\nAll assignments become equations\nSymbolic evaluation prioritized\nNumeric approximation secondary @enduml ``` ```plantuml @startuml Calculator_MAV_Architecture_Corrected !define RECTANGLE class title Calculator MAV - Architecture with Pure Algebraic Engine package "Application Layer" { [calc.py] as launcher [main_calc_app.py] as gui } package "Core Processing" { [main_evaluation_puro.py] as pure_engine [tl_bracket_parser.py] as parser [type_registry.py] as registry note top of pure_engine : **Pure Algebraic Engine**\n• All assignments → equations\n• SymPy-first evaluation\n• Persistent equation system\n• Smart variable resolution } package "Unused Components" #lightgray { [main_evaluation.py] as hybrid_engine note bottom of hybrid_engine : Not currently used\nin main application } package "Type System" { folder "custom_types/" { [intbase_type.py] [fourbytes_type.py] [ip4_type.py] [... more types] } } package "Support Components" { [sympy_Base.py] as base [class_base.py] as classbase [tl_popup.py] as popup [sympy_helper.py] as helper } package "External Dependencies" { [SymPy Library] as sympy [Tkinter GUI] as tkinter } ' Active connections launcher --> gui : "Initialize" gui --> pure_engine : "evaluate_line()" pure_engine --> parser : "process_expression()" parser --> registry : "get_registered_tokenization_patterns()" pure_engine --> registry : "get_registered_base_context()" pure_engine --> sympy : "sympify(), solve(), Eq()" ' Type system integration registry --> intbase_type.py : "Auto-discover" registry --> fourbytes_type.py : "Load patterns" registry --> "... more types" : "Dynamic loading" ' Inheritance intbase_type.py --> base fourbytes_type.py --> classbase base --> sympy ' Support gui --> helper : "Contextual help" gui --> popup : "Interactive results" ' Unused connection (grayed out) hybrid_engine -.-> sympy : "Not used" @enduml ```