Calc/.doc/DESCRIPTION.md

9.3 KiB

MAV Calculator Application Logic Documentation

Overview

The MAV Calculator is a hybrid Computer Algebra System (CAS) built around a pure algebraic engine that treats all assignments as equations. The application follows a clean pipeline from user input to result display, with sophisticated tokenization and symbolic computation capabilities.

The application has this main components:

  • Algebraic components using sympy engine with sympify, solve, evalf. This includes all the mathematical functions and the functions of sympy.
  • Special objects called Types or classes under custom_types folder.
    • This classes are automatically discovered at startup.
    • every class has functions that some are for the interaction with other clases o with sympy. Other functions can be used directly by the user with parameters and returning the same object or other object.
    • special tokenization patterns & substitution using data collected from classes under custom_types folder.
    • every class has the Helper function to assist the user when on the line it is detected an error and the line starts with some patter
    • every class has a descriptor of functions that can be used for this object to permit the autocomplete popup help the user when they press "."

Concepts

  • Types : Special classes under custom_types folder. That are automatically discovered at startup.
  • Cycle: every time the user change the input panel start a cycle that ends when all lines are evaluated and produced an output
  • Input panel: tk text area where the user can write or modify text.
  • Output panel: read only tk area text correlated 1:1 to every line on the input panel . Every input line must correspond to only 1 line on the output. The output lines can have colors and binds to click for opening the plots or to show matrix or lists.
  • Persistence: The app maintain the state of all configurated setup and dimension of the window and all the text on the input panel.

Application Architecture

Entry Point and Initialization

The application starts through calc.py, which serves as a launcher with comprehensive logging and error handling. It initializes the main GUI application (HybridCalculatorApp) which in turn creates a PureAlgebraicEngine instance as its computational core.

During initialization, the system performs auto-discovery of custom types from the custom_types/ directory. Each type module can define tokenization patterns, helper functions, and computational behaviors. This creates a registry of available types and their associated transformation rules.

Calculation Cycle Flow

1. Input Capture and Triggering

The calculation cycle begins when the user types in the input panel. The GUI uses a debounced key release handler that triggers evaluation after a 300ms delay, preventing excessive computation during active typing.

2. Line Processing Pipeline

The engine processes all input lines sequentially, maintaining a clean context for each evaluation cycle:

Context Reset: Before each evaluation cycle, the engine clears its internal context completely. This ensures that each modification to the input re-evaluates everything from scratch, maintaining consistency.

Line Classification: Each line is categorized as:

  • Empty or comment (ignored)
  • Equation (contains = but not as comparison operator)
  • Solve shortcut (pattern variable=?)
  • Expression (everything else)

3. Tokenization System

The tokenization system operates through a distributed pattern-matching architecture:

Pattern Discovery: During initialization, the system discovers tokenization patterns from all registered type classes. Each type can define multiple patterns with priorities and replacement functions.

Pattern Application: Tokenization applies patterns in priority order (higher priority first). Each pattern consists of:

  • A regular expression to match
  • A replacement function that transforms the match
  • Priority level for ordering
  • Description for debugging

Example Transformations:

  • 192.168.1.1 becomes FourBytes("192.168.1.1")
  • 16#FF becomes IntBase("FF", 16)
  • 2#1010 becomes IntBase("1010", 2)

Bracket Parser Integration: After tokenization, the bracket parser processes any remaining bracket syntax transformations for legacy compatibility. ==Must be removed==

Also every constructor of every Type must be instantiated using eval. For example if a line has "a = IP4(10.1.1.1)" the tokeniser first will translate to "a = IP4(FourBytes("10.1.1.1"))" then eval needs to instantiate the IP4 object so the a will be equal to an object IP4.

4. Algebraic Engine Processing

The PureAlgebraicEngine implements a pure algebraic approach where all assignments become equations:

Equation Detection: The engine distinguishes between:

  • Simple assignments (x = 5) - creates both a variable assignment and an implicit equation-
  • Complex equations (x**2 + 2*x = 8) - added directly to the equation system
  • Solve shortcuts (x=?) - equivalent to solve(x) using the current equation system

Symbol Management: Variables are automatically and must maintain the type as long as possible. Also if there are aritmetic use with Types we need to cast the result to the Type involved. For example if we have "IP4(10.1.1.1)+1" the result must be IP4 object. The engine maintains a symbol table and equation list that increase every line that persist until the end of the cycle.

Context Building: For each evaluation, the engine builds a complete context including:

  • Base mathematical functions (sin, cos, solve, etc.)
  • Dynamically registered custom types
  • Current variable assignments
  • Helper functions from type registry

5. Expression Evaluation Strategy

The engine uses a hybrid evaluation strategy:

Symbolic Priority: Expressions are first attempted through SymPy's sympify to maintain symbolic forms. This preserves exact mathematical representations.

Automatic Substitution:

  • The engine automatically substitutes known numerical values into symbolic expressions when possible, while preserving symbolic forms for unknown variables.
  • ==Funtions

Numerical Approximation: When beneficial, the engine provides numerical approximations alongside symbolic results. The decision is based on whether the numerical form differs meaningfully from the symbolic representation.

6. Result Processing and Display

Result Classification: Each evaluation produces an EvaluationResult with:

  • The computed result (symbolic or numerical)
  • Result type classification
  • Success/error status
  • Optional numerical approximation
  • Metadata about the evaluation

Interactive Elements: The display system identifies results that benefit from interactivity:

  • Large matrices become expandable views
  • Plot commands create interactive matplotlib windows
  • Long lists become scrollable displays
  • Complex objects get detailed inspection windows

Tag-Based Formatting: Results are displayed with color-coded tags based on their type and semantic meaning. The GUI applies appropriate formatting for equations, errors, symbolic expressions, and custom type outputs.

Type System Integration

Dynamic Type Loading

The type system loads custom classes from the custom_types/ directory at startup. Each type module can define:

  • Class behaviors and arithmetic operations
  • Tokenization patterns for automatic recognition
  • Helper functions for contextual assistance
  • Display and conversion methods

Inheritance Patterns

Types inherit from either:

  • ClassBase - for basic custom types
  • SympyClassBase - for types requiring full SymPy integration

This allows seamless interaction between custom types and the symbolic algebra system.

Method Discovery

The system automatically discovers and exposes methods from custom types for autocompletion and help systems. This includes both instance methods and static helper functions.

Error Handling and Recovery

The application implements comprehensive error handling at each stage:

Tokenization Errors: Failed tokenization patterns are logged but don't halt processing, allowing partial transformations to proceed.

Evaluation Errors: Helper from classes first, then if there is no match SymPy evaluation errors trigger fallback strategies, including symbol creation for undefined variables and alternative parsing approaches.

Display Errors: Rendering failures fall back to string representations, ensuring results are always visible even if formatting fails.

Performance Characteristics

Lazy Evaluation: Complex computations are deferred until needed, with caching of intermediate results where appropriate.

Incremental Processing: Only changed content triggers re-evaluation, though the current implementation re-evaluates everything for consistency.

Memory Management: The system manages symbol tables and equation lists efficiently, with cleanup mechanisms for large sessions.

Session Persistence

The application maintains session continuity through:

History Persistence: Input content is automatically saved and restored between sessions. Context Preservation: Variable assignments and equations persist during the scope of every cycle. The context is added on every line and cleared at the begining of ever cycle. This means that every time the user changes the input panel the context is cleared. Settings Management: UI state and preferences are preserved across application restarts.