Files
Entropyk/bindings/wasm/README.md

211 lines
6.7 KiB
Markdown

# Entropyk WebAssembly Bindings
WebAssembly bindings for the [Entropyk](https://github.com/entropyk/entropyk) thermodynamic simulation library.
## Features
- **Browser-native execution**: Run thermodynamic simulations directly in the browser
- **TabularBackend**: Pre-computed fluid tables for fast property lookups (100x faster than direct EOS calls)
- **Zero server dependency**: No backend required - runs entirely client-side
- **JSON serialization**: All results are JSON-serializable for easy integration
## Installation
```bash
npm install @entropyk/wasm
```
## Quick Start
```javascript
import init, {
WasmSystem,
WasmCompressor,
WasmCondenser,
WasmEvaporator,
WasmExpansionValve,
WasmFallbackConfig
} from '@entropyk/wasm';
// Initialize the WASM module
await init();
// Create components
// WasmCompressor(fluid, speed_rpm, displacement_m3_per_rev, efficiency, m1..m10)
const compressor = new WasmCompressor(
"R134a", // fluid
2900.0, // speed_rpm
0.0001, // displacement_m3_per_rev
0.85, // mechanical_efficiency
1.0, 0.0, 0.0, 0.0, 0.0, // AHRI 540 coefficients m1-m5
0.0, 0.0, 0.0, 0.0, 0.0 // AHRI 540 coefficients m6-m10
);
// WasmCondenser(ua) — thermal conductance in W/K
const condenser = new WasmCondenser(1000.0);
// WasmEvaporator(ua) — thermal conductance in W/K
const evaporator = new WasmEvaporator(800.0);
// WasmExpansionValve(fluid, capacity_kW) — pass 0 for no capacity limit
const valve = new WasmExpansionValve("R134a", 0.0);
// Create system and add components
const system = new WasmSystem();
const n0 = system.add_component(compressor.into_component());
const n1 = system.add_component(condenser.into_component());
const n2 = system.add_component(valve.into_component());
const n3 = system.add_component(evaporator.into_component());
// Connect components in a cycle
system.add_edge(n0, n1)?; // compressor → condenser
system.add_edge(n1, n2)?; // condenser → valve
system.add_edge(n2, n3)?; // valve → evaporator
system.add_edge(n3, n0)?; // evaporator → compressor
// Finalize topology
system.finalize()?;
// Configure solver
const config = new WasmFallbackConfig();
// Solve
const result = system.solve(config);
console.log(result.toJson());
// {
// "converged": true,
// "iterations": 12,
// "final_residual": 1e-8,
// "status": "Converged"
// }
// Get thermodynamic state at a node
const state = system.get_node_result(0);
console.log(state.toJson());
// {
// "pressure": { "pascals": 1000000.0 },
// "temperature": { "kelvin": 310.5 },
// "enthalpy": { "joules_per_kg": 420000.0 },
// "mass_flow": { "kg_per_s": 0.0 }
// }
```
## API Reference
### Core Types
- `WasmPressure` — Pressure in Pascals (constructor validates non-negative)
- `new(pascals)` — from Pascals
- `from_bar(bar)` — from bar
- `WasmTemperature` — Temperature in Kelvin (constructor validates non-negative)
- `new(kelvin)` — from Kelvin
- `from_celsius(celsius)` — from Celsius
- `WasmEnthalpy` — Enthalpy in J/kg (constructor rejects NaN)
- `new(joules_per_kg)` — from J/kg
- `from_kj_per_kg(kj_per_kg)` — from kJ/kg
- `WasmMassFlow` — Mass flow in kg/s (constructor rejects NaN)
- `new(kg_per_s)` — from kg/s
All types have a `toJson()` method returning a JSON string.
### Components
- `WasmCompressor` — AHRI 540 compressor model
- `new(fluid, speed_rpm, displacement, efficiency, m1..m10)` — all 10 AHRI coefficients required
- `WasmCondenser` — Heat rejection heat exchanger
- `new(ua)` — thermal conductance in W/K (must be positive)
- `WasmEvaporator` — Heat absorption heat exchanger
- `new(ua)` — thermal conductance in W/K (must be positive)
- `WasmExpansionValve` — Isenthalpic expansion device
- `new(fluid, capacity_kW)` — pass 0 for no capacity limit
- `WasmPipe` — Transport pipe
- `new(fluid, length, diameter, density, viscosity)` — all parameters required
Each component has an `into_component()` method that converts it to a generic `WasmComponent` for adding to the system.
### Solver
- `WasmSystem` — Thermodynamic system container
- `add_component(component)` → node index
- `add_edge(from_idx, to_idx)` — connect two component nodes
- `finalize()` — finalize topology before solving
- `solve(config)` — solve with fallback strategy
- `solve_newton(config)` — solve with Newton-Raphson only
- `get_node_result(idx)` — get thermodynamic state at a node after solving
- `WasmNewtonConfig` — Newton-Raphson solver configuration
- `set_max_iterations(n)`, `set_tolerance(tol)`
- `WasmPicardConfig` — Sequential substitution solver configuration
- `set_max_iterations(n)`, `set_relaxation_factor(omega)` — omega clamped to (0, 1]
- `WasmFallbackConfig` — Intelligent fallback solver configuration
- `set_fallback_enabled(bool)`, `set_return_to_newton_threshold(f64)`, `set_max_fallback_switches(usize)`
- `WasmConvergedState` — Solver result with `converged`, `iterations`, `final_residual`, `status`
### Fluid Management
- `list_available_fluids()` — returns array of available fluid names
- `load_fluid_table(json_string)` — load a custom fluid table from JSON
## Build Requirements
- Rust 1.70+
- wasm-pack: `cargo install wasm-pack`
- wasm32 target: `rustup target add wasm32-unknown-unknown`
## Building from Source
```bash
# Clone the repository
git clone https://github.com/entropyk/entropyk.git
cd entropyk/bindings/wasm
# Build for browsers
wasm-pack build --target web
# Build for Node.js
wasm-pack build --target nodejs
# Run Rust WASM tests
wasm-pack test --node
```
## TypeScript Support
TypeScript definitions are auto-generated by `wasm-pack build` in the `pkg/` directory.
After building, import the generated `.d.ts` file:
```typescript
import init, { WasmSystem } from './pkg/entropyk_wasm';
```
## Performance
| Operation | Target | Typical |
|-----------|--------|---------|
| Simple cycle solve | < 100ms | 30-50ms |
| Property query | < 1μs | ~0.5μs |
| Cold start | < 500ms | 200-300ms |
## Limitations
- **CoolProp unavailable**: The WASM build uses TabularBackend with pre-computed tables. CoolProp C++ cannot compile to WebAssembly.
- **Limited fluid library**: By default, only R134a is embedded. Additional fluids can be loaded from JSON tables generated by the entropyk CLI.
- **Custom fluid tables**: `load_fluid_table` validates the table but registration in the global backend requires additional infrastructure (planned).
## Browser Compatibility
- Chrome/Edge 80+
- Firefox 75+
- Safari 14+
- Node.js 14+
## License
MIT OR Apache-2.0
## Links
- [Documentation](https://docs.rs/entropyk)
- [Repository](https://github.com/entropyk/entropyk)
- [npm Package](https://www.npmjs.com/package/@entropyk/wasm)