Python Code Generation ====================== Generate optimized NumPy-based Python code for integration with existing workflows. Overview -------- While MechanicsDSL simulations run in Python by default, you can export a standalone Python module with: - Pre-compiled equations (no symbolic overhead) - NumPy-optimized array operations - No MechanicsDSL dependency at runtime This is useful for: - Sharing simulations without the full package - Integration into larger Python projects - Educational purposes (readable generated code) Basic Usage ----------- .. code-block:: python from mechanics_dsl import PhysicsCompiler compiler = PhysicsCompiler() compiler.compile_dsl(source) # Generate standalone Python module compiler.export_python("pendulum_sim.py") Generated Code Structure ------------------------ The exported file contains: .. code-block:: python """ Generated by MechanicsDSL System: simple_pendulum """ import numpy as np from scipy.integrate import solve_ivp # Parameters m = 1.0 # kg l = 1.0 # m g = 9.81 # m/s^2 def derivatives(t, y): """Compute dy/dt for the system.""" theta, theta_dot = y # Equations of motion (derived from Lagrangian) theta_ddot = -(g/l) * np.sin(theta) return [theta_dot, theta_ddot] def simulate(t_span=(0, 10), y0=[0.5, 0.0], **kwargs): """Run simulation and return solution.""" return solve_ivp(derivatives, t_span, y0, dense_output=True, **kwargs) if __name__ == "__main__": sol = simulate() print(f"Final state: {sol.y[:, -1]}") Using Generated Code -------------------- The exported module can be used independently: .. code-block:: python # Import the generated module import pendulum_sim # Run with default parameters solution = pendulum_sim.simulate() # Or customize solution = pendulum_sim.simulate( t_span=(0, 20), y0=[1.0, 0.5], # Different initial conditions method='DOP853', rtol=1e-10 ) # Access results t = solution.t theta = solution.y[0] theta_dot = solution.y[1] Performance Comparison ---------------------- Generated Python vs interpreted MechanicsDSL: .. list-table:: :header-rows: 1 * - System - MechanicsDSL (s) - Generated (s) - Speedup * - Simple pendulum - 0.15 - 0.05 - 3x * - Double pendulum - 0.45 - 0.21 - 2x The speedup comes from: 1. No symbolic parsing overhead 2. Pre-simplified equations 3. Direct NumPy operations Note: For significant speedups, use C++ code generation instead. Customization Options --------------------- .. code-block:: python compiler.export_python( "output.py", include_plotting=True, # Add matplotlib code include_animation=True, # Add animation code docstrings=True # Include documentation ) Limitations ----------- - Python generation does not support SPH fluids (use C++ instead) - Performance is still limited by Python interpreter - For real-time applications, prefer compiled targets