Core API Reference
The mechanics_dsl.core package contains the fundamental components of the
MechanicsDSL framework: the compiler, parser, symbolic engine, and numerical solver.
PhysicsCompiler
- class mechanics_dsl.core.PhysicsCompiler
The main entry point for MechanicsDSL. Orchestrates the entire pipeline from DSL source code to simulation results and visualization.
Example:
from mechanics_dsl import PhysicsCompiler compiler = PhysicsCompiler() result = compiler.compile_dsl(source) solution = compiler.simulate((0, 10)) compiler.animate(solution)
- compile_dsl(source: str) dict
Compile DSL source code into an executable simulation.
- Parameters:
source (str) – DSL source code string
- Returns:
Compilation result dictionary
- Return type:
dict
Result Dictionary:
{ 'success': bool, # True if compilation succeeded 'system_name': str, # Name from \system{} command 'coordinates': list, # List of generalized coordinates 'parameters': dict, # Parameter name -> value mapping 'initial_conditions': dict, # Initial state 'equations': dict, # Symbolic equations of motion 'error': str, # Error message if failed (optional) }
- simulate(t_span: tuple, num_points: int = 1000, method: str = None, rtol: float = None, atol: float = None, detect_stiff: bool = True) dict
Run numerical simulation of the compiled system.
- Parameters:
t_span (tuple) – Time interval (t_start, t_end)
num_points (int) – Number of output time points
method (str) – Integration method (RK45, LSODA, Radau, etc.)
rtol (float) – Relative tolerance
atol (float) – Absolute tolerance
detect_stiff (bool) – Automatically detect stiff systems
- Returns:
Simulation result dictionary
- Return type:
dict
Result Dictionary:
{ 'success': bool, # True if simulation succeeded 't': np.ndarray, # Time points 'y': np.ndarray, # State vector (2n x m matrix) 'coordinates': list, # Coordinate names 'nfev': int, # Function evaluations 'status': int, # Solver status code 'message': str, # Status message }
- visualize(solution: dict = None, animation_type: str = 'auto') None
Create visualization of simulation results.
- Parameters:
solution – Simulation result (uses last simulation if None)
animation_type – ‘auto’, ‘pendulum’, ‘oscillator’, ‘phase_space’
- plot_energy(solution: dict = None) None
Plot energy conservation analysis.
- compile_to_cpp(filename: str = 'simulation.cpp', target: str = 'standard') str
Generate C++ code for the compiled system.
- Parameters:
filename – Output file path
target – ‘standard’, ‘openmp’, or ‘wasm’
- Returns:
Path to generated file
- set_parameter(name: str, value: float) None
Update a parameter value after compilation.
- set_initial_condition(name: str, value: float) None
Update an initial condition after compilation.
MechanicsParser
- class mechanics_dsl.core.MechanicsParser
Parser for the MechanicsDSL language. Converts tokenized input into an Abstract Syntax Tree (AST).
Example:
from mechanics_dsl.core.parser import tokenize, MechanicsParser tokens = tokenize(source) parser = MechanicsParser(tokens) ast = parser.parse()
SymbolicEngine
- class mechanics_dsl.core.SymbolicEngine
Symbolic mathematics engine built on SymPy. Handles:
Conversion from AST expressions to SymPy
Euler-Lagrange equation derivation
Hamilton’s equations derivation
Symbolic simplification and caching
Example:
from mechanics_dsl.core.symbolic import SymbolicEngine engine = SymbolicEngine() engine.set_coordinates(['theta']) engine.set_lagrangian(lagrangian_expr) equations = engine.derive_equations()
- set_coordinates(coords: List[str]) None
Set the generalized coordinates.
- set_lagrangian(expr) None
Set the Lagrangian expression.
- set_hamiltonian(expr) None
Set the Hamiltonian expression.
- derive_euler_lagrange() Dict[str, sp.Expr]
Derive Euler-Lagrange equations.
- Returns:
Mapping of acceleration symbols to expressions
- derive_hamiltons_equations() Dict[str, sp.Expr]
Derive Hamilton’s equations of motion.
- solve_for_accelerations() Dict[str, sp.Expr]
Solve the EOM for acceleration terms.
NumericalSimulator
- class mechanics_dsl.core.NumericalSimulator
Numerical integration engine using SciPy solvers.
Example:
from mechanics_dsl.core.solver import NumericalSimulator sim = NumericalSimulator(symbolic_engine) sim.set_parameters(params) sim.set_initial_conditions(ic) solution = sim.simulate((0, 10))
- __init__(symbolic_engine: SymbolicEngine)
Initialize with a compiled symbolic engine.
- set_parameters(params: Dict[str, float]) None
Set physical parameter values.
- set_initial_conditions(ic: Dict[str, float]) None
Set initial state values.
- compile_equations() None
Compile symbolic equations to numerical functions.
- simulate(t_span: tuple, num_points: int = 1000, **kwargs) dict
Run the numerical simulation.
- detect_stiffness() str
Automatically detect if system is stiff and suggest solver.
AST Node Types
The parser produces the following AST node types:
Node Type |
Purpose |
Key Attributes |
|---|---|---|
|
System name |
|
|
Variable definition |
|
|
Parameter definition |
|
|
Lagrangian expression |
|
|
Hamiltonian expression |
|
|
Holonomic constraint |
|
|
External force |
|
|
Damping term |
|
|
Initial state |
|
|
Fluid region |
|
|
Boundary region |
|
Expression Types
Mathematical expressions are represented by:
NumberExpr: Numeric literalsIdentExpr: Variable/parameter identifiersBinaryOpExpr: Binary operations (+, -, *, /, ^)UnaryOpExpr: Unary operations (-)FractionExpr: Fractions (\frac{}{})DerivativeVarExpr: Time derivatives (\dot{}, q_dot)FunctionCallExpr: Function calls (\sin, \cos, etc.)GreekLetterExpr: Greek letters (\theta, \phi)
Error Handling
- exception mechanics_dsl.core.parser.ParserError
Raised when the parser encounters invalid syntax.
Attributes:
message: Error descriptionline: Line number (if available)column: Column number (if available)
Token Types
The tokenizer recognizes these token types:
Token Type |
Pattern |
|---|---|
|
|
|
|
|
|
|
Integer or floating point |
|
Word characters |
|
|
|
|
|
|
|
|
|
|
|
|
|
End of input |