Neqsim dynamic equipment implementation

From equinor/neqsim · View interactive version

Neqsim dynamic equipment implementation is an AI agent skill from the GitHub repository equinor/neqsim. Implement and test NeqSim process-equipment runTransient support. USE WHEN: adding dynamic simulation behavior to any ProcessEquipmentInterface class, including inventory volume, pressure/level/temperature state, controller response, and JUnit regression tests for transient timesteps.

How to use this skill

Skill file

Dynamic Equipment Implementation

Use this skill when a NeqSim equipment class needs real dynamic simulation support instead of the default steady-state fallback or unsupported transient behavior.

This complements neqsim-dynamic-simulation, which explains how to run dynamic studies. This skill explains how to implement and test the Java code that makes equipment participate correctly in ProcessSystem.runTransient(dt, id).

Local Architecture

Implementation Decision Tree

  1. Is the equipment purely algebraic?
  1. Does the equipment hold mass or energy inventory?
  1. Does the equipment have actuator or mechanical state?
  1. Does the equipment need thermal inertia?

Required Code Pattern

For any new transient implementation:

  1. Add serializable state fields with defaults that preserve existing steady-state behavior.
  2. Add public setters/getters for dynamic configuration such as volume, residence time, metal mass, ramp rate, or initial inventory.
  3. Override runTransient(double dt, UUID id).
  4. Keep the steady-state branch first:
  1. Initialize transient state lazily on the first dynamic step from the last steady-state solution.
  2. Run controllers or actuator logic before solving the equipment response when the class exposes controller behavior.
  3. Integrate component and energy balances over the timestep:
  1. Re-flash the updated inventory with the appropriate flash operation (TPflash, TVflash, PHflash, or VUflash) and call initProperties() or the class-equivalent physical-property initialization before reading transport properties.

After a VUflash, check OptimizedVUflash.isLastRunConverged(). When a vessel step is slow, wasColdFallbackUsed(),

wasEquilibriumRecoveryUsed(), getEquilibriumRecoveryFlashCount() and wasEquilibriumPolishUsed() show which

fallback stage closed the volume/energy specification (stages run in that order, cheapest first). In a healthy

three-phase vessel run all of them stay false/zero; repeated fallbacks point at the inner TP flash, not the vessel

model. In a JUnit test of a captured vessel state, assert that no fallback was needed, and call the

OptimizedVUflash constructor with volume in NeqSim's internal unit (m3 x 1e5), as ThermodynamicOperations.VUflash

converts it.

  1. Update every outlet stream from the new state and preserve mass/energy consistency.
  2. For explicit inventory integration, override getMaxStableTransientTimeStep() (from ProcessEquipmentInterface,

default positive infinity) with the largest stable step for the current state, valid before and after transient

initialization. Separator returns 0.1 * gasDensity * gasVolume / max(inletMassFlow, outletMassFlow).

ProcessSystem.runTransient splits each requested step below the smallest unit value and, with complete

TransientStateParticipant coverage, rolls back and retries sub-steps that throw or that end in a state whose

limit is under 25 % of the step taken. Units without a limit are never sub-stepped on their own account.

  1. Call increaseTime(dt) and set the calculation identifier before returning.

Equipment Configuration Guidance

Dynamic behavior needs physical capacity. Prefer existing mechanical-design data when it already exists, but expose a simple runtime configuration path for simulations:

Do not hide required dynamic capacity behind mechanical design only. Task notebooks and MCP workflows need direct, documented setters for dynamic parameters.

Testing Requirements

Create focused JUnit 5 tests under the matching package in src/test/java/neqsim/....

Minimum test coverage for each dynamic implementation:

  1. Steady-state compatibility: runTransient(dt, id) with calculateSteadyState=true matches or preserves the existing run(id) behavior.
  2. Dynamic branch executes: with calculateSteadyState=false, runTransient(dt, id) does not throw and advances equipment time.
  3. Inventory response: a flow, heat, pressure, valve-opening, speed, or level disturbance changes a physically relevant state in the expected direction.
  4. Mass balance: integrated inlet minus outlet accumulation matches inventory change within a reasonable tolerance.
  5. Energy or temperature response: when relevant, heat/work input changes internal energy, outlet temperature, or pressure consistently.
  6. Controller interaction: if the equipment has controllers, verify one timestep calls/runs controller logic and applies bounded output.
  7. Bounds and robustness: zero/low flow, empty inventory, small dt, and repeated timesteps remain finite and non-negative.
  8. Serialization/copy safety: if new fields are non-serializable, mark them transient; otherwise verify normal equipment copy behavior still works.

Use physical assertions, not private implementation details. Prefer monotonic or bounded assertions over fragile exact transient values unless a regression baseline is intentional.

Validation Commands

After editing Java files in the NeqSim repo, run:

mvnw.cmd spotless:apply
mvnw.cmd test "-Dtest=YourDynamicTest"
mvnw.cmd spotless:check

When public APIs or JavaDoc were added or changed, also run:

mvnw.cmd javadoc:javadoc

When only agent/skill files were edited, run:

uv run --project devtools --locked devtools/verify_skills_agents.py
uv run --project devtools --locked devtools/generate_agent_skill_map.py
uv run --project devtools --locked devtools/verify_skills_agents.py

Common Pitfalls

For TwoFluidPipe and related finite-volume code, include all three phase inventories in

rejection/positivity checks, even though the class name says two-fluid. Preserve phase identity

at exact water-cut endpoints and separate phase momenta through primitive/conservative recovery.

Distinguish explicit caller velocities from internal recovery: test legacy bulk updates after

recovery, recovered slip, and zero-to-positive phase appearance without overwriting donor momentum.

Pressure-correction face fluxes must share each donor phase's inventory budget. A positivity repair

that moves mass between phases can hide a phase-balance defect behind an exact total-mass balance.

Source-splitting helpers must not run primitive recovery on an invalid trial before its rejection

check; exercise the same negative-phase test with stiff source terms enabled.

Rollback must restore configured closures and their accepted diagnostics, pressure and phase

densities as well as the state vector; a generic clone may discard transient closure fields.

Pressure and density must use the same applied correction after bounds. Independent cell clipping

can reverse Newton face directions and make an upwind active set cycle; test bounded convergence.

A substep budget

must never enlarge a CFL-limited step or silently truncate a requested interval; compare accepted

time with both equipment and solver clocks. Tracker overlay inventory is separate from Eulerian

inventory, so dissolution must not return mass that initialization never withdrew. Read

docs/wiki/two_fluid_reporting_and_validation.md for the distinction between numerical regression

coverage and currently disabled experimental qualification gates.

Conservative slug/film coupling uses subcell reconstruction with the Eulerian seven-variable

state as the sole inventory. Assert that every reconstructed variable averages back to its cell

value, including energy after momentum redistribution. Enthalpy reference shifts must not change

the reconstruction. Recover positive trace-phase velocities from their exact momentum/mass

ratios so primitive recovery thresholds cannot alter the numerical flux. Use one shared face

flux per phase, with independent oil/water donors when slip is enabled, and cancel the pressure

part using the same phase face holdups and pressures. Test gas-free and one-cell limits explicitly.

Subcell face holdup can greatly exceed its cell average: include the phase-inventory draining

time in the CFL limit, not only reconstructed velocities. Test a thin body crossing a cell face.

Closed boundaries must constrain the external flux after reconstruction; zeroing cell velocities

alone does not prevent a reconstructed slug from leaking through a valve. Prescribed feeds

belong on external face states, not in the evolving cell density/momentum/holdup inventory.

For total energy, transport phase enthalpy plus kinetic energy, include gravitational work,

and do not add stationary-wall friction dissipation as an external energy source.

Independent experimental comparisons must retain source-cell provenance, source-definition

ambiguities, missing predictions and predeclared tolerances. A prescribed-flow marker experiment

tests a closure; label an actual time-marching pipe comparison separately. Coordinate source

freezes across agents before builds because desktop background compilers can modify target/classes.

Test initially volume-exact alternating pressure and velocity modes before claiming convective-CFL

stability of a collocated pressure correction. Include pressure-correction face transfers in

component/thermal transport after acceptance; global energy conservation alone does not establish

local EOS/pressure-work consistency. Record slug crossings during accepted motion and distinguish

union-occupancy changes from internal endpoints or instantaneous merge/birth geometry.

Reject nonfinite or negative raw phase predictors even when adaptive retry is disabled;

fixed stepping must fail at the last accepted state instead of using a positivity repair

to hide lost phase inventory. Separate clock-resolution/invalid-step failures from actual

attempt-budget exhaustion. A configured minimum timestep must never enlarge a CFL bound.

Pressure-solve convergence must include prescribed boundary pressure as well as volume

closure, and reset/failed steps must clear stale correction results and transfer ledgers.

Exercise five-/six-variable legacy inputs after a populated seven-variable state, including

zero and trace liquid. Do not suppress positive trace holdup in an interior flux while

external faces still transport it. For variable areas, match the momentum flux's face area

in the geometric pressure source. At either boundary, preserve each positive phase holdup

directly; subtracting a nearly unit gas fraction can round a trace liquid to zero. Evaluate

all tracked-interface kinematics against the

same accepted geometry before moving any marker; count reverse inlet exits separately

from downstream outlet arrivals without depositing overlay mass into Eulerian cells.

freshly flashed inventory phases, preserve configured valve-capacity flow rates, and initialize properties without

another equilibrium flash. This keeps outlets current and avoids multiplying expensive CPA flashes per timestep.

Handoff Checklist

Before considering a dynamic equipment implementation complete, confirm:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.