diff --git a/.github/workflows/process-flowsheet-studio.yml b/.github/workflows/process-flowsheet-studio.yml index 83363d6..784156e 100644 --- a/.github/workflows/process-flowsheet-studio.yml +++ b/.github/workflows/process-flowsheet-studio.yml @@ -7,10 +7,7 @@ on: - "pages/00_NeqSim_Studio.py" - "pages/10_Studio_Results.py" - "pages/25_Pipeline.py" - - "pages/34_NeqSim_Games.py" - "pages/35_Process_Flowsheet_Studio.py" - - "pages/36_NeqSim_Plant_Operator.py" - - "pages/37_NeqSim_Phase_Equilibrium_Lab.py" - "pages/90_Process_Chat.py" - "pipeline_hydraulics.py" - "studio/**" @@ -21,12 +18,7 @@ on: - "process_chat/solver_diagnostics.py" - "process_chat/subflowsheet_schema.py" - "process_chat/process_model.py" - - "process_chat/plant_operator_game.py" - - "process_chat/phase_equilibrium_game.py" - - "process_chat/flashcard_game.py" - "process_chat/studio_context.py" - - "tests/test_plant_operator_game.py" - - "tests/test_plant_operator_page.py" - "tests/test_process_chat_studio_handoff.py" - "tests/test_process_chat_studio_context.py" - "tests/test_studio_navigation.py" @@ -52,11 +44,6 @@ on: - "tests/test_solver_diagnostics.py" - "tests/test_studio_warm_deployment.py" - "tests/test_subflowsheet_schema.py" - - "tests/test_phase_equilibrium_game.py" - - "tests/test_flashcard_game.py" - - "tests/test_games_pages.py" - - "docs/neqsim_plant_operator_game.md" - - "docs/neqsim_games.md" - "docs/neqsim_web_studio_interoperability.md" - "docs/neqsim_web_studio_execution_isolation.md" - ".github/workflows/process-flowsheet-studio.yml" @@ -88,10 +75,7 @@ jobs: pages/00_NeqSim_Studio.py \ pages/10_Studio_Results.py \ pages/25_Pipeline.py \ - pages/34_NeqSim_Games.py \ pages/35_Process_Flowsheet_Studio.py \ - pages/36_NeqSim_Plant_Operator.py \ - pages/37_NeqSim_Phase_Equilibrium_Lab.py \ pages/90_Process_Chat.py \ pipeline_hydraulics.py \ studio/case_context.py \ @@ -105,12 +89,7 @@ jobs: process_chat/solver_diagnostics.py \ process_chat/subflowsheet_schema.py \ process_chat/process_model.py \ - process_chat/plant_operator_game.py \ - process_chat/phase_equilibrium_game.py \ - process_chat/flashcard_game.py \ process_chat/studio_context.py \ - tests/test_plant_operator_game.py \ - tests/test_plant_operator_page.py \ tests/test_process_chat_studio_handoff.py \ tests/test_process_chat_studio_context.py \ tests/test_studio_case_context.py \ @@ -131,19 +110,9 @@ jobs: tests/test_runtime_imports.py \ tests/test_solver_diagnostics.py \ tests/test_studio_warm_deployment.py \ - tests/test_subflowsheet_schema.py \ - tests/test_phase_equilibrium_game.py \ - tests/test_flashcard_game.py \ - tests/test_games_pages.py + tests/test_subflowsheet_schema.py - name: Run Studio workspace navigation regressions run: python tests/test_studio_navigation.py -v - - name: Run NeqSim game regressions - run: | - python tests/test_plant_operator_game.py -v - python tests/test_plant_operator_page.py -v - python tests/test_phase_equilibrium_game.py -v - python tests/test_flashcard_game.py -v - python tests/test_games_pages.py -v - name: Run shared Studio case lifecycle regressions run: python tests/test_studio_case_context.py -v - name: Run Studio case migration interoperability regressions diff --git a/README.md b/README.md index 26349aa..9aa1308 100644 --- a/README.md +++ b/README.md @@ -71,32 +71,3 @@ 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 Games - -**NeqSim Games** is the shared Studio menu for native calculation challenges -and reusable flashcard games. - -**Plant Operator** is backed by native NeqSim process calculations. Its 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. Build, solve, and evidence extraction share one -180-second execution budget; partial or timed-out models are not published. - -**Phase Equilibrium Lab** runs a bounded native SRK TP flash for a fixed rich -gas. The player searches temperature and pressure for a narrow retrograde -window defined by phase split, gas density, gas Z-factor, liquid density, -liquid viscosity, and phase-fraction closure. The result includes gas and -liquid compositions, component K-values, mixture properties, and downloadable -evidence. - -The Games hub also provides a built-in phase-equilibrium and fluid-properties -flashcard deck. Users can author their own cards, play the custom deck, track -session mastery, and import or export a bounded versioned JSON deck. - -See [docs/neqsim_plant_operator_game.md](docs/neqsim_plant_operator_game.md) -for the process scenario contract. See -[docs/neqsim_games.md](docs/neqsim_games.md) for the shared menu, phase-game -targets, native evidence, flashcard schema, and validation boundaries. diff --git a/docs/neqsim_games.md b/docs/neqsim_games.md deleted file mode 100644 index 745dcea..0000000 --- a/docs/neqsim_games.md +++ /dev/null @@ -1,122 +0,0 @@ -# NeqSim Games - -NeqSim Games is the shared Studio entry point for engineering simulation games -and reusable flashcard games. Open **NeqSim Studio → NeqSim Games** to reach: - -- **Plant Operator** — a native process-simulation optimization challenge; -- **Phase Equilibrium Lab** — a native thermodynamics and fluid-property - challenge; and -- **Flashcard game** — a built-in learning deck plus a session-local deck - builder with JSON import and export. - -The calculated games are educational. They expose their native evidence and do -not replace fluid characterization, equipment design, operating procedures, or -engineering approval. - -## Phase Equilibrium Lab - -### Challenge: Catch the Retrograde Window - -The player selects temperature from -20 to 80 °C and absolute pressure from 10 -to 130 bara for a fixed synthetic rich gas. Each attempt creates a new NeqSim -`SystemSrkEos`, applies mixing rule 2, enables multiphase checking, and executes -one bounded TP flash. The feed mole fractions are: - -| Component | Mole fraction | -|---|---:| -| CO2 | 0.005 | -| methane | 0.720 | -| ethane | 0.080 | -| propane | 0.060 | -| i-butane | 0.025 | -| n-butane | 0.035 | -| i-pentane | 0.015 | -| n-pentane | 0.015 | -| n-hexane | 0.020 | -| n-heptane | 0.015 | -| n-octane | 0.010 | - -One attempt wins only when every native evidence check passes: - -| Check | Requirement | Score weight | -|---|---:|---:| -| Equilibrium phases | exactly gas + hydrocarbon liquid | 180 | -| Condensate split | 16–20 mol% | 220 | -| Gas density | 78–92 kg/m³ | 140 | -| Gas compressibility | Z = 0.80–0.83 | 140 | -| Liquid density | 480–510 kg/m³ | 120 | -| Liquid viscosity | < 0.12 cP | 100 | -| Phase-fraction closure | error ≤ 1×10⁻¹⁰ | 100 | - -The maximum score is 1,000. A missing or non-finite native property fails its -check. A partial score cannot override a failed win condition. - -The challenge was calibrated with a native grid sweep. A representative winning -point is 50 °C and 80 bara: approximately 16.93 mol% hydrocarbon liquid, -79.45 kg/m³ gas density, gas Z of 0.8186, 499.52 kg/m³ liquid density, and -0.1051 cP liquid viscosity. The starting point at 20 °C and 50 bara fails the -gas-density, Z-factor, liquid-density, and viscosity bands. This gives the game -a feasible but constrained operating region rather than a single hard-coded -answer. - -### Equilibrium evidence - -The result view reports phase fractions, densities, viscosities, gas Z, -mixture enthalpy, mixture Cp, and phase-fraction closure. It also reports feed, -gas, and liquid mole fractions for each component plus `K = y/x`. Values above -one identify components that favor the gas phase at that equilibrium point; -values below one identify components that favor the liquid phase. - -The evidence export is version-neutral JSON containing the controls, solved -properties, component splits, K-values, assessment, and elapsed flash time. - -## Flashcard games - -The Games hub includes a built-in **Phase equilibrium & fluid properties** deck -covering TP flashes, dew and bubble points, K-values, retrograde condensation, -Z-factor, density, viscosity, heat capacity, equations of state, and evidence -validation. The player reveals each answer and self-marks it as mastered or for -review. Progress and mastery are session-local. - -The deck builder accepts a topic, front, back, optional explanation, and one of -three difficulty levels: `foundation`, `applied`, or `advanced`. Custom cards -can be played immediately, cleared, downloaded, and imported later. - -Portable deck JSON uses schema version 1: - -```json -{ - "schema_version": 1, - "name": "My custom NeqSim deck", - "description": "A user-authored learning game.", - "cards": [ - { - "card_id": "custom-1", - "topic": "Phase equilibrium", - "prompt": "What does K > 1 mean?", - "answer": "The component favors the gas phase.", - "explanation": "K = y/x.", - "difficulty": "applied" - } - ] -} -``` - -Imports are bounded to 100 cards and 100 kB, require unique card identifiers, -reject unknown schema versions, and validate all required text fields. Custom -prompt text is escaped before being placed in the styled card surface. - -## Validation and execution boundaries - -- Initial Games and Phase Lab page loads do not start NeqSim. -- A native flash starts only after the player presses the run button. -- Each flash has one 60-second caller wait budget; a timeout discards the - partial fluid state. -- Player controls are finite and bounded before the JVM starts. -- Previous results become stale immediately when the controls change. -- Native property absence never becomes a passing check. -- Unit, initial-render, HTTP-health, native calibration, compilation, and - navigation tests are part of the Process Flowsheet Studio workflow. - -See [neqsim_plant_operator_game.md](neqsim_plant_operator_game.md) for the Plant -Operator process challenge contract. diff --git a/docs/neqsim_plant_operator_game.md b/docs/neqsim_plant_operator_game.md deleted file mode 100644 index d3d9a16..0000000 --- a/docs/neqsim_plant_operator_game.md +++ /dev/null @@ -1,87 +0,0 @@ -# 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. - -Plant Operator is launched from the shared **NeqSim Games** Studio destination, -alongside Phase Equilibrium Lab and the reusable flashcard game. - -## 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 | less than 4,200 kW | -| Specific compression energy | at most 41 kWh/tonne | -| Total cooling duty | less than 5,500 kW | -| System mass-balance error | at most 0.10% | -| System energy-balance error | at most 0.10% | -| Other native NeqSim constraints | no failed or unavailable checks | - -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/pages/34_NeqSim_Games.py b/pages/34_NeqSim_Games.py deleted file mode 100644 index ed42bb8..0000000 --- a/pages/34_NeqSim_Games.py +++ /dev/null @@ -1,352 +0,0 @@ -"""NeqSim Games hub with simulation challenges and reusable flashcards.""" - -from __future__ import annotations - -import html -import os -import sys - -import pandas as pd -import streamlit as st - - -_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.flashcard_game import ( # noqa: E402 - PHASE_EQUILIBRIUM_DECK, - Flashcard, - FlashcardDeck, - custom_deck, - deck_from_json, - deck_to_json, - score_flashcards, - validate_card, -) -from theme import apply_theme, theme_toggle # noqa: E402 - - -CUSTOM_CARDS_KEY = "neqsim_games_custom_cards" -FLASHCARD_DECK_KEY = "neqsim_games_flashcard_deck" -FLASHCARD_INDEX_KEY = "neqsim_games_flashcard_index" -FLASHCARD_REVEALED_KEY = "neqsim_games_flashcard_revealed" -FLASHCARD_MARKS_KEY = "neqsim_games_flashcard_marks" - - -def _initialize_state() -> None: - st.session_state.setdefault(CUSTOM_CARDS_KEY, []) - st.session_state.setdefault(FLASHCARD_DECK_KEY, "Built-in phase deck") - st.session_state.setdefault(FLASHCARD_INDEX_KEY, 0) - st.session_state.setdefault(FLASHCARD_REVEALED_KEY, False) - st.session_state.setdefault(FLASHCARD_MARKS_KEY, {}) - - -def _reset_flashcard_session() -> None: - st.session_state[FLASHCARD_INDEX_KEY] = 0 - st.session_state[FLASHCARD_REVEALED_KEY] = False - st.session_state[FLASHCARD_MARKS_KEY] = {} - - -def _custom_cards() -> tuple[Flashcard, ...]: - cards = st.session_state.get(CUSTOM_CARDS_KEY, []) - return tuple(card for card in cards if isinstance(card, Flashcard)) - - -def _active_deck() -> FlashcardDeck | None: - if st.session_state[FLASHCARD_DECK_KEY] == "Built-in phase deck": - return PHASE_EQUILIBRIUM_DECK - cards = _custom_cards() - return custom_deck(cards) if cards else None - - -def _mark_card(deck: FlashcardDeck, mastered: bool) -> None: - index = int(st.session_state[FLASHCARD_INDEX_KEY]) % len(deck.cards) - marks = dict(st.session_state[FLASHCARD_MARKS_KEY]) - marks[deck.cards[index].card_id] = bool(mastered) - st.session_state[FLASHCARD_MARKS_KEY] = marks - st.session_state[FLASHCARD_INDEX_KEY] = (index + 1) % len(deck.cards) - st.session_state[FLASHCARD_REVEALED_KEY] = False - - -st.set_page_config( - page_title="NeqSim Games", - page_icon="images/neqsimlogocircleflat.png", - layout="wide", -) -apply_theme() -theme_toggle() -_initialize_state() - -st.markdown( - """ - -""", - unsafe_allow_html=True, -) - -with st.sidebar: - st.markdown("### NeqSim Games") - st.caption("Simulation challenges and learning decks") - if st.button("← NeqSim Studio", use_container_width=True): - st.switch_page("pages/00_NeqSim_Studio.py") - st.divider() - st.caption( - "All game scores are educational. Native calculations remain visible " - "and are not design certification." - ) - -st.markdown( - """ -
-

NeqSim Games

-

- Learn thermodynamics and process engineering by changing real model inputs, - reading native evidence, and practicing concepts with reusable flashcard decks. -

-
-""", - unsafe_allow_html=True, -) - -simulation_tab, flashcard_tab, builder_tab = st.tabs( - ["Simulation games", "Flashcard game", "Create a flashcard deck"] -) - -with simulation_tab: - st.subheader("Choose a native NeqSim challenge") - plant_column, phase_column = st.columns(2, gap="large") - with plant_column: - st.markdown( - """ -
- -

Plant Operator

-

Increase gas throughput while balancing compression, cooling, export conditions, and conservation.

- Process simulation · operating decisions -
-""", - unsafe_allow_html=True, - ) - if st.button("Open Plant Operator", use_container_width=True): - st.switch_page("pages/36_NeqSim_Plant_Operator.py") - with phase_column: - st.markdown( - """ -
- -

Phase Equilibrium Lab

-

Find a narrow retrograde-condensate window using temperature, pressure, phase split, density, viscosity, and Z.

- TP flash · equilibrium and properties -
-""", - unsafe_allow_html=True, - ) - if st.button("Open Phase Equilibrium Lab", use_container_width=True): - st.switch_page("pages/37_NeqSim_Phase_Equilibrium_Lab.py") - -with flashcard_tab: - header_column, reset_column = st.columns([4, 1]) - with header_column: - st.subheader("Practice a deck") - with reset_column: - if st.button("Reset progress", use_container_width=True): - _reset_flashcard_session() - st.rerun() - - st.radio( - "Deck", - ("Built-in phase deck", "My custom deck"), - horizontal=True, - key=FLASHCARD_DECK_KEY, - on_change=_reset_flashcard_session, - ) - deck = _active_deck() - if deck is None: - st.info( - "Your custom deck is empty. Add or import cards in " - "**Create a flashcard deck**." - ) - else: - index = int(st.session_state[FLASHCARD_INDEX_KEY]) % len(deck.cards) - card = deck.cards[index] - marks = { - card_id: value - for card_id, value in dict( - st.session_state[FLASHCARD_MARKS_KEY] - ).items() - if card_id in {item.card_id for item in deck.cards} - } - score = score_flashcards(deck, marks) - metric_1, metric_2, metric_3 = st.columns(3) - metric_1.metric("Card", f"{index + 1}/{len(deck.cards)}") - metric_2.metric("Reviewed", score.reviewed) - metric_3.metric("Mastery", f"{score.mastery_pct:.0f}%") - st.progress(score.reviewed / len(deck.cards)) - st.markdown( - f""" -
-

{html.escape(card.topic)} · {html.escape(card.difficulty)}

-

{html.escape(card.prompt)}

-
-""", - unsafe_allow_html=True, - ) - if not st.session_state[FLASHCARD_REVEALED_KEY]: - if st.button("Reveal answer", type="primary", use_container_width=True): - st.session_state[FLASHCARD_REVEALED_KEY] = True - st.rerun() - else: - st.success(card.answer) - if card.explanation: - st.caption(card.explanation) - knew_column, review_column = st.columns(2) - with knew_column: - if st.button("I knew this", use_container_width=True): - _mark_card(deck, True) - st.rerun() - with review_column: - if st.button("Review again", use_container_width=True): - _mark_card(deck, False) - st.rerun() - st.caption(f"Session status: {score.label}") - -with builder_tab: - st.subheader("Build a reusable flashcard game") - st.write( - "Create a session deck, practice it immediately, and download the " - "versioned JSON to share or import later." - ) - with st.form("neqsim_flashcard_builder", clear_on_submit=True): - topic = st.text_input("Topic", placeholder="e.g. Gas compressibility") - prompt = st.text_area("Question / front") - answer = st.text_area("Answer / back") - explanation = st.text_area("Optional explanation") - difficulty = st.selectbox( - "Difficulty", - ("foundation", "applied", "advanced"), - ) - add_card = st.form_submit_button("Add card to custom deck") - if add_card: - try: - existing = _custom_cards() - used_ids = {card.card_id for card in existing} - next_number = len(existing) + 1 - card_id = f"custom-{next_number}" - while card_id in used_ids: - next_number += 1 - card_id = f"custom-{next_number}" - new_card = validate_card( - Flashcard( - card_id=card_id, - topic=topic, - prompt=prompt, - answer=answer, - explanation=explanation, - difficulty=difficulty, - ) - ) - candidate_deck = custom_deck((*existing, new_card)) - # Guarantee that anything stored by the builder can immediately - # round-trip through the same bounded JSON import contract. - deck_to_json(candidate_deck) - except ValueError as error: - st.error(str(error)) - else: - st.session_state[CUSTOM_CARDS_KEY] = list(candidate_deck.cards) - _reset_flashcard_session() - st.success("Card added. Select **My custom deck** to play it.") - - uploaded_deck = st.file_uploader( - "Import a flashcard deck", - type=("json",), - help="Imports the validated NeqSim flashcard schema v1.", - ) - import_column, clear_column = st.columns(2) - with import_column: - if st.button( - "Import uploaded deck", - disabled=uploaded_deck is None, - use_container_width=True, - ): - try: - imported = deck_from_json(uploaded_deck.getvalue()) - except ValueError as error: - st.error(str(error)) - else: - st.session_state[CUSTOM_CARDS_KEY] = list(imported.cards) - _reset_flashcard_session() - st.success(f"Imported {len(imported.cards)} cards.") - st.rerun() - with clear_column: - if st.button("Clear custom deck", use_container_width=True): - st.session_state[CUSTOM_CARDS_KEY] = [] - _reset_flashcard_session() - st.rerun() - - custom_cards = _custom_cards() - st.metric("Custom cards", len(custom_cards)) - if custom_cards: - session_deck = custom_deck(custom_cards) - st.dataframe( - pd.DataFrame( - [ - { - "Topic": card.topic, - "Question": card.prompt, - "Difficulty": card.difficulty, - } - for card in custom_cards - ] - ), - use_container_width=True, - hide_index=True, - ) - st.download_button( - "Download custom deck JSON", - data=deck_to_json(session_deck), - file_name="neqsim_flashcard_deck.json", - mime="application/json", - use_container_width=True, - ) - -st.divider() -st.caption( - "NeqSim Games · native simulation evidence for calculated challenges · " - "portable schema-v1 flashcard decks for knowledge practice." -) diff --git a/pages/36_NeqSim_Plant_Operator.py b/pages/36_NeqSim_Plant_Operator.py deleted file mode 100644 index 4ee9c2a..0000000 --- a/pages/36_NeqSim_Plant_Operator.py +++ /dev/null @@ -1,504 +0,0 @@ -"""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", -) -_existing_java_tool_options = os.environ.get("JAVA_TOOL_OPTIONS", "").strip() -_existing_java_tokens = set(_existing_java_tool_options.split()) -_missing_jvm_opens = tuple( - option for option in _JVM_OPENS if option not in _existing_java_tokens -) -if _missing_jvm_opens: - os.environ["JAVA_TOOL_OPTIONS"] = " ".join( - part - for part in (_existing_java_tool_options, *_missing_jvm_opens) - if part - ) - -_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 Games", use_container_width=True): - st.switch_page("pages/34_NeqSim_Games.py") - 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.2 MW, specific energy below 41 kWh/tonne, cooling below - 5.5 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/pages/37_NeqSim_Phase_Equilibrium_Lab.py b/pages/37_NeqSim_Phase_Equilibrium_Lab.py deleted file mode 100644 index 3edfb21..0000000 --- a/pages/37_NeqSim_Phase_Equilibrium_Lab.py +++ /dev/null @@ -1,364 +0,0 @@ -"""Phase Equilibrium Lab — a native NeqSim thermodynamics game.""" - -from __future__ import annotations - -from dataclasses import asdict -import json -import math -import os -import sys - -import pandas as pd -import streamlit as st - - -_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.phase_equilibrium_game import ( # noqa: E402 - CHALLENGE_NAME, - CHALLENGE_TIMEOUT_MS, - MAX_PRESSURE_BARA, - MAX_TEMPERATURE_C, - MIN_PRESSURE_BARA, - MIN_TEMPERATURE_C, - RICH_GAS_COMPOSITION, - PhaseChallengeRun, - PhaseControls, - run_phase_challenge, -) -from theme import apply_theme, theme_toggle # noqa: E402 - - -LAST_RUN_KEY = "phase_lab_last_run" -ATTEMPT_COUNT_KEY = "phase_lab_attempt_count" -BEST_SCORE_KEY = "phase_lab_best_score" -TEMPERATURE_KEY = "phase_lab_temperature_c" -PRESSURE_KEY = "phase_lab_pressure_bara" - - -def _initialize_state() -> None: - st.session_state.setdefault(TEMPERATURE_KEY, 20.0) - st.session_state.setdefault(PRESSURE_KEY, 50.0) - st.session_state.setdefault(ATTEMPT_COUNT_KEY, 0) - st.session_state.setdefault(BEST_SCORE_KEY, 0) - - -def _reset_lab() -> None: - st.session_state[TEMPERATURE_KEY] = 20.0 - st.session_state[PRESSURE_KEY] = 50.0 - st.session_state[ATTEMPT_COUNT_KEY] = 0 - st.session_state[BEST_SCORE_KEY] = 0 - st.session_state.pop(LAST_RUN_KEY, None) - - -def _display(value: float | None, digits: int = 3) -> str: - if value is None or not math.isfinite(value): - return "Unavailable" - return f"{value:,.{digits}f}" - - -def _property_rows(run: PhaseChallengeRun) -> list[dict[str, object]]: - evidence = run.evidence - return [ - {"Property": "Gas phase fraction", "Value": evidence.gas_fraction_mol_pct, "Unit": "mol%"}, - { - "Property": "Liquid phase fraction", - "Value": evidence.liquid_fraction_mol_pct, - "Unit": "mol%", - }, - {"Property": "Gas density", "Value": evidence.gas_density_kg_m3, "Unit": "kg/m³"}, - {"Property": "Liquid density", "Value": evidence.liquid_density_kg_m3, "Unit": "kg/m³"}, - {"Property": "Gas compressibility factor", "Value": evidence.gas_z_factor, "Unit": "–"}, - {"Property": "Gas viscosity", "Value": evidence.gas_viscosity_cp, "Unit": "cP"}, - {"Property": "Liquid viscosity", "Value": evidence.liquid_viscosity_cp, "Unit": "cP"}, - {"Property": "Mixture enthalpy", "Value": evidence.mixture_enthalpy_kj_kg, "Unit": "kJ/kg"}, - {"Property": "Mixture Cp", "Value": evidence.mixture_cp_kj_kgk, "Unit": "kJ/(kg·K)"}, - { - "Property": "Phase-fraction closure error", - "Value": evidence.phase_fraction_closure_error, - "Unit": "–", - }, - ] - - -st.set_page_config( - page_title="NeqSim Phase Equilibrium Lab", - page_icon="images/neqsimlogocircleflat.png", - layout="wide", -) -apply_theme() -theme_toggle() -_initialize_state() - -st.markdown( - """ - -""", - unsafe_allow_html=True, -) - -with st.sidebar: - st.markdown("### Phase Equilibrium Lab") - st.caption("Native SRK TP-flash challenge") - if st.button("← NeqSim Games", use_container_width=True): - st.switch_page("pages/34_NeqSim_Games.py") - if st.button("NeqSim Studio", use_container_width=True): - st.switch_page("pages/00_NeqSim_Studio.py") - if st.button("Reset lab", use_container_width=True): - _reset_lab() - st.rerun() - st.divider() - attempt_metric_placeholder = st.empty() - best_score_metric_placeholder = st.empty() - st.caption( - "Synthetic educational fluid. Results are equilibrium-training " - "evidence, not a certified fluid characterization." - ) - -st.markdown( - f""" -
-

{CHALLENGE_NAME}

-

- You have a fixed rich-gas sample. Move temperature and pressure until a - native NeqSim TP flash lands inside a narrow gas-condensate property window. -

-
-""", - unsafe_allow_html=True, -) - -st.markdown( - """ -
- Win condition: form exactly gas + hydrocarbon liquid, recover - 16–20 mol% condensate, hold gas density at 78–92 kg/m³ and Z at 0.80–0.83, - hold liquid density at 480–510 kg/m³, keep liquid viscosity below 0.12 cP, - and close the native phase fractions. -
-""", - unsafe_allow_html=True, -) - -control_panel, result_panel = st.columns([0.86, 1.35], gap="large") -with control_panel: - st.subheader("Flash conditions") - st.slider( - "Temperature [°C]", - min_value=float(MIN_TEMPERATURE_C), - max_value=float(MAX_TEMPERATURE_C), - step=1.0, - key=TEMPERATURE_KEY, - help=( - "Cooling generally promotes liquid dropout, but gas-condensate " - "phase behavior is non-linear." - ), - ) - st.slider( - "Pressure [bara]", - min_value=float(MIN_PRESSURE_BARA), - max_value=float(MAX_PRESSURE_BARA), - step=1.0, - key=PRESSURE_KEY, - help="Pressure changes phase split, density, and real-gas compressibility together.", - ) - current_controls = PhaseControls( - temperature_c=float(st.session_state[TEMPERATURE_KEY]), - pressure_bara=float(st.session_state[PRESSURE_KEY]), - ) - run_clicked = st.button( - "▶ Run native TP flash", - type="primary", - use_container_width=True, - ) - st.caption( - "Model: SRK equation of state · mixing rule 2 · multiphase stability enabled." - ) - with st.expander("Fixed rich-gas composition"): - st.dataframe( - pd.DataFrame( - [ - {"Component": component, "Feed mole %": fraction * 100.0} - for component, fraction in RICH_GAS_COMPOSITION.items() - ] - ), - use_container_width=True, - hide_index=True, - ) - -if run_clicked: - try: - with st.spinner("NeqSim is solving phase equilibrium and properties…"): - completed_run = run_phase_challenge( - current_controls, - timeout_ms=CHALLENGE_TIMEOUT_MS, - ) - except TimeoutError: - st.session_state.pop(LAST_RUN_KEY, None) - st.error( - "The TP flash exceeded its execution budget. The partial native " - "fluid state was discarded." - ) - except Exception as error: - st.session_state.pop(LAST_RUN_KEY, None) - st.error(f"The NeqSim TP flash failed: {error}") - else: - st.session_state[LAST_RUN_KEY] = completed_run - st.session_state[ATTEMPT_COUNT_KEY] += 1 - st.session_state[BEST_SCORE_KEY] = max( - int(st.session_state[BEST_SCORE_KEY]), - completed_run.assessment.score, - ) - -attempt_metric_placeholder.metric( - "Attempts", - int(st.session_state[ATTEMPT_COUNT_KEY]), -) -best_score_metric_placeholder.metric( - "Best score", - f"{int(st.session_state[BEST_SCORE_KEY])}/1000", -) - -last_run = st.session_state.get(LAST_RUN_KEY) -run_is_current = ( - isinstance(last_run, PhaseChallengeRun) - and last_run.controls == current_controls -) - -with result_panel: - st.subheader("Equilibrium result") - if not isinstance(last_run, PhaseChallengeRun): - st.info( - "The sample starts outside the target property window. Choose " - "temperature and pressure, then run the first TP flash." - ) - elif not run_is_current: - st.warning( - "Flash conditions changed after the last solve. Run again before " - "using the score or property evidence." - ) - else: - assessment = last_run.assessment - if assessment.won: - st.success(assessment.grade) - else: - st.warning(assessment.grade) - score_column, phase_column, liquid_column, time_column = st.columns(4) - score_column.metric("Score", f"{assessment.score}/1000") - phase_column.metric("Phases", " + ".join(last_run.evidence.phase_types)) - liquid_column.metric( - "Condensate", - f"{_display(last_run.evidence.liquid_fraction_mol_pct, 2)} mol%", - ) - time_column.metric("Flash time", f"{last_run.elapsed_seconds:.2f} s") - st.progress(assessment.score / 1000.0) - st.dataframe( - pd.DataFrame( - [ - { - "Status": "PASS" if check.passed else "FAIL", - "Target": check.name, - "Solved value": check.actual, - "Requirement": check.requirement, - } - for check in assessment.checks - ] - ), - use_container_width=True, - hide_index=True, - ) - st.markdown("#### Thermodynamic feedback") - for guidance in assessment.guidance: - st.write(f"• {guidance}") - -if run_is_current: - st.divider() - properties_tab, equilibrium_tab, replay_tab = st.tabs( - ["Fluid properties", "Phase compositions & K-values", "Evidence export"] - ) - with properties_tab: - properties = pd.DataFrame(_property_rows(last_run)) - st.dataframe( - properties.style.format( - {"Value": lambda value: _display(value, 6)} - ), - use_container_width=True, - hide_index=True, - ) - st.caption( - "Properties are read from the converged native phases; unavailable " - "values remain unavailable and cannot pass a target." - ) - with equilibrium_tab: - st.dataframe( - pd.DataFrame( - [ - { - "Component": row.component, - "Feed x": row.feed_mole_fraction, - "Gas y": row.gas_mole_fraction, - "Liquid x": row.liquid_mole_fraction, - "K = y/x": row.k_value, - } - for row in last_run.evidence.components - ] - ).style.format( - { - "Feed x": "{:.6f}", - "Gas y": "{:.6f}", - "Liquid x": "{:.6f}", - "K = y/x": "{:.4f}", - }, - na_rep="Unavailable", - ), - use_container_width=True, - hide_index=True, - ) - st.info( - "K > 1 means the component favors the gas phase; K < 1 means it " - "favors the hydrocarbon liquid at this equilibrium point." - ) - with replay_tab: - st.download_button( - "Download solved phase evidence JSON", - data=json.dumps(asdict(last_run), indent=2, allow_nan=False), - file_name="neqsim_phase_equilibrium_attempt.json", - mime="application/json", - use_container_width=True, - ) - st.caption( - "The export records controls, native properties, phase compositions, " - "K-values, checks, score, and solve time." - ) - -st.divider() -st.caption( - "Phase Equilibrium Lab v1 · synthetic rich gas · SRK + mixing rule 2 · " - "one bounded native TP flash per attempt." -) diff --git a/process_chat/__init__.py b/process_chat/__init__.py index 2e3ed7b..32c473e 100644 --- a/process_chat/__init__.py +++ b/process_chat/__init__.py @@ -18,9 +18,6 @@ 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 - phase_equilibrium_game — Native TP-flash and fluid-property challenge - flashcard_game — Portable validated learning-game decks and scoring signal_tracker — Signal/property tracking across multiple chat interactions dexpi_integration — DEXPI P&ID (Proteus XML) import, parsing, and NeqSim bridge """ diff --git a/process_chat/flashcard_game.py b/process_chat/flashcard_game.py deleted file mode 100644 index 8ac5b39..0000000 --- a/process_chat/flashcard_game.py +++ /dev/null @@ -1,339 +0,0 @@ -"""Reusable, validated flashcard decks for NeqSim learning games.""" - -from __future__ import annotations - -import json -from dataclasses import asdict, dataclass -from typing import Iterable, Mapping - - -FLASHCARD_SCHEMA_VERSION = 1 -MAX_DECK_CARDS = 100 -MAX_DECK_JSON_BYTES = 100_000 -VALID_DIFFICULTIES = frozenset({"foundation", "applied", "advanced"}) - - -@dataclass(frozen=True) -class Flashcard: - """One two-sided learning card.""" - - card_id: str - topic: str - prompt: str - answer: str - explanation: str = "" - difficulty: str = "foundation" - - -@dataclass(frozen=True) -class FlashcardDeck: - """A portable flashcard game deck.""" - - name: str - description: str - cards: tuple[Flashcard, ...] - schema_version: int = FLASHCARD_SCHEMA_VERSION - - -@dataclass(frozen=True) -class FlashcardScore: - """Current self-assessment score for a deck session.""" - - reviewed: int - mastered: int - review_again: int - mastery_pct: float - label: str - - -def _clean_text(value, field_name: str, *, maximum: int) -> str: - if not isinstance(value, str): - raise ValueError(f"{field_name} must be text.") - cleaned = value.strip() - if not cleaned: - raise ValueError(f"{field_name} cannot be empty.") - if len(cleaned) > maximum: - raise ValueError(f"{field_name} cannot exceed {maximum} characters.") - return cleaned - - -def validate_card(card: Flashcard) -> Flashcard: - """Return a normalized card or reject unsafe/ambiguous content.""" - if not isinstance(card, Flashcard): - raise ValueError("Cards must use the Flashcard schema.") - difficulty = str(card.difficulty).strip().lower() - if difficulty not in VALID_DIFFICULTIES: - raise ValueError( - "Difficulty must be foundation, applied, or advanced." - ) - if card.explanation is not None and not isinstance(card.explanation, str): - raise ValueError("Explanation must be text.") - explanation = str(card.explanation or "").strip() - if len(explanation) > 2_000: - raise ValueError("Explanation cannot exceed 2000 characters.") - return Flashcard( - card_id=_clean_text(card.card_id, "Card id", maximum=80), - topic=_clean_text(card.topic, "Topic", maximum=80), - prompt=_clean_text(card.prompt, "Prompt", maximum=1_000), - answer=_clean_text(card.answer, "Answer", maximum=2_000), - explanation=explanation, - difficulty=difficulty, - ) - - -def validate_deck(deck: FlashcardDeck) -> FlashcardDeck: - """Validate deck size, identifiers, and all card fields.""" - if not isinstance(deck, FlashcardDeck): - raise ValueError("Deck must use the FlashcardDeck schema.") - if ( - isinstance(deck.schema_version, bool) - or not isinstance(deck.schema_version, int) - or deck.schema_version != FLASHCARD_SCHEMA_VERSION - ): - raise ValueError("Unsupported flashcard schema version.") - name = _clean_text(deck.name, "Deck name", maximum=120) - description = str(deck.description or "").strip()[:1_000] - cards = tuple(validate_card(card) for card in deck.cards) - if not cards: - raise ValueError("A flashcard deck must contain at least one card.") - if len(cards) > MAX_DECK_CARDS: - raise ValueError( - f"A flashcard deck cannot exceed {MAX_DECK_CARDS} cards." - ) - card_ids = [card.card_id for card in cards] - if len(card_ids) != len(set(card_ids)): - raise ValueError("Flashcard ids must be unique within a deck.") - return FlashcardDeck( - name=name, - description=description, - cards=cards, - schema_version=FLASHCARD_SCHEMA_VERSION, - ) - - -def deck_to_json(deck: FlashcardDeck) -> str: - """Serialize a validated deck to portable, versioned JSON.""" - normalized = validate_deck(deck) - payload = { - "schema_version": normalized.schema_version, - "name": normalized.name, - "description": normalized.description, - "cards": [asdict(card) for card in normalized.cards], - } - encoded = json.dumps(payload, indent=2, ensure_ascii=False) - if len(encoded.encode("utf-8")) > MAX_DECK_JSON_BYTES: - raise ValueError("Flashcard deck JSON is too large.") - return encoded - - -def deck_from_json(payload: str | bytes) -> FlashcardDeck: - """Load a bounded, versioned deck from JSON.""" - if isinstance(payload, bytes): - raw_bytes = payload - try: - payload = payload.decode("utf-8") - except UnicodeDecodeError as exc: - raise ValueError("Flashcard deck must be UTF-8 JSON.") from exc - elif isinstance(payload, str): - raw_bytes = payload.encode("utf-8") - else: - raise ValueError("Flashcard deck must be JSON text.") - if len(raw_bytes) > MAX_DECK_JSON_BYTES: - raise ValueError("Flashcard deck JSON is too large.") - try: - raw = json.loads(payload) - except json.JSONDecodeError as exc: - raise ValueError("Flashcard deck contains invalid JSON.") from exc - if not isinstance(raw, dict): - raise ValueError("Flashcard deck JSON must contain one object.") - raw_cards = raw.get("cards") - if not isinstance(raw_cards, list): - raise ValueError("Flashcard deck cards must be a list.") - if len(raw_cards) > MAX_DECK_CARDS: - raise ValueError( - f"A flashcard deck cannot exceed {MAX_DECK_CARDS} cards." - ) - cards: list[Flashcard] = [] - for raw_card in raw_cards: - if not isinstance(raw_card, dict): - raise ValueError("Every flashcard must be an object.") - try: - cards.append( - Flashcard( - card_id=raw_card["card_id"], - topic=raw_card["topic"], - prompt=raw_card["prompt"], - answer=raw_card["answer"], - explanation=raw_card.get("explanation", ""), - difficulty=raw_card.get("difficulty", "foundation"), - ) - ) - except KeyError as exc: - raise ValueError( - f"Flashcard is missing required field: {exc.args[0]}." - ) from exc - normalized = validate_deck( - FlashcardDeck( - name=raw.get("name", ""), - description=raw.get("description", ""), - cards=tuple(cards), - schema_version=raw.get("schema_version"), - ) - ) - # The app always exposes imported decks through the canonical, indented - # download format. A compact upload can fit the input bound while that - # normalized representation does not, so accept only round-trippable - # decks and keep import/export limits symmetric. - deck_to_json(normalized) - return normalized - - -def score_flashcards( - deck: FlashcardDeck, - marks: Mapping[str, bool], -) -> FlashcardScore: - """Score only reviewed cards; unknown identifiers are rejected.""" - normalized = validate_deck(deck) - known_ids = {card.card_id for card in normalized.cards} - unknown = set(marks) - known_ids - if unknown: - raise ValueError( - "Marks contain unknown flashcard ids: " + ", ".join(sorted(unknown)) - ) - if any(not isinstance(value, bool) for value in marks.values()): - raise ValueError("Flashcard marks must be boolean self-assessments.") - reviewed = len(marks) - mastered = sum(1 for value in marks.values() if value) - review_again = reviewed - mastered - mastery_pct = 100.0 * mastered / reviewed if reviewed else 0.0 - label = ( - "Mastered" - if reviewed == len(normalized.cards) and mastery_pct >= 90.0 - else "Building confidence" - if mastery_pct >= 60.0 - else "Keep practicing" - ) - return FlashcardScore( - reviewed=reviewed, - mastered=mastered, - review_again=review_again, - mastery_pct=mastery_pct, - label=label, - ) - - -def custom_deck(cards: Iterable[Flashcard]) -> FlashcardDeck: - """Build the standard session-local custom deck.""" - return validate_deck( - FlashcardDeck( - name="My custom NeqSim deck", - description="A user-authored flashcard game exported from NeqSim Games.", - cards=tuple(cards), - ) - ) - - -PHASE_EQUILIBRIUM_DECK = validate_deck( - FlashcardDeck( - name="Phase equilibrium & fluid properties", - description=( - "Foundation and applied cards covering TP flashes, phase splits, " - "K-values, equations of state, and key fluid properties." - ), - cards=( - Flashcard( - "phase-tp-flash", - "Phase equilibrium", - "What does a TP flash calculate?", - "The equilibrium phases, their amounts, compositions, and " - "properties at specified temperature and pressure.", - "The total feed composition is fixed while NeqSim minimizes " - "the thermodynamic equilibrium condition.", - ), - Flashcard( - "phase-dew-point", - "Phase equilibrium", - "What is the hydrocarbon dew point?", - "The condition where the first infinitesimal liquid hydrocarbon " - "phase forms from a gas.", - difficulty="foundation", - ), - Flashcard( - "phase-bubble-point", - "Phase equilibrium", - "What is the bubble point?", - "The condition where the first infinitesimal gas bubble forms from a liquid.", - difficulty="foundation", - ), - Flashcard( - "phase-k-value", - "Phase equilibrium", - "For Kᵢ = yᵢ/xᵢ, what does Kᵢ > 1 mean?", - "Component i preferentially partitions to the gas phase.", - "yᵢ is gas-phase mole fraction and xᵢ is liquid-phase mole fraction.", - difficulty="applied", - ), - Flashcard( - "phase-retrograde", - "Phase equilibrium", - "What is retrograde condensation?", - "Liquid dropout caused by pressure reduction or compression-path " - "changes in a gas-condensate system, even without ordinary " - "cooling below a normal boiling point.", - difficulty="advanced", - ), - Flashcard( - "property-z-factor", - "Fluid properties", - "What does gas compressibility factor Z correct in PV = ZnRT?", - "It corrects ideal-gas behavior for real-fluid intermolecular effects.", - difficulty="foundation", - ), - Flashcard( - "property-density", - "Fluid properties", - "At fixed temperature, what usually happens to gas density as pressure rises?", - "Gas density generally increases, although the real-fluid " - "relationship depends on Z and phase behavior.", - difficulty="applied", - ), - Flashcard( - "property-viscosity", - "Fluid properties", - "Which property measures resistance to shear flow?", - "Dynamic viscosity, commonly reported in cP or Pa·s.", - difficulty="foundation", - ), - Flashcard( - "property-cp", - "Fluid properties", - "What does isobaric heat capacity Cp describe?", - "The enthalpy change per unit temperature change at constant pressure.", - difficulty="applied", - ), - Flashcard( - "model-eos", - "Thermodynamic models", - "Why must a phase-equilibrium result identify its equation of state?", - "Different models and mixing rules predict fugacity, phase " - "boundaries, and properties differently.", - "The game uses SRK with mixing rule 2 for a reproducible training case.", - difficulty="applied", - ), - Flashcard( - "balance-beta", - "Validation", - "What should all equilibrium phase mole fractions sum to?", - "One, within numerical tolerance.", - difficulty="foundation", - ), - Flashcard( - "validation-missing", - "Validation", - "Should a missing native property be treated as a passing game check?", - "No. Missing or non-finite native evidence must block the affected check.", - difficulty="applied", - ), - ), - ) -) diff --git a/process_chat/phase_equilibrium_game.py b/process_chat/phase_equilibrium_game.py deleted file mode 100644 index 1fbb70f..0000000 --- a/process_chat/phase_equilibrium_game.py +++ /dev/null @@ -1,496 +0,0 @@ -"""Native phase-equilibrium and fluid-property training challenge. - -NeqSim owns every flash and property calculation. This module defines one -reproducible rich-gas sample, validates the player controls, captures native -evidence, and translates the solved state into an explicit game assessment. -""" - -from __future__ import annotations - -import math -import os -from dataclasses import dataclass -from time import perf_counter -from typing import Optional - -_REQUIRED_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", -) -_existing_java_options = os.environ.get("JAVA_TOOL_OPTIONS", "").split() -_missing_java_options = [ - option for option in _REQUIRED_JVM_OPENS if option not in _existing_java_options -] -if _missing_java_options: - os.environ["JAVA_TOOL_OPTIONS"] = " ".join( - [*_existing_java_options, *_missing_java_options] - ) - -from .process_model import NeqSimProcessModel - - -CHALLENGE_NAME = "Catch the Retrograde Window" -CHALLENGE_TIMEOUT_MS = 60_000 -MIN_TEMPERATURE_C = -20.0 -MAX_TEMPERATURE_C = 80.0 -MIN_PRESSURE_BARA = 10.0 -MAX_PRESSURE_BARA = 130.0 - -MIN_LIQUID_FRACTION_MOL_PCT = 16.0 -MAX_LIQUID_FRACTION_MOL_PCT = 20.0 -MIN_GAS_DENSITY_KG_M3 = 78.0 -MAX_GAS_DENSITY_KG_M3 = 92.0 -MIN_GAS_Z_FACTOR = 0.80 -MAX_GAS_Z_FACTOR = 0.83 -MIN_LIQUID_DENSITY_KG_M3 = 480.0 -MAX_LIQUID_DENSITY_KG_M3 = 510.0 -MAX_LIQUID_VISCOSITY_CP = 0.12 -MAX_PHASE_FRACTION_CLOSURE_ERROR = 1.0e-10 - -RICH_GAS_COMPOSITION = { - "CO2": 0.005, - "methane": 0.720, - "ethane": 0.080, - "propane": 0.060, - "i-butane": 0.025, - "n-butane": 0.035, - "i-pentane": 0.015, - "n-pentane": 0.015, - "n-hexane": 0.020, - "n-heptane": 0.015, - "n-octane": 0.010, -} - - -@dataclass(frozen=True) -class PhaseControls: - """Player-adjustable temperature and pressure for one TP flash.""" - - temperature_c: float = 20.0 - pressure_bara: float = 50.0 - - -@dataclass(frozen=True) -class ComponentEquilibrium: - """Feed and equilibrium phase composition for one component.""" - - component: str - feed_mole_fraction: float - gas_mole_fraction: Optional[float] - liquid_mole_fraction: Optional[float] - k_value: Optional[float] - - -@dataclass(frozen=True) -class PhaseEvidence: - """Native NeqSim phase state and fluid properties used by the game.""" - - temperature_c: float - pressure_bara: float - phase_types: tuple[str, ...] - gas_fraction_mol_pct: Optional[float] - liquid_fraction_mol_pct: Optional[float] - gas_density_kg_m3: Optional[float] - liquid_density_kg_m3: Optional[float] - gas_z_factor: Optional[float] - gas_viscosity_cp: Optional[float] - liquid_viscosity_cp: Optional[float] - mixture_enthalpy_kj_kg: Optional[float] - mixture_cp_kj_kgk: Optional[float] - phase_fraction_closure_error: Optional[float] - components: tuple[ComponentEquilibrium, ...] = () - - -@dataclass(frozen=True) -class PhaseCheck: - """One objective acceptance check with its solved evidence.""" - - name: str - passed: bool - actual: str - requirement: str - - -@dataclass(frozen=True) -class PhaseAssessment: - """Transparent score and feedback for one flash result.""" - - score: int - won: bool - grade: str - checks: tuple[PhaseCheck, ...] - guidance: tuple[str, ...] - - -@dataclass(frozen=True) -class PhaseChallengeRun: - """One completed native TP-flash attempt.""" - - controls: PhaseControls - evidence: PhaseEvidence - assessment: PhaseAssessment - elapsed_seconds: float - - -def _finite_between( - value: float, - name: str, - minimum: float, - maximum: float, -) -> float: - if isinstance(value, bool): - raise ValueError(f"{name} must be numeric.") - try: - numeric = float(value) - except (TypeError, ValueError) as exc: - raise ValueError(f"{name} must be numeric.") from exc - if not math.isfinite(numeric): - raise ValueError(f"{name} must be finite.") - if not minimum <= numeric <= maximum: - raise ValueError( - f"{name} must be between {minimum:g} and {maximum:g}." - ) - return numeric - - -def validate_controls(controls: PhaseControls) -> PhaseControls: - """Validate public game controls before starting native calculation.""" - if not isinstance(controls, PhaseControls): - raise ValueError("Phase controls must use PhaseControls.") - return PhaseControls( - temperature_c=_finite_between( - controls.temperature_c, - "Temperature", - MIN_TEMPERATURE_C, - MAX_TEMPERATURE_C, - ), - pressure_bara=_finite_between( - controls.pressure_bara, - "Pressure", - MIN_PRESSURE_BARA, - MAX_PRESSURE_BARA, - ), - ) - - -def _validate_timeout_ms(timeout_ms: int) -> int: - if isinstance(timeout_ms, bool): - raise ValueError("Timeout must be a positive integer number of milliseconds.") - try: - numeric = float(timeout_ms) - except (TypeError, ValueError) as exc: - raise ValueError( - "Timeout must be a positive integer number of milliseconds." - ) from exc - if not math.isfinite(numeric) or numeric <= 0 or not numeric.is_integer(): - raise ValueError("Timeout must be a positive integer number of milliseconds.") - return int(numeric) - - -def _safe_float(callback) -> Optional[float]: - try: - value = float(callback()) - except Exception: - return None - return value if math.isfinite(value) else None - - -def _formatted(value: Optional[float], unit: str, digits: int = 3) -> str: - if value is None or not math.isfinite(value): - return "unavailable" - return f"{value:.{digits}f} {unit}".strip() - - -def _between(value: Optional[float], minimum: float, maximum: float) -> bool: - return ( - value is not None - and math.isfinite(value) - and minimum <= value <= maximum - ) - - -def _below(value: Optional[float], maximum: float) -> bool: - return value is not None and math.isfinite(value) and value < maximum - - -def assess_phase_evidence(evidence: PhaseEvidence) -> PhaseAssessment: - """Score native evidence without inferring or repairing missing values.""" - two_phase = set(evidence.phase_types) == {"gas", "oil"} - closure_passed = _between( - evidence.phase_fraction_closure_error, - 0.0, - MAX_PHASE_FRACTION_CLOSURE_ERROR, - ) - checks = ( - PhaseCheck( - "Equilibrium phase state", - two_phase, - " + ".join(evidence.phase_types) if evidence.phase_types else "unavailable", - "exactly gas + hydrocarbon liquid", - ), - PhaseCheck( - "Condensate split", - _between( - evidence.liquid_fraction_mol_pct, - MIN_LIQUID_FRACTION_MOL_PCT, - MAX_LIQUID_FRACTION_MOL_PCT, - ), - _formatted(evidence.liquid_fraction_mol_pct, "mol%"), - f"{MIN_LIQUID_FRACTION_MOL_PCT:.0f}–{MAX_LIQUID_FRACTION_MOL_PCT:.0f} mol%", - ), - PhaseCheck( - "Gas density", - _between( - evidence.gas_density_kg_m3, - MIN_GAS_DENSITY_KG_M3, - MAX_GAS_DENSITY_KG_M3, - ), - _formatted(evidence.gas_density_kg_m3, "kg/m³", 2), - f"{MIN_GAS_DENSITY_KG_M3:.0f}–{MAX_GAS_DENSITY_KG_M3:.0f} kg/m³", - ), - PhaseCheck( - "Gas compressibility", - _between( - evidence.gas_z_factor, - MIN_GAS_Z_FACTOR, - MAX_GAS_Z_FACTOR, - ), - _formatted(evidence.gas_z_factor, "", 4), - f"Z = {MIN_GAS_Z_FACTOR:.2f}–{MAX_GAS_Z_FACTOR:.2f}", - ), - PhaseCheck( - "Liquid density", - _between( - evidence.liquid_density_kg_m3, - MIN_LIQUID_DENSITY_KG_M3, - MAX_LIQUID_DENSITY_KG_M3, - ), - _formatted(evidence.liquid_density_kg_m3, "kg/m³", 2), - f"{MIN_LIQUID_DENSITY_KG_M3:.0f}–{MAX_LIQUID_DENSITY_KG_M3:.0f} kg/m³", - ), - PhaseCheck( - "Liquid viscosity", - _below(evidence.liquid_viscosity_cp, MAX_LIQUID_VISCOSITY_CP), - _formatted(evidence.liquid_viscosity_cp, "cP", 4), - f"< {MAX_LIQUID_VISCOSITY_CP:.2f} cP", - ), - PhaseCheck( - "Phase-fraction closure", - closure_passed, - _formatted(evidence.phase_fraction_closure_error, "", 3), - f"≤ {MAX_PHASE_FRACTION_CLOSURE_ERROR:.0e}", - ), - ) - weights = (180, 220, 140, 140, 120, 100, 100) - score = sum(weight for weight, check in zip(weights, checks) if check.passed) - won = all(check.passed for check in checks) - - guidance: list[str] = [] - if not two_phase: - if evidence.phase_types == ("gas",): - guidance.append( - "The sample is single-phase gas. Cool it or explore a different " - "pressure to enter the phase envelope." - ) - elif evidence.phase_types == ("oil",): - guidance.append( - "The sample is single-phase liquid. Warm it or reduce pressure " - "to recover a gas phase." - ) - else: - guidance.append( - "NeqSim did not return the required gas–oil equilibrium state; " - "this attempt cannot win." - ) - liquid_fraction = evidence.liquid_fraction_mol_pct - if liquid_fraction is None: - guidance.append( - "Condensate fraction is unavailable; establish both gas and oil " - "phases first." - ) - elif liquid_fraction < MIN_LIQUID_FRACTION_MOL_PCT: - guidance.append( - "Condensate recovery is low. Try cooling the sample or increasing " - "pressure." - ) - elif liquid_fraction > MAX_LIQUID_FRACTION_MOL_PCT: - guidance.append("Too much liquid dropped out. Try warming the sample or reducing pressure.") - gas_density = evidence.gas_density_kg_m3 - if gas_density is not None and gas_density < MIN_GAS_DENSITY_KG_M3: - guidance.append("Gas density is low; increasing pressure is the strongest local lever.") - elif gas_density is not None and gas_density > MAX_GAS_DENSITY_KG_M3: - guidance.append( - "Gas density is high; reduce pressure while protecting the " - "condensate target." - ) - if not checks[3].passed: - guidance.append( - "Z-factor is outside its band. Adjust pressure and temperature " - "together, then re-flash." - ) - if not checks[4].passed or not checks[5].passed: - guidance.append( - "The liquid property targets favor a warmer, denser operating " - "window than the starting point." - ) - if not closure_passed: - guidance.append("Phase-fraction evidence is missing or does not close; discard the result.") - if won: - guidance = [ - "Retrograde window captured. Compare the gas and liquid " - "compositions: K > 1 favors vapor, while K < 1 favors liquid." - ] - - grade = ( - "Phase window captured" - if won - else "Close — refine the flash conditions" - if score >= 650 - else "Keep exploring the phase envelope" - ) - return PhaseAssessment( - score=int(score), - won=won, - grade=grade, - checks=checks, - guidance=tuple(guidance), - ) - - -def _native_phase_evidence(controls: PhaseControls) -> PhaseEvidence: - """Execute one NeqSim SRK TP flash and extract its solved state.""" - from neqsim import jneqsim - from neqsim.thermo import TPflash - - fluid = jneqsim.thermo.system.SystemSrkEos( - controls.temperature_c + 273.15, - controls.pressure_bara, - ) - for component, mole_fraction in RICH_GAS_COMPOSITION.items(): - fluid.addComponent(component, mole_fraction) - fluid.setMixingRule(2) - fluid.setMultiPhaseCheck(True) - TPflash(fluid) - fluid.init(3) - fluid.initProperties() - - phase_types = tuple( - phase_type - for phase_type in ("gas", "oil", "aqueous", "solid") - if bool(fluid.hasPhaseType(phase_type)) - ) - gas = fluid.getPhase("gas") if "gas" in phase_types else None - liquid = fluid.getPhase("oil") if "oil" in phase_types else None - - gas_beta = _safe_float(gas.getBeta) if gas is not None else None - liquid_beta = _safe_float(liquid.getBeta) if liquid is not None else None - phase_betas = [ - _safe_float(fluid.getPhase(index).getBeta) - for index in range(int(fluid.getNumberOfPhases())) - ] - phase_fraction_closure_error = ( - abs(sum(phase_betas) - 1.0) - if phase_betas and all(value is not None for value in phase_betas) - else None - ) - - components: list[ComponentEquilibrium] = [] - for component, feed_fraction in RICH_GAS_COMPOSITION.items(): - gas_fraction = ( - _safe_float(lambda name=component: gas.getComponent(name).getx()) - if gas is not None - else None - ) - liquid_fraction = ( - _safe_float(lambda name=component: liquid.getComponent(name).getx()) - if liquid is not None - else None - ) - k_value = ( - gas_fraction / liquid_fraction - if gas_fraction is not None - and liquid_fraction is not None - and liquid_fraction > 0.0 - else None - ) - components.append( - ComponentEquilibrium( - component=component, - feed_mole_fraction=feed_fraction, - gas_mole_fraction=gas_fraction, - liquid_mole_fraction=liquid_fraction, - k_value=k_value, - ) - ) - - return PhaseEvidence( - temperature_c=controls.temperature_c, - pressure_bara=controls.pressure_bara, - phase_types=phase_types, - gas_fraction_mol_pct=gas_beta * 100.0 if gas_beta is not None else None, - liquid_fraction_mol_pct=( - liquid_beta * 100.0 if liquid_beta is not None else None - ), - gas_density_kg_m3=( - _safe_float(lambda: gas.getDensity("kg/m3")) if gas is not None else None - ), - liquid_density_kg_m3=( - _safe_float(lambda: liquid.getDensity("kg/m3")) - if liquid is not None - else None - ), - gas_z_factor=_safe_float(gas.getZ) if gas is not None else None, - gas_viscosity_cp=( - _safe_float(lambda: gas.getViscosity("cP")) if gas is not None else None - ), - liquid_viscosity_cp=( - _safe_float(lambda: liquid.getViscosity("cP")) - if liquid is not None - else None - ), - mixture_enthalpy_kj_kg=_safe_float(lambda: fluid.getEnthalpy("kJ/kg")), - mixture_cp_kj_kgk=_safe_float(lambda: fluid.getCp("kJ/kgK")), - phase_fraction_closure_error=phase_fraction_closure_error, - components=tuple(components), - ) - - -def run_phase_challenge( - controls: PhaseControls, - *, - timeout_ms: int = CHALLENGE_TIMEOUT_MS, -) -> PhaseChallengeRun: - """Run one bounded NeqSim phase-equilibrium game attempt.""" - validated_controls = validate_controls(controls) - validated_timeout = _validate_timeout_ms(timeout_ms) - started = perf_counter() - - def _bounded_flash() -> PhaseEvidence: - try: - return _native_phase_evidence(validated_controls) - finally: - # JPype auto-attaches Python worker threads to the JVM. Explicitly - # detach this short-lived watchdog worker so command-line tests and - # batch callers can shut down cleanly after the flash completes. - try: - import jpype - - if jpype.java.lang.Thread.isAttached(): - jpype.java.lang.Thread.detach() - except Exception: - pass - - evidence = NeqSimProcessModel._run_bounded_call( - _bounded_flash, - validated_timeout, - operation="phase-equilibrium flash", - ) - assessment = assess_phase_evidence(evidence) - return PhaseChallengeRun( - controls=validated_controls, - evidence=evidence, - assessment=assessment, - elapsed_seconds=perf_counter() - started, - ) diff --git a/process_chat/plant_operator_game.py b/process_chat/plant_operator_game.py deleted file mode 100644 index 1e94330..0000000 --- a/process_chat/plant_operator_game.py +++ /dev/null @@ -1,565 +0,0 @@ -"""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_200.0 -MAX_SPECIFIC_POWER_KWH_PER_TONNE = 41.0 -MAX_COOLING_DUTY_KW = 5_500.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).strip().upper() not in {"OK", "WARN"} - 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:,.2f} kW", - f"less than {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:,.2f} kW", - f"less than {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 failed or unavailable checks" - if not evidence.native_violations - else ", ".join(evidence.native_violations) - ), - "no failed or unavailable native constraints", - ), - ) - - 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=5_400.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): - raise ValueError("Challenge timeout must be a positive integer.") - try: - numeric_timeout_ms = float(timeout_ms) - except (TypeError, ValueError) as exc: - raise ValueError("Challenge timeout must be a positive integer.") from exc - if ( - not math.isfinite(numeric_timeout_ms) - or not numeric_timeout_ms.is_integer() - or numeric_timeout_ms <= 0 - ): - raise ValueError("Challenge timeout must be a positive integer.") - timeout_ms = int(numeric_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/studio/navigation.py b/studio/navigation.py index 9200869..d80bddc 100644 --- a/studio/navigation.py +++ b/studio/navigation.py @@ -82,17 +82,6 @@ def available(self) -> bool: status=STATUS_AVAILABLE, page="pages/10_Studio_Results.py", ), - StudioDestination( - key="games", - title="NeqSim Games", - description=( - "Play native process and phase-equilibrium challenges, practice " - "thermodynamics with flashcards, or build a reusable learning deck." - ), - icon="🎮", - status=STATUS_AVAILABLE, - page="pages/34_NeqSim_Games.py", - ), StudioDestination( key="dynamics", title="Dynamics & Controls", diff --git a/tests/test_flashcard_game.py b/tests/test_flashcard_game.py deleted file mode 100644 index 18a1b97..0000000 --- a/tests/test_flashcard_game.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Tests for portable NeqSim flashcard game decks.""" - -import json -import unittest - -from process_chat.flashcard_game import ( - MAX_DECK_CARDS, - MAX_DECK_JSON_BYTES, - PHASE_EQUILIBRIUM_DECK, - Flashcard, - FlashcardDeck, - custom_deck, - deck_from_json, - deck_to_json, - score_flashcards, - validate_deck, -) - - -class FlashcardGameTest(unittest.TestCase): - """Keep decks portable, bounded, unique, and honestly scored.""" - - def test_builtin_phase_deck_covers_equilibrium_and_properties(self): - deck = validate_deck(PHASE_EQUILIBRIUM_DECK) - - self.assertGreaterEqual(len(deck.cards), 10) - self.assertIn("Phase equilibrium", {card.topic for card in deck.cards}) - self.assertIn("Fluid properties", {card.topic for card in deck.cards}) - self.assertIn("advanced", {card.difficulty for card in deck.cards}) - - def test_versioned_json_round_trip_preserves_cards(self): - encoded = deck_to_json(PHASE_EQUILIBRIUM_DECK) - decoded = deck_from_json(encoded) - - self.assertEqual(decoded, PHASE_EQUILIBRIUM_DECK) - self.assertEqual(json.loads(encoded)["schema_version"], 1) - - def test_invalid_and_duplicate_cards_fail_loudly(self): - duplicate = Flashcard("same", "Topic", "Question", "Answer") - with self.assertRaisesRegex(ValueError, "ids must be unique"): - validate_deck( - FlashcardDeck("Duplicates", "", (duplicate, duplicate)) - ) - with self.assertRaisesRegex(ValueError, "invalid JSON"): - deck_from_json("not-json") - with self.assertRaisesRegex(ValueError, "Difficulty"): - validate_deck( - FlashcardDeck( - "Bad difficulty", - "", - ( - Flashcard( - "one", - "Topic", - "Question", - "Answer", - difficulty="impossible", - ), - ), - ) - ) - with self.assertRaisesRegex(ValueError, "schema version"): - validate_deck( - FlashcardDeck( - "Bad schema", - "", - (Flashcard("one", "Topic", "Question", "Answer"),), - schema_version=True, - ) - ) - - def test_custom_builder_rejects_card_and_json_size_overflow(self): - cards = tuple( - Flashcard( - f"custom-{index}", - "Topic", - "Question", - "Answer", - ) - for index in range(MAX_DECK_CARDS + 1) - ) - with self.assertRaisesRegex(ValueError, "cannot exceed"): - custom_deck(cards) - - oversized_but_field_valid = FlashcardDeck( - "Oversized JSON", - "", - tuple( - Flashcard( - f"large-{index}", - "Topic", - "Q" * 1_000, - "A" * 2_000, - "E" * 2_000, - ) - for index in range(30) - ), - ) - with self.assertRaisesRegex(ValueError, "JSON is too large"): - deck_to_json(oversized_but_field_valid) - - def test_import_rejects_deck_that_cannot_be_exported(self): - raw = { - "schema_version": 1, - "name": "Boundary", - "description": "", - "cards": [ - { - "card_id": f"{index:02d}" + "i" * 78, - "topic": "T" * 80, - "prompt": "Q" * 1_000, - "answer": "A" * 2_000, - "explanation": "E" * 2_000, - "difficulty": "foundation", - } - for index in range(19) - ], - } - compact = json.dumps(raw, separators=(",", ":"), ensure_ascii=False) - self.assertLess(len(compact.encode("utf-8")), MAX_DECK_JSON_BYTES) - - with self.assertRaisesRegex(ValueError, "JSON is too large"): - deck_from_json(compact) - - def test_score_counts_only_reviewed_known_cards(self): - deck = PHASE_EQUILIBRIUM_DECK - score = score_flashcards( - deck, - { - deck.cards[0].card_id: True, - deck.cards[1].card_id: False, - }, - ) - - self.assertEqual(score.reviewed, 2) - self.assertEqual(score.mastered, 1) - self.assertEqual(score.review_again, 1) - self.assertEqual(score.mastery_pct, 50.0) - with self.assertRaisesRegex(ValueError, "unknown flashcard ids"): - score_flashcards(deck, {"not-in-deck": True}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_games_pages.py b/tests/test_games_pages.py deleted file mode 100644 index 063dd79..0000000 --- a/tests/test_games_pages.py +++ /dev/null @@ -1,116 +0,0 @@ -"""Source and initial-render regressions for the NeqSim Games pages.""" - -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] -GAMES_PAGE = PROJECT_ROOT / "pages" / "34_NeqSim_Games.py" -PHASE_PAGE = PROJECT_ROOT / "pages" / "37_NeqSim_Phase_Equilibrium_Lab.py" - - -class GamesPagesTest(unittest.TestCase): - """Keep the shared menu, flashcards, and native phase game discoverable.""" - - def test_games_hub_is_the_single_studio_destination(self): - destination = destination_by_key("games") - source = GAMES_PAGE.read_text(encoding="utf-8") - - self.assertTrue(destination.available) - self.assertEqual(destination.page, "pages/34_NeqSim_Games.py") - self.assertIn("pages/36_NeqSim_Plant_Operator.py", source) - self.assertIn("pages/37_NeqSim_Phase_Equilibrium_Lab.py", source) - self.assertIn("Create a flashcard deck", source) - self.assertIn("Download custom deck JSON", source) - self.assertIn( - "candidate_deck = custom_deck((*existing, new_card))", - source, - ) - - def test_both_pages_are_valid_python(self): - ast.parse(GAMES_PAGE.read_text(encoding="utf-8")) - phase_source = PHASE_PAGE.read_text(encoding="utf-8") - ast.parse(phase_source) - self.assertIn("run_phase_challenge(", phase_source) - self.assertIn("Phase compositions & K-values", phase_source) - self.assertIn("last_run.controls == current_controls", phase_source) - - def test_games_hub_initial_render_does_not_start_native_calculation(self): - app = AppTest.from_file(str(GAMES_PAGE)).run(timeout=30) - - if app.exception: - details = "\n".join(str(item.value) for item in app.exception) - self.fail(f"Games hub raised exceptions:\n{details}") - button_labels = [button.label for button in app.button] - self.assertIn("Open Plant Operator", button_labels) - self.assertIn("Open Phase Equilibrium Lab", button_labels) - self.assertIn("Reveal answer", button_labels) - - def test_flashcard_reveal_and_self_check_update_mastery(self): - app = AppTest.from_file(str(GAMES_PAGE)).run(timeout=30) - reveal = next( - button for button in app.button if button.label == "Reveal answer" - ) - - app = reveal.click().run(timeout=30) - self.assertIn( - "The equilibrium phases, their amounts, compositions, and " - "properties at specified temperature and pressure.", - [item.value for item in app.success], - ) - knew = next( - button for button in app.button if button.label == "I knew this" - ) - app = knew.click().run(timeout=30) - - metrics = {item.label: item.value for item in app.metric} - self.assertEqual(metrics["Reviewed"], "1") - self.assertEqual(metrics["Mastery"], "100%") - - def test_phase_lab_initial_render_waits_for_player(self): - app = AppTest.from_file(str(PHASE_PAGE)).run(timeout=30) - - if app.exception: - details = "\n".join(str(item.value) for item in app.exception) - self.fail(f"Phase lab raised exceptions:\n{details}") - self.assertIn( - "▶ Run native TP flash", - [button.label for button in app.button], - ) - self.assertEqual( - [slider.label for slider in app.slider], - ["Temperature [°C]", "Pressure [bara]"], - ) - - def test_phase_lab_winning_controls_publish_current_evidence(self): - app = AppTest.from_file( - str(PHASE_PAGE), - default_timeout=90, - ).run() - app.slider[0].set_value(50.0) - app.slider[1].set_value(80.0) - run_button = next( - button - for button in app.button - if button.label == "▶ Run native TP flash" - ) - - app = run_button.click().run(timeout=90) - - if app.exception: - details = "\n".join(str(item.value) for item in app.exception) - self.fail(f"Phase lab winning attempt raised exceptions:\n{details}") - self.assertIn("Phase window captured", [item.value for item in app.success]) - metrics = {item.label: item.value for item in app.metric} - self.assertEqual(metrics["Score"], "1000/1000") - self.assertEqual(metrics["Attempts"], "1") - self.assertEqual(metrics["Best score"], "1000/1000") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_phase_equilibrium_game.py b/tests/test_phase_equilibrium_game.py deleted file mode 100644 index 3dddb4c..0000000 --- a/tests/test_phase_equilibrium_game.py +++ /dev/null @@ -1,113 +0,0 @@ -"""Tests for the native phase-equilibrium and fluid-property game.""" - -import math -import unittest - -from process_chat.phase_equilibrium_game import ( - RICH_GAS_COMPOSITION, - ComponentEquilibrium, - PhaseControls, - PhaseEvidence, - assess_phase_evidence, - run_phase_challenge, - validate_controls, -) - - -def _winning_evidence(**overrides) -> PhaseEvidence: - values = { - "temperature_c": 50.0, - "pressure_bara": 80.0, - "phase_types": ("gas", "oil"), - "gas_fraction_mol_pct": 83.1, - "liquid_fraction_mol_pct": 16.9, - "gas_density_kg_m3": 79.5, - "liquid_density_kg_m3": 499.5, - "gas_z_factor": 0.819, - "gas_viscosity_cp": 0.015, - "liquid_viscosity_cp": 0.105, - "mixture_enthalpy_kj_kg": -77.2, - "mixture_cp_kj_kgk": 2.8, - "phase_fraction_closure_error": 0.0, - "components": (), - } - values.update(overrides) - return PhaseEvidence(**values) - - -class PhaseEquilibriumGameTest(unittest.TestCase): - """Protect controls, evidence integrity, and the calibrated native window.""" - - def test_training_fluid_is_normalized_and_reproducible(self): - self.assertAlmostEqual(sum(RICH_GAS_COMPOSITION.values()), 1.0) - self.assertEqual(RICH_GAS_COMPOSITION["methane"], 0.720) - self.assertIn("n-octane", RICH_GAS_COMPOSITION) - - def test_rejects_invalid_controls_before_native_execution(self): - with self.assertRaisesRegex(ValueError, "Temperature must be finite"): - validate_controls(PhaseControls(temperature_c=math.nan)) - with self.assertRaisesRegex(ValueError, "Pressure must be between"): - validate_controls(PhaseControls(pressure_bara=500.0)) - with self.assertRaisesRegex(ValueError, "must use PhaseControls"): - validate_controls(object()) - - def test_rejects_invalid_timeout_before_native_execution(self): - with self.assertRaisesRegex(ValueError, "positive integer"): - run_phase_challenge(PhaseControls(), timeout_ms=1.5) - with self.assertRaisesRegex(ValueError, "positive integer"): - run_phase_challenge(PhaseControls(), timeout_ms="not-a-timeout") - - def test_every_native_property_target_is_required_to_win(self): - assessment = assess_phase_evidence(_winning_evidence()) - - self.assertTrue(assessment.won) - self.assertEqual(assessment.score, 1000) - self.assertTrue(all(check.passed for check in assessment.checks)) - - missing_property = assess_phase_evidence( - _winning_evidence(gas_z_factor=None) - ) - self.assertFalse(missing_property.won) - self.assertLess(missing_property.score, 1000) - self.assertIn( - "Gas compressibility", - {check.name for check in missing_property.checks if not check.passed}, - ) - - def test_wrong_phase_state_blocks_otherwise_matching_properties(self): - assessment = assess_phase_evidence( - _winning_evidence( - phase_types=("gas",), - liquid_fraction_mol_pct=None, - ) - ) - - self.assertFalse(assessment.won) - self.assertTrue(any("single-phase gas" in item for item in assessment.guidance)) - - def test_native_winning_window_and_starting_point_failure(self): - winning = run_phase_challenge(PhaseControls(50.0, 80.0)) - starting = run_phase_challenge(PhaseControls(20.0, 50.0)) - - self.assertTrue(winning.assessment.won) - self.assertEqual(winning.assessment.score, 1000) - self.assertFalse(starting.assessment.won) - self.assertEqual(winning.evidence.phase_types, ("gas", "oil")) - self.assertLessEqual( - winning.evidence.phase_fraction_closure_error, - 1.0e-10, - ) - self.assertEqual(len(winning.evidence.components), len(RICH_GAS_COMPOSITION)) - methane = next( - row for row in winning.evidence.components if row.component == "methane" - ) - octane = next( - row for row in winning.evidence.components if row.component == "n-octane" - ) - self.assertIsInstance(methane, ComponentEquilibrium) - self.assertGreater(methane.k_value, 1.0) - self.assertLess(octane.k_value, 1.0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_plant_operator_game.py b/tests/test_plant_operator_game.py deleted file mode 100644 index 911c192..0000000 --- a/tests/test_plant_operator_game.py +++ /dev/null @@ -1,208 +0,0 @@ -"""Unit tests for the NeqSim Plant Operator challenge contract.""" - -import math -from types import SimpleNamespace -import unittest - -from process_chat.plant_operator_game import ( - ChallengeControls, - ChallengeEvidence, - MAX_COOLING_DUTY_KW, - MAX_TOTAL_POWER_KW, - TARGET_FLOW_KG_HR, - assess_challenge, - build_challenge_spec, - collect_evidence, - run_challenge, - 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_rejects_non_convertible_timeout_with_public_value_error(self): - for timeout_ms in (None, "abc", True, 0, -1, 1.5, math.inf, math.nan): - with self.subTest(timeout_ms=timeout_ms): - with self.assertRaisesRegex( - ValueError, - "Challenge timeout must be a positive integer", - ): - run_challenge(ChallengeControls(), timeout_ms=timeout_ms) - - def test_unknown_native_validation_status_blocks_a_win(self): - class FakeOutlet: - def getTemperature(self, _unit): - return 40.0 - - def getPressure(self, _unit): - return 130.0 - - class FakeUnit: - def getOutletStream(self): - return FakeOutlet() - - class FakeModel: - def get_unit(self, _name): - return FakeUnit() - - result = SimpleNamespace( - kpis={ - "total_power_kW": SimpleNamespace(value=4_300.0), - "total_duty_kW": SimpleNamespace(value=6_500.0), - "mass_balance_pct": SimpleNamespace(value=0.001), - "energy_balance_pct": SimpleNamespace(value=0.002), - }, - constraints=( - SimpleNamespace(name="unit_balance_coverage", status="UNKNOWN"), - SimpleNamespace(name="execution_quality", status="WARN"), - ), - ) - - evidence = collect_evidence( - ChallengeControls(feed_flow_kg_hr=TARGET_FLOW_KG_HR), - FakeModel(), - result, - ) - assessment = assess_challenge(evidence) - - self.assertEqual(evidence.native_violations, ("unit_balance_coverage",)) - self.assertFalse(assessment.won) - native_check = next( - check - for check in assessment.checks - if check.name == "Native NeqSim checks" - ) - self.assertFalse(native_check.passed) - - 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_150.0, - total_cooling_duty_kw=5_450.0, - specific_power_kwh_per_tonne=37.7, - 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)) - native_check = next( - check - for check in assessment.checks - if check.name == "Native NeqSim checks" - ) - self.assertEqual(native_check.actual, "No failed or unavailable checks") - self.assertGreaterEqual(assessment.score, 700) - self.assertLessEqual(assessment.score, 1000) - - def test_power_and_cooling_limits_are_strict(self): - evidence = ChallengeEvidence( - feed_flow_kg_hr=TARGET_FLOW_KG_HR, - export_pressure_bara=128.0, - export_temperature_c=45.0, - stage_1_discharge_temperature_c=70.0, - stage_2_discharge_temperature_c=70.0, - total_power_kw=MAX_TOTAL_POWER_KW, - total_cooling_duty_kw=MAX_COOLING_DUTY_KW, - specific_power_kwh_per_tonne=38.0, - mass_balance_error_pct=0.0, - energy_balance_error_pct=0.0, - native_violations=(), - ) - - assessment = assess_challenge(evidence) - failed = {check.name for check in assessment.checks if not check.passed} - - self.assertFalse(assessment.won) - self.assertEqual( - {"Compression power", "Cooling-system load"}, - failed, - ) - checks = {check.name: check for check in assessment.checks} - self.assertEqual(checks["Compression power"].actual, "4,200.00 kW") - self.assertEqual(checks["Cooling-system load"].actual, "5,500.00 kW") - - 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() diff --git a/tests/test_plant_operator_page.py b/tests/test_plant_operator_page.py deleted file mode 100644 index 6448eb4..0000000 --- a/tests/test_plant_operator_page.py +++ /dev/null @@ -1,98 +0,0 @@ -"""Source-level regression tests for the Plant Operator Streamlit page.""" - -import ast -import os -from pathlib import Path -import unittest -from unittest.mock import patch - -from streamlit.testing.v1 import AppTest - -PROJECT_ROOT = Path(__file__).resolve().parents[1] -PAGE_PATH = PROJECT_ROOT / "pages" / "36_NeqSim_Plant_Operator.py" -GAMES_PAGE_PATH = PROJECT_ROOT / "pages" / "34_NeqSim_Games.py" - - -class PlantOperatorPageTest(unittest.TestCase): - """Keep the game discoverable, bounded, accessible, and interoperable.""" - - def test_page_is_valid_python_and_registered_in_games_hub(self): - source = PAGE_PATH.read_text(encoding="utf-8") - ast.parse(source) - games_source = GAMES_PAGE_PATH.read_text(encoding="utf-8") - self.assertIn("pages/36_NeqSim_Plant_Operator.py", games_source) - - 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('st.switch_page("pages/34_NeqSim_Games.py")', 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) - self.assertIn("_existing_java_tool_options", source) - self.assertIn("_existing_java_tokens", source) - self.assertIn("_missing_jvm_opens", source) - self.assertIn("option not in _existing_java_tokens", source) - - def test_page_reconciles_partial_jvm_opens_without_dropping_options(self): - existing = ( - "--enable-native-access=ALL-UNNAMED " - "--add-opens=java.base/java.net=ALL-UNNAMED " - "--add-opens=java.base/java.util=ALL-UNNAMED" - ) - required = ( - "--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", - ) - - with patch.dict(os.environ, {"JAVA_TOOL_OPTIONS": existing}): - app = AppTest.from_file(str(PAGE_PATH)).run(timeout=30) - options = os.environ["JAVA_TOOL_OPTIONS"].split() - - 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("--enable-native-access=ALL-UNNAMED", options) - self.assertIn("--add-opens=java.base/java.net=ALL-UNNAMED", options) - for required_option in required: - self.assertEqual(options.count(required_option), 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_studio_navigation.py b/tests/test_studio_navigation.py index e7dc80b..721809d 100644 --- a/tests/test_studio_navigation.py +++ b/tests/test_studio_navigation.py @@ -48,15 +48,6 @@ 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_games_is_the_available_training_workflow_hub(self): - destination = destination_by_key("games") - - self.assertTrue(destination.available) - self.assertEqual( - destination.page, - "pages/34_NeqSim_Games.py", - ) - def test_unknown_destination_fails_loudly(self): with self.assertRaisesRegex(KeyError, "Unknown Studio destination"): destination_by_key("not-a-real-workflow") diff --git a/tests/test_workspace_http_health.py b/tests/test_workspace_http_health.py index 39f6aff..30c58a6 100644 --- a/tests/test_workspace_http_health.py +++ b/tests/test_workspace_http_health.py @@ -22,10 +22,7 @@ "pages/00_NeqSim_Studio.py", "pages/10_Studio_Results.py", "pages/25_Pipeline.py", - "pages/34_NeqSim_Games.py", "pages/35_Process_Flowsheet_Studio.py", - "pages/36_NeqSim_Plant_Operator.py", - "pages/37_NeqSim_Phase_Equilibrium_Lab.py", "pages/90_Process_Chat.py", } ) @@ -137,15 +134,6 @@ 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_games_http_health(self): - self._probe_streamlit_page("pages/34_NeqSim_Games.py") - - def test_neqsim_plant_operator_http_health(self): - self._probe_streamlit_page("pages/36_NeqSim_Plant_Operator.py") - - def test_phase_equilibrium_lab_http_health(self): - self._probe_streamlit_page("pages/37_NeqSim_Phase_Equilibrium_Lab.py") - def test_process_chat_http_health(self): self._probe_streamlit_page("pages/90_Process_Chat.py")