JavaScript Code Generation
Generate JavaScript simulation modules for browser and Node.js.
Features
ES6 modules + CommonJS: Works in browsers, Node.js, and bundlers
Three integrators: Euler, RK4, and adaptive RK4-5
Canvas visualization: Built-in pendulum drawing helper
CSV and JSON export:
exportCSV()andexportJSON()functionsTypeScript definitions: Optional
.d.tsgenerationZero dependencies: Pure JavaScript, no npm packages required
Basic Usage
from mechanics_dsl.codegen.javascript import JavaScriptGenerator
import sympy as sp
theta, g, l = sp.symbols('theta g l')
gen = JavaScriptGenerator(
system_name="pendulum",
coordinates=["theta"],
parameters={"g": 9.81, "l": 1.0},
initial_conditions={"theta": 0.5, "theta_dot": 0.0},
equations={"theta_ddot": -g/l * sp.sin(theta)},
integrator="rk4",
generate_typescript=True
)
gen.generate("pendulum.js")
Parameters
integrator: Integration method —euler,rk4, oradaptive(default:rk4)generate_typescript: Generate.d.tstype definitions (default:False)
Usage in Node.js
const sim = require('./pendulum');
const results = sim.simulate({ tEnd: 10, dt: 0.01, trackEnergy: true });
console.log(`Points: ${results.t.length}`);
Usage in Browser
<script src="pendulum.js"></script>
<script>
const results = simulate({ tEnd: 10, dt: 0.01 });
</script>
Canvas Animation
The generated code includes a drawPendulum() helper:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const results = simulate({ tEnd: 10, dt: 0.01 });
let frame = 0;
function animate() {
drawPendulum(ctx, results.y[frame]);
frame = (frame + 1) % results.t.length;
requestAnimationFrame(animate);
}
animate();
Generated Code Structure
Physical constants: Module-level
constdeclarations``equationsOfMotion(t, y)``: State derivative function
Integrators:
eulerStep,rk4Step,adaptiveStep``simulate(config)``: Main simulation loop with configurable solver
``computeEnergy(y)``: Mechanical energy computation
``exportCSV(results)``: CSV string generation
``exportJSON(results)``: JSON serialization
``drawPendulum(ctx, state)``: Canvas rendering helper
Module exports: CommonJS and browser globals
Integrator Comparison
Integrator |
Order |
Use Case |
|---|---|---|
|
1st |
Fast, low accuracy, educational |
|
4th |
General purpose (default) |
|
4th-5th |
Variable step, automatic accuracy |
See Also
WebAssembly Code Generation - WebAssembly for near-native browser performance
Python Code Generation - NumPy-accelerated Python
Code Generation Overview - All code generation targets