--- stepsCompleted: [1, 2, 3, 4, 5] inputDocuments: [] date: 2026-02-12 author: Sepehr --- # Product Brief: RustThermoCycle ## Executive Summary RustThermoCycle is a high-performance thermodynamic cycle simulation library written in Rust, designed to overcome the fundamental limitations of current open-source tools. While Python-based solutions like tespy and CoolProp suffice for single calculations, they become prohibitive bottlenecks during multi-variable optimizations requiring 10,000+ iterations. Furthermore, existing tools couple physical models tightly with solvers, leaving users blocked when algorithms diverge at critical operating points. RustThermoCycle delivers a modular, solver-agnostic architecture that enables R&D engineers and researchers to simulate Heat Pumps and Refrigeration systems with unprecedented speed and flexibility. By leveraging Rust's zero-cost abstractions and type safety, the library supports seamless switching between Sequential Substitution (Picard) and Newton-Raphson solvers without modifying component code—a capability absent from both open-source and many commercial alternatives. The library's graph-based topology system enables Modelica-like component connection (Port A → Port B) while maintaining Rust's execution speed. Critical industry needs such as Inverse Control—calculating valve openings from target superheat constraints—are handled through integrated residual solvers. With planned WebAssembly (Wasm) compilation support, RustThermoCycle bridges the gap between high-performance simulation and accessible web interfaces. --- ## Core Vision ### Problem Statement Current thermodynamic cycle simulation tools force users into an unacceptable trade-off: either accept Python's interpreter overhead that makes multi-variable optimization impractical, or tolerate rigid solver architectures that fail at phase transition critical points without recourse. ### Problem Impact For R&D engineers dimensioning Heat Pump systems, this means: - **Optimization cycles measured in hours instead of minutes** when exploring design parameter spaces - **Solver divergence at critical operating points** halting entire simulation workflows - **Inability to simulate real-world control scenarios** where input variables must be calculated from output constraints (Inverse Control) For researchers testing novel cycle architectures: - **Limited flexibility to experiment with solver strategies** for exotic working fluids or unconventional component arrangements - **Maintenance burden of pure equation-based models** (à la EES) or rigid block diagrams ### Why Existing Solutions Fall Short **Python-Based Tools (tespy, CoolProp bindings):** - Suffer from interpreter overhead making 10,000+ iteration optimizations prohibitively slow - Lack compile-time guarantees that could prevent unit mixing or invalid thermodynamic states **Commercial Tools (EES, Type S):** - Often based on pure equation approaches that are difficult to maintain and extend - Solver strategies typically hard-coded without runtime switching capability - Expensive licensing restricts academic access and collaborative development **Current Open-Source Alternatives:** - Tightly couple physical models with specific solver implementations - Provide no clean abstraction for Inverse Control scenarios common in industry - Miss the performance/safety balance that Rust provides ### Proposed Solution RustThermoCycle delivers a modular Rust library with four architectural pillars: 1. **Graph-Based Topology**: Components (Compressors, Evaporators, Condensers) connect through typed Fluid Nodes, enabling intuitive cycle construction à la Modelica but with Rust's performance. 2. **Solver Decoupling via Traits**: A trait-based abstraction layer allows seamless switching between Sequential Substitution (Picard iteration) for robust initialization and Newton-Raphson (via nalgebra) for rapid quadratic convergence—without touching component implementations. Dynamic fallback between strategies when divergence is detected. 3. **Inverse Control Framework**: Built-in residual solvers transform output constraints (target superheat, subcooling) into solvable systems for unknown inputs (valve openings, compressor speeds)—matching real-world control logic. 4. **Academic Rigor & Portability**: - 3-Zone heat exchanger models with rigorous energy balances - AHRI polynomial compressor maps - CoolProp integration via Rust bindings for high-fidelity fluid properties - WebAssembly compilation target for browser-based interfaces ### Key Differentiators **🚀 Modelica-Like Interface in Rust** The unique combination of declarative component connection syntax with systems language performance. No existing tool offers this balance of expressiveness and speed. **🔄 Dynamic Multi-Solver Strategy** The only open-source tool enabling runtime switching between Sequential Substitution and Newton-Raphson, with automatic fallback handling. Commercial tools typically lock users into one approach. **🎛️ Native Inverse Control** First-class support for control-oriented simulations where outputs drive input calculations—essential for real-world Heat Pump optimization but often bolted-on or missing in other tools. **⚡ WebAssembly Ready** Architecture designed for future Wasm compilation, enabling high-performance simulation in web browsers without Python backend dependencies. **🔒 Type-State Safety** Leverages Rust's type system to enforce valid thermodynamic states at compile time (e.g., preventing negative enthalpies), catching errors before runtime. --- ## Target Users ### Primary Users #### 1. Optimization Alice — R&D Heat Pump Engineer **Profile:** Alice is a thermal systems engineer at a major Heat Pump manufacturer. Her job is to optimize system performance across varying climate conditions and usage patterns. She lives in the world of SEER/SCOP ratings and regulatory compliance. **Context & Environment:** - Works with HVAC system simulation teams - Needs to generate performance maps for product certification - Runs parametric studies involving 10,000-50,000+ simulation points - Currently uses Python-based tools (tespy, CoolProp) or commercial software (EES) - Familiar with scripting and CLI tools, prefers automation **Pain Points:** - **Python interpreter overhead** makes large optimization studies run overnight instead of hours - **Solver divergence at critical points** (phase transitions, extreme conditions) stops entire batch runs - **No clean inverse control** — cannot easily specify target outputs (superheat) and solve for inputs (valve position) - Commercial tools are expensive and lock her into rigid solver strategies **Technical Interactions with RustThermoCycle:** *Graph Interaction:* - Constructs standard vapor-compression cycles programmatically via API - Uses pre-built component library (Compressor, Condenser, Evaporator, Expansion Valve) - Connects components through typed Fluid Nodes with working fluid specification - Expects graph validation to catch connection errors at compile time (Rust type safety) *Solver Interaction:* - **Primary need:** Batch execution with minimal overhead - Uses Sequential Substitution for initial guesses, then Newton-Raphson for convergence - Requires solver switching when divergence detected (automatic fallback) - Needs convergence diagnostics to identify problematic operating points - Expects parallel execution capabilities (multi-threading) for parameter sweeps *Success Moment:* When she runs a 50,000-point SEER map calculation in 20 minutes instead of 8 hours, with automatic handling of edge cases that used to crash her workflow. --- #### 2. Graph-Builder Bob — Thermodynamics Researcher **Profile:** Bob is a post-doc researcher in thermal systems engineering, exploring novel refrigeration cycle architectures. He works on unconventional configurations like ejector-enhanced cycles, cascade systems with multiple working fluids, and waste heat recovery loops. **Context & Environment:** - Academic research lab with focus on next-generation HVAC technologies - Experiments with exotic working fluids and non-standard component arrangements - Currently uses Modelica for modeling but frustrated by its steep learning curve and performance limitations - Also uses EES but finds pure equation-based approaches hard to maintain - Comfortable with code, prefers explicit control over simulation behavior **Pain Points:** - **Black-box solvers crash** on his non-conventional fluid models without explanation - **Rigid component libraries** don't support his custom components (ejector, novel heat exchanger geometries) - **No visibility into solver internals** — cannot debug why convergence fails - **Solver hard-coding** — cannot switch strategies when Newton-Raphson diverges on exotic conditions **Technical Interactions with RustThermoCycle:** *Graph Interaction:* - Builds custom cycle topologies manually using `connect(A, B)` API - Creates custom components implementing the component Trait interface - Needs flexible node types (refrigerant, air, brine, multi-fluid connections) - Expects graph visualization/debugging capabilities to verify topology - Requires support for multi-domain systems (refrigerant side + air side + controls) *Solver Interaction:* - **Primary need:** Solver transparency and control - Explicitly switches between Sequential Substitution (robust for initialization) and Newton-Raphson (fast convergence) - Inspects residual vectors and Jacobian matrices for debugging - Adjusts solver parameters (tolerances, damping factors) based on physics - Implements custom convergence criteria for exotic cycles *Success Moment:* When he can define a novel ejector-enhanced cascade cycle, switch to Sequential Substitution when Newton-Raphson fails on a critical point, inspect the residuals to understand the issue, and ultimately get convergence where all other tools failed. --- ### Secondary Users #### 3. Web-Dev Charlie — Frontend/Full-Stack Developer **Profile:** Charlie builds web-based tools for HVAC companies — internal configurators, customer-facing sizing tools, and educational simulators. He's a React/TypeScript expert who needs to embed thermodynamic calculations in browser applications. **Context & Environment:** - Works at HVAC software consultancies or equipment manufacturers - Builds React/Vue applications with complex calculation needs - Currently forced to use Python backends (Flask/FastAPI) for thermodynamic calculations - Struggles with server costs and latency for real-time web applications - Familiar with WebAssembly concepts but hasn't worked extensively with Rust **Pain Points:** - **Python backend dependency** requires expensive servers and creates latency issues - **Cannot run heavy calculations client-side** due to Python browser limitations (PyScript too slow) - **Type safety gaps** between JavaScript frontend and Python backend cause runtime bugs - **Deployment complexity** — needs to maintain Python environments on servers **Technical Interactions with RustThermoCycle:** *Graph Interaction:* - Uses high-level WASM bindings to construct cycles from JSON/YAML definitions - Relies on pre-validated component templates (standard Heat Pump, Refrigeration unit) - Expects type-safe API bindings generated for TypeScript - Needs serialization/deserialization of cycle graphs for save/load functionality *Solver Interaction:* - **Primary need:** Reliability and browser performance - Uses default solver strategy (automatic selection) without manual tuning - Expects WASM-compiled library to run at near-native speed in browser - Requires error handling that maps Rust errors to JavaScript exceptions cleanly - Needs deterministic execution for consistent UI updates *Success Moment:* When he ships a browser-based Heat Pump configurator where customers adjust sliders (evap temp, cond temp, superheat) and see real-time COP calculations instantly—without any backend server calls. --- ### User Journey #### Optimization Alice — Journey Map **Discovery:** Finds RustThermoCycle through Rust community forums or engineering software benchmarks showing 100x speedup over Python alternatives. **Onboarding:** 1. Installs via `cargo add rust-thermo-cycle` 2. Runs example script simulating standard Heat Pump cycle 3. Verifies performance with timing benchmarks 4. Adapts existing Python scripts to Rust API **Core Usage:** - Writes Rust scripts defining parameter sweeps (climate zones, load profiles) - Constructs cycles using builder pattern API - Executes batch simulations with Rayon parallelization - Exports results to CSV/Parquet for analysis in Python/R - Uses Inverse Control API to solve for valve positions given target constraints **Success Moment:** Completes full SEER calculation (50,000 points) before lunch instead of waiting overnight. Identifies optimal charge amount and valve settings automatically. **Long-term:** Integrates RustThermoCycle into company's CI/CD pipeline for automated performance regression testing. Becomes internal champion for Rust adoption in simulation team. --- #### Graph-Builder Bob — Journey Map **Discovery:** Discovers project through academic Twitter or Rust science community, intrigued by "Modelica-like interface in Rust" claim. **Onboarding:** 1. Clones repository and builds from source 2. Reads architecture docs on Trait-based component system 3. Implements custom Ejector component following Component trait 4. Constructs first exotic cycle topology using connect() API 5. Experiments with solver switching on challenging operating points **Core Usage:** - Defines custom components implementing thermodynamic equations - Builds unconventional cycle topologies (cascade, ejector-enhanced, multi-stage) - Switches between Sequential Substitution and Newton-Raphson based on convergence behavior - Inspects residual vectors to debug convergence failures - Publishes research with reproducible Rust code in supplementary materials **Success Moment:** Successfully simulates a novel cycle architecture that diverged in all other tools, with full transparency into solver behavior and physics-based debugging. **Long-term:** Contributes custom components back to open-source library. Publishes paper on solver strategy comparison for exotic refrigeration cycles. Uses library for graduate course on thermodynamic system modeling. --- #### Web-Dev Charlie — Journey Map **Discovery:** Finds project searching for "thermodynamics WebAssembly Rust" while evaluating options for client HVAC configurator project. **Onboarding:** 1. Checks npm registry for `rust-thermo-cycle` WASM package 2. Installs via `npm install rust-thermo-cycle` 3. Imports TypeScript bindings in React app 4. Loads pre-built cycle template via JSON configuration 5. Binds UI sliders (temperatures, superheat) to WASM calculation inputs **Core Usage:** - Embeds WASM module in React/Vue applications - Constructs cycles from JSON definitions sent to WASM bindings - Calls solver through simplified high-level API - Receives results as JavaScript objects for UI rendering - Implements real-time updates as users adjust parameters - Deploys static site to CDN (no backend servers needed) **Success Moment:** Launches customer-facing Heat Pump selector tool where users adjust operating conditions and see instant COP/efficiency calculations — all running client-side with zero backend costs. **Long-term:** Builds library of reusable React components (CycleDiagram, EfficiencyChart) wrapping RustThermoCycle WASM. Creates white-label configurator product sold to HVAC manufacturers. --- ## Success Metrics ### User Success Metrics #### Optimization Alice — Performance & Throughput **Speedup Factor (vs. Python)** - **Target:** 50x to 100x faster than equivalent Python (tespy / scipy.optimize) - **Measurement:** Average time to solve a simple Rankine cycle (1,000 iterations) - **Success Criteria:** Demonstrated through benchmark suite comparing identical thermodynamic problems **Simulation Throughput** - **Target:** > 10,000 operating points per minute on standard CPU (4 cores) using Rust parallelism (Rayon) - **Measurement:** Batch execution time for parametric studies across climate/load conditions - **Success Criteria:** SEER/SCOP mapping completes in < 20 minutes instead of 8+ hours **Batch Stability** - **Target:** < 0.1% Panics/Crashes over 50,000-point search space - **Measurement:** Automated stress testing across extreme operating conditions - **Success Criteria:** Software returns clean `Error` types, never crashes the process; graceful handling of divergence --- #### Graph-Builder Bob — Robustness & Solver Resilience **Solver Fallback Success Rate** - **Target:** > 90% recovery rate when Newton-Raphson diverges - **Measurement:** Automatic switching to Sequential Substitution (Picard) when residual > tolerance - **Success Criteria:** Convergence achieved after fallback; detailed residual logs available for debugging **Thermodynamic Accuracy** - **Target:** Global energy balance < 1e-6 kW; Mass balance < 1e-9 kg/s - **Measurement:** Comparison against AHRI-certified data and validated EES examples - **Success Criteria:** Conservation equations satisfied within numerical precision; validation suite passes --- #### Web-Dev Charlie — Portability & Integration **WebAssembly Binary Size** - **Target:** < 2 MB (gzipped) for complete core including essential fluid tables - **Measurement:** Optimized WASM build with dead code elimination - **Success Criteria:** Fast browser loading; CDN-friendly distribution **Time to First Solve** - **Target:** < 50ms to instantiate WASM module and solve first simple cycle in React app - **Measurement:** End-to-end integration test with React/Vue frontend - **Success Criteria:** Instant feedback for user interactions; zero perceived latency --- ### Business Objectives #### Technical Excellence & Adoption **Community Growth** - **3-Month Target:** 50+ GitHub stars, 5+ active contributors, 3+ research institutions evaluating - **12-Month Target:** 500+ GitHub stars, 20+ contributors, 2+ published papers citing the library **Industry Adoption** - **3-Month Target:** 2+ HVAC manufacturers in pilot evaluation - **12-Month Target:** 5+ commercial integrations, 1+ white-label product (Web-Dev Charlie scenario) **Open Source Sustainability** - **3-Month Target:** Complete documentation and API stability - **12-Month Target:** Stable 1.0 release with semantic versioning, established governance model --- ### Key Performance Indicators #### Technical KPIs | KPI | Target | Measurement Method | |-----|--------|-------------------| | Speedup vs. Python | 50-100x | Benchmark suite (criterion.rs) | | Batch Success Rate | 99.9% | Automated stress testing | | Solver Fallback Recovery | > 90% | Convergence test suite | | Energy Balance Precision | < 1e-6 kW | Validation against reference data | | WASM Bundle Size | < 2 MB | wasm-opt + gzip analysis | | Test Coverage | > 85% | tarpaulin + codecov | | Public API Documentation | 100% | rustdoc + doctest compliance | #### User Outcome KPIs | KPI | Target | Measurement Method | |-----|--------|-------------------| | SEER Map Calculation Time | < 20 min for 50K points | User-reported benchmarks | | Exotic Cycle Convergence | Success on 3+ novel architectures | Bob's research cases | | Web Integration Time | < 1 day for React app | Developer onboarding test | --- ### Vision of Success **The Migration Success Story:** The project will be considered a success when an engineering team can migrate their Python optimization script from an 8-hour overnight batch run to a RustThermoCycle execution completing in under 10 minutes — while maintaining the guarantee that conservation equations are satisfied to within 10^-6 precision. **Success Indicators:** ✅ **Performance Unlocked:** Multi-variable optimization studies (10,000+ iterations) complete during coffee breaks, not overnight ✅ **Robustness Proven:** Exotic cycle architectures converge where commercial tools fail, with full transparency into solver behavior ✅ **Portability Delivered:** Browser-based configurators run thermodynamic calculations client-side at near-native speed, eliminating backend costs ✅ **Quality Assured:** Every public API is documented, tested, and type-safe; thermodynamic errors caught at compile time ✅ **Community Thriving:** Active open-source community with contributions from both industry (R&D engineers) and academia (researchers) --- ## MVP Scope ### Core Features (IN - Périmètre MVP) #### 1. Graph-Based Topology System **Objective:** Enable Modelica-like component connection for standard vapor-compression cycles. **Implementation:** - Graph structure via `petgraph` or custom implementation - **Nodes:** Compressor, Condenser, ExpansionValve, Evaporator (4 core components) - **Edges:** FluidState carrying thermodynamic properties (P, h, m_dot) - Type-safe connections with compile-time validation - Builder pattern API for cycle construction **Success Criteria:** Users can programmatically construct a standard Heat Pump cycle with clear, intuitive API. --- #### 2. Sequential Substitution Solver (Picard Iteration) **Objective:** Robust solver for steady-state cycle convergence. **Implementation:** - Fixed-point iteration solver with damping - Residual calculation based on mass and energy balances - Configurable convergence tolerance and max iterations - **Architectural Constraint:** Generic `Solver` trait designed to accommodate future Newton-Raphson implementation **Success Criteria:** Standard cycles converge reliably; solver trait abstraction allows future solver swapping without component code changes. --- #### 3. Residual-Ready Architecture (Critical Foundation) **Objective:** Prepare foundation for Inverse Control without full implementation. **Implementation:** - All components expose `compute_residuals()` method - Residuals represent deviation between calculated and target states - Unified residual vector for the complete cycle - Jacobian structure preparation (sparsity pattern) for future Newton-Raphson **Why This Matters:** Designing for Forward-only calculation now would require major Trait refactoring for Inverse Control. Residual-ready architecture enables seamless transition to constraint-based solving in v2. **Success Criteria:** Components can report residuals; architecture supports future residual-based solving without breaking changes. --- #### 4. Safe CoolProp Integration **Objective:** High-fidelity fluid properties with robust error handling. **Implementation:** - Rust bindings to CoolProp C++ library - Safe wrappers preventing panics (e.g., P < 0, invalid temperature ranges) - Error types for thermodynamic domain violations - Support for common refrigerants (R410A, R32, R134a) **Success Criteria:** Property calculations are safe (no panics); errors are handled gracefully with meaningful messages. --- #### 5. Performance Benchmark (Proof of Concept) **Objective:** Demonstrate speedup vs. Python from day one. **Implementation:** - Benchmark suite using `criterion.rs` - Test case: 1,000 iterations of simple Rankine cycle - Comparison baseline: Equivalent Python implementation (tespy/CoolProp) - Target: Demonstrate measurable speedup (initial goal: 10x+ as stepping stone to 50-100x) **Success Criteria:** Benchmark proves performance advantage; "Optimization Alice" sees immediate value. --- ### Out of Scope for MVP (OUT - v2+) #### Deferred to v2.0 - **Newton-Raphson Solver:** Full Jacobian matrix implementation with nalgebra - **Solver Fallback:** Automatic switching between Sequential Substitution and Newton-Raphson - **WebAssembly Build:** wasm-bindgen integration and npm package distribution - **Inverse Control:** Full constraint-based solving (architecture ready, implementation deferred) - **Custom Components:** User-defined component creation beyond core 4 - **Advanced Components:** Ejectors, multi-stream heat exchangers, internal heat exchangers #### Deferred to v3.0+ - **GUI/Web Interface:** Visual cycle builder, React/Vue components - **Optimization Framework:** Built-in parameter sweep and optimization tools - **Parallel Execution:** Rayon-based multi-threading for batch operations - **Additional Working Fluids:** Full refrigerant database integration --- ### MVP Success Criteria #### Technical Validation | Criterion | Target | Measurement | |-----------|--------|-------------| | Cycle Convergence | 100% success on standard Heat Pump cycles | Automated test suite | | Performance Speedup | 10x+ vs. Python (MVP stepping stone to 50-100x) | Criterion benchmarks | | API Stability | No breaking changes to core traits | Code review | | Test Coverage | > 70% for core modules | Tarpaulin coverage | #### User Validation | Persona | Success Indicator | |---------|-----------------| | Optimization Alice | Can run 1,000-point parameter study in < 5 minutes (vs. hours in Python) | | Graph-Builder Bob | Can construct custom cycle topology via code; components expose residuals for inspection | #### Community Validation - Public GitHub repository with clear README - Basic documentation (rustdoc) for all public APIs - At least one complete example: "Standard Heat Pump simulation" - CI/CD pipeline with automated testing --- ### Future Vision #### v2.0: Solver Flexibility & Portability - **Newton-Raphson Implementation:** Fast quadratic convergence for well-behaved cycles - **Dynamic Solver Strategy:** Automatic fallback when Newton diverges; user-controlled solver selection - **Inverse Control:** Full constraint-based solving — specify outputs, solve for inputs - **WebAssembly Target:** Browser-compatible builds for web applications - **TypeScript Bindings:** Type-safe integration for Web-Dev Charlie #### v3.0: Ecosystem & Advanced Features - **Component Library Expansion:** Ejectors, multi-stage compression, complex heat exchangers - **Optimization Framework:** Built-in parameter sweep, sensitivity analysis, COP optimization - **Parallel Execution:** Multi-threaded batch processing for massive parameter studies - **Visualization Tools:** SVG cycle diagrams, performance charts, T-s diagrams - **Industry Partnerships:** Validated component models from manufacturers #### v4.0+: Platform & Enterprise - **Cloud Simulation:** Distributed computing for massive design space exploration - **Real-time Simulation:** Hardware-in-the-loop testing with actual controllers - **Machine Learning Integration:** Surrogate models for ultra-fast approximations - **Enterprise Features:** Multi-user collaboration, version control for cycles, audit trails --- ### Architectural Foundation Strategy **The "Residual-Ready" Decision:** By exposing residuals at the component level in MVP, we create the mathematical foundation for Inverse Control without implementing the full constraint solver. This architectural choice: ✅ **Prevents Refactoring:** Traits won't need redesign for v2 Inverse Control ✅ **Enables Debugging:** Users can inspect residuals during Sequential Substitution ✅ **Prepares for Newton:** Residual vector + sparsity pattern = ready for Jacobian assembly ✅ **Validates Physics:** Residuals prove conservation equations are satisfied **Trade-off Acknowledged:** Slightly more complex component API in MVP, but pays dividends in v2. **Validation Gate:** If MVP succeeds, v2 development focuses on solver algorithms rather than architecture — dramatically reducing technical risk.