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
    • 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
    • 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
    • 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
    • remove

      public boolean remove(String name)
      Removes a process by its name.
      Parameters:
      name - a String object
      Returns:
      a boolean
    • 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
    • captureStreamStates

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