Class ProcessModel
- All Implemented Interfaces:
Serializable, Runnable
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:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceInterface for monitoring ProcessModel execution progress. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate booleanWhen true, validateSetup() is called on each ProcessSystem before the first iteration.private booleanWhether automatic checkpointing is enabled during model execution.private intNumber of iterations between automatic checkpoints.private StringFile path for saving checkpoint files.private doubleprivate intprivate doubleprivate doubleprivate double(package private) static org.apache.logging.log4j.LoggerLogger object for class.private intprivate booleanprivate doubleprivate Map<String, ProcessSystem> Transient listener for model-level progress callbacks.private booleanWhen true, lifecycle events are published to the ProcessEventBus singleton during model execution.private booleanprivate static final longprivate doubleprivate booleanWhen true, every ProcessSystem registered with this model has flash warm-start enabled for the duration of its run (viaProcessSystem.setUseFlashWarmStart(boolean)).private boolean -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionbooleanadd(String name, ProcessSystem process) Adds a process to the model.intAuto-sizes all equipment in this model that implementsAutoSizeable.intautoSizeEquipment(double safetyFactor) Auto-sizes all equipment in this model with the specified safety factor.intautoSizeEquipment(String companyStandard, String trDocument) Auto-sizes all equipment in this model using company-specific design standards.private List<List<ProcessSystem>> Partitions ProcessSystems into execution levels based on inter-area stream dependencies.private double[]calculateConvergenceErrors(Map<String, double[]> previous, Map<String, double[]> current) Calculate maximum relative errors between previous and current stream states.Capture current state of all streams in all processes.captureStreamStates(Set<Object> boundaryStreams) Capture current state of streams in all processes, optionally restricted to the supplied boundary set.Check mass balance of all unit operations in all processes using kg/sec.checkMassBalance(String unit) Check mass balance of all unit operations in all processes.Collect the identity-set of streams that cross area boundaries in the currentProcessModel.private static doubleconvertEnergy(double valueJ, String unit) Convert Joules to the requested energy / power unit.Exports the current state of this ProcessModel for inspection or modification.private List<List<ProcessSystem>> Finds groups of independent ProcessSystems that can run in parallel.static ProcessModelBuilds a ProcessModel from a JSON string containing named process areas.static ProcessModelfromJsonAndRun(String json) Builds and immediately runs a ProcessModel from a JSON string.generateReferenceDesignations(String locationPrefix) Generates IEC 81346 reference designations for all equipment across all process areas in this model.generateReferenceDesignations(String functionPrefix, String locationPrefix) Generates IEC 81346 reference designations with hierarchical function structure.Retrieves a process by its name.Retrieves a list of all processes.Returns the names of all process areas.Returns an automation facade for this process model.intGets the checkpoint interval (number of iterations between checkpoints).Gets the file path for checkpoint files.Get a summary of the convergence status after running the model.doublegetError()Get the maximum error across all variables (flow, temperature, pressure).Gets a combined execution partition analysis for all ProcessSystems.Build a structuredExergyAnalysisReportcovering every unit operation in every process area, with each entry tagged by its area name.doublegetExergyChange(String unit) Total change in stream exergy (outlet − inlet) aggregated over every unit operation in every process area.doublegetExergyDestruction(String unit) Total exergy destruction rate aggregated over every unit operation in every process area.Get unit operations that failed mass balance check in all processes using kg/sec and default threshold.getFailedMassBalance(double percentThreshold) Get unit operations that failed mass balance check in all processes using specified threshold.getFailedMassBalance(String unit, double percentThreshold) Get unit operations that failed mass balance check in all processes based on percentage error threshold.Get a formatted report of failed mass balance checks for all processes using kg/sec and default threshold.getFailedMassBalanceReport(double percentThreshold) Get a formatted report of failed mass balance checks for all processes using specified threshold.getFailedMassBalanceReport(String unit, double percentThreshold) Get a formatted report of failed mass balance checks for all processes.doubleGet flow tolerance for convergence check (relative error).intGet the number of iterations from the last run.doubleGet maximum flow error from the last iteration.doubleGet maximum pressure error from the last iteration.doubleGet maximum temperature error from the last iteration.Get a formatted mass balance report for all processes using kg/sec.getMassBalanceReport(String unit) Get a formatted mass balance report for all processes.intGet the maximum number of iterations for the model.doubleGet pressure tolerance for convergence check (relative error).Returns the names of all process systems in insertion order.Get the current model progress listener.getReport_json.doubleGet temperature tolerance for convergence check (relative error).(Optional) Creates separate threads for each process (if you need them).getUnitByReferenceDesignation(String refDesignation) Looks up a process equipment unit across all process areas by its IEC 81346 reference designation string (e.g.Returns the names of all unit operations across all process areas.getUnitNames(String areaName) Returns the names of unit operations in a specific process area.Get a formatted validation report for all processes.getVariableList(String unitName) Returns all available variables for the named unit operation.doublegetVariableValue(String address, String unitOfMeasure) Reads the current value of a simulation variable by its address.booleanChecks whether a process system with the given name exists.booleanReturns whether auto-validation is enabled.booleanChecks if automatic checkpointing is enabled.booleanChecks if all processes are finished.booleanCheck if the model converged in the last run.booleanReturns whether event publishing is enabled.booleanChecks if all processes in the model are ready to run.booleanChecks if the model is running in step mode.booleanReturns whether flash warm-start is enabled for the ProcessSystems in this model.booleanCheck if optimized execution is enabled for individual ProcessSystems.static ProcessModelLoads a ProcessModel with automatic format detection based on file extension.static ProcessModelloadFromNeqsim(String filename) Loads a ProcessModel from a compressed .neqsim file.static ProcessModelloadStateFromFile(String filename) Loads ProcessModel state from a JSON file.private voidnotifyBeforeIteration(int iterationNumber) Notify the listener that an iteration is about to start.private voidnotifyBeforeProcessArea(String areaName, ProcessSystem process, int areaIndex, int totalAreas, int iterationNumber) Notify the listener that a process area is about to run.private voidnotifyIterationComplete(int iterationNumber, boolean converged, double maxError) Notify the listener that an iteration has completed.private voidnotifyModelComplete(int totalIterations, boolean converged) Notify the listener that the model has completed.private voidnotifyModelStart(int totalAreas) Notify the listener that the model is starting.private voidnotifyProcessAreaComplete(String areaName, ProcessSystem process, int areaIndex, int totalAreas, int iterationNumber) Notify the listener that a process area has completed.private booleannotifyProcessAreaError(String areaName, ProcessSystem process, Exception exception) Notify the listener that a process area encountered an error.private voidpublishModelEvent(ProcessEvent.EventType type, String description, ProcessEvent.Severity severity) Publish a model-level event to the ProcessEventBus if event publishing is enabled.booleanRemoves a process by its name.voidrun()private voidRuns all ProcessSystems, using parallel execution for independent systems.private voidrunAllProcessesWithHooks(int iterationNumber) Runs all ProcessSystems with listener hooks, firing before/after area callbacks sequentially.Future<?> Runs this model in a separate thread using the global NeqSim thread pool.Deprecated.private voidRun auto-validation on all ProcessSystems.private voidrunSingleProcess(ProcessSystem process) Runs a single ProcessSystem using the configured execution strategy.voidrunStep()Runs all processes in a single step (used outside of the thread model).booleanSaves this ProcessModel with automatic format detection based on file extension.booleansaveStateToFile(String filename) Exports the current state of this ProcessModel to a JSON file.booleansaveToNeqsim(String filename) Saves this ProcessModel (with all ProcessSystems) to a compressed .neqsim file.voidsetAutoValidate(boolean validate) Enables or disables automatic validation of each ProcessSystem before the first iteration.intsetCapacityAnalysisEnabled(boolean enabled) Enables or disables capacity analysis for all equipment in all process systems.voidsetCheckpointEnabled(boolean checkpointEnabled) Sets whether automatic checkpointing is enabled during model execution.voidsetCheckpointInterval(int checkpointInterval) Sets the checkpoint interval.voidsetCheckpointPath(String checkpointPath) Sets the file path for saving checkpoint files.voidsetFlowTolerance(double flowTolerance) Set flow tolerance for convergence check (relative error).voidsetMaxIterations(int maxIterations) Set the maximum number of iterations for the model.voidsetPressureTolerance(double pressureTolerance) Set pressure tolerance for convergence check (relative error).voidSet a listener to receive progress updates during model execution.voidsetPublishEvents(boolean publish) Enables or disables event publishing to the ProcessEventBus singleton.intApply an acceleration method to everyRecycleunit across all areas in thisProcessModel.voidsetRunStep(boolean runStep) Sets the step mode for the process.voidsetTemperatureTolerance(double temperatureTolerance) Set temperature tolerance for convergence check (relative error).voidsetTolerance(double tolerance) Set all tolerances at once.voidsetUseFlashWarmStart(boolean useWarmStart) Enable or disable flash warm-start K-values for every ProcessSystem in this model.voidsetUseOptimizedExecution(boolean useOptimizedExecution) Enable or disable optimized execution for individual ProcessSystems.voidsetVariableValue(String address, double value, String unitOfMeasure) Sets the value of a simulation input variable.intsize()Returns the number of process systems in this model.toJson()Exports this ProcessModel to a JSON string containing all named process areas.toJson(boolean prettyPrint) Exports this ProcessModel to a JSON string.Validates all processes and returns results organized by process name.Validates the setup of all processes in this model.private voidwaitForFutures(List<Future<?>> futures) Waits for all futures to complete and logs any errors.
-
Field Details
-
serialVersionUID
private static final long serialVersionUID- See Also:
-
logger
static org.apache.logging.log4j.Logger loggerLogger object for class. -
processes
-
runStep
private boolean runStep -
maxIterations
private int maxIterations -
useOptimizedExecution
private boolean useOptimizedExecution -
progressListener
Transient listener for model-level progress callbacks. Marked transient to avoid serialization issues. -
publishEvents
private boolean publishEventsWhen true, lifecycle events are published to the ProcessEventBus singleton during model execution. Default is false for zero overhead when not needed. -
autoValidate
private boolean autoValidateWhen true, validateSetup() is called on each ProcessSystem before the first iteration. Validation warnings are logged but do not abort execution. -
useFlashWarmStart
private boolean useFlashWarmStartWhen true, every ProcessSystem registered with this model has flash warm-start enabled for the duration of its run (viaProcessSystem.setUseFlashWarmStart(boolean)). Default isfalse. Setting this flag updates all currently registered ProcessSystems and applies to any ProcessSystem added afterwards. -
checkpointEnabled
private boolean checkpointEnabledWhether automatic checkpointing is enabled during model execution. -
checkpointInterval
private int checkpointIntervalNumber of iterations between automatic checkpoints. -
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 sequentialSimulationInterface.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 viaadd(String, ProcessSystem). Each ProcessSystem manages the underlyingThermodynamicModelSettingsflag with try/finally inside its ownrun()so the setting never leaks past the model run. Default isfalse(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
Set a listener to receive progress updates during model execution.- Parameters:
listener- the progress listener, or null to disable callbacks
-
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
Adds a process to the model.- Parameters:
name- aStringobjectprocess- aProcessSystemobject- Returns:
- a boolean
-
get
Retrieves a process by its name.- Parameters:
name- aStringobject- Returns:
- a
ProcessSystemobject
-
getProcessSystemNames
-
size
public int size()Returns the number of process systems in this model.- Returns:
- the number of process systems
-
has
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
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
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
nullif not found in any area
-
remove
-
setRecycleAccelerationMethod
Apply an acceleration method to everyRecycleunit across all areas in thisProcessModel.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 benull)- Returns:
- total number of
Recycleunits updated across all areas
-
getExergyChange
Total change in stream exergy (outlet − inlet) aggregated over every unit operation in every process area. Each area contributes using its ownsurrounding 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
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
Build a structuredExergyAnalysisReportcovering 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
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 usesProcessSystem.runOptimized()for best performance. -
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
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
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
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
-
captureStreamStates
-
captureStreamStates
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)). WhenboundaryStreamsisnullor empty, all streams are captured (backward-compatible behaviour).- Parameters:
boundaryStreams- identity-set of streams to capture, ornullfor all streams- Returns:
- map of stream name to [flowRate, temperature, pressure]
-
collectBoundaryStreams
Collect the identity-set of streams that cross area boundaries in the currentProcessModel. A stream is a boundary stream if it appears in at least twoProcessSystems.- 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 statescurrent- current stream states- Returns:
- array of [maxFlowError, maxTempError, maxPressError]
-
getConvergenceSummary
Get a summary of the convergence status after running the model.- Returns:
- formatted convergence summary 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
Runs this model in a separate thread using the global NeqSim thread pool.This method submits the model to the shared
NeqSimThreadPooland returns aFuturethat can be used to monitor completion, cancel the task, or retrieve any exceptions that occurred.- Returns:
- a
Futurerepresenting the pending completion of the task - See Also:
-
runAsThread
Deprecated.UserunAsTask()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
Threadobject
-
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
-
getAllProcesses
Retrieves a list of all processes.- Returns:
- a
CollectionofProcessSystemobjects
-
checkMassBalance
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
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
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
-
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
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
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
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
-
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
JsonProcessBuilderschema (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
Exports this ProcessModel to a JSON string.- Parameters:
prettyPrint- whether to format the JSON with indentation- Returns:
- JSON string representing all process areas
-
fromJson
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
Builds and immediately runs a ProcessModel from a JSON string.Convenience method that combines
fromJson(String)andrun()in a single call. This is the round-trip counterpart totoJson().- 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
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
ValidationResultcontaining all validation issues across all processes
-
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
Mapmapping 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
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
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
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
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
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
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
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
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 implementsAutoSizeable.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
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 performedconverged- 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 completedconverged- whether convergence was achievedmaxError- 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 areaprocess- the ProcessSystemareaIndex- area indextotalAreas- total number of areasiterationNumber- 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 areaprocess- the ProcessSystemareaIndex- area indextotalAreas- total number of areasiterationNumber- current iteration
-
notifyProcessAreaError
Notify the listener that a process area encountered an error.- Parameters:
areaName- name of the failed areaprocess- the ProcessSystem that failedexception- 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 typedescription- event descriptionseverity- 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
Gets the file path for checkpoint files.- Returns:
- the checkpoint file path, or null if not set
-
setCheckpointPath
Sets the file path for saving checkpoint files.- Parameters:
checkpointPath- the file path for checkpoint files
-
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
ProcessAutomationfacade
-
getUnitNames
Returns the names of all unit operations across all process areas. Names are area-qualified in the format"AreaName::UnitName". Convenience delegate forProcessAutomation.getUnitList().- Returns:
- unmodifiable list of area-qualified unit operation names
-
getAreaNames
Returns the names of all process areas. Convenience delegate forProcessAutomation.getAreaList().- Returns:
- unmodifiable list of area names
-
getUnitNames
Returns the names of unit operations in a specific process area. Convenience delegate forProcessAutomation.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
Returns all available variables for the named unit operation. TheunitNamemay be area-qualified:"AreaName::UnitName". Convenience delegate forProcessAutomation.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
Reads the current value of a simulation variable by its address. The address should be area-qualified:"AreaName::unitName.property". Convenience delegate forProcessAutomation.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
Sets the value of a simulation input variable. The address should be area-qualified:"AreaName::Compressor.outletPressure". Convenience delegate forProcessAutomation.setVariableValue(String, double, String).- Parameters:
address- the area-qualified address, e.g. "Compression::Compressor.outletPressure"value- the value to setunitOfMeasure- the unit of the provided value, e.g. "bara", "C"- Throws:
IllegalArgumentException- if the address cannot be resolved or the variable is read-only
-
runAsTask()instead for better resource management.