Class ProcessModel

java.lang.Object
neqsim.process.processmodel.ProcessModel
All Implemented Interfaces:
Serializable, Runnable

public class ProcessModel extends Object implements Runnable, Serializable

ProcessModel class. Manages a collection of processes that can be run in steps or continuously.

This class supports serialization via saveToNeqsim(String) and loadFromNeqsim(String) for full model persistence.

Version:
1.0
Author:
ESOL
See Also:
  • Field Details

    • serialVersionUID

      private static final long serialVersionUID
      See Also:
    • logger

      static org.apache.logging.log4j.Logger logger
      Logger object for class.
    • processes

      private Map<String, ProcessSystem> processes
    • runStep

      private boolean runStep
    • maxIterations

      private int maxIterations
    • useOptimizedExecution

      private boolean useOptimizedExecution
    • progressListener

      private transient ProcessModel.ModelProgressListener progressListener
      Transient listener for model-level progress callbacks. Marked transient to avoid serialization issues.
    • publishEvents

      private boolean publishEvents
      When true, lifecycle events are published to the ProcessEventBus singleton during model execution. Default is false for zero overhead when not needed.
    • autoValidate

      private boolean autoValidate
      When true, validateSetup() is called on each ProcessSystem before the first iteration. Validation warnings are logged but do not abort execution.
    • useFlashWarmStart

      private boolean useFlashWarmStart
      When true, every ProcessSystem registered with this model has flash warm-start enabled for the duration of its run (via ProcessSystem.setUseFlashWarmStart(boolean)). Default is false. Setting this flag updates all currently registered ProcessSystems and applies to any ProcessSystem added afterwards.
    • checkpointEnabled

      private boolean checkpointEnabled
      Whether automatic checkpointing is enabled during model execution.
    • checkpointInterval

      private int checkpointInterval
      Number of iterations between automatic checkpoints.
    • checkpointPath

      private String checkpointPath
      File path for saving checkpoint files.
    • flowTolerance

      private double flowTolerance
    • temperatureTolerance

      private double temperatureTolerance
    • pressureTolerance

      private double pressureTolerance
    • lastIterationCount

      private int lastIterationCount
    • lastMaxFlowError

      private double lastMaxFlowError
    • lastMaxTemperatureError

      private double lastMaxTemperatureError
    • lastMaxPressureError

      private double lastMaxPressureError
    • modelConverged

      private boolean modelConverged
  • Constructor Details

    • ProcessModel

      public ProcessModel()
  • Method Details

    • isRunStep

      public boolean isRunStep()
      Checks if the model is running in step mode.
      Returns:
      a boolean
    • setRunStep

      public void setRunStep(boolean runStep)
      Sets the step mode for the process.
      Parameters:
      runStep - a boolean
    • isUseOptimizedExecution

      public boolean isUseOptimizedExecution()
      Check if optimized execution is enabled for individual ProcessSystems.

      When enabled (default), each ProcessSystem uses ProcessSystem.runOptimized() which auto-selects the best execution strategy based on topology.

      Returns:
      true if optimized execution is enabled
    • setUseOptimizedExecution

      public void setUseOptimizedExecution(boolean useOptimizedExecution)
      Enable or disable optimized execution for individual ProcessSystems.

      When enabled (default), each ProcessSystem uses ProcessSystem.runOptimized() which auto-selects the best execution strategy (parallel for feed-forward, hybrid for recycle processes). When disabled, uses standard sequential SimulationInterface.run().

      Parameters:
      useOptimizedExecution - true to enable optimized execution
    • setUseFlashWarmStart

      public void setUseFlashWarmStart(boolean useWarmStart)
      Enable or disable flash warm-start K-values for every ProcessSystem in this model.

      When enabled, the iterative TPflash inside every fluid evaluation re-uses the previously converged K-values as the initial estimate instead of seeding from Wilson on every call. This is delegated to ProcessSystem.setUseFlashWarmStart(boolean) on every currently registered ProcessSystem and is also applied to any ProcessSystem added afterwards via add(String, ProcessSystem). Each ProcessSystem manages the underlying ThermodynamicModelSettings flag with try/finally inside its own run() so the setting never leaks past the model run. Default is false (historical behaviour) — recycle-heavy multi-area models are sensitive to flash trajectory and warm-start can shift the converged fixed point.

      Parameters:
      useWarmStart - true to enable warm-start across all ProcessSystems in this model
    • isUseFlashWarmStart

      public boolean isUseFlashWarmStart()
      Returns whether flash warm-start is enabled for the ProcessSystems in this model.
      Returns:
      true if warm-start K-values are propagated to every ProcessSystem in this model
    • getMaxIterations

      public int getMaxIterations()
      Get the maximum number of iterations for the model.
      Returns:
      maximum number of iterations
    • setMaxIterations

      public void setMaxIterations(int maxIterations)
      Set the maximum number of iterations for the model.
      Parameters:
      maxIterations - maximum number of iterations
    • getFlowTolerance

      public double getFlowTolerance()
      Get flow tolerance for convergence check (relative error).
      Returns:
      flow tolerance
    • setFlowTolerance

      public void setFlowTolerance(double flowTolerance)
      Set flow tolerance for convergence check (relative error).
      Parameters:
      flowTolerance - relative tolerance for flow rate convergence (e.g., 1e-4 = 0.01%)
    • getTemperatureTolerance

      public double getTemperatureTolerance()
      Get temperature tolerance for convergence check (relative error).
      Returns:
      temperature tolerance
    • setTemperatureTolerance

      public void setTemperatureTolerance(double temperatureTolerance)
      Set temperature tolerance for convergence check (relative error).
      Parameters:
      temperatureTolerance - relative tolerance for temperature convergence
    • getPressureTolerance

      public double getPressureTolerance()
      Get pressure tolerance for convergence check (relative error).
      Returns:
      pressure tolerance
    • setPressureTolerance

      public void setPressureTolerance(double pressureTolerance)
      Set pressure tolerance for convergence check (relative error).
      Parameters:
      pressureTolerance - relative tolerance for pressure convergence
    • setTolerance

      public void setTolerance(double tolerance)
      Set all tolerances at once.
      Parameters:
      tolerance - relative tolerance for all variables (flow, temperature, pressure)
    • getLastIterationCount

      public int getLastIterationCount()
      Get the number of iterations from the last run.
      Returns:
      iteration count
    • isModelConverged

      public boolean isModelConverged()
      Check if the model converged in the last run.
      Returns:
      true if converged
    • getLastMaxFlowError

      public double getLastMaxFlowError()
      Get maximum flow error from the last iteration.
      Returns:
      maximum relative flow error
    • getLastMaxTemperatureError

      public double getLastMaxTemperatureError()
      Get maximum temperature error from the last iteration.
      Returns:
      maximum relative temperature error
    • getLastMaxPressureError

      public double getLastMaxPressureError()
      Get maximum pressure error from the last iteration.
      Returns:
      maximum relative pressure error
    • getError

      public double getError()
      Get the maximum error across all variables (flow, temperature, pressure).

      This is the largest relative error from the last iteration, useful for quick convergence check.

      Returns:
      maximum relative error across all variables
    • setProgressListener

      public void setProgressListener(ProcessModel.ModelProgressListener listener)
      Set a listener to receive progress updates during model execution.
      Parameters:
      listener - the progress listener, or null to disable callbacks
    • getProgressListener

      public ProcessModel.ModelProgressListener getProgressListener()
      Get the current model progress listener.
      Returns:
      the current listener, or null if none is set
    • setPublishEvents

      public void setPublishEvents(boolean publish)
      Enables or disables event publishing to the ProcessEventBus singleton. When enabled, lifecycle events (model start/complete, area errors, convergence) are published during execution.
      Parameters:
      publish - true to enable event publishing, false to disable (default)
    • isPublishEvents

      public boolean isPublishEvents()
      Returns whether event publishing is enabled.
      Returns:
      true if events are published to ProcessEventBus during model execution
    • setAutoValidate

      public void setAutoValidate(boolean validate)
      Enables or disables automatic validation of each ProcessSystem before the first iteration. When enabled, validateSetup() is called on each ProcessSystem. Validation failures are logged as warnings but do not abort execution.
      Parameters:
      validate - true to enable auto-validation, false to disable (default)
    • isAutoValidate

      public boolean isAutoValidate()
      Returns whether auto-validation is enabled.
      Returns:
      true if process systems are validated before model runs
    • add

      public boolean add(String name, ProcessSystem process)
      Adds a process to the model.
      Parameters:
      name - a String object
      process - a ProcessSystem object
      Returns:
      a boolean
    • get

      public ProcessSystem get(String name)
      Retrieves a process by its name.
      Parameters:
      name - a String object
      Returns:
      a ProcessSystem object
    • getProcessSystemNames

      public List<String> getProcessSystemNames()
      Returns the names of all process systems in insertion order.
      Returns:
      a List of process system names
    • size

      public int size()
      Returns the number of process systems in this model.
      Returns:
      the number of process systems
    • has

      public boolean has(String name)
      Checks whether a process system with the given name exists.
      Parameters:
      name - the name to look up
      Returns:
      true if a process system with that name exists
    • generateReferenceDesignations

      public ReferenceDesignationGenerator generateReferenceDesignations(String locationPrefix)
      Generates IEC 81346 reference designations for all equipment across all process areas in this model. Each area receives a unique function sub-level (A1, A2, A3, ...).

      This is a convenience wrapper around ReferenceDesignationGenerator.

      Parameters:
      locationPrefix - the location-aspect prefix (e.g. "P1" for a specific platform)
      Returns:
      the generator instance (for further queries such as toJson())
    • generateReferenceDesignations

      public ReferenceDesignationGenerator generateReferenceDesignations(String functionPrefix, String locationPrefix)
      Generates IEC 81346 reference designations with hierarchical function structure. Each area receives a nested function sub-level under the given prefix (e.g. "A1.A1", "A1.A2").
      Parameters:
      functionPrefix - the top-level function prefix (e.g. "A1")
      locationPrefix - the location-aspect prefix (e.g. "P1")
      Returns:
      the generator instance
    • getUnitByReferenceDesignation

      public ProcessEquipmentInterface getUnitByReferenceDesignation(String refDesignation)
      Looks up a process equipment unit across all process areas by its IEC 81346 reference designation string (e.g. "=A1.B1", "-B1").
      Parameters:
      refDesignation - the reference designation string to match
      Returns:
      the matching equipment, or null if not found in any area
    • remove

      public boolean remove(String name)
      Removes a process by its name.
      Parameters:
      name - a String object
      Returns:
      a boolean
    • setRecycleAccelerationMethod

      public int setRecycleAccelerationMethod(AccelerationMethod method)
      Apply an acceleration method to every Recycle unit across all areas in this ProcessModel.

      For large multi-area plants with many recycle loops, Wegstein acceleration typically reduces outer-loop iteration count by 2-3x over the default direct substitution. This is a bulk convenience that delegates to ProcessSystem.setRecycleAccelerationMethod(neqsim.process.equipment.util.AccelerationMethod) on every registered area.

      Parameters:
      method - acceleration method to apply (must not be null)
      Returns:
      total number of Recycle units updated across all areas
    • getExergyChange

      public double getExergyChange(String unit)
      Total change in stream exergy (outlet − inlet) aggregated over every unit operation in every process area. Each area contributes using its own surrounding temperature.
      Parameters:
      unit - energy / power unit of the returned value (J, kJ, MJ, W, kW, MW)
      Returns:
      total exergy change in the requested unit
    • getExergyDestruction

      public double getExergyDestruction(String unit)
      Total exergy destruction rate aggregated over every unit operation in every process area. Each area contributes using its own surrounding temperature.
      Parameters:
      unit - energy / power unit of the returned value
      Returns:
      total exergy destruction in the requested unit
    • getExergyAnalysis

      public ExergyAnalysisReport getExergyAnalysis()
      Build a structured ExergyAnalysisReport covering every unit operation in every process area, with each entry tagged by its area name. The surrounding temperature of the report is taken from the first registered area (or 288.15 K if the model is empty).
      Returns:
      a new report suitable for ranking destruction hot-spots across a plant-wide flowsheet
    • convertEnergy

      private static double convertEnergy(double valueJ, String unit)
      Convert Joules to the requested energy / power unit.
      Parameters:
      valueJ - value in Joules (treated identically to watts for rate quantities)
      unit - target unit (J, kJ, MJ, W, kW, MW)
      Returns:
      converted value
    • run

      public void run()

      - If runStep == true, each process is run in "step" mode exactly once. - Otherwise (continuous mode), it loops up to maxIterations or until all processes are finished (isFinished() == true). If forceIteration is true, the loop runs all maxIterations regardless of convergence.

      When isUseOptimizedExecution() is true (default), each ProcessSystem uses ProcessSystem.runOptimized() for best performance.

      Specified by:
      run in interface Runnable
    • runAllProcesses

      private void runAllProcesses()
      Runs all ProcessSystems, using parallel execution for independent systems.

      If there are multiple independent ProcessSystems (no shared streams between them), they are executed concurrently using the NeqSim thread pool. Systems that depend on each other are executed sequentially in insertion order.

    • runSingleProcess

      private void runSingleProcess(ProcessSystem process)
      Runs a single ProcessSystem using the configured execution strategy.
      Parameters:
      process - the process to run
    • runAllProcessesWithHooks

      private void runAllProcessesWithHooks(int iterationNumber)
      Runs all ProcessSystems with listener hooks, firing before/after area callbacks sequentially. For dependent processes (shared streams), runs sequentially with hooks. For independent processes without a listener, delegates to the parallel strategy.
      Parameters:
      iterationNumber - current outer iteration number (starts at 1)
    • findIndependentProcessGroups

      private List<List<ProcessSystem>> findIndependentProcessGroups()
      Finds groups of independent ProcessSystems that can run in parallel.

      Two ProcessSystems are dependent if any outlet stream of one is used as an inlet stream of another. Independent systems have no shared stream references.

      Returns:
      list of groups, where systems within each group are independent of each other
    • buildAreaExecutionLevels

      private List<List<ProcessSystem>> buildAreaExecutionLevels()
      Partitions ProcessSystems into execution levels based on inter-area stream dependencies. Areas at the same level share no producer/consumer link and can run in parallel; areas at level N+1 start only after all areas at level N complete.

      Direction is inferred from stream ownership: if a stream is an outlet of some equipment in area A and also present (directly or as a consumed inlet) in area B, then A is the producer and B is the consumer, so A → B in the meta-graph. Ambiguous links (stream is produced in both areas) fall back to insertion order to preserve legacy behaviour.

      Returns:
      ordered list of execution levels; each level contains areas that can run in parallel
    • waitForFutures

      private void waitForFutures(List<Future<?>> futures)
      Waits for all futures to complete and logs any errors.
      Parameters:
      futures - list of futures to wait for
    • captureStreamStates

      private Map<String,double[]> captureStreamStates()
      Capture current state of all streams in all processes.
      Returns:
      map of stream name to [flowRate, temperature, pressure]
    • captureStreamStates

      private Map<String,double[]> captureStreamStates(Set<Object> boundaryStreams)
      Capture current state of streams in all processes, optionally restricted to the supplied boundary set.

      For multi-area ProcessModels, inter-area convergence is driven only by streams that cross area boundaries. Passing the boundary set avoids scanning every stream in every iteration (O(N×M) → O(boundary)). When boundaryStreams is null or empty, all streams are captured (backward-compatible behaviour).

      Parameters:
      boundaryStreams - identity-set of streams to capture, or null for all streams
      Returns:
      map of stream name to [flowRate, temperature, pressure]
    • collectBoundaryStreams

      private Set<Object> collectBoundaryStreams()
      Collect the identity-set of streams that cross area boundaries in the current ProcessModel. A stream is a boundary stream if it appears in at least two ProcessSystems.
      Returns:
      identity-based set of boundary streams (may be empty)
    • calculateConvergenceErrors

      private double[] calculateConvergenceErrors(Map<String,double[]> previous, Map<String,double[]> current)
      Calculate maximum relative errors between previous and current stream states.
      Parameters:
      previous - previous stream states
      current - current stream states
      Returns:
      array of [maxFlowError, maxTempError, maxPressError]
    • getConvergenceSummary

      public String getConvergenceSummary()
      Get a summary of the convergence status after running the model.
      Returns:
      formatted convergence summary string
    • getExecutionPartitionInfo

      public String getExecutionPartitionInfo()
      Gets a combined execution partition analysis for all ProcessSystems.

      This method provides insight into how each ProcessSystem will be executed, including:

      • Whether each system has recycle loops
      • Number of units and parallel levels
      • Which execution strategy will be used
      Returns:
      combined execution partition info for all ProcessSystems
    • runAsTask

      public Future<?> runAsTask()
      Runs this model in a separate thread using the global NeqSim thread pool.

      This method submits the model to the shared NeqSimThreadPool and returns a Future that can be used to monitor completion, cancel the task, or retrieve any exceptions that occurred.

      Returns:
      a Future representing the pending completion of the task
      See Also:
    • runAsThread

      @Deprecated public Thread runAsThread()
      Deprecated.
      Use runAsTask() instead for better resource management. This method creates a new unmanaged thread directly.
      Starts this model in a new thread and returns that thread.
      Returns:
      a Thread object
    • isFinished

      public boolean isFinished()
      Checks if all processes are finished.
      Returns:
      a boolean
    • runStep

      public void runStep()
      Runs all processes in a single step (used outside of the thread model).
    • getThreads

      public Map<String,Thread> getThreads()
      (Optional) Creates separate threads for each process (if you need them).
      Returns:
      a Map object
    • getAllProcesses

      public Collection<ProcessSystem> getAllProcesses()
      Retrieves a list of all processes.
      Returns:
      a Collection of ProcessSystem objects
    • checkMassBalance

      public Map<String, Map<String, ProcessSystem.MassBalanceResult>> checkMassBalance(String unit)
      Check mass balance of all unit operations in all processes.
      Parameters:
      unit - unit for mass flow rate (e.g., "kg/sec", "kg/hr", "mole/sec")
      Returns:
      a map with process name and unit operation name as key and mass balance result as value
    • checkMassBalance

      public Map<String, Map<String, ProcessSystem.MassBalanceResult>> checkMassBalance()
      Check mass balance of all unit operations in all processes using kg/sec.
      Returns:
      a map with process name and unit operation name as key and mass balance result as value in kg/sec
    • getFailedMassBalance

      public Map<String, Map<String, ProcessSystem.MassBalanceResult>> getFailedMassBalance(String unit, double percentThreshold)
      Get unit operations that failed mass balance check in all processes based on percentage error threshold.
      Parameters:
      unit - unit for mass flow rate (e.g., "kg/sec", "kg/hr", "mole/sec")
      percentThreshold - percentage error threshold (default: 0.1%)
      Returns:
      a map with process name and a map of failed unit operation names and their mass balance results
    • getFailedMassBalance

      public Map<String, Map<String, ProcessSystem.MassBalanceResult>> getFailedMassBalance()
      Get unit operations that failed mass balance check in all processes using kg/sec and default threshold.
      Returns:
      a map with process name and a map of failed unit operation names and their mass balance results
    • getFailedMassBalance

      public Map<String, Map<String, ProcessSystem.MassBalanceResult>> getFailedMassBalance(double percentThreshold)
      Get unit operations that failed mass balance check in all processes using specified threshold.
      Parameters:
      percentThreshold - percentage error threshold
      Returns:
      a map with process name and a map of failed unit operation names and their mass balance results in kg/sec
    • getMassBalanceReport

      public String getMassBalanceReport(String unit)
      Get a formatted mass balance report for all processes.
      Parameters:
      unit - unit for mass flow rate (e.g., "kg/sec", "kg/hr", "mole/sec")
      Returns:
      a formatted string report with process name and mass balance results
    • getMassBalanceReport

      public String getMassBalanceReport()
      Get a formatted mass balance report for all processes using kg/sec.
      Returns:
      a formatted string report with process name and mass balance results
    • getFailedMassBalanceReport

      public String getFailedMassBalanceReport(String unit, double percentThreshold)
      Get a formatted report of failed mass balance checks for all processes.
      Parameters:
      unit - unit for mass flow rate (e.g., "kg/sec", "kg/hr", "mole/sec")
      percentThreshold - percentage error threshold
      Returns:
      a formatted string report with process name and failed unit operations
    • getFailedMassBalanceReport

      public String getFailedMassBalanceReport()
      Get a formatted report of failed mass balance checks for all processes using kg/sec and default threshold.
      Returns:
      a formatted string report with process name and failed unit operations
    • getFailedMassBalanceReport

      public String getFailedMassBalanceReport(double percentThreshold)
      Get a formatted report of failed mass balance checks for all processes using specified threshold.
      Parameters:
      percentThreshold - percentage error threshold
      Returns:
      a formatted string report with process name and failed unit operations
    • getReport_json

      public String getReport_json()

      getReport_json.

      Returns:
      a String object
    • toJson

      public String toJson()
      Exports this ProcessModel to a JSON string containing all named process areas.

      The exported JSON has a top-level "areas" object where each key is the process area name and each value is a JSON object in the JsonProcessBuilder schema (with "fluid" and "process" sections). This format can be used to reconstruct the model or to export individual areas to external simulators (e.g., UniSim Design via COM automation).

      Example output:

      { "areas": { "separation": { "fluid": {...}, "process": [...] }, "compression": {
      "fluid": {...}, "process": [...] } } } 
      Returns:
      JSON string representing all process areas @see JsonProcessExporter @see ProcessSystem#toJson()
    • toJson

      public String toJson(boolean prettyPrint)
      Exports this ProcessModel to a JSON string.
      Parameters:
      prettyPrint - whether to format the JSON with indentation
      Returns:
      JSON string representing all process areas
    • fromJson

      public static ProcessModel fromJson(String json)
      Builds a ProcessModel from a JSON string containing named process areas.

      Expected JSON format:

      { "areas": { "separation": { "fluid": {...}, "process": [...] }, "compression": {
      "fluid": {...}, "process": [...] } } } 

      Each area is built independently using JsonProcessBuilder. If any area fails to build, it is skipped and a warning is logged.

      Parameters:
      json - the JSON string with the "areas" structure
      Returns:
      the built ProcessModel (not yet run)
      Throws:
      IllegalArgumentException - if JSON is null, empty, or missing the "areas" key
      See Also:
    • fromJsonAndRun

      public static ProcessModel fromJsonAndRun(String json)
      Builds and immediately runs a ProcessModel from a JSON string.

      Convenience method that combines fromJson(String) and run() in a single call. This is the round-trip counterpart to toJson().

      Parameters:
      json - the JSON string with the "areas" structure
      Returns:
      the built and executed ProcessModel
      Throws:
      IllegalArgumentException - if JSON is null, empty, or missing the "areas" key
    • validateSetup

      public ValidationResult validateSetup()
      Validates the setup of all processes in this model.

      This method iterates through all ProcessSystems and validates each one. The results are aggregated into a single ValidationResult. Use this method before running the model to identify configuration issues.

      Returns:
      a ValidationResult containing all validation issues across all processes
    • validateAll

      public Map<String, ValidationResult> validateAll()
      Validates all processes and returns results organized by process name.

      This method provides detailed validation results for each ProcessSystem separately, making it easier to identify which process has issues.

      Returns:
      a Map mapping process names to their validation results
    • isReadyToRun

      public boolean isReadyToRun()
      Checks if all processes in the model are ready to run.

      This is a convenience method that returns true if no CRITICAL validation errors exist across all processes. Use this for a quick go/no-go check before running the model.

      Returns:
      true if no critical validation errors exist, false otherwise
    • getValidationReport

      public String getValidationReport()
      Get a formatted validation report for all processes.

      This method provides a human-readable summary of all validation issues across all processes in the model.

      Returns:
      a formatted validation report string
    • saveToNeqsim

      public boolean saveToNeqsim(String filename)
      Saves this ProcessModel (with all ProcessSystems) to a compressed .neqsim file.

      This is the recommended format for production use, providing compact storage with full model state preservation including all ProcessSystems. The file can be loaded with loadFromNeqsim(String).

      Example usage:

      ProcessModel model = new ProcessModel();
      model.add("upstream", upstreamProcess);
      model.add("downstream", downstreamProcess);
      model.run();
      model.saveToNeqsim("multi_process_model.neqsim");
      
      Parameters:
      filename - the file path to save to (recommended extension: .neqsim)
      Returns:
      true if save was successful, false otherwise
    • loadFromNeqsim

      public static ProcessModel loadFromNeqsim(String filename)
      Loads a ProcessModel from a compressed .neqsim file.

      After loading, the model is automatically run to reinitialize calculations. This ensures the internal state is consistent for all ProcessSystems.

      Example usage:

      ProcessModel loaded = ProcessModel.loadFromNeqsim("multi_process_model.neqsim");
      // Model is already run and ready to use
      ProcessSystem upstream = loaded.get("upstream");
      
      Parameters:
      filename - the file path to load from
      Returns:
      the loaded ProcessModel, or null if loading fails
    • saveAuto

      public boolean saveAuto(String filename)
      Saves this ProcessModel with automatic format detection based on file extension.

      File format is determined by extension:

      • .neqsim → XStream compressed XML (full serialization)
      • .json → JSON state (lightweight, Git-friendly, requires ProcessModelState)
      • other → Java binary serialization (legacy)
      Parameters:
      filename - the file path to save to
      Returns:
      true if save was successful
    • loadAuto

      public static ProcessModel loadAuto(String filename)
      Loads a ProcessModel with automatic format detection based on file extension.

      File format is determined by extension:

      • .neqsim → XStream compressed XML (full serialization)
      • .json → JSON state (requires matching ProcessSystems already configured)
      • other → Java binary serialization (legacy)
      Parameters:
      filename - the file path to load from
      Returns:
      the loaded ProcessModel, or null if loading fails
    • saveStateToFile

      public boolean saveStateToFile(String filename)
      Exports the current state of this ProcessModel to a JSON file.

      This exports state for all ProcessSystems in the model. The JSON format is Git-friendly and human-readable, suitable for version control and diffing.

      Parameters:
      filename - the file path to save to (recommended extension: .json)
      Returns:
      true if save was successful
    • loadStateFromFile

      public static ProcessModel loadStateFromFile(String filename)
      Loads ProcessModel state from a JSON file.

      Note: This returns a new ProcessModel with ProcessSystems initialized from the saved state. Full reconstruction requires the original equipment configuration.

      Parameters:
      filename - the file path to load from
      Returns:
      the loaded ProcessModel, or null if loading fails
    • exportState

      public ProcessModelState exportState()
      Exports the current state of this ProcessModel for inspection or modification.
      Returns:
      a ProcessModelState snapshot of the current model
    • autoSizeEquipment

      public int autoSizeEquipment()
      Auto-sizes all equipment in this model that implements AutoSizeable.

      This method iterates through all process systems in the model and calls autoSize() on each equipment that implements the AutoSizeable interface. The equipment is sized using the default safety factor (1.2 = 20% margin).

      Important: This method should be called AFTER running the process model so that flow rates and conditions are known for sizing calculations.

      Example usage:

      ProcessModel model = new ProcessModel();
      model.add("upstream", upstreamProcess);
      model.add("downstream", downstreamProcess);
      model.run();
      model.autoSizeEquipment(); // Size all equipment based on actual flow rates
      model.run(); // Re-run with sized equipment
      
      Returns:
      the number of equipment items that were auto-sized
    • autoSizeEquipment

      public int autoSizeEquipment(double safetyFactor)
      Auto-sizes all equipment in this model with the specified safety factor.

      This method iterates through all process systems in the model and calls autoSize() on each equipment that implements the AutoSizeable interface.

      Parameters:
      safetyFactor - multiplier for design capacity, typically 1.1-1.3 (10-30% over design)
      Returns:
      the number of equipment items that were auto-sized
    • autoSizeEquipment

      public int autoSizeEquipment(String companyStandard, String trDocument)
      Auto-sizes all equipment in this model using company-specific design standards.

      This method applies design rules from the specified company's technical requirements (TR) documents. The standards are loaded from the NeqSim design database.

      Parameters:
      companyStandard - company name (e.g., "Equinor", "Shell", "TotalEnergies")
      trDocument - TR document reference (e.g., "TR2000", "DEP-31.38.01.11")
      Returns:
      the number of equipment items that were auto-sized
    • setCapacityAnalysisEnabled

      public int setCapacityAnalysisEnabled(boolean enabled)
      Enables or disables capacity analysis for all equipment in all process systems.

      This is a convenience method that applies the setting to all equipment in all processes. When disabled, equipment is excluded from:

      • System bottleneck detection
      • Capacity utilization summaries
      • Equipment near capacity lists
      • Optimization constraint checking
      Parameters:
      enabled - true to enable capacity analysis for all equipment, false to disable
      Returns:
      the number of equipment items that were updated
    • notifyModelStart

      private void notifyModelStart(int totalAreas)
      Notify the listener that the model is starting.
      Parameters:
      totalAreas - total number of process areas
    • notifyModelComplete

      private void notifyModelComplete(int totalIterations, boolean converged)
      Notify the listener that the model has completed.
      Parameters:
      totalIterations - total iterations performed
      converged - whether the model converged
    • notifyBeforeIteration

      private void notifyBeforeIteration(int iterationNumber)
      Notify the listener that an iteration is about to start.
      Parameters:
      iterationNumber - the iteration about to start
    • notifyIterationComplete

      private void notifyIterationComplete(int iterationNumber, boolean converged, double maxError)
      Notify the listener that an iteration has completed.
      Parameters:
      iterationNumber - the iteration that completed
      converged - whether convergence was achieved
      maxError - maximum relative error across all variables
    • notifyBeforeProcessArea

      private void notifyBeforeProcessArea(String areaName, ProcessSystem process, int areaIndex, int totalAreas, int iterationNumber)
      Notify the listener that a process area is about to run.
      Parameters:
      areaName - name of the area
      process - the ProcessSystem
      areaIndex - area index
      totalAreas - total number of areas
      iterationNumber - current iteration
    • notifyProcessAreaComplete

      private void notifyProcessAreaComplete(String areaName, ProcessSystem process, int areaIndex, int totalAreas, int iterationNumber)
      Notify the listener that a process area has completed.
      Parameters:
      areaName - name of the area
      process - the ProcessSystem
      areaIndex - area index
      totalAreas - total number of areas
      iterationNumber - current iteration
    • notifyProcessAreaError

      private boolean notifyProcessAreaError(String areaName, ProcessSystem process, Exception exception)
      Notify the listener that a process area encountered an error.
      Parameters:
      areaName - name of the failed area
      process - the ProcessSystem that failed
      exception - the exception
      Returns:
      true to continue execution, false to abort
    • publishModelEvent

      private void publishModelEvent(ProcessEvent.EventType type, String description, ProcessEvent.Severity severity)
      Publish a model-level event to the ProcessEventBus if event publishing is enabled.
      Parameters:
      type - the event type
      description - event description
      severity - event severity
    • runModelAutoValidation

      private void runModelAutoValidation()
      Run auto-validation on all ProcessSystems. Called once before the first iteration when autoValidate is enabled. Validation failures are logged as warnings.
    • isCheckpointEnabled

      public boolean isCheckpointEnabled()
      Checks if automatic checkpointing is enabled.
      Returns:
      true if checkpointing is enabled
    • setCheckpointEnabled

      public void setCheckpointEnabled(boolean checkpointEnabled)
      Sets whether automatic checkpointing is enabled during model execution.
      Parameters:
      checkpointEnabled - true to enable checkpointing
    • getCheckpointInterval

      public int getCheckpointInterval()
      Gets the checkpoint interval (number of iterations between checkpoints).
      Returns:
      the checkpoint interval
    • setCheckpointInterval

      public void setCheckpointInterval(int checkpointInterval)
      Sets the checkpoint interval.
      Parameters:
      checkpointInterval - number of iterations between automatic checkpoints
    • getCheckpointPath

      public String getCheckpointPath()
      Gets the file path for checkpoint files.
      Returns:
      the checkpoint file path, or null if not set
    • setCheckpointPath

      public void setCheckpointPath(String checkpointPath)
      Sets the file path for saving checkpoint files.
      Parameters:
      checkpointPath - the file path for checkpoint files
    • getAutomation

      public ProcessAutomation getAutomation()
      Returns an automation facade for this process model. The facade provides a stable, string-addressable API for scripts and AI agents to interact with all process areas using area-qualified addresses like "AreaName::UnitName.property".
      Returns:
      a ProcessAutomation facade
    • getUnitNames

      public List<String> getUnitNames()
      Returns the names of all unit operations across all process areas. Names are area-qualified in the format "AreaName::UnitName". Convenience delegate for ProcessAutomation.getUnitList().
      Returns:
      unmodifiable list of area-qualified unit operation names
    • getAreaNames

      public List<String> getAreaNames()
      Returns the names of all process areas. Convenience delegate for ProcessAutomation.getAreaList().
      Returns:
      unmodifiable list of area names
    • getUnitNames

      public List<String> getUnitNames(String areaName)
      Returns the names of unit operations in a specific process area. Convenience delegate for ProcessAutomation.getUnitList(String).
      Parameters:
      areaName - the name of the process area
      Returns:
      unmodifiable list of unit operation names
      Throws:
      IllegalArgumentException - if the area is not found
    • getVariableList

      public List<SimulationVariable> getVariableList(String unitName)
      Returns all available variables for the named unit operation. The unitName may be area-qualified: "AreaName::UnitName". Convenience delegate for ProcessAutomation.getVariableList(String).
      Parameters:
      unitName - the name of the unit operation, optionally area-qualified
      Returns:
      list of variable descriptors
      Throws:
      IllegalArgumentException - if the unit is not found
    • getVariableValue

      public double getVariableValue(String address, String unitOfMeasure)
      Reads the current value of a simulation variable by its address. The address should be area-qualified: "AreaName::unitName.property". Convenience delegate for ProcessAutomation.getVariableValue(String, String).
      Parameters:
      address - the area-qualified address, e.g. "Separation::HP Sep.gasOutStream.temperature"
      unitOfMeasure - the desired unit, e.g. "C", "bara", "kg/hr"
      Returns:
      the variable value in the requested unit
      Throws:
      IllegalArgumentException - if the address cannot be resolved
    • setVariableValue

      public void setVariableValue(String address, double value, String unitOfMeasure)
      Sets the value of a simulation input variable. The address should be area-qualified: "AreaName::Compressor.outletPressure". Convenience delegate for ProcessAutomation.setVariableValue(String, double, String).
      Parameters:
      address - the area-qualified address, e.g. "Compression::Compressor.outletPressure"
      value - the value to set
      unitOfMeasure - the unit of the provided value, e.g. "bara", "C"
      Throws:
      IllegalArgumentException - if the address cannot be resolved or the variable is read-only