### Install neqsim_dev_setup Package Source: https://github.com/equinor/neqsim/blob/master/docs/development/jupyter_development_workflow.md Install the development setup module in editable mode. This ensures that any changes made to the module files are immediately reflected in the project. ```bash pip install -e devtools/ ``` -------------------------------- ### Python Example: Integrated Optimization Setup Source: https://github.com/equinor/neqsim/blob/master/docs/emissions/index.md Sets up a NEQSim process model with specified operating parameters. Requires NEQSim and SciPy libraries. ```python from neqsim import jneqsim from scipy.optimize import minimize, differential_evolution import numpy as np # === SETUP NEQSIM PROCESS MODEL === def create_process(sep_pressure, sep_temp, compressor_speed): """Create offshore process with given operating parameters.""" # Reservoir fluid fluid = jneqsim.thermo.system.SystemSrkCPAstatoil(273.15 + 80, 50.0) fluid.addComponent("water", 0.15) fluid.addComponent("CO2", 0.02) fluid.addComponent("methane", 0.60) fluid.addComponent("ethane", 0.10) fluid.addComponent("propane", 0.08) fluid.addComponent("n-butane", 0.05) fluid.setMixingRule(10) # Build process Stream = jneqsim.process.equipment.stream.Stream Separator = jneqsim.process.equipment.separator.Separator Compressor = jneqsim.process.equipment.compressor.Compressor inlet = Stream("Well-Feed", fluid) inlet.setFlowRate(50000, "kg/hr") inlet.setTemperature(sep_temp, "C") inlet.setPressure(sep_pressure, "bara") sep = Separator("HP-Sep", inlet) compressor = Compressor("Export-Comp", sep.getGasOutStream()) compressor.setOutletPressure(120.0, "bara") compressor.setPolytropicEfficiency(0.75) # Run simulation process = jneqsim.process.processmodel.ProcessSystem() process.add(inlet) process.add(sep) process.add(compressor) process.run() return process, sep, compressor ``` -------------------------------- ### Python Quick Start with NeqSim Source: https://github.com/equinor/neqsim/blob/master/README.md Install NeqSim using pip and run a basic thermodynamic system simulation with a flash calculation. This example demonstrates creating a natural gas fluid, setting components and mixing rules, and performing a TP flash. ```bash pip install neqsim ``` ```python from neqsim import jneqsim # Create a natural gas fluid fluid = jneqsim.thermo.system.SystemSrkEos(273.15 + 25.0, 60.0) # 25°C, 60 bara fluid.addComponent("methane", 0.85) fluid.addComponent("ethane", 0.10) fluid.addComponent("propane", 0.05) fluid.setMixingRule("classic") # Run a flash calculation ops = jneqsim.thermodynamicoperations.ThermodynamicOperations(fluid) ops.TPflash() fluid.initProperties() print(f"Gas density: {fluid.getPhase('gas').getDensity('kg/m3'):.2f} kg/m³") print(f"Gas viscosity: {fluid.getPhase('gas').getViscosity('kg/msec'):.6f} kg/(m·s)") print(f"Z-factor: {fluid.getPhase('gas').getZ():.4f}") ``` -------------------------------- ### Python Basic Setup with JPype and NeqSim Source: https://github.com/equinor/neqsim/blob/master/docs/integration/EXTERNAL_OPTIMIZER_INTEGRATION.md Start the Java Virtual Machine with NeqSim JARs and import necessary NeqSim and Python modules for process simulation and optimization. ```python import jpype import jpype.imports import numpy as np from scipy.optimize import minimize, differential_evolution # Start JVM with NeqSim jpype.startJVM(classpath=['neqsim.jar']) from neqsim.process.util.optimizer import ProcessSimulationEvaluator from neqsim.process.processmodel import ProcessSystem from neqsim.process.equipment.stream import Stream from neqsim.process.equipment.valve import ThrottlingValve from neqsim.thermo.system import SystemSrkEos ``` -------------------------------- ### NeqSim Setup and Initialization Source: https://github.com/equinor/neqsim/blob/master/examples/notebooks/process/offshore_wind_to_hydrogen.ipynb Sets up NeqSim by either loading from local development tools or installing and importing from the pip package. It initializes the NeqSim environment and imports necessary classes. ```python # NeqSim setup - dual-boot (devtools for local dev, pip for Colab) import importlib, subprocess, sys try: from neqsim_dev_setup import neqsim_init, neqsim_classes ns = neqsim_init(recompile=False) ns = neqsim_classes(ns) NEQSIM_MODE = "devtools" print("NeqSim loaded via devtools (local dev mode)") except ImportError: try: import neqsim except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "neqsim"]) from neqsim import jneqsim NEQSIM_MODE = "pip" print("NeqSim loaded via pip package") ``` -------------------------------- ### Setup NeqSim PaperLab environment Source: https://github.com/equinor/neqsim/blob/master/neqsim-paperlab/README.md Initializes the environment by navigating to the project directory and installing required dependencies. ```bash cd neqsim-paperlab pip install -r requirements.txt ``` -------------------------------- ### Setup NeqSim Development Environment Source: https://github.com/equinor/neqsim/blob/master/docs/tutorials/solve-engineering-task.md Commands to clone the repository, build the Java physics engine, and install necessary Python dependencies. ```powershell # Clone the repo git clone https://github.com/equinor/neqsim.git cd neqsim # Build NeqSim (compiles the Java physics engine) ./mvnw install # Linux/Mac mvnw.cmd install # Windows # Install Python helpers pip install -e devtools/ # NeqSim dev setup (boots JVM from your local build) pip install python-docx matplotlib # For reports and plots ``` -------------------------------- ### Simulate a Complete Pump System Source: https://github.com/equinor/neqsim/blob/master/docs/wiki/pump_usage_guide.md Full example demonstrating fluid system setup, pump curve definition, and simulation execution. ```java // Create fluid system SystemInterface water = new SystemSrkEos(298.15, 1.5); water.addComponent("water", 1.0); water.setTemperature(25.0, "C"); water.setPressure(1.5, "bara"); water.setTotalFlowRate(75.0, "m3/hr"); Stream feed = new Stream("Pump Feed", water); feed.run(); // Create pump with curve Pump pump = new Pump("Booster Pump", feed); double[] speed = new double[] {1450.0}; double[] flowPoints = {30, 50, 70, 90, 110, 130}; double[] headPoints = {45, 44, 42, 38, 32, 24}; double[] effPoints = {68, 76, 82, 84, 80, 70}; double[][] flow = new double[][] {flowPoints}; double[][] head = new double[][] {headPoints}; double[][] eff = new double[][] {effPoints}; pump.getPumpChart().setCurves(new double[]{}, speed, flow, head, eff); pump.getPumpChart().setHeadUnit("meter"); pump.setSpeed(1450.0); pump.setCheckNPSH(true); pump.setNPSHMargin(1.3); // Run simulation pump.run(); // Check results System.out.println("Outlet pressure: " + pump.getOutletPressure() + " bara"); System.out.println("Power: " + pump.getPower("kW") + " kW"); System.out.println("Outlet temp: " + pump.getOutletStream().getTemperature("C") + " °C"); System.out.println("NPSHa: " + pump.getNPSHAvailable() + " m"); System.out.println("Status: " + pump.getPumpChart().getOperatingStatus(75.0, 1450.0)); if (pump.isCavitating()) { System.out.println("WARNING: Cavitation risk!"); } ``` -------------------------------- ### Basic Production Optimization Setup (Java) Source: https://github.com/equinor/neqsim/blob/master/docs/examples/PRODUCTION_OPTIMIZATION_GUIDE.md Sets up a basic production optimization scenario in Java, initializing the optimizer and defining the system to be optimized. This is a starting point for more complex configurations. ```java ProductionOptimizer optimizer = new ProductionOptimizer(); ProcessSystem processSystem = new ProcessSystem(); optimizer.setProcessSystem(processSystem); ``` -------------------------------- ### Complete Process Integration Source: https://github.com/equinor/neqsim/blob/master/docs/integration/ai_platform_integration.md A comprehensive example demonstrating process system setup, virtual flow metering, online calibration, event bus subscription, and time-series data export. ```java // Create process system SystemInterface fluid = new SystemSrkEos(298.15, 50.0); fluid.addComponent("methane", 0.85); fluid.addComponent("ethane", 0.10); fluid.addComponent("propane", 0.05); fluid.setMixingRule("classic"); Stream inlet = new Stream("Inlet", fluid); inlet.setFlowRate(10000, "kg/hr"); inlet.run(); ProcessSystem process = new ProcessSystem(); process.add(inlet); // Setup streaming ProcessDataPublisher publisher = new ProcessDataPublisher(process); // Setup VFM VirtualFlowMeter vfm = new VirtualFlowMeter("VFM-1", inlet); // Setup online calibration OnlineCalibrator calibrator = new OnlineCalibrator(process); calibrator.setTunableParameters(Arrays.asList("efficiency")); calibrator.setDeviationThreshold(0.05); // Setup event bus ProcessEventBus eventBus = ProcessEventBus.getInstance(); eventBus.subscribe(ProcessEvent.EventType.MODEL_DEVIATION, event -> { // Trigger recalibration on significant deviation if (calibrator.getQualityMetrics().needsRecalibration()) { calibrator.fullRecalibration(); } }); // Setup data export TimeSeriesExporter exporter = new TimeSeriesExporter(process); // Real-time loop while (running) { // Run simulation step process.run(); // Publish streaming data publisher.publishFromProcessSystem(); // Get VFM estimate VFMResult vfmResult = vfm.calculate(); // Check for deviations if (Math.abs(vfmResult.getGasFlowRate() - measuredGasRate) / measuredGasRate > 0.1) { eventBus.publish(ProcessEvent.modelDeviation( "VFM-1", "gas_rate", measuredGasRate, vfmResult.getGasFlowRate() )); } // Record for calibration calibrator.recordDataPoint(measurements, predictions); // Collect for export exporter.collectSnapshot(); Thread.sleep(1000); } // Export training data String trainingData = exporter.exportToCsv(); ``` -------------------------------- ### Quick Process Simulation Example in Colab Source: https://github.com/equinor/neqsim/blob/master/docs/quickstart/colab-quickstart.md Build and run a simple process simulation including a separator and a compressor. This example demonstrates setting up streams, equipment, and running the process system. Requires NeqSim to be installed and imported. ```python from neqsim import jneqsim # Aliases for cleaner code SystemSrkEos = jneqsim.thermo.system.SystemSrkEos ProcessSystem = jneqsim.process.processmodel.ProcessSystem Stream = jneqsim.process.equipment.stream.Stream Separator = jneqsim.process.equipment.separator.Separator Compressor = jneqsim.process.equipment.compressor.Compressor # Create fluid fluid = SystemSrkEos(273.15 + 30, 50.0) fluid.addComponent("methane", 0.80) fluid.addComponent("ethane", 0.10) fluid.addComponent("propane", 0.05) fluid.addComponent("n-butane", 0.05) fluid.setMixingRule("classic") # Build process process = ProcessSystem() feed = Stream("Feed", fluid) feed.setFlowRate(5000, "kg/hr") process.add(feed) sep = Separator("Separator", feed) process.add(sep) comp = Compressor("Compressor", sep.getGasOutStream()) comp.setOutletPressure(100.0) process.add(comp) # Run process.run() # Results print(f"Gas rate: {sep.getGasOutStream().getFlowRate('kg/hr'):.0f} kg/hr") print(f"Liquid rate: {sep.getLiquidOutStream().getFlowRate('kg/hr'):.0f} kg/hr") print(f"Compressor power: {comp.getPower('kW'):.1f} kW") ``` -------------------------------- ### Complete Single-Speed Compressor Chart Example (Java) Source: https://github.com/equinor/neqsim/blob/master/docs/process/equipment/compressor_curves.md This example demonstrates the full setup for a single-speed compressor chart, including initializing the chart, adding performance maps at different molecular weights, and applying the chart to a compressor object. ```java CompressorChartMWInterpolation chart = new CompressorChartMWInterpolation(); chart.setHeadUnit("kJ/kg"); chart.setAutoGenerateSurgeCurves(true); chart.setAutoGenerateStoneWallCurves(true); double speed = 10000; // Single speed (RPM) // Map at MW = 18 g/mol double[] flow18 = {3000, 3500, 4000, 4500, 5000}; double[] head18 = {120, 115, 108, 98, 85}; double[] eff18 = {75, 78, 80, 78, 73}; chart.addMapAtMW(18.0, speed, flow18, head18, eff18); // Map at MW = 22 g/mol double[] flow22 = {2800, 3300, 3800, 4300, 4800}; double[] head22 = {100, 96, 90, 82, 71}; double[] eff22 = {73, 76, 78, 76, 71}; chart.addMapAtMW(22.0, speed, flow22, head22, eff22); // Use with compressor Compressor comp = new Compressor("K-100", inletStream); comp.setCompressorChart(chart); comp.setSpeed(speed); comp.run(); ``` -------------------------------- ### Setup NeqSim and Environment Source: https://github.com/equinor/neqsim/blob/master/examples/notebooks/process_extraction_from_document.ipynb Imports necessary libraries and sets up the NeqSim environment, either via local devtools or pip. Ensures python-docx is installed. ```python # --- Environment Setup (dual-boot: devtools or pip) --- import importlib, subprocess, sys try: from neqsim_dev_setup import neqsim_init, neqsim_classes ns = neqsim_init(recompile=False) ns = neqsim_classes(ns) NEQSIM_MODE = "devtools" print("NeqSim loaded via devtools (local dev mode)") except ImportError: try: import neqsim except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "neqsim"]) from neqsim import jneqsim NEQSIM_MODE = "pip" print("NeqSim loaded via pip package") # Ensure python-docx is available try: import docx except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "python-docx"]) import docx import json import os import matplotlib.pyplot as plt import numpy as np print(f"Mode: {NEQSIM_MODE}") ``` ```text Output: Classpath: 1. C:\Users\ESOL\Documents\GitHub\neqsim\target\classes 2. C:\Users\ESOL\Documents\GitHub\neqsim\src\main\resources 3. C:\Users\ESOL\Documents\GitHub\neqsim\target\neqsim-3.6.1.jar JVM started: C:\Users\ESOL\graalvm\graalvm-jdk-25.0.1+8.1\bin\server\jvm.dll Ready — call neqsim_classes(ns) to import classes All NeqSim classes imported OK NeqSim loaded via devtools (local dev mode) Mode: devtools ``` -------------------------------- ### Setup and Import NeqSim Classes Source: https://github.com/equinor/neqsim/blob/master/examples/notebooks/TwoFluidPipeMultiphaseFlowTutorial.ipynb Initializes the NeqSim environment, either using local development tools or the installed pip package. Imports necessary classes based on the detected mode. ```python import importlib, subprocess, sys try: from neqsim_dev_setup import neqsim_init, neqsim_classes ns = neqsim_init(recompile=False) ns = neqsim_classes(ns) NEQSIM_MODE = "devtools" print("NeqSim loaded via devtools (local dev mode)") except ImportError: try: import neqsim except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "neqsim"]) from neqsim import jneqsim NEQSIM_MODE = "pip" print("NeqSim loaded via pip package") ``` ```python # Import classes based on mode import numpy as np import matplotlib.pyplot as plt import pandas as pd import jpype if NEQSIM_MODE == "devtools": # Classes already on ns.* SystemSrkEos = ns.SystemSrkEos Stream = ns.Stream ProcessSystem = ns.ProcessSystem TwoFluidPipe = ns.JClass("neqsim.process.equipment.pipeline.TwoFluidPipe") PipeBeggsAndBrills = ns.JClass("neqsim.process.equipment.pipeline.PipeBeggsAndBrills") UUID = ns.JClass("java.util.UUID") else: # Load from jneqsim SystemSrkEos = jneqsim.thermo.system.SystemSrkEos Stream = jneqsim.process.equipment.stream.Stream ProcessSystem = jneqsim.process.processmodel.ProcessSystem TwoFluidPipe = jpype.JClass("neqsim.process.equipment.pipeline.TwoFluidPipe") PipeBeggsAndBrills = jpype.JClass("neqsim.process.equipment.pipeline.PipeBeggsAndBrills") UUID = jpype.JClass("java.util.UUID") print("Classes imported successfully") ``` -------------------------------- ### Basic Multi-Stream Heat Exchanger Setup in Python Source: https://github.com/equinor/neqsim/blob/master/docs/process/equipment/multistream_heat_exchanger.md This example demonstrates how to set up a basic multi-stream heat exchanger with known and unknown outlet temperatures. Ensure all necessary classes are imported from the neqsim library. ```python from neqsim import jneqsim # Import classes SystemSrkEos = jneqsim.thermo.system.SystemSrkEos Stream = jneqsim.process.equipment.stream.Stream MultiStreamHeatExchanger2 = jneqsim.process.equipment.heatexchanger.MultiStreamHeatExchanger2 ProcessSystem = jneqsim.process.processmodel.ProcessSystem # Create fluid fluid = SystemSrkEos(273.15 + 50.0, 50.0) fluid.addComponent("methane", 0.85) fluid.addComponent("ethane", 0.10) fluid.addComponent("propane", 0.05) fluid.setMixingRule("classic") # Create streams hot1 = Stream("Hot-1", fluid.clone()) hot1.setTemperature(100.0, "C") hot1.setFlowRate(20000.0, "kg/hr") hot2 = Stream("Hot-2", fluid.clone()) hot2.setTemperature(90.0, "C") hot2.setFlowRate(20000.0, "kg/hr") cold1 = Stream("Cold-1", fluid.clone()) cold1.setTemperature(0.0, "C") cold1.setFlowRate(20000.0, "kg/hr") cold2 = Stream("Cold-2", fluid.clone()) cold2.setTemperature(10.0, "C") cold2.setFlowRate(10000.0, "kg/hr") # Create MSHE mshx = MultiStreamHeatExchanger2("LNG-MCHE") # Add streams (stream, type, outlet_temp) # Use None for unknown outlet temperatures mshx.addInStreamMSHE(hot1, "hot", None) # Unknown mshx.addInStreamMSHE(hot2, "hot", 80.0) # Known: 80°C mshx.addInStreamMSHE(cold1, "cold", None) # Unknown mshx.addInStreamMSHE(cold2, "cold", 85.0) # Known: 85°C # Set constraints mshx.setTemperatureApproach(5.0) # 5°C minimum approach # Build and run process process = ProcessSystem() process.add(hot1) process.add(hot2) process.add(cold1) process.add(cold2) process.add(mshx) process.run() # Results print(f"Hot-1 outlet: {mshx.getOutStream(0).getTemperature('C'):.1f} °C") print(f"Cold-1 outlet: {mshx.getOutStream(2).getTemperature('C'):.1f} °C") print(f"UA value: {mshx.getUA():.0f} W/K") ``` -------------------------------- ### Basic Dynamic Compressor Setup in Java Source: https://github.com/equinor/neqsim/blob/master/docs/process/equipment/compressor_curves.md This snippet demonstrates the initial setup of a compressor for dynamic simulation, including enabling operating history, setting rotational inertia, and defining acceleration/deceleration rates. It also configures surge margin thresholds and the anti-surge controller with PID parameters and valve response time. Finally, it initiates the compressor startup sequence. ```java Compressor comp = new Compressor("K-100", inletStream); comp.setOutletPressure(100.0, "bara"); comp.setSpeed(10000); comp.run(); // Enable dynamic simulation features comp.enableOperatingHistory(); comp.setRotationalInertia(15.0); // kg⋅m² combined rotor inertia comp.setMaxAccelerationRate(100.0); // RPM/s comp.setMaxDecelerationRate(200.0); // RPM/s // Set surge margin thresholds comp.setSurgeWarningThreshold(0.15); // 15% margin triggers warning comp.setSurgeCriticalThreshold(0.05); // 5% margin triggers critical alarm // Configure anti-surge controller AntiSurge antiSurge = comp.getAntiSurge(); antiSurge.setControlStrategy(AntiSurge.ControlStrategy.PID); antiSurge.setPIDParameters(2.0, 0.5, 0.1); antiSurge.setValveResponseTime(2.0); // seconds // Start compressor with startup profile comp.startCompressor(10000); // Target speed ``` -------------------------------- ### Complete Pipeline Design Workflow in Python Source: https://github.com/equinor/neqsim/blob/master/docs/process/topside_piping_design.md This Python snippet demonstrates the NEQSim design workflow for pipelines, mirroring the Java example. It covers fluid creation, stream setup, pipeline configuration, and mechanical design calculations. Ensure the jNeqSim module is installed and imported. ```python from neqsim.thermo import fluid from neqsim import jNeqSim # Create fluid gas = fluid('srk') gas.addComponent('methane', 0.9) gas.addComponent('ethane', 0.07) gas.addComponent('propane', 0.03) gas.setMixingRule('classic') # Create stream Stream = jNeqSim.process.equipment.stream.Stream feed = Stream("Feed", gas) feed.setFlowRate(10000.0, "kg/hr") feed.setTemperature(40.0, "C") feed.setPressure(50.0, "bara") feed.run() # Create topside piping TopsidePiping = jNeqSim.process.equipment.pipeline.TopsidePiping gasHeader = TopsidePiping.createProcessGas("Gas Header", feed) gasHeader.setLength(50.0) gasHeader.setDiameter(0.2032) gasHeader.setElevation(0.0) gasHeader.run() # Get mechanical design design = gasHeader.getTopsideMechanicalDesign() design.setMaxOperationPressure(55.0) design.setMaterialGrade("A106-B") design.readDesignSpecifications() design.calcDesign() # Get calculator results calc = design.getTopsideCalculator() print(f"Support spacing: {calc.getSupportSpacing():.2f} m") print(f"Velocity OK: {calc.isVelocityCheckPassed()}") # Export JSON import json report = json.loads(design.toJson()) print(json.dumps(report, indent=2)) ``` -------------------------------- ### Get Example from ExampleCatalog Source: https://github.com/equinor/neqsim/blob/master/docs/integration/mcp_neqsim_core_layer.md Retrieves a specific JSON example from the ExampleCatalog by category and name. Useful for LLMs learning input formats. ```java String example = ExampleCatalog.getExample("flash", "tp-simple-gas"); ``` -------------------------------- ### Complete ProcessSystem Integration Workflow Example Source: https://github.com/equinor/neqsim/blob/master/docs/process/instrument-design.md This example demonstrates building a process, running it, and then obtaining a plant-wide instrument summary including I/O counts, cabinet sizing, and total capital expenditure (CAPEX). ```java // Build process SystemInterface gas = new SystemSrkEos(273.15 + 25.0, 60.0); gas.addComponent("methane", 0.85); gas.addComponent("ethane", 0.10); gas.addComponent("propane", 0.05); gas.setMixingRule("classic"); ProcessSystem process = new ProcessSystem(); Stream feed = new Stream("Feed", gas); feed.setFlowRate(50000.0, "kg/hr"); process.add(feed); Separator hpSep = new Separator("HP Separator", feed); process.add(hpSep); Compressor comp = new Compressor("Export Compressor", hpSep.getGasOutStream()); comp.setOutletPressure(120.0); process.add(comp); Cooler afterCooler = new Cooler("Aftercooler", comp.getOutletStream()); afterCooler.setOutTemperature(273.15 + 40.0); process.add(afterCooler); // Run process process.run(); // Get plant-wide instrument summary SystemInstrumentDesign sysInstr = process.getSystemInstrumentDesign(); sysInstr.calcDesign(); System.out.println("=== Plant Instrument Summary ==="); System.out.println("Total instruments: " + sysInstr.getTotalInstruments()); System.out.println("Total I/O: " + sysInstr.getTotalIO()); System.out.println("DCS cabinets: " + sysInstr.getDcsCabinets()); System.out.println("SIS cabinets: " + sysInstr.getSisCabinets()); System.out.println("Total CAPEX: $" + sysInstr.getTotalInstrumentCostUSD()); System.out.println(sysInstr.toJson()); ``` -------------------------------- ### Run Isothermal First-Order Gas Phase Reaction Example Source: https://github.com/equinor/neqsim/blob/master/docs/process/equipment/plug_flow_reactor.md A complete example demonstrating feed setup, kinetic reaction definition, and reactor execution. ```java // Feed: 90% methane (A) + 10% ethane (B) at 300°C, 20 bara SystemInterface gas = new SystemSrkEos(273.15 + 300.0, 20.0); gas.addComponent("methane", 0.90); gas.addComponent("ethane", 0.10); gas.setMixingRule("classic"); Stream feed = new Stream("Feed", gas); feed.setFlowRate(10.0, "mole/sec"); feed.run(); // Define reaction: methane -> ethane (illustrative) KineticReaction rxn = new KineticReaction("A to B"); rxn.addReactant("methane", 1.0, 1.0); // stoich=1, order=1 rxn.addProduct("ethane", 1.0); // stoich=1 rxn.setPreExponentialFactor(1.0e4); rxn.setActivationEnergy(50000.0); // 50 kJ/mol rxn.setHeatOfReaction(-50000.0); // exothermic rxn.setRateType(KineticReaction.RateType.POWER_LAW); // Reactor PlugFlowReactor pfr = new PlugFlowReactor("PFR-1", feed); pfr.addReaction(rxn); pfr.setLength(5.0, "m"); pfr.setDiameter(0.10, "m"); pfr.setEnergyMode(PlugFlowReactor.EnergyMode.ISOTHERMAL); pfr.setNumberOfSteps(100); pfr.setKeyComponent("methane"); pfr.run(); System.out.println("Conversion: " + pfr.getConversion()); System.out.println("Pressure drop: " + pfr.getPressureDrop() + " bar"); ``` -------------------------------- ### Basic Compressor Setup and Operation Source: https://github.com/equinor/neqsim/blob/master/docs/process/equipment/compressors.md Demonstrates the fundamental steps to initialize a compressor, set outlet pressure and efficiency, run the simulation, and retrieve results like power and temperature. Requires an inlet stream object. ```java import neqsim.process.equipment.compressor.Compressor; Compressor compressor = new Compressor("K-100", inletStream); compressor.setOutletPressure(80.0, "bara"); compressor.setIsentropicEfficiency(0.75); compressor.run(); // Results double power = compressor.getPower("kW"); double outletT = compressor.getOutletStream().getTemperature("C"); double polytropicHead = compressor.getPolytropicHead("kJ/kg"); System.out.println("Power: " + power + " kW"); System.out.println("Outlet temperature: " + outletT + " °C"); ``` -------------------------------- ### GET /getExample Source: https://github.com/equinor/neqsim/blob/master/neqsim-mcp-server/README.md Retrieves ready-to-use JSON examples for flash and process simulations. ```APIDOC ## GET /getExample ### Description Returns ready-to-use JSON examples for various flash and process simulation scenarios. ### Method GET ### Endpoint /getExample ### Parameters #### Query Parameters - **category** (string) - Required - The category of the example (e.g., flash, process). - **name** (string) - Required - The specific name of the example template. ``` -------------------------------- ### Create and Configure a Calculator Source: https://github.com/equinor/neqsim/blob/master/docs/process/equipment/util/calculators.md Demonstrates the basic setup of a Calculator by creating an instance, adding input variables, setting an output variable, and adding it to the process. ```java import neqsim.process.equipment.util.Calculator; // Create calculator Calculator calc = new Calculator("Duty Calculator"); // Add input variables calc.addInputVariable(stream1); calc.addInputVariable(stream2); // Set output variable calc.setOutputVariable(heater); // Add to process process.add(calc); ``` -------------------------------- ### Complete Gas Valve Sizing Example Source: https://github.com/equinor/neqsim/blob/master/docs/process/ValveMechanicalDesign.md A comprehensive example demonstrating the setup, configuration, and sizing of a gas throttling valve using the IEC 60534 standard in NEQSim. ```java import neqsim.thermo.system.SystemSrkEos; import neqsim.process.equipment.stream.Stream; import neqsim.process.equipment.valve.ThrottlingValve; import neqsim.process.processmodel.ProcessSystem; import neqsim.process.mechanicaldesign.valve.ValveMechanicalDesign; // 1. Create fluid SystemInterface fluid = new SystemSrkEos(273.15 + 25, 50); fluid.addComponent("methane", 0.9); fluid.addComponent("ethane", 0.1); fluid.setMixingRule("classic"); fluid.setTotalFlowRate(10000.0, "kg/hr"); // 2. Build process Stream feed = new Stream("feed", fluid); ThrottlingValve valve = new ThrottlingValve("PCV-100", feed); valve.setOutletPressure(25.0); valve.setPercentValveOpening(100); // 3. Select sizing standard and configure ValveMechanicalDesign mechDesign = (ValveMechanicalDesign) valve.getMechanicalDesign(); mechDesign.setValveSizingStandard("IEC 60534"); mechDesign.getValveSizingMethod().setxT(0.75); // 4. Run and size ProcessSystem process = new ProcessSystem(); process.add(feed); process.add(valve); process.run(); valve.calcKv(); // 5. Read results System.out.printf("Cv = %.2f%n", valve.getCv()); System.out.printf("Kv = %.2f%n", valve.getKv()); ``` -------------------------------- ### Implement Full Workflow Example Source: https://github.com/equinor/neqsim/blob/master/docs/process/OPTIMIZATION_IMPROVEMENT_PROPOSAL.md This example demonstrates a complete workflow from defining a fluid and process basis to designing and optimizing a process system using templates and the DesignOptimizer. It also shows how to auto-size individual equipment. ```java import neqsim.process.design.*; import neqsim.process.design.template.ThreeStageSeparationTemplate; import neqsim.thermo.system.SystemSrkEos; // Define fluid SystemInterface wellFluid = new SystemSrkEos(60.0, 33.0); wellFluid.addComponent("methane", 0.7); wellFluid.addComponent("ethane", 0.1); wellFluid.addComponent("propane", 0.1); wellFluid.addComponent("nC10", 0.1); wellFluid.setMixingRule("classic"); // Define process basis with company standards ProcessBasis basis = new ProcessBasis.Builder() .designFlowRate(5000.0, "Sm3/hr") .designPressure(33.0, "bara") .designTemperature(60.0, "C") .turndown(0.3) .maxCapacity(1.2) .companyStandard("Equinor") .trDocument("TR1414") .safetyFactor(1.2) .build(); // Create process from template ProcessTemplate template = new ThreeStageSeparationTemplate(); template.validate(basis); // Check all required parameters ProcessSystem process = template.instantiate(wellFluid, basis); // Design and optimize in one call DesignOptimizer optimizer = new DesignOptimizer(); DesignResult result = optimizer.designAndOptimize(process, basis); // Access results ProcessSystem optimizedProcess = result.getProcess(); double maxRate = result.getOptimalRate(); String bottleneck = result.getBottleneck(); Map sizingResults = result.getSizingResults(); System.out.println("Optimal rate: " + maxRate + " Sm3/hr"); System.out.println("Bottleneck: " + bottleneck); System.out.println("Sizing results: " + sizingResults); // Auto-size individual equipment with company standards Separator separator = (Separator) process.getUnit("HP-Separator"); separator.autoSize("Equinor", "TR2000"); // Connects to MechanicalDesign System.out.println(separator.getSizingReport()); ``` -------------------------------- ### Complete Gas Processing Optimization Example Source: https://github.com/equinor/neqsim/blob/master/docs/integration/EXTERNAL_OPTIMIZER_INTEGRATION.md A full example demonstrating process system setup, optimization configuration, and execution using scipy.optimize.minimize with NEQSim's ProcessSimulationEvaluator. ```python import jpype import jpype.imports import numpy as np from scipy.optimize import minimize import matplotlib.pyplot as plt # Start JVM jpype.startJVM(classpath=['neqsim.jar']) from neqsim.process.util.optimizer import ProcessSimulationEvaluator from neqsim.process.processmodel import ProcessSystem from neqsim.process.equipment.stream import Stream from neqsim.process.equipment.compressor import Compressor from neqsim.process.equipment.cooler import Cooler from neqsim.thermo.system import SystemSrkEos # Create process fluid = SystemSrkEos(273.15 + 30.0, 20.0) fluid.addComponent("methane", 0.85) fluid.addComponent("ethane", 0.10) fluid.addComponent("propane", 0.05) fluid.setMixingRule("classic") fluid.setTotalFlowRate(50000.0, "kg/hr") feed = Stream("feed", fluid) compressor = Compressor("compressor", feed) compressor.setOutletPressure(80.0) cooler = Cooler("cooler", compressor.getOutletStream()) cooler.setOutletTemperature(273.15 + 40.0) process = ProcessSystem() process.add(feed) process.add(compressor) process.add(cooler) process.run() # Setup optimization evaluator = ProcessSimulationEvaluator(process) # Decision variables evaluator.addParameter("feed", "flowRate", 10000.0, 100000.0, "kg/hr") evaluator.addParameter("compressor", "outletPressure", 50.0, 120.0, "bara") # Minimize compressor power evaluator.addObjective("power", lambda p: p.getUnit("compressor").getEnergy("kW")) # Constraints evaluator.addConstraintLowerBound("minOutletPressure", lambda p: p.getUnit("cooler").getOutletStream().getPressure("bara"), 60.0) evaluator.addConstraintUpperBound("maxOutletTemp", lambda p: p.getUnit("cooler").getOutletStream().getTemperature("C"), 50.0) # Optimize with SLSQP def objective(x): return evaluator.evaluateObjective(x) def constraint_margins(x): return evaluator.getConstraintMargins(x) bounds = [(b[0], b[1]) for b in evaluator.getBounds()] x0 = evaluator.getInitialValues() result = minimize( objective, x0, method='SLSQP', bounds=bounds, constraints={'type': 'ineq', 'fun': constraint_margins}, options={'maxiter': 100, 'disp': True} ) # Display results print("\n=== Optimization Results ===") print(f"Optimal flow rate: {result.x[0]:.1f} kg/hr") print(f"Optimal outlet pressure: {result.x[1]:.1f} bara") print(f"Minimum power: {result.fun:.1f} kW") print(f"Constraint margins: {constraint_margins(result.x)}") print(f"Total evaluations: {evaluator.getEvaluationCount()}") jpype.shutdownJVM() ``` -------------------------------- ### Install and Import NeqSim Libraries Source: https://github.com/equinor/neqsim/blob/master/examples/notebooks/air_cooler_and_packed_column.ipynb Installs the neqsim library if not already present and imports necessary Java classes for process modeling. This setup is required before using NeqSim functionalities. ```python # Setup - Install neqsim if needed and import import subprocess, sys try: import neqsim except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "neqsim"]) from neqsim import jneqsim import matplotlib.pyplot as plt import numpy as np # Import NeqSim Java classes SystemSrkEos = jneqsim.thermo.system.SystemSrkEos Stream = jneqsim.process.equipment.stream.Stream AirCooler = jneqsim.process.equipment.heatexchanger.AirCooler ProcessSystem = jneqsim.process.processmodel.ProcessSystem print("NeqSim loaded successfully") ``` -------------------------------- ### Simulate Gas Pipeline Source: https://github.com/equinor/neqsim/blob/master/docs/wiki/water_hammer_implementation.md Example demonstrating the setup and simulation of a natural gas pipeline. ```java // Natural gas pipeline SystemInterface gas = new SystemSrkEos(298.15, 70.0); gas.addComponent("methane", 0.90); gas.addComponent("ethane", 0.05); gas.addComponent("propane", 0.03); gas.addComponent("CO2", 0.02); gas.setMixingRule("classic"); gas.setTotalFlowRate(1000000, "Sm3/day"); Stream gasFeed = new Stream("gas feed", gas); gasFeed.run(); WaterHammerPipe gasPipe = new WaterHammerPipe("gas pipeline", gasFeed); gasPipe.setLength(100, "km"); gasPipe.setDiameter(0.5); // 500 mm gasPipe.setNumberOfNodes(500); gasPipe.setDownstreamBoundary(BoundaryType.VALVE); gasPipe.run(); // Gas has lower wave speed (~400 m/s) and lower density // So pressure surges are typically smaller than for liquids System.out.println("Gas wave speed: " + gasPipe.getWaveSpeed() + " m/s"); ``` -------------------------------- ### NEQSim Process Simulation Setup and Run Source: https://github.com/equinor/neqsim/blob/master/examples/notebooks/electrical/power_from_shore_feasibility.ipynb Sets up a process simulation with separators, compressors, and pumps, then runs the simulation and calculates electrical demand. Requires NEQSim library and fluid definitions. ```python process = ProcessSystem() feed = Stream("Well Stream", fluid) feed.setFlowRate(80000.0, "kg/hr") process.add(feed) hp_sep = Separator("HP Separator", feed) process.add(hp_sep) gas_comp1 = Compressor("Gas Compressor", hp_sep.getGasOutStream()) gas_comp1.setOutletPressure(120.0) process.add(gas_comp1) gas_cooler = Cooler("Gas Aftercooler", gas_comp1.getOutletStream()) gas_cooler.setOutTemperature(273.15 + 40.0) process.add(gas_cooler) gas_comp2 = Compressor("Booster Compressor", gas_cooler.getOutletStream()) gas_comp2.setOutletPressure(180.0) process.add(gas_comp2) export_pump = Pump("Export Pump", hp_sep.getLiquidOutStream()) export_pump.setOutletPressure(80.0) process.add(export_pump) process.run() process.runAllElectricalDesigns() load_list = process.getElectricalLoadList() platform_demand_kw = float(load_list.getMaximumDemandKW()) platform_demand_kva = float(load_list.getMaximumDemandKVA()) platform_pf = float(load_list.getOverallPowerFactor()) print("=== Platform Electrical Demand ===") print(f"Maximum demand: {platform_demand_kw:.0f} kW / {platform_demand_kva:.0f} kVA") print(f"Power factor: {platform_pf:.3f}") print(f"Equipment count: {load_list.getLoadCount()}") ``` -------------------------------- ### Compile and Run NeqSim Example Source: https://github.com/equinor/neqsim/blob/master/docs/safety/alarm_triggered_logic_example.md Commands to build and execute the alarm integration example. ```bash # Compile mvn compile # Run mvn exec:java -Dexec.mainClass="neqsim.process.util.example.ProcessLogicAlarmIntegratedExample" ``` -------------------------------- ### Multi-step Agent Task Example Source: https://github.com/equinor/neqsim/blob/master/docs/development/TASK_SOLVING_GUIDE.md Demonstrates chaining specialist AI agents for a complex task. This example involves fluid setup, building a dehydration unit, and writing regression tests. ```bash 1. @thermo.fluid → "Create a CPA fluid for gas with 5% MEG and water" 2. @solve.process → "Build a TEG dehydration unit using that fluid" 3. @neqsim.test → "Write regression tests for the dehydration results" ``` -------------------------------- ### Build and Run a ProcessSystem Source: https://github.com/equinor/neqsim/blob/master/docs/process/README.md Demonstrates initializing a process system, adding equipment like streams and valves, and executing the simulation. ```java import neqsim.process.processmodel.ProcessSystem; import neqsim.process.equipment.stream.Stream; import neqsim.process.equipment.separator.Separator; import neqsim.process.equipment.valve.ThrottlingValve; // Create process system ProcessSystem process = new ProcessSystem("Gas Processing Plant"); // Create feed stream SystemInterface feed = new SystemSrkEos(300.0, 80.0); feed.addComponent("methane", 0.85); feed.addComponent("ethane", 0.08); feed.addComponent("propane", 0.05); feed.addComponent("n-butane", 0.02); feed.setMixingRule("classic"); Stream feedStream = new Stream("Feed", feed); feedStream.setFlowRate(1000.0, "kg/hr"); // Add equipment to process process.add(feedStream); // Letdown valve ThrottlingValve valve = new ThrottlingValve("Inlet Valve", feedStream); valve.setOutletPressure(40.0, "bara"); process.add(valve); // Separator Separator separator = new Separator("HP Separator", valve.getOutletStream()); process.add(separator); // Run process (recommended - auto-optimized) process.runOptimized(); // Get results System.out.println("Separator gas rate: " + separator.getGasOutStream().getFlowRate("kg/hr") + " kg/hr"); System.out.println("Separator liquid rate: " + separator.getLiquidOutStream().getFlowRate("kg/hr") + " kg/hr"); ``` -------------------------------- ### Claude Code / Cursor Prompt Source: https://github.com/equinor/neqsim/blob/master/docs/tutorials/solve-engineering-task.md Example prompt for guiding AI agents through the task-solving workflow. ```text Read docs/development/TASK_SOLVING_GUIDE.md for the full workflow. Read the task README at task_solve/YYYY-MM-DD_your_task/README.md. Follow the 3-step workflow. ``` -------------------------------- ### Initialize and Configure Startup Logic Source: https://github.com/equinor/neqsim/blob/master/docs/simulation/process_logic_implementation_summary.md Basic setup for a StartupLogic instance, adding steps with actions and enabling automatic progression. ```java StartupLogic startup = new StartupLogic("Separator Train Startup"); startup.addStep("Pre-checks").addPermissive(/* ... */); startup.addStep("Open isolation").addAction(/* ... */); startup.addStep("Ramp up flow").addAction(/* ... */); startup.enableAutoProgression(); // Automatic step advancement ``` -------------------------------- ### VS Code Java Settings for Google Style Guide Source: https://github.com/equinor/neqsim/blob/master/CONTRIBUTING.md Configure VS Code to use the Google Java style guide for formatting and organizing imports. Ensure the Checkstyle extension is installed and configured. ```json { "java.configuration.updateBuildConfiguration": "interactive", "[java]": { "editor.defaultFormatter": "redhat.java", "editor.formatOnSave": true, "editor.tabSize": 2, "editor.insertSpaces": true, "editor.detectIndentation": false }, "java.format.settings.url": "https://raw.githubusercontent.com/google/styleguide/gh-pages/eclipse-java-google-style.xml", "java.saveActions.organizeImports": true, "java.checkstyle.version": "10.18.1", "java.checkstyle.configuration": "${workspaceFolder}/.config/checkstyle_neqsim.xml", "java.debug.settings.hotCodeReplace": "never", "[xml]": { "editor.tabSize": 4, "editor.insertSpaces": false }, "[json]": { "editor.tabSize": 4, "editor.insertSpaces": true } } ```