From 4439942722349bf40ecea43670c57e1423cc7325 Mon Sep 17 00:00:00 2001 From: Even Solbraa <41290109+EvenSol@users.noreply.github.com> Date: Sun, 30 Aug 2026 15:31:51 +0200 Subject: [PATCH 1/4] feat(game): add native throughput challenge engine --- process_chat/plant_operator_game.py | 555 ++++++++++++++++++++++++++++ tests/test_plant_operator_game.py | 116 ++++++ 2 files changed, 671 insertions(+) create mode 100644 process_chat/plant_operator_game.py create mode 100644 tests/test_plant_operator_game.py diff --git a/process_chat/plant_operator_game.py b/process_chat/plant_operator_game.py new file mode 100644 index 0000000..dcce30a --- /dev/null +++ b/process_chat/plant_operator_game.py @@ -0,0 +1,555 @@ +"""Native NeqSim simulation and scoring for Plant Operator challenges. + +The game layer deliberately stays thin: NeqSim owns the thermodynamics, +equipment calculations, process convergence, and conservation evidence. This +module only defines a reproducible training case and translates its solved +engineering evidence into a transparent challenge score. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from time import perf_counter +from typing import Any + +from .process_builder import ProcessBuilder +from .process_model import ModelRunResult, NeqSimProcessModel, ProcessRunTimeoutError + + +CHALLENGE_NAME = "The 10% Throughput Challenge" +BASELINE_FLOW_KG_HR = 100_000.0 +TARGET_FLOW_KG_HR = 110_000.0 +MIN_EXPORT_PRESSURE_BARA = 128.0 +MAX_EXPORT_TEMPERATURE_C = 45.0 +MAX_COMPRESSOR_DISCHARGE_TEMPERATURE_C = 120.0 +MAX_TOTAL_POWER_KW = 4_500.0 +MAX_SPECIFIC_POWER_KWH_PER_TONNE = 41.0 +MAX_COOLING_DUTY_KW = 7_000.0 +MAX_BALANCE_ERROR_PCT = 0.10 +CHALLENGE_TIMEOUT_MS = 180_000 + + +@dataclass(frozen=True) +class ChallengeControls: + """Player-adjustable operating decisions for the first challenge.""" + + feed_flow_kg_hr: float = BASELINE_FLOW_KG_HR + stage_1_pressure_bara: float = 80.0 + stage_2_pressure_bara: float = 130.0 + intercooler_temperature_c: float = 35.0 + export_temperature_c: float = 40.0 + + +@dataclass(frozen=True) +class ChallengeEvidence: + """Solved evidence used by the score; all values come from NeqSim.""" + + feed_flow_kg_hr: float + export_pressure_bara: float + export_temperature_c: float + stage_1_discharge_temperature_c: float + stage_2_discharge_temperature_c: float + total_power_kw: float + total_cooling_duty_kw: float + specific_power_kwh_per_tonne: float + mass_balance_error_pct: float + energy_balance_error_pct: float + native_violations: tuple[str, ...] = () + + +@dataclass(frozen=True) +class ChallengeCheck: + """One objective engineering acceptance check.""" + + name: str + passed: bool + actual: str + requirement: str + + +@dataclass(frozen=True) +class ChallengeAssessment: + """Scored assessment returned to the game interface.""" + + score: int + won: bool + grade: str + checks: tuple[ChallengeCheck, ...] + guidance: tuple[str, ...] + + +@dataclass +class ChallengeRun: + """A reproducible NeqSim run plus the game-facing assessment.""" + + controls: ChallengeControls + spec: dict[str, Any] + builder: ProcessBuilder + model: NeqSimProcessModel + result: ModelRunResult + evidence: ChallengeEvidence + assessment: ChallengeAssessment + elapsed_seconds: float + + +def _finite_between(value: float, name: str, minimum: float, maximum: float) -> float: + """Return a validated finite float inside an inclusive range.""" + if isinstance(value, bool): + raise ValueError(f"{name} must be numeric.") + try: + numeric_value = float(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"{name} must be numeric.") from exc + if not math.isfinite(numeric_value): + raise ValueError(f"{name} must be finite.") + if not minimum <= numeric_value <= maximum: + raise ValueError( + f"{name} must be between {minimum:g} and {maximum:g}." + ) + return numeric_value + + +def validate_controls(controls: ChallengeControls) -> ChallengeControls: + """Validate the public game input contract before starting the JVM.""" + if not isinstance(controls, ChallengeControls): + raise ValueError("Challenge controls must use ChallengeControls.") + values = { + "feed_flow_kg_hr": _finite_between( + controls.feed_flow_kg_hr, + "Feed flow", + 90_000.0, + 125_000.0, + ), + "stage_1_pressure_bara": _finite_between( + controls.stage_1_pressure_bara, + "Stage 1 pressure", + 60.0, + 110.0, + ), + "stage_2_pressure_bara": _finite_between( + controls.stage_2_pressure_bara, + "Stage 2 pressure", + 115.0, + 145.0, + ), + "intercooler_temperature_c": _finite_between( + controls.intercooler_temperature_c, + "Intercooler temperature", + 20.0, + 60.0, + ), + "export_temperature_c": _finite_between( + controls.export_temperature_c, + "Export temperature", + 20.0, + 55.0, + ), + } + if values["stage_1_pressure_bara"] >= values["stage_2_pressure_bara"]: + raise ValueError("Stage 1 pressure must be below Stage 2 pressure.") + return ChallengeControls(**values) + + +def build_challenge_spec(controls: ChallengeControls) -> dict[str, Any]: + """Build the minimum reproducible ProcessBuilder specification.""" + controls = validate_controls(controls) + fluid_spec = { + "eos_model": "srk", + "mixing_rule": 2, + "components": { + "nitrogen": 0.010, + "CO2": 0.020, + "methane": 0.850, + "ethane": 0.060, + "propane": 0.030, + "i-butane": 0.008, + "n-butane": 0.012, + "i-pentane": 0.004, + "n-pentane": 0.003, + "n-hexane": 0.003, + }, + "composition_basis": "mole_fraction", + "temperature_C": 30.0, + "pressure_bara": 50.0, + "total_flow": controls.feed_flow_kg_hr, + "flow_unit": "kg/hr", + } + process = [ + { + "name": "feed gas", + "type": "stream", + "params": { + "temperature_C": 30.0, + "pressure_bara": 50.0, + "flow_rate": controls.feed_flow_kg_hr, + "flow_unit": "kg/hr", + }, + }, + { + "name": "inlet scrubber", + "type": "separator", + "outlet": "gas", + }, + { + "name": "compressor stage 1", + "type": "compressor", + "params": { + "outlet_pressure_bara": controls.stage_1_pressure_bara, + "isentropic_efficiency": 0.78, + }, + }, + { + "name": "intercooler", + "type": "cooler", + "params": { + "outlet_temperature_C": controls.intercooler_temperature_c, + "pressure_drop_bar": 0.0, + }, + }, + { + "name": "interstage scrubber", + "type": "separator", + "outlet": "gas", + }, + { + "name": "compressor stage 2", + "type": "compressor", + "params": { + "outlet_pressure_bara": controls.stage_2_pressure_bara, + "isentropic_efficiency": 0.78, + }, + }, + { + "name": "export cooler", + "type": "cooler", + "params": { + "outlet_temperature_C": controls.export_temperature_c, + "pressure_drop_bar": 0.0, + }, + }, + ] + return { + "name": CHALLENGE_NAME, + "description": ( + "Synthetic gas-compression training case. Increase throughput by " + "10% while respecting export, power, temperature, and conservation " + "constraints." + ), + "assumptions": [ + "Steady-state training scenario using the SRK equation of state.", + "Pressures are absolute (bara).", + "Flow is mass flow in kg/hr.", + "Both compressor isentropic efficiencies are fixed at 0.78.", + "The score is educational and is not a design certification.", + ], + "fluid": fluid_spec, + "process": process, + } + + +def _outlet_state(model: NeqSimProcessModel, unit_name: str) -> tuple[float, float]: + """Return temperature in degC and pressure in bara for one unit outlet.""" + unit = model.get_unit(unit_name) + outlet = None + for getter_name in ("getOutletStream", "getOutStream", "getGasOutStream"): + if not hasattr(unit, getter_name): + continue + try: + outlet = getattr(unit, getter_name)() + except Exception: + continue + if outlet is not None: + break + if outlet is None: + raise RuntimeError(f"{unit_name} did not expose a solved outlet stream.") + return ( + float(outlet.getTemperature("C")), + float(outlet.getPressure("bara")), + ) + + +def collect_evidence( + controls: ChallengeControls, + model: NeqSimProcessModel, + result: ModelRunResult, +) -> ChallengeEvidence: + """Collect only solved NeqSim values used by the challenge score.""" + stage_1_temperature_c, _ = _outlet_state(model, "compressor stage 1") + stage_2_temperature_c, _ = _outlet_state(model, "compressor stage 2") + export_temperature_c, export_pressure_bara = _outlet_state( + model, + "export cooler", + ) + + total_power_kw = abs(float(result.kpis["total_power_kW"].value)) + total_cooling_duty_kw = abs(float(result.kpis["total_duty_kW"].value)) + specific_power = total_power_kw * 1000.0 / controls.feed_flow_kg_hr + mass_balance = result.kpis.get("mass_balance_pct") + energy_balance = result.kpis.get("energy_balance_pct") + native_violations = tuple( + constraint.name + for constraint in result.constraints + if str(constraint.status).upper() == "VIOLATION" + and constraint.name not in {"mass_balance", "energy_balance"} + ) + return ChallengeEvidence( + feed_flow_kg_hr=controls.feed_flow_kg_hr, + export_pressure_bara=export_pressure_bara, + export_temperature_c=export_temperature_c, + stage_1_discharge_temperature_c=stage_1_temperature_c, + stage_2_discharge_temperature_c=stage_2_temperature_c, + total_power_kw=total_power_kw, + total_cooling_duty_kw=total_cooling_duty_kw, + specific_power_kwh_per_tonne=specific_power, + mass_balance_error_pct=( + float(mass_balance.value) if mass_balance is not None else math.inf + ), + energy_balance_error_pct=( + float(energy_balance.value) if energy_balance is not None else math.inf + ), + native_violations=native_violations, + ) + + +def _bounded_score(value: float, best: float, worst: float, points: float) -> float: + """Scale lower-is-better evidence into a bounded point contribution.""" + if not math.isfinite(value) or worst <= best: + return 0.0 + fraction = (worst - value) / (worst - best) + return points * min(1.0, max(0.0, fraction)) + + +def assess_challenge(evidence: ChallengeEvidence) -> ChallengeAssessment: + """Evaluate one solved operating strategy with a transparent score.""" + maximum_discharge_temperature_c = max( + evidence.stage_1_discharge_temperature_c, + evidence.stage_2_discharge_temperature_c, + ) + checks = ( + ChallengeCheck( + "Throughput target", + evidence.feed_flow_kg_hr >= TARGET_FLOW_KG_HR, + f"{evidence.feed_flow_kg_hr:,.0f} kg/hr", + f"at least {TARGET_FLOW_KG_HR:,.0f} kg/hr", + ), + ChallengeCheck( + "Export pressure", + evidence.export_pressure_bara >= MIN_EXPORT_PRESSURE_BARA, + f"{evidence.export_pressure_bara:.2f} bara", + f"at least {MIN_EXPORT_PRESSURE_BARA:.0f} bara", + ), + ChallengeCheck( + "Export temperature", + evidence.export_temperature_c <= MAX_EXPORT_TEMPERATURE_C, + f"{evidence.export_temperature_c:.2f} °C", + f"at most {MAX_EXPORT_TEMPERATURE_C:.0f} °C", + ), + ChallengeCheck( + "Compressor discharge temperature", + maximum_discharge_temperature_c + <= MAX_COMPRESSOR_DISCHARGE_TEMPERATURE_C, + f"{maximum_discharge_temperature_c:.2f} °C maximum", + ( + "at most " + f"{MAX_COMPRESSOR_DISCHARGE_TEMPERATURE_C:.0f} °C" + ), + ), + ChallengeCheck( + "Compression power", + evidence.total_power_kw <= MAX_TOTAL_POWER_KW, + f"{evidence.total_power_kw:,.0f} kW", + f"at most {MAX_TOTAL_POWER_KW:,.0f} kW", + ), + ChallengeCheck( + "Specific compression energy", + evidence.specific_power_kwh_per_tonne + <= MAX_SPECIFIC_POWER_KWH_PER_TONNE, + f"{evidence.specific_power_kwh_per_tonne:.2f} kWh/tonne", + f"at most {MAX_SPECIFIC_POWER_KWH_PER_TONNE:.0f} kWh/tonne", + ), + ChallengeCheck( + "Cooling-system load", + evidence.total_cooling_duty_kw <= MAX_COOLING_DUTY_KW, + f"{evidence.total_cooling_duty_kw:,.0f} kW", + f"at most {MAX_COOLING_DUTY_KW:,.0f} kW", + ), + ChallengeCheck( + "Mass balance", + evidence.mass_balance_error_pct <= MAX_BALANCE_ERROR_PCT, + f"{evidence.mass_balance_error_pct:.6g}% error", + f"at most {MAX_BALANCE_ERROR_PCT:.2f}% error", + ), + ChallengeCheck( + "Energy balance", + evidence.energy_balance_error_pct <= MAX_BALANCE_ERROR_PCT, + f"{evidence.energy_balance_error_pct:.6g}% error", + f"at most {MAX_BALANCE_ERROR_PCT:.2f}% error", + ), + ChallengeCheck( + "Native NeqSim checks", + not evidence.native_violations, + ( + "No violations" + if not evidence.native_violations + else ", ".join(evidence.native_violations) + ), + "no native constraint violations", + ), + ) + + production_fraction = min( + 1.0, + max(0.0, evidence.feed_flow_kg_hr / TARGET_FLOW_KG_HR), + ) + production_points = 400.0 * production_fraction + stretch_bonus = 50.0 * min( + 1.0, + max( + 0.0, + (evidence.feed_flow_kg_hr - TARGET_FLOW_KG_HR) + / (TARGET_FLOW_KG_HR * 0.10), + ), + ) + energy_points = _bounded_score( + evidence.specific_power_kwh_per_tonne, + best=38.5, + worst=MAX_SPECIFIC_POWER_KWH_PER_TONNE, + points=250.0, + ) + thermal_points = _bounded_score( + maximum_discharge_temperature_c, + best=70.0, + worst=MAX_COMPRESSOR_DISCHARGE_TEMPERATURE_C, + points=100.0, + ) + cooling_points = _bounded_score( + evidence.total_cooling_duty_kw, + best=6_000.0, + worst=MAX_COOLING_DUTY_KW, + points=50.0, + ) + integrity_checks = checks[-3:] + integrity_points = 150.0 * ( + sum(check.passed for check in integrity_checks) + / len(integrity_checks) + ) + score = int( + round( + min( + 1000.0, + production_points + + stretch_bonus + + energy_points + + thermal_points + + cooling_points + + integrity_points, + ) + ) + ) + won = all(check.passed for check in checks) + if won and score >= 900: + grade = "Outstanding operation" + elif won: + grade = "Challenge completed" + elif score >= 700: + grade = "Close — one more adjustment" + elif score >= 500: + grade = "Developing strategy" + else: + grade = "Plant constraints not controlled" + + failed_names = {check.name for check in checks if not check.passed} + guidance: list[str] = [] + if "Throughput target" in failed_names: + guidance.append("Increase feed flow to at least 110,000 kg/hr.") + if "Export pressure" in failed_names: + guidance.append("Raise the second-stage discharge-pressure setpoint.") + if "Export temperature" in failed_names: + guidance.append("Lower the export-cooler temperature setpoint.") + if { + "Compression power", + "Specific compression energy", + }.intersection(failed_names): + ideal_interstage_pressure = math.sqrt( + 50.0 * evidence.export_pressure_bara + ) + guidance.append( + "Move the interstage pressure toward the equal-ratio value " + f"of about {ideal_interstage_pressure:.0f} bara and keep the " + "intercooler effective." + ) + if "Compressor discharge temperature" in failed_names: + guidance.append( + "Reduce the intercooler setpoint or rebalance the pressure ratio." + ) + if "Cooling-system load" in failed_names: + guidance.append( + "Reduce avoidable cooling load while keeping compression energy and " + "discharge temperatures inside their limits." + ) + if {"Mass balance", "Energy balance", "Native NeqSim checks"}.intersection( + failed_names + ): + guidance.append( + "Treat the run as invalid until the native validation evidence passes." + ) + if not guidance: + guidance.append( + "All constraints pass. Try a higher throughput or lower specific " + "energy to improve the score." + ) + return ChallengeAssessment( + score=score, + won=won, + grade=grade, + checks=checks, + guidance=tuple(guidance), + ) + + +def run_challenge( + controls: ChallengeControls, + *, + timeout_ms: int = CHALLENGE_TIMEOUT_MS, +) -> ChallengeRun: + """Build, solve, validate, and score one strategy within one time budget.""" + controls = validate_controls(controls) + if isinstance(timeout_ms, bool) or int(timeout_ms) <= 0: + raise ValueError("Challenge timeout must be a positive integer.") + timeout_ms = int(timeout_ms) + started = perf_counter() + deadline = started + timeout_ms / 1000.0 + + def remaining_budget_ms() -> int: + remaining_ms = int((deadline - perf_counter()) * 1000.0) + if remaining_ms <= 0: + raise ProcessRunTimeoutError( + f"Plant Operator run exceeded its {timeout_ms} ms budget; " + "discard the partial model." + ) + return remaining_ms + + spec = build_challenge_spec(controls) + builder = ProcessBuilder() + model = builder.build_from_spec_bounded( + spec, + timeout_ms=remaining_budget_ms(), + ) + result = model.run_bounded(timeout_ms=remaining_budget_ms()) + evidence = model.run_bounded_operation( + lambda: collect_evidence(controls, model, result), + timeout_ms=remaining_budget_ms(), + operation="Plant Operator evidence collection", + ) + assessment = assess_challenge(evidence) + return ChallengeRun( + controls=controls, + spec=spec, + builder=builder, + model=model, + result=result, + evidence=evidence, + assessment=assessment, + elapsed_seconds=perf_counter() - started, + ) diff --git a/tests/test_plant_operator_game.py b/tests/test_plant_operator_game.py new file mode 100644 index 0000000..66184c5 --- /dev/null +++ b/tests/test_plant_operator_game.py @@ -0,0 +1,116 @@ +"""Unit tests for the NeqSim Plant Operator challenge contract.""" + +import math +import unittest + +from process_chat.plant_operator_game import ( + ChallengeControls, + ChallengeEvidence, + TARGET_FLOW_KG_HR, + assess_challenge, + build_challenge_spec, + validate_controls, +) + + +class PlantOperatorGameTest(unittest.TestCase): + """Protect reproducibility, validation, and transparent scoring.""" + + def test_builds_minimum_reproducible_native_process_spec(self): + controls = ChallengeControls( + feed_flow_kg_hr=112_000.0, + stage_1_pressure_bara=82.0, + stage_2_pressure_bara=131.0, + intercooler_temperature_c=32.0, + export_temperature_c=39.0, + ) + + spec = build_challenge_spec(controls) + + self.assertEqual(spec["fluid"]["eos_model"], "srk") + self.assertEqual(spec["fluid"]["flow_unit"], "kg/hr") + self.assertAlmostEqual(sum(spec["fluid"]["components"].values()), 1.0) + self.assertEqual(spec["fluid"]["total_flow"], 112_000.0) + self.assertEqual( + [step["type"] for step in spec["process"]], + [ + "stream", + "separator", + "compressor", + "cooler", + "separator", + "compressor", + "cooler", + ], + ) + self.assertEqual( + spec["process"][2]["params"]["outlet_pressure_bara"], + 82.0, + ) + self.assertEqual( + spec["process"][5]["params"]["outlet_pressure_bara"], + 131.0, + ) + + def test_rejects_invalid_or_nonphysical_controls_before_native_execution(self): + with self.assertRaisesRegex(ValueError, "Feed flow must be finite"): + validate_controls(ChallengeControls(feed_flow_kg_hr=math.nan)) + with self.assertRaisesRegex(ValueError, "Stage 1 pressure must be between"): + validate_controls(ChallengeControls(stage_1_pressure_bara=140.0)) + with self.assertRaisesRegex(ValueError, "Export temperature must be between"): + validate_controls(ChallengeControls(export_temperature_c=80.0)) + + def test_winning_evidence_requires_every_engineering_check(self): + evidence = ChallengeEvidence( + feed_flow_kg_hr=TARGET_FLOW_KG_HR, + export_pressure_bara=130.0, + export_temperature_c=40.0, + stage_1_discharge_temperature_c=90.0, + stage_2_discharge_temperature_c=105.0, + total_power_kw=4_300.0, + total_cooling_duty_kw=6_500.0, + specific_power_kwh_per_tonne=39.1, + mass_balance_error_pct=0.001, + energy_balance_error_pct=0.002, + native_violations=(), + ) + + assessment = assess_challenge(evidence) + + self.assertTrue(assessment.won) + self.assertTrue(all(check.passed for check in assessment.checks)) + self.assertGreaterEqual(assessment.score, 700) + self.assertLessEqual(assessment.score, 1000) + + def test_failed_evidence_returns_specific_operating_guidance(self): + evidence = ChallengeEvidence( + feed_flow_kg_hr=100_000.0, + export_pressure_bara=120.0, + export_temperature_c=50.0, + stage_1_discharge_temperature_c=155.0, + stage_2_discharge_temperature_c=160.0, + total_power_kw=12_000.0, + total_cooling_duty_kw=11_000.0, + specific_power_kwh_per_tonne=120.0, + mass_balance_error_pct=2.0, + energy_balance_error_pct=2.0, + native_violations=("compressor_map.stage 2",), + ) + + assessment = assess_challenge(evidence) + + self.assertFalse(assessment.won) + failed = {check.name for check in assessment.checks if not check.passed} + self.assertIn("Throughput target", failed) + self.assertIn("Export pressure", failed) + self.assertIn("Compression power", failed) + self.assertTrue( + any("equal-ratio" in guidance for guidance in assessment.guidance) + ) + self.assertTrue( + any("invalid" in guidance for guidance in assessment.guidance) + ) + + +if __name__ == "__main__": + unittest.main() From 1bd7754401e4a3a5f1b72e1896b535d290084986 Mon Sep 17 00:00:00 2001 From: Even Solbraa <41290109+EvenSol@users.noreply.github.com> Date: Sun, 30 Aug 2026 15:32:13 +0200 Subject: [PATCH 2/4] feat(game): add Plant Operator Studio workflow --- pages/36_NeqSim_Plant_Operator.py | 493 ++++++++++++++++++++++++++++++ studio/navigation.py | 12 + tests/test_plant_operator_page.py | 70 +++++ tests/test_studio_navigation.py | 9 + 4 files changed, 584 insertions(+) create mode 100644 pages/36_NeqSim_Plant_Operator.py create mode 100644 tests/test_plant_operator_page.py diff --git a/pages/36_NeqSim_Plant_Operator.py b/pages/36_NeqSim_Plant_Operator.py new file mode 100644 index 0000000..859a426 --- /dev/null +++ b/pages/36_NeqSim_Plant_Operator.py @@ -0,0 +1,493 @@ +"""NeqSim Plant Operator — an engineering training game.""" + +from __future__ import annotations + +import json +import os +import sys + +import pandas as pd +import streamlit as st + + +_JVM_OPENS = ( + "--add-opens=java.base/java.util=ALL-UNNAMED " + "--add-opens=java.base/java.lang=ALL-UNNAMED " + "--add-opens=java.base/java.lang.reflect=ALL-UNNAMED " + "--add-opens=java.base/java.io=ALL-UNNAMED" +) +if "add-opens" not in os.environ.get("JAVA_TOOL_OPTIONS", ""): + os.environ["JAVA_TOOL_OPTIONS"] = _JVM_OPENS + +_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if _PROJECT_ROOT not in sys.path: + sys.path.insert(0, _PROJECT_ROOT) + +from process_chat.plant_operator_game import ( # noqa: E402 + BASELINE_FLOW_KG_HR, + CHALLENGE_NAME, + CHALLENGE_TIMEOUT_MS, + ChallengeControls, + ChallengeRun, + run_challenge, +) +from theme import apply_theme, theme_toggle # noqa: E402 + + +LAST_RUN_STATE_KEY = "plant_operator_last_run" +ATTEMPT_COUNT_STATE_KEY = "plant_operator_attempt_count" +BEST_SCORE_STATE_KEY = "plant_operator_best_score" +CONTROL_DEFAULTS = { + "plant_operator_feed_flow": BASELINE_FLOW_KG_HR, + "plant_operator_stage_1_pressure": 80.0, + "plant_operator_stage_2_pressure": 125.0, + "plant_operator_intercooler_temperature": 40.0, + "plant_operator_export_temperature": 45.0, +} + + +def _initialize_state() -> None: + """Create stable widget and progress state for this session.""" + for key, value in CONTROL_DEFAULTS.items(): + st.session_state.setdefault(key, value) + st.session_state.setdefault(ATTEMPT_COUNT_STATE_KEY, 0) + st.session_state.setdefault(BEST_SCORE_STATE_KEY, 0) + + +def _reset_challenge() -> None: + """Reset controls and session-local progress to the original plant state.""" + for key, value in CONTROL_DEFAULTS.items(): + st.session_state[key] = value + st.session_state.pop(LAST_RUN_STATE_KEY, None) + st.session_state[ATTEMPT_COUNT_STATE_KEY] = 0 + st.session_state[BEST_SCORE_STATE_KEY] = 0 + + +def _controls_from_widgets() -> ChallengeControls: + """Return the current player decisions as the engine input contract.""" + return ChallengeControls( + feed_flow_kg_hr=float(st.session_state["plant_operator_feed_flow"]), + stage_1_pressure_bara=float( + st.session_state["plant_operator_stage_1_pressure"] + ), + stage_2_pressure_bara=float( + st.session_state["plant_operator_stage_2_pressure"] + ), + intercooler_temperature_c=float( + st.session_state["plant_operator_intercooler_temperature"] + ), + export_temperature_c=float( + st.session_state["plant_operator_export_temperature"] + ), + ) + + +def _evidence_dataframe(run: ChallengeRun) -> pd.DataFrame: + """Format the score evidence with explicit units.""" + evidence = run.evidence + return pd.DataFrame( + [ + { + "Metric": "Feed throughput", + "Value": evidence.feed_flow_kg_hr, + "Unit": "kg/hr", + }, + { + "Metric": "Export pressure", + "Value": evidence.export_pressure_bara, + "Unit": "bara", + }, + { + "Metric": "Export temperature", + "Value": evidence.export_temperature_c, + "Unit": "°C", + }, + { + "Metric": "Stage 1 discharge temperature", + "Value": evidence.stage_1_discharge_temperature_c, + "Unit": "°C", + }, + { + "Metric": "Stage 2 discharge temperature", + "Value": evidence.stage_2_discharge_temperature_c, + "Unit": "°C", + }, + { + "Metric": "Compression power", + "Value": evidence.total_power_kw, + "Unit": "kW", + }, + { + "Metric": "Specific compression energy", + "Value": evidence.specific_power_kwh_per_tonne, + "Unit": "kWh/tonne", + }, + { + "Metric": "Cooling duty", + "Value": evidence.total_cooling_duty_kw, + "Unit": "kW", + }, + { + "Metric": "Mass-balance error", + "Value": evidence.mass_balance_error_pct, + "Unit": "%", + }, + { + "Metric": "Energy-balance error", + "Value": evidence.energy_balance_error_pct, + "Unit": "%", + }, + ] + ) + + +st.set_page_config( + page_title="NeqSim Plant Operator", + page_icon="images/neqsimlogocircleflat.png", + layout="wide", +) +apply_theme() +theme_toggle() +_initialize_state() + +st.markdown( + """ + +""", + unsafe_allow_html=True, +) + +with st.sidebar: + st.markdown("### Plant Operator") + st.caption("Native NeqSim engineering challenge") + if st.button("← NeqSim Studio", use_container_width=True): + st.switch_page("pages/00_NeqSim_Studio.py") + if st.button("Reset challenge", use_container_width=True): + _reset_challenge() + st.rerun() + st.divider() + attempt_metric_placeholder = st.empty() + best_score_metric_placeholder = st.empty() + st.caption( + "Synthetic educational case. Results are engineering-screening " + "evidence, not design certification." + ) + +st.markdown( + f""" +
+

NeqSim Plant Operator · Challenge 1

+

{CHALLENGE_NAME}

+

+ Raise production from 100,000 to 110,000 kg/hr. Balance the two-stage + compressor train, satisfy export conditions, and keep the native NeqSim + conservation checks trustworthy. +

+
+""", + unsafe_allow_html=True, +) + +st.markdown( + """ + +""", + unsafe_allow_html=True, +) + +st.markdown( + """ +
+ Win condition: achieve at least 110,000 kg/hr and 128 bara, + keep export gas at or below 45 °C, compressor discharges at or below 120 °C, + compression below 4.5 MW, specific energy below 41 kWh/tonne, cooling below + 7 MW, and pass the native mass, energy, and solver checks. +
+""", + unsafe_allow_html=True, +) + +control_panel, result_panel = st.columns([0.92, 1.35], gap="large") +with control_panel: + st.subheader("Operating decisions") + st.slider( + "Feed throughput [kg/hr]", + min_value=90_000.0, + max_value=125_000.0, + step=1_000.0, + key="plant_operator_feed_flow", + help="The original plant operates at 100,000 kg/hr.", + ) + st.slider( + "Stage 1 discharge pressure [bara]", + min_value=60.0, + max_value=110.0, + step=1.0, + key="plant_operator_stage_1_pressure", + ) + st.slider( + "Stage 2 discharge pressure [bara]", + min_value=115.0, + max_value=145.0, + step=1.0, + key="plant_operator_stage_2_pressure", + ) + st.slider( + "Intercooler outlet temperature [°C]", + min_value=20.0, + max_value=60.0, + step=1.0, + key="plant_operator_intercooler_temperature", + ) + st.slider( + "Export cooler outlet temperature [°C]", + min_value=20.0, + max_value=55.0, + step=1.0, + key="plant_operator_export_temperature", + ) + run_attempt = st.button( + "▶ Run operating strategy", + type="primary", + use_container_width=True, + ) + with st.expander("Operator hint", expanded=False): + st.write( + "For ideal compression with good intercooling, an approximately " + "equal pressure ratio in each stage tends to reduce power. Real " + "phase behaviour and liquid removal are still calculated by NeqSim." + ) + +current_controls = _controls_from_widgets() +if run_attempt: + try: + with st.spinner("NeqSim is building, solving, and validating the plant..."): + completed_run = run_challenge( + current_controls, + timeout_ms=CHALLENGE_TIMEOUT_MS, + ) + except TimeoutError: + st.session_state.pop(LAST_RUN_STATE_KEY, None) + st.error( + "The attempt exceeded the 180-second execution budget. The partial " + "native model was discarded; change the settings and try again." + ) + except Exception as error: + st.session_state.pop(LAST_RUN_STATE_KEY, None) + st.error(f"The NeqSim attempt failed: {error}") + else: + st.session_state[LAST_RUN_STATE_KEY] = completed_run + st.session_state[ATTEMPT_COUNT_STATE_KEY] += 1 + st.session_state[BEST_SCORE_STATE_KEY] = max( + int(st.session_state[BEST_SCORE_STATE_KEY]), + completed_run.assessment.score, + ) + +attempt_metric_placeholder.metric( + "Attempts", + int(st.session_state[ATTEMPT_COUNT_STATE_KEY]), +) +best_score_metric_placeholder.metric( + "Best score", + f"{int(st.session_state[BEST_SCORE_STATE_KEY])}/1000", +) + +last_run = st.session_state.get(LAST_RUN_STATE_KEY) +run_is_current = isinstance(last_run, ChallengeRun) and last_run.controls == current_controls + +with result_panel: + st.subheader("Control-room result") + if not isinstance(last_run, ChallengeRun): + st.info( + "The plant is at its original operating point. Adjust the controls " + "and run your first native NeqSim attempt." + ) + elif not run_is_current: + st.warning( + "Controls changed after the last solve. Run the strategy again before " + "using its score or engineering evidence." + ) + else: + assessment = last_run.assessment + if assessment.won: + st.success(f"{assessment.grade}.") + else: + st.warning(assessment.grade) + + score_col, power_col, production_col, time_col = st.columns(4) + score_col.metric("Score", f"{assessment.score}/1000") + power_col.metric("Compression", f"{last_run.evidence.total_power_kw:,.0f} kW") + production_col.metric( + "Throughput", + f"{last_run.evidence.feed_flow_kg_hr:,.0f} kg/hr", + delta=( + f"{(last_run.evidence.feed_flow_kg_hr / BASELINE_FLOW_KG_HR - 1.0) * 100:.1f}%" + ), + ) + time_col.metric("Solve time", f"{last_run.elapsed_seconds:.2f} s") + st.progress(assessment.score / 1000.0) + + check_rows = [ + { + "Status": "PASS" if check.passed else "FAIL", + "Constraint": check.name, + "Solved value": check.actual, + "Requirement": check.requirement, + } + for check in assessment.checks + ] + st.dataframe( + pd.DataFrame(check_rows), + use_container_width=True, + hide_index=True, + ) + st.markdown("#### Engineering feedback") + for guidance in assessment.guidance: + st.write(f"• {guidance}") + +if run_is_current: + st.divider() + evidence_tab, validation_tab, replay_tab = st.tabs( + ["Solved evidence", "Native validation", "Replay & Process Chat"] + ) + with evidence_tab: + st.dataframe( + _evidence_dataframe(last_run).style.format({"Value": "{:,.6g}"}), + use_container_width=True, + hide_index=True, + ) + st.caption( + "All score inputs are solved NeqSim values. Standard, mass, and energy " + "units are kept explicit." + ) + with validation_tab: + native_rows = [ + { + "Check": constraint.name, + "Status": constraint.status, + "Detail": constraint.detail, + } + for constraint in last_run.result.constraints + ] + st.dataframe( + pd.DataFrame(native_rows), + use_container_width=True, + hide_index=True, + ) + st.caption( + "The game never converts a failed or unavailable native check into a pass." + ) + with replay_tab: + st.download_button( + "Download reproducible challenge JSON", + data=json.dumps(last_run.spec, indent=2), + file_name="neqsim_10_percent_throughput_challenge.json", + mime="application/json", + use_container_width=True, + ) + if st.button("Analyze solved attempt in Process Chat", use_container_width=True): + st.session_state["process_model"] = last_run.model + st.session_state["process_model_name"] = "plant_operator_challenge.neqsim" + st.switch_page("pages/90_Process_Chat.py") + st.caption( + "Process Chat receives the exact solved NeqSim model from this attempt." + ) + +st.divider() +st.caption( + "NeqSim Plant Operator v1 · synthetic public training fluid · steady-state " + "SRK model · one shared 180-second build/solve/evidence budget." +) diff --git a/studio/navigation.py b/studio/navigation.py index d80bddc..491dc56 100644 --- a/studio/navigation.py +++ b/studio/navigation.py @@ -82,6 +82,18 @@ def available(self) -> bool: status=STATUS_AVAILABLE, page="pages/10_Studio_Results.py", ), + StudioDestination( + key="plant_operator", + title="NeqSim Plant Operator", + description=( + "Play a native NeqSim operating challenge: increase gas-plant " + "throughput while respecting product, power, temperature and " + "conservation constraints." + ), + icon="🎮", + status=STATUS_AVAILABLE, + page="pages/36_NeqSim_Plant_Operator.py", + ), StudioDestination( key="dynamics", title="Dynamics & Controls", diff --git a/tests/test_plant_operator_page.py b/tests/test_plant_operator_page.py new file mode 100644 index 0000000..eb2e673 --- /dev/null +++ b/tests/test_plant_operator_page.py @@ -0,0 +1,70 @@ +"""Source-level regression tests for the Plant Operator Streamlit page.""" + +import ast +from pathlib import Path +import unittest + +from streamlit.testing.v1 import AppTest + +from studio.navigation import destination_by_key + + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +PAGE_PATH = PROJECT_ROOT / "pages" / "36_NeqSim_Plant_Operator.py" + + +class PlantOperatorPageTest(unittest.TestCase): + """Keep the game discoverable, bounded, accessible, and interoperable.""" + + def test_page_is_valid_python_and_navigation_target(self): + source = PAGE_PATH.read_text(encoding="utf-8") + ast.parse(source) + + destination = destination_by_key("plant_operator") + self.assertTrue(destination.available) + self.assertEqual(destination.page, "pages/36_NeqSim_Plant_Operator.py") + + def test_page_exposes_primary_game_flow_and_native_evidence(self): + source = PAGE_PATH.read_text(encoding="utf-8") + + self.assertIn("▶ Run operating strategy", source) + self.assertIn("run_challenge(", source) + self.assertIn("Native validation", source) + self.assertIn("Download reproducible challenge JSON", source) + self.assertIn("Analyze solved attempt in Process Chat", source) + self.assertIn('role="img"', source) + self.assertIn('aria-label="Mission constraints"', source) + self.assertIn("@media (max-width: 600px)", source) + + def test_initial_control_room_renders_without_starting_native_solve(self): + app = AppTest.from_file(str(PAGE_PATH)).run(timeout=30) + + if app.exception: + details = "\n".join(str(item.value) for item in app.exception) + self.fail(f"Plant Operator page raised exceptions:\n{details}") + + self.assertIn( + "▶ Run operating strategy", + [button.label for button in app.button], + ) + self.assertEqual( + [slider.label for slider in app.slider], + [ + "Feed throughput [kg/hr]", + "Stage 1 discharge pressure [bara]", + "Stage 2 discharge pressure [bara]", + "Intercooler outlet temperature [°C]", + "Export cooler outlet temperature [°C]", + ], + ) + + def test_page_preserves_shared_timeout_and_stale_result_guards(self): + source = PAGE_PATH.read_text(encoding="utf-8") + + self.assertIn("timeout_ms=CHALLENGE_TIMEOUT_MS", source) + self.assertIn("last_run.controls == current_controls", source) + self.assertIn("native model was discarded", source) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_studio_navigation.py b/tests/test_studio_navigation.py index 721809d..ff01973 100644 --- a/tests/test_studio_navigation.py +++ b/tests/test_studio_navigation.py @@ -48,6 +48,15 @@ def test_results_and_existing_studies_share_one_solved_model_adapter(self): self.assertTrue(destination.available) self.assertEqual(destination.page, "pages/10_Studio_Results.py") + def test_plant_operator_is_an_available_native_training_workflow(self): + destination = destination_by_key("plant_operator") + + self.assertTrue(destination.available) + self.assertEqual( + destination.page, + "pages/36_NeqSim_Plant_Operator.py", + ) + def test_unknown_destination_fails_loudly(self): with self.assertRaisesRegex(KeyError, "Unknown Studio destination"): destination_by_key("not-a-real-workflow") From 0d81991b775617763e12f7078190b865266ca463 Mon Sep 17 00:00:00 2001 From: Even Solbraa <41290109+EvenSol@users.noreply.github.com> Date: Sun, 30 Aug 2026 15:32:31 +0200 Subject: [PATCH 3/4] docs(game): document Plant Operator workflow --- README.md | 20 +++++++ docs/neqsim_plant_operator_game.md | 84 ++++++++++++++++++++++++++++++ process_chat/__init__.py | 1 + 3 files changed, 105 insertions(+) create mode 100644 docs/neqsim_plant_operator_game.md diff --git a/README.md b/README.md index 9aa1308..6f7a872 100644 --- a/README.md +++ b/README.md @@ -71,3 +71,23 @@ Streamlit reruns while the last trustworthy result stays hidden. The current UniSim-parity assessment and production-readiness gaps are tracked in [docs/process_flowsheet_unisim_parity.md](docs/process_flowsheet_unisim_parity.md). + +## NeqSim Plant Operator + +**NeqSim Plant Operator** is a playable Studio workflow backed by native NeqSim +process calculations. The first scenario, **The 10% Throughput Challenge**, +starts from a synthetic 100,000 kg/hr gas-compression case. The player changes +feed rate, interstage pressure, export pressure, intercooling, and export +cooling to reach at least 110,000 kg/hr without violating the published +product, power, temperature, cooling, or conservation limits. + +The game score uses only solved NeqSim evidence. It reports every pass/fail +criterion, mass and energy closure, native solver constraints, and the exact +process inputs. A successful attempt can be downloaded as reproducible JSON or +passed directly to Process Chat for deterministic what-if analysis. Build, +solve, and evidence extraction share one 180-second execution budget; partial +or timed-out models are not published as results. + +See [docs/neqsim_plant_operator_game.md](docs/neqsim_plant_operator_game.md) +for the scenario contract, score definition, validation scope, and current +limitations. diff --git a/docs/neqsim_plant_operator_game.md b/docs/neqsim_plant_operator_game.md new file mode 100644 index 0000000..43504be --- /dev/null +++ b/docs/neqsim_plant_operator_game.md @@ -0,0 +1,84 @@ +# NeqSim Plant Operator + +NeqSim Plant Operator turns native process-simulation results into bounded, +auditable engineering challenges. It is an educational workflow for learning +how operating choices affect production, product conditions, energy use, and +process constraints. It is not design certification or operator-procedure +authorization. + +## Challenge 1: The 10% Throughput Challenge + +The supplied process is a synthetic gas-rich feed at 50 bara and 30 °C. The +fixed train is: + +1. inlet scrubber; +2. first-stage compressor; +3. intercooler; +4. interstage scrubber; +5. second-stage compressor; and +6. export cooler. + +The thermodynamic model is SRK with mixing rule 2. The two compressor +isentropic efficiencies are fixed at 0.78. The player controls feed mass flow, +the two compressor discharge pressures, intercooler outlet temperature, and +export-cooler outlet temperature. Pressures are absolute and all game inputs +use the units displayed in the interface. + +### Win conditions + +One attempt wins only when every check passes: + +| Check | Requirement | +|---|---:| +| Feed throughput | at least 110,000 kg/hr | +| Export pressure | at least 128 bara | +| Export temperature | at most 45 °C | +| Maximum compressor discharge temperature | at most 120 °C | +| Total compressor power | at most 4,500 kW | +| Specific compression energy | at most 41 kWh/tonne | +| Total cooling duty | at most 7,000 kW | +| System mass-balance error | at most 0.10% | +| System energy-balance error | at most 0.10% | +| Other native NeqSim constraints | no violations | + +All values are extracted after the native NeqSim process has converged. The +game does not convert a missing, failed, or unavailable conservation result +into a pass. + +## Score + +The score is bounded from 0 to 1,000 points: + +- production target: 400 points; +- stretch throughput above the 10% target: up to 50 points; +- specific compression energy: up to 250 points; +- compressor discharge temperature: up to 100 points; +- cooling-system load: up to 50 points; and +- mass balance, energy balance, and native validation integrity: 150 points. + +The published win conditions are independent of the score. A high score cannot +override a failed engineering check. The score rewards efficient operation +inside the feasible region; the check table remains the authoritative outcome. + +## Reproducibility and interoperability + +Each attempt follows this chain: + +`controls -> ProcessBuilder specification -> native NeqSim solve -> engineering evidence -> score` + +Build, solve, and evidence extraction use one shared 180-second deadline. A +timeout discards the partial model. The interface hides a previous result when +the player changes a control, preventing stale evidence from being presented +as current. + +The solved ProcessBuilder specification can be downloaded as JSON. The exact +in-memory solved `NeqSimProcessModel` can also be handed to Process Chat within +the same Streamlit session. + +## Current scope and next increments + +Version 1 is a steady-state, single-scenario training game. It does not yet +include dynamic controllers, compressor trips, hydrate-margin calculations, +economic prices, emissions pricing, persistent leaderboards, or multiplayer +state. Those should be added as separate validated challenges so that each new +game mechanic retains a clear NeqSim calculation and acceptance contract. diff --git a/process_chat/__init__.py b/process_chat/__init__.py index 32c473e..7615632 100644 --- a/process_chat/__init__.py +++ b/process_chat/__init__.py @@ -18,6 +18,7 @@ safety_systems — PSV sizing per API 520/521, relief scenario analysis flow_assurance — Hydrate, wax, corrosion prediction and inhibitor dosing production_scenario — Production/reservoir fluid scenario studies (GOR, watercut, blending) + plant_operator_game — Native NeqSim training challenge and transparent scoring signal_tracker — Signal/property tracking across multiple chat interactions dexpi_integration — DEXPI P&ID (Proteus XML) import, parsing, and NeqSim bridge """ From 8c5f6c862bda4dfb7bea254b19e567dc1e02195f Mon Sep 17 00:00:00 2001 From: Even Solbraa <41290109+EvenSol@users.noreply.github.com> Date: Sun, 30 Aug 2026 15:37:46 +0200 Subject: [PATCH 4/4] test(game): cover Plant Operator HTTP health --- tests/test_workspace_http_health.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/test_workspace_http_health.py b/tests/test_workspace_http_health.py index 30c58a6..376ac4a 100644 --- a/tests/test_workspace_http_health.py +++ b/tests/test_workspace_http_health.py @@ -23,6 +23,7 @@ "pages/10_Studio_Results.py", "pages/25_Pipeline.py", "pages/35_Process_Flowsheet_Studio.py", + "pages/36_NeqSim_Plant_Operator.py", "pages/90_Process_Chat.py", } ) @@ -134,6 +135,9 @@ def test_studio_results_http_health(self): def test_process_flowsheet_studio_http_health(self): self._probe_streamlit_page("pages/35_Process_Flowsheet_Studio.py") + def test_neqsim_plant_operator_http_health(self): + self._probe_streamlit_page("pages/36_NeqSim_Plant_Operator.py") + def test_process_chat_http_health(self): self._probe_streamlit_page("pages/90_Process_Chat.py")