# Neqsim Compressor Antisurge Recycle

> Set up anti-surge recycle control for a centrifugal compressor in NeqSim, including compressor-chart generation, steady-state AntiSurgeRecycleCalculator use, dynamic AntiSurgeController PI control, and CompressorAntiSurgeApplication topology binding for hot/cold recycle valves and speed runback. USE WHEN: a task needs to protect a NeqSim compressor from surge with a recycle (spill-back) loop and…

- **Type:** Skill
- **Install:** `agentstack add skill-equinor-neqsim-community-skills-compressor-antisurge-recycle`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [equinor](https://agentstack.voostack.com/s/equinor)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** Apache-2.0
- **Upstream author:** [equinor](https://github.com/equinor)
- **Source:** https://github.com/equinor/neqsim-community-skills/tree/main/skills/process/compressor-antisurge-recycle
- **Website:** https://equinor.github.io/neqsimhome/

## Install

```sh
agentstack add skill-equinor-neqsim-community-skills-compressor-antisurge-recycle
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Compressor Anti-Surge Recycle Setup

This skill explains how to protect a centrifugal compressor against surge in a
NeqSim `ProcessSystem` by adding a recycle (spill-back) loop. It covers the
preferred steady-state helper (`AntiSurgeRecycleCalculator`), the dynamic
reverse-acting PI controller (`AntiSurgeController`), and the application-level
supervisor (`CompressorAntiSurgeApplication`) that can bind directly to real
NeqSim topology objects such as a compressor, hot recycle valve, cold recycle
valve, cooler, mixer, recycle blocks, and `ProcessSystem`. It also explains how
to **auto-generate a compressor chart with surge and stonewall curves** when no
vendor chart is available, because every anti-surge option needs a surge limit
to act against.

The pure-Python helper (`AntiSurgeRecycleModel`) is an educational planning aid
that mirrors NeqSim's proportional anti-surge step so an agent can pre-estimate
the recycle flow and decide whether a chart must be generated first. Real
control design must use the validated NeqSim equipment classes below and a
qualified rotating-equipment review (API 617 / API 692).

## When to Use

Use this skill when:

- A NeqSim compressor operating point can fall to the left of its surge line at
  low throughput (turndown, start-up, trips) and needs recycle protection.
- You must build the anti-surge recycle topology (surge curve, recycle stream,
  discharge splitter or recycle branch, anti-surge valve, `Recycle`, and
  optional cooler/mixer).
- You need an executable dynamic application model where
  `CompressorAntiSurgeApplication` writes hot/cold recycle valve openings and
  optional compressor speed runback to real NeqSim units.
- **No vendor compressor chart is provided** and a chart with surge and
  stonewall curves must be generated from the compressor's design point.
- You want a screening estimate of the recycle flow required to keep the
  compressor off surge before running the full simulation.

Do not use this skill as a substitute for vendor performance maps, anti-surge
controller tuning, dynamic surge/transient analysis, or rotating-equipment
design review.

## Inputs

- Compressor inlet (suction) volumetric flow at the operating point (m3/h).
- Surge-limit flow at the operating head and speed (m3/h). When no vendor chart
  is available, this comes from the generated surge curve.
- Whether a vendor compressor chart is provided (`chart_provided`).
- Existing recycle flow, if any (m3/h).
- For chart generation: a design speed, the number of speed lines, and
  optionally impeller diameter / number of stages for advanced corrections.

## Outputs

- `needs_chart_generation` — whether a chart must be generated before control.
- `in_surge` — whether the operating point is at or below the surge flow.
- `surge_margin_fraction` — `(inlet_flow - surge_flow) / surge_flow`.
- `recommended_recycle_flow` — screening recycle flow to add at suction (m3/h).
- `total_suction_flow` — inlet flow plus recommended recycle (m3/h).
- `recycle_warning` — `ok`, `recycle`, or `surge`.
- Assumptions and limitations.

## Engineering Method

A centrifugal compressor surges when the inlet volumetric flow drops below the
surge flow at the current head/speed. Anti-surge control opens a recycle line
from discharge back to suction to keep the **total** suction flow above the
surge limit plus a margin.

For steady-state recycle sizing and initialization, prefer
`AntiSurgeRecycleCalculator` for a charted compressor. It runs the compressor,
checks natural inlet flow against the surge-control line, and iterates a cooled
recycle stream until the target distance-to-surge margin is met. Use the older
splitter-based `Calculator` / `AntiSurgeCalculator` pattern only when you need
to reproduce an existing flowsheet that already uses a discharge splitter.

The legacy splitter-based topology is:

1. A **surge curve** on the compressor chart provides the surge flow versus head.
2. A low-flow **recycle stream** is added into the compressor suction.
3. A **splitter** on the compressor discharge creates a forward branch
   (`getSplitStream(0)`) and a recycle branch (`getSplitStream(1)`).
4. An **anti-surge `Calculator`** (legacy name-prefix API) or typed
  `AntiSurgeCalculator` reads the compressor and writes the splitter recycle
  flow each iteration. Internally it compares the inlet flow to the surge flow:
  far from surge (`inlet_flow > 1.2 * surge_flow`) it drives recycle to a
  minimum; otherwise it adds a proportional, capped step
  `0.5 * (surge_flow - inlet_flow)` to the recycle branch.
5. An **anti-surge valve** on the recycle branch drops the discharge pressure
   back to suction pressure.
6. A **`Recycle`** unit closes the loop, feeding the valve outlet back into the
   placeholder suction recycle stream.

### Generating a Compressor Chart When None Is Given

The anti-surge loop needs a surge limit, so if no vendor chart exists a chart
must be generated first. NeqSim builds a chart from the compressor's design
operating point and **automatically populates both the surge curve and the
stonewall curve**:

- `Compressor.generateCompressorChart("normal curves", numberOfSpeeds)` builds a
  multi-speed chart whose lowest-flow points form the surge curve and whose
  highest-flow points form the stonewall curve.
- `CompressorChartGenerator` gives finer control (chart type, Reynolds/Mach
  corrections, multistage surge correction, impeller diameter) and also returns
  a chart with surge and stonewall curves attached.

After generation, the surge flow at the operating head is available through
`Compressor.getSurgeFlowRate()` and the distance to surge through
`Compressor.getDistanceToSurge()`.

The `AntiSurgeRecycleModel` mirrors step 4 so you can estimate the recycle flow
and flag whether chart generation (`needs_chart_generation`) is required before
wiring the loop.

## Python Usage Pattern

Screening estimate of the recycle flow (no NeqSim required):

```python
from compressor_antisurge_recycle import AntiSurgeRecycleModel

model = AntiSurgeRecycleModel()
plan = model.plan(
    inlet_flow=4200.0,   # m3/h at suction
    surge_flow=5000.0,   # m3/h surge limit at operating head
    chart_provided=True,
    current_recycle=0.0,
)
print(plan.recommended_recycle_flow, plan.recycle_warning)
```

Generate a compressor chart (with surge and stonewall curves) when none is
given, using NeqSim through the `neqsim` package:

```python
from neqsim import jneqsim

# `compressor` is an existing neqsim.process.equipment.compressor.Compressor
compressor.setSpeed(8000.0)   # design speed (rpm)
compressor.run()              # solve the design point first
compressor.generateCompressorChart("normal curves", 5)  # 5 speed lines

# Surge and stonewall curves are now populated automatically.
chart = compressor.getCompressorChart()
surge_flow = compressor.getSurgeFlowRate()
distance_to_surge = compressor.getDistanceToSurge()
```

Finer control with the generator (optional corrections):

```python
from neqsim import jneqsim

generator = jneqsim.process.equipment.compressor.CompressorChartGenerator(compressor)
generator.setChartType("interpolate and extrapolate")
generator.enableAdvancedCorrections(numberOfStages)  # Reynolds + Mach + multistage
chart = generator.generateCompressorChart("normal curves", 5)
compressor.setCompressorChart(chart)
```

Wire the anti-surge recycle loop (generic data, after a chart exists):

```python
from neqsim import jneqsim

splitter_pkg = jneqsim.process.equipment.splitter
valve_pkg = jneqsim.process.equipment.valve
util_pkg = jneqsim.process.equipment.util

suction_pressure = compressor.getInletStream().getPressure("bara")

# 2. Low-flow placeholder recycle stream into the compressor suction.
recycle_gas = compressor.getInletStream().clone()
recycle_gas.setName("anti surge recycle gas")
recycle_gas.setFlowRate(1.0, "kg/hr")
recycle_gas.run()
process.add(recycle_gas)

# 3. Splitter on the compressor discharge: branch 0 forward, branch 1 recycle.
gas_splitter = splitter_pkg.Splitter("anti surge splitter", compressor.getOutletStream(), 2)
gas_splitter.run()
process.add(gas_splitter)

# 4. Anti-surge Calculator (name MUST start with "anti surge calculator").
anti_surge_calc = util_pkg.Calculator("anti surge calculator 1")
anti_surge_calc.addInputVariable(compressor)
anti_surge_calc.setOutputVariable(gas_splitter)
process.add(anti_surge_calc)

# 5. Anti-surge valve on the recycle branch back to suction pressure.
anti_surge_valve = valve_pkg.ThrottlingValve("anti surge valve", gas_splitter.getSplitStream(1))
anti_surge_valve.setOutletPressure(suction_pressure, "bara")
anti_surge_valve.run()
process.add(anti_surge_valve)

# 6. Recycle unit closes the loop into the placeholder suction stream.
recycle = util_pkg.Recycle("recycle anti surge")
recycle.addStream(anti_surge_valve.getOutletStream())
recycle.setOutletStream(recycle_gas)
recycle.setTolerance(1e-2)
process.add(recycle)

process.run()
```

The forward process continues on `gas_splitter.getSplitStream(0)`.

Preferred steady-state helper for a charted compressor:

```java
AntiSurgeRecycleCalculator calc = new AntiSurgeRecycleCalculator(compressor, suctionStream);
calc.setSurgeControlMargin(0.10);
calc.setRecycleCoolerTemperature(35.0, "C");
AntiSurgeRecycleCalculator.Result result = calc.solve();
```

## Dynamic Anti-Surge Control (AntiSurgeController)

The `Calculator`-driven loop above is a **steady-state** recycle solver. For a
**dynamic (transient)** anti-surge response, NeqSim provides a dedicated
reverse-acting PI controller, `AntiSurgeController`
(`neqsim.process.controllerdevice.AntiSurgeController`), that reads
`Compressor.getDistanceToSurge()` and drives a recycle `ThrottlingValve` open as
the margin falls below the set point, then closes it again on recovery.

```python
from neqsim import jneqsim

controllerdevice = jneqsim.process.controllerdevice

# `recycle_valve` is the anti-surge ThrottlingValve on the recycle branch.
asc = controllerdevice.AntiSurgeController("anti-surge", compressor, recycle_valve)
asc.setSurgeMarginSetPoint(0.10)   # protect a 10% distance-to-surge margin
asc.setProportionalGain(400.0)     # percent opening per unit margin error
asc.setIntegralTime(20.0)          # s
asc.setOpeningRange(0.0, 100.0)    # valve opening clamp (%) with anti-windup
asc.setActive(True)
recycle_valve.addController("anti-surge", asc)
```

Control law each transient step: `error = setPoint - distanceToSurge`,
`integral += Kp/Ti * error * dt`, `opening = clamp(Kp*error + integral)` with
anti-windup. A reproducible benchmark,
`neqsim.process.util.scenario.AntiSurgeDynamicBenchmark`, drives the real
controller against a transparent first-order gas-path surrogate
(`m_next = m - disturbance*dt + authority*(opening/100)*dt`) and is the preferred
way to verify or tune the control law without solver fragility.

**Critical gotchas when building a full dynamic recycle flowsheet:**

- A fixed-factor `Splitter` (`setSplitFactors([0.97, 0.03])`) **pins the recycle
  fraction** in dynamic mode, so the anti-surge valve has no authority over the
  actual recycle flow — it can reach 100% open with no effect. Let the recycle
  flow be set by the valve (`Cv`/resistance), or keep the steady-state
  `Calculator` pattern.
- Once the operating point crosses left of the surge line,
  `getDistanceToSurge()` **clamps at -1.0 and the steady solver cannot recover**;
  a flowsheet driven into deep surge will not self-heal even after the inlet is
  reopened. Apply gradual/ramped disturbances and keep the machine off deep surge.
- Aggressive proportional gain can slam the recycle valve to minimum opening,
  starve a stream, and trigger an SRK flash `NaN`
  (`PhaseSrkEos:molarVolume ... NaN`). Keep gains moderate.

Dynamic controller tuning and transient surge analysis still require qualified
rotating-equipment review (API 617 / API 692).

## Application-Level Dynamic Topology Binding

For realistic dynamic studies with coordinated pressure, speed, hot recycle, and
cold recycle behavior, use `CompressorAntiSurgeApplication`. It is a
deterministic supervisory scan layer that can write directly to real NeqSim
objects and then advance the bound process one transient step.

```java
CompressorAntiSurgeApplication application = new CompressorAntiSurgeApplication("export compression");
CompressorAntiSurgeApplication.StageApplication stage = application.addStage("K-101");

CompressorAntiSurgeApplication.TopologyBinding binding = stage.bindTopology(
  process,
  compressor,
  hotRecycleValve,
  coldRecycleValve,
  recycleCooler,
  suctionMixer,
  hotRecycle,
  coldRecycle);
binding.enableSpeedControl(95.0, 25.0, 8500.0, 12500.0, 150.0);

application.setRunningMode();
application.runDynamicStep(null, 0.25);
```

When the scan input is `null`, the stage reads the bound compressor margin and
inlet flow where available, falls back to the stage design basis where needed,
writes the hot and cold recycle valve openings, applies the optional compressor
speed command/runback, and advances the bound `ProcessSystem` with
`runTransient()`. Keep `Recycle` blocks algebraic unless the specific class has
transient inventory support; the valve, compressor, cooler, mixer, and any
volume-capable equipment carry the dynamic response.

`CompressorAntiSurgeApplication` is still a simulation and advisory layer. Its
certification status remains `NOT_CERTIFIED_FOR_PROTECTION`; use it for
engineering studies, training, digital twins, and commissioning evidence, not as
a certified machinery-protection package.

## Validation Checklist

- The compressor has a chart with an active surge curve before the loop runs;
  if not, generate one and confirm `getSurgeCurve().isActive()` is true.
- For steady-state recycle initialization, use `AntiSurgeRecycleCalculator` when
  practical; if using the legacy splitter path, the anti-surge `Calculator` name
  starts with `"anti surge calculator"` or the typed `AntiSurgeCalculator` is
  used.
- For the legacy splitter path, the `Calculator` input is the `Compressor` and
  the output is the discharge `Splitter`.
- The anti-surge valve sits on `getSplitStream(1)` and drops to suction pressure.
- The `Recycle` outlet stream is the placeholder suction recycle stream.
- After `process.run()`, the total suction flow exceeds the surge flow plus the
  intended margin (`getDistanceToSurge()` is positive).
- Recycle convergence tolerance is set (for example `setTolerance(1e-2)`).
- For `CompressorAntiSurgeApplication` topology binding, hot/cold recycle valves
  are real `ThrottlingValve` units, speed-control limits are bounded, and
  `runDynamicStep(...)` is used only after the process has a converged initial
  state.

## Common Mistakes

- Naming the legacy calculator anything that does not start with
  `"anti surge calculator"` — the legacy anti-surge logic then never triggers.
- Wiring the anti-surge valve to the forward branch `getSplitStream(0)` instead
  of the recycle branch `getSplitStream(1)`.
- Running the loop without a surge curve, so there is no surge flow to compare
  against (generate a chart first when no vendor chart is given).
- Using a zero or negative placeholder recycle flow that the `Recycle` cannot
  converge from; start from a small positive flow (for example 1 kg/hr).
- Reading the surge flow at the wrong head or speed — the surge flow must match
  the operating head and speed.
- Treating the generated chart as a vendor-validated map; generated charts are
  estimates for modelling, not design certification.
- For dynamic studies, leaving a fixed-factor `Splitter` on the recycle branch so
  the `AntiSurgeController` valve has no authority over the recycle flow.
- Driving a dynamic recycle flowsheet straight into deep surge, where
  `getDistanceToSurge()` clamps at -1.0 and the steady solver cannot recover.

## Limitations

- Screening logic only; it does not tune an anti-surge controller or set
  recycle valve `Cv`, response time, or surge control line

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [equinor](https://github.com/equinor)
- **Source:** [equinor/neqsim-community-skills](https://github.com/equinor/neqsim-community-skills)
- **License:** Apache-2.0
- **Homepage:** https://equinor.github.io/neqsimhome/

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-equinor-neqsim-community-skills-compressor-antisurge-recycle
- Seller: https://agentstack.voostack.com/s/equinor
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
