chore: sync project state and current artifacts

This commit is contained in:
Sepehr
2026-02-22 23:27:31 +01:00
parent 1b6415776e
commit dd77089b22
232 changed files with 37056 additions and 4296 deletions

View File

@@ -1,97 +1,138 @@
# Entropyk: The Definitive Guide
# Entropyk: Technical Manual & Reference Guide
Entropyk is a high-performance thermodynamic simulation framework designed for precision modeling of HVAC/R systems. It combines deep physical principles with modern software engineering patterns to provide a robust, scalable, and cross-platform simulation engine.
## 1. Core Philosophy
### Physics First (Type-Safe Units)
Entropyk eliminates unit errors at the compiler level. Instead of using `f64` for all physical values, we use strong types:
- `Pressure` (Pascals, bar, psi)
- `Temperature` (Kelvin, Celsius, Fahrenheit)
- `Enthalpy` (J/kg, kJ/kg)
- `MassFlow` (kg/s, g/s)
These types prevent accidents like adding Celsius to Kelvin or confusing bar with Pascals.
### Topology Safety (Type-State Connections)
Using Rust's type system, ports transition from `Disconnected` to `Connected`. A `Connected` port is guaranteed to have the same fluid, pressure, and enthalpy as its peer. The solver only accepts systems with fully connected and validated topologies.
Entropyk is a high-performance thermodynamic simulation framework designed for precision modeling of HVAC/R systems. This manual provides exhaustive documentation of the physical models, solver mechanics, and multi-platform APIs.
---
## 2. Core Modules
## 1. Physical Foundations
### 💧 Fluids (`entropyk-fluids`)
The thermodynamic property backbone.
- **CoolProp Backend**: Full Equation of State (EOS) for hundreds of fluids and mixtures.
- **Tabular Backend**: High-performance bicubic interpolation for real-time applications (HIL).
- **Caching Layer**: Intelligent LRU caching and SIMD-optimized lookups.
### 1.1 Dimensional Analysis & Type Safety
Entropyk utilizes a "Type-Safe Dimension" pattern to eliminate unit errors. Every physical quantity is wrapped in a NewType that enforces SI base units internally.
### 🧱 Components (`entropyk-components`)
Highly modular building blocks.
- **Compressor**: AHRI 540 10-coefficient and SST/SDT polynomial models.
- **Heat Exchangers**: ε-NTU and LMTD models with support for phase changes.
- **Advanced Topology**: `FlowSplitter`, `FlowMerger`, `FlowSource`, and `FlowSink`.
- **Customizable**: Implement the `Component` trait to add your own physics.
| Quantity | Internal Unit (SI) | Documentation Symbol |
| :--- | :--- | :--- |
| Pressure | Pascal ($Pa$) | $P$ |
| Temperature | Kelvin ($K$) | $T$ |
| Enthalpy | Joule per kilogram ($J/kg$) | $h$ |
| Mass Flow | Kilogram per second ($kg/s$) | $\dot{m}$ |
| Density | Kilogram per cubic meter ($kg/m^3$) | $\rho$ |
### 🔄 Solver (`entropyk-solver`)
The convergence engine.
- **Newton-Raphson**: Fast, quadratic convergence with line search and step clipping.
- **Picard (Sequential Substitution)**: Robust fallback for systems with high non-linearity.
- **Jacobian Freezing**: Performance optimization that skips expensive derivative calculations when appropriate.
### 1.2 Conservation Laws
The solver operates on the principle of local conservation at every node $i$:
- **Mass Conservation**: $\sum \dot{m}_{in} - \sum \dot{m}_{out} = 0$
- **Energy Conservation**: $\sum (\dot{m} \cdot h)_{in} - \sum (\dot{m} \cdot h)_{out} + \dot{Q} - \dot{W} = 0$
---
## 3. Advanced Modeling
## 2. Fluid Physics (`entropyk-fluids`)
### Multi-Circuit Brilliance
Entropyk naturally supports systems with multiple independent circuits (e.g., a Chiller with a refrigerant loop and a water loop) through thermal coupling via Heat Exchangers.
The `FluidBackend` trait provides thermodynamic properties $(T, \rho, c_p, s)$ as functions of state variables $(P, h)$.
### Inverse Control & Parameter Estimation
Go beyond "What happens if...?" to "What must I do to...?"
- **Bounded Control**: Set limits on control variables (e.g., valve opening 0.0-1.0).
- **Constraint Solver**: Target specific outputs (e.g., "Set speed to achieve 7°C water exit").
- **Inverse Calibration**: Estimate physical parameters (like UA or efficiency) from experimental data using the one-shot solver.
### 2.1 Backend Implementations
#### A. CoolProp Backend
Utilizes full Helmholtz energy equations of state (EOS).
- **Domain**: Precise research and steady-state validation.
- **Complexity**: $O(N)$ high overhead due to iterative property calls.
#### B. Tabular Backend (Bicubic)
Uses high-fidelity lookup tables with bicubic Hermite spline interpolation.
- **Equation**: $Z(P, h) = \sum_{i=0}^3 \sum_{j=0}^3 a_{ij} \cdot P^i \cdot h^j$
- **Performance**: $O(1)$ constant time with SIMD acceleration. Recommended for HIL.
#### C. Incompressible Backend (Linearized)
For water, glycols, and brines where $\rho$ is nearly constant.
- **Density**: $\rho(T) = \rho_0 \cdot [1 - \beta(T - T_0)]$
- **Enthalpy**: $h = c_p \cdot (T - T_0)$
### 2.2 Phase Change Logic
Fluid backends automatically identify the fluid phase:
1. **Subcooled**: $h < h_{sat,l}(P)$
2. **Two-Phase**: $h_{sat,l}(P) \le h \le h_{sat,v}(P)$
3. **Superheated**: $h > h_{sat,v}(P)$
For two-phase flow, quality $x$ is defined as:
$$x = \frac{h - h_{sat,l}}{h_{sat,v} - h_{sat,l}}$$
### Physical Validation
Every solution is automatically validated for:
- **Mass Balance**: Σ ṁ_in = Σ ṁ_out within 1e-9 kg/s.
- **Energy Balance**: (Planned) Conservation of enthalpy across joints.
---
## 4. Multi-Platform Ecosystem
## 3. Component Technical Reference (`entropyk-components`)
### 🐍 Python
Mirroring the Rust API, our Python bindings offer the same speed and safety with the flexibility of data science tools (NumPy, Pandas, Jupyter).
### 3.1 Compressor (`Compressor`)
### 🛠️ C / FFI
Integrate Entropyk into PLC controllers, HIL systems (dSPACE, Speedgoat), or legacy C++ codebases with our zero-allocation C header.
#### A. AHRI 540 (10-Coefficient)
Standard model for positive displacement compressors. Mass flow $\dot{m}$ and power $W$ are calculated using the 3rd-order polynomial:
$$X = C_1 + C_2 T_s + C_3 T_d + C_4 T_s^2 + C_5 T_s T_d + C_6 T_d^2 + C_7 T_s^3 + C_8 T_d T_s^2 + C_9 T_s T_d^2 + C_{10} T_d^3$$
*Note: $T_s$ is suction temperature and $T_d$ is discharge temperature in Fahrenheit or Celsius depending on coefficients.*
### 🌐 WebAssembly
The same Rust physics engine running in your browser for interactive design tools and client-side simulations.
#### B. SST/SDT Polynomials
Used for variable speed compressors where coefficients are adjusted for RPM:
$$\dot{m} = \sum_{i=0}^3 \sum_{j=0}^3 A_{ij} \cdot SST^i \cdot SDT^j$$
### 3.2 Pipe (`Pipe`)
- **Pressure Drop**: $\Delta P = f \cdot \frac{L}{D} \cdot \frac{\rho v^2}{2}$
- **Haaland Approximation** (Friction Factor $f$):
$$\frac{1}{\sqrt{f}} \approx -1.8 \log_{10} \left[ \left(\frac{\epsilon/D}{3.7}\right)^{1.11} + \frac{6.9}{Re} \right]$$
*Where $Re = \frac{\rho v D}{\mu}$ is the Reynolds number.*
### 3.3 Heat Exchanger (`HeatExchanger`)
Single-phase and phase-change modeling via the $\varepsilon$-NTU method.
- **Heat Transfer**: $\dot{Q} = \varepsilon \cdot C_{min} \cdot (T_{h,in} - T_{c,in})$
- **Effectiveness ($\varepsilon$)**:
- **Counter-Flow**: $\varepsilon = \frac{1 - \exp(-NTU(1 - C^*))}{1 - C^* \exp(-NTU(1 - C^*))}$
- **Evaporator/Condenser**: $\varepsilon = 1 - \exp(-NTU)$ (since $C^* \to 0$ during phase change)
---
## 5. Developer Ecosystem & Platform Specifics
## 4. Solver Engine (`entropyk-solver`)
### 🐍 Python: Integration & Data Science
- **Performance**: Rust-native speed with zero-copy data passing for large state vectors.
- **Exception Hierarchy**: Specific catchable exceptions like `SolverError`, `FluidError`, and `ValidationError`.
- **Interchange**: System states can be exported to NumPy arrays for analysis.
The engine solves $\mathbf{F}(\mathbf{x}) = \mathbf{0}$ where $\mathbf{x}$ is the state vector $[P, h]$ for all edges.
### 🛠️ C / FFI: HIL & Real-Time
- **Ownership**: Explicit `create`/`free` patterns. Adding a component to a `System` transfers ownership to Rust.
- **Real-Time Ready**: No dynamic allocations in the `solve` hot path when using the C FFI.
- **Header**: Single `entropyk.h` required for integration.
### 4.1 Newton-Raphson Solver
Primary strategy for fast, quadratic convergence.
$$\mathbf{J}(\mathbf{x}_k) \Delta \mathbf{x} = -\mathbf{F}(\mathbf{x}_k)$$
$$\mathbf{x}_{k+1} = \mathbf{x}_k + \alpha \Delta \mathbf{x}$$
### 🌐 WebAssembly: Client-Side Physics
- **Initialization**: Must call `await init()` before use.
- **Fluid Tables**: Uses `TabularBackend`. Custom fluids loaded via `load_fluid_table(json_string)`.
- **JSON First**: Optimized for passing system definitions and results as JSON objects.
- **Armijo Line Search**: Dynamically adjusts $\alpha$ to ensure steady residual reduction.
- **Step Clipping**: Hard bounds on $\Delta P$ and $\Delta h$ to maintain physical sanity (e.g., $P > 0$).
- **Jacobian Freezing**: Reuses $\mathbf{J}$ for $N$ steps if convergence is stable, improving speed by ~40%.
### 4.2 Sequential Substitution (Picard)
Fixed-point iteration for robust initialization:
$$\mathbf{x}_{k+1} = \mathbf{x}_k - \omega \cdot \mathbf{F}(\mathbf{x}_k)$$
*Where $\omega \in (0, 1]$ is the relaxation factor (default 0.5).*
---
## 5. Advanced Features
### 5.1 Inverse Control
Swaps independent variables for targets.
- **Constraints**: Force specific outputs (e.g., Exit Superheat $= 5K$).
- **Bounded Variables**: Physical limits on inputs (e.g., Valve Opening $0 \le x \le 1$).
### 5.2 Multi-Circuit Coupling
Modeled via bridge components (typically `HeatExchanger`). The solver constructs a unified Jacobian for both circuits to handle thermal feedback loops in a single pass.
---
## 6. Multi-Platform API Reference
Entropyk provides high-fidelity bindings with near-perfect parity.
| Feature | Rust (`-core`) | Python (`entropyk`) | C / FFI | WASM |
| :--- | :--- | :--- | :--- | :--- |
| **Component Creation** | `Compressor::new()` | `ek.Compressor()` | `ek_compressor_create()` | `new Compressor()` |
| **System Finalization** | `system.finalize()` | `system.finalize()` | `ek_system_finalize()` | `system.finalize()` |
| **Solving** | `config.solve(&sys)` | `config.solve(sys)` | `ek_solve(sys, cfg)` | `await config.solve(sys)` |
| **Inverse Control** | `sys.add_constraint()` | `sys.add_constraint()` | `ek_sys_add_constraint()` | `sys.addConstraint()` |
| **Memory Management** | RAII (Automatic) | Ref-Counted (PyO3) | Manual Free (`_free`) | JS Garbage Collected |
---
## 7. Getting Started
- **Basic Example**: See [EXAMPLES_FULL.md](./EXAMPLES_FULL.md) for a "Simple Cycle" walkthrough.
- **Performance Tuning**: Use `JacobianBuilder` for custom components to maximize sparse matrix efficiency.
- **API Reference**: `cargo doc --open` for the full technical API.
- **Step-by-Step Instructions**: Refer to [EXAMPLES_FULL.md](./EXAMPLES_FULL.md).
- **Performance**: Use `TabularBackend` for real-time HIL applications.
- **Custom Physics**: Implement the `Component` trait in Rust for specialized modeling.