Class ProcessOptimizationEngine

java.lang.Object
neqsim.process.util.optimizer.ProcessOptimizationEngine
All Implemented Interfaces:
Serializable

public class ProcessOptimizationEngine extends Object implements Serializable
Unified process optimization engine.

This class provides a comprehensive API for process optimization combining:

  • Flow rate optimization (finding max throughput for given pressure drop)
  • Pressure optimization (finding required pressures for target flow)
  • Equipment constraint evaluation across entire process
  • Multi-objective optimization (maximize throughput while minimizing power)
  • Gradient-based optimization for faster convergence
  • Sensitivity analysis for constraint insights

Optimization Levels:

  • Low-level: Single equipment constraint evaluation
  • Mid-level: Process segment optimization (inlet to outlet)
  • High-level: Full process system optimization with recycles

Example Usage:

ProcessOptimizationEngine engine = new ProcessOptimizationEngine(processSystem);

// Find maximum throughput with gradient acceleration
engine.setSearchAlgorithm(SearchAlgorithm.GRADIENT_ACCELERATED);
OptimizationResult result =
    engine.findMaximumThroughput(inletPressure, outletPressure, minFlow, maxFlow);

// Get sensitivity analysis
SensitivityResult sens = engine.analyzeSensitivity(result.getOptimalValue());

// Evaluate all constraints
ConstraintReport report = engine.evaluateAllConstraints();

// Generate lift curve
LiftCurve curve = engine.generateLiftCurve(pressures, temperatures, waterCuts, GORs);
Version:
2.0
Author:
NeqSim Development Team
See Also:
  • Field Details

    • serialVersionUID

      private static final long serialVersionUID
      Serialization version UID.
      See Also:
    • logger

      private static final org.apache.logging.log4j.Logger logger
      Logger.
    • processSystem

      private ProcessSystem processSystem
      The process system to optimize.
    • processModule

      private ProcessModule processModule
      The process module to optimize (alternative to processSystem).
    • strategyRegistry

      private transient EquipmentCapacityStrategyRegistry strategyRegistry
      Strategy registry for equipment constraint evaluation.
    • tolerance

      private double tolerance
      Optimization tolerance.
    • maxIterations

      private int maxIterations
      Maximum iterations for optimization.
    • searchAlgorithm

      Search algorithm to use.
    • enforceConstraints

      private boolean enforceConstraints
      Whether to check all constraints during optimization.
    • constraintCache

      private transient Map<String, List<CapacityConstraint>> constraintCache
      Constraint evaluation cache.
    • armijoC1

      private double armijoC1
    • wolfeC2

      private double wolfeC2
    • maxLineSearchIterations

      private int maxLineSearchIterations
    • bfgsGradientTolerance

      private double bfgsGradientTolerance
    • feedStreamName

      private String feedStreamName
      Name of the feed stream to vary during optimization.
    • outletStreamName

      private String outletStreamName
      Name of the outlet stream to monitor during optimization.
    • constraintEvaluator

      private transient ProcessConstraintEvaluator constraintEvaluator
      Constraint evaluator for caching and sensitivity analysis.
  • Constructor Details

    • ProcessOptimizationEngine

      public ProcessOptimizationEngine()
      Default constructor.
    • ProcessOptimizationEngine

      public ProcessOptimizationEngine(ProcessSystem processSystem)
      Constructor with process system.
      Parameters:
      processSystem - the process system to optimize
    • ProcessOptimizationEngine

      public ProcessOptimizationEngine(ProcessModule processModule)
      Constructor with process module.
      Parameters:
      processModule - the process module to optimize
  • Method Details

    • getStrategyRegistry

      private EquipmentCapacityStrategyRegistry getStrategyRegistry()
      Gets the strategy registry, initializing if needed (after deserialization).
      Returns:
      the strategy registry, never null
    • runSimulation

      private void runSimulation()
      Run the simulation (either ProcessSystem or ProcessModule).
    • getAllUnitOperations

      private List<ProcessEquipmentInterface> getAllUnitOperations()
      Get all unit operations from either ProcessSystem or ProcessModule.
      Returns:
      list of all unit operations
    • hasProcess

      private boolean hasProcess()
      Check if a process (system or module) is configured.
      Returns:
      true if either processSystem or processModule is set
    • getPrimaryProcessSystem

      private ProcessSystem getPrimaryProcessSystem()
      Get the primary ProcessSystem (first one if using module).
      Returns:
      the ProcessSystem or null
    • findMaximumThroughput

      public ProcessOptimizationEngine.OptimizationResult findMaximumThroughput(double inletPressure, double outletPressure, double minFlow, double maxFlow)
      Finds the maximum throughput for given inlet and outlet pressures.
      Parameters:
      inletPressure - inlet pressure in bara
      outletPressure - outlet pressure in bara
      minFlow - minimum flow to search in kg/hr
      maxFlow - maximum flow to search in kg/hr
      Returns:
      optimization result
    • findRequiredInletPressure

      public ProcessOptimizationEngine.OptimizationResult findRequiredInletPressure(double targetFlow, double outletPressure, double minPressure, double maxPressure)
      Finds the required inlet pressure for a target flow rate.
      Parameters:
      targetFlow - target flow in kg/hr
      outletPressure - outlet pressure in bara
      minPressure - minimum inlet pressure to search in bara
      maxPressure - maximum inlet pressure to search in bara
      Returns:
      optimization result with optimal inlet pressure
    • evaluateAllConstraints

      public ProcessOptimizationEngine.ConstraintReport evaluateAllConstraints()
      Evaluates all constraints across all equipment in the process.
      Returns:
      constraint report with utilizations and violations
    • findBottleneckEquipment

      public String findBottleneckEquipment()
      Finds the bottleneck equipment in the process.
      Returns:
      name of bottleneck equipment or null if no bottleneck
    • generateLiftCurve

      public ProcessOptimizationEngine.LiftCurveData generateLiftCurve(double[] pressures, double[] temperatures, double[] waterCuts, double[] GORs)
      Generates a lift curve for the process.
      Parameters:
      pressures - array of inlet pressures to evaluate in bara
      temperatures - array of inlet temperatures in Kelvin
      waterCuts - array of water cuts as fraction
      GORs - array of gas-oil ratios in Sm3/Sm3
      Returns:
      lift curve data
    • evaluateLiftCurvePoint

      private ProcessOptimizationEngine.LiftCurvePoint evaluateLiftCurvePoint(double pressure, double temperature, double waterCut, double gor)
      Evaluates a single lift curve point.
    • goldenSectionSearch

      private double goldenSectionSearch(double inletPressure, double outletPressure, double minFlow, double maxFlow)
      Golden section search for maximum flow.
    • binarySearch

      private double binarySearch(double inletPressure, double outletPressure, double minFlow, double maxFlow)
      Binary search for maximum flow.
    • pressureBinarySearch

      private double pressureBinarySearch(double targetFlow, double outletPressure, double minPressure, double maxPressure)
      Binary search for required inlet pressure.
    • evaluateFlowObjective

      private double evaluateFlowObjective(double inletPressure, double outletPressure, double flow)
      Evaluates the flow objective function.
    • canAchieveFlow

      private boolean canAchieveFlow(double inletPressure, double outletPressure, double flow)
      Checks if a flow rate can be achieved.
    • canAchieveFlowWithPressure

      private boolean canAchieveFlowWithPressure(double flow, double inletPressure, double outletPressure)
      Checks if flow can be achieved with given inlet pressure.
    • areAllConstraintsSatisfied

      private boolean areAllConstraintsSatisfied()
      Checks if all constraints are satisfied.
    • evaluateAllConstraintViolations

      private List<String> evaluateAllConstraintViolations()
      Evaluates all constraint violations.
    • findMaxFlowAtConditions

      private double findMaxFlowAtConditions(double inletPressure)
      Finds the maximum achievable flow at the given inlet pressure.

      Uses golden section search with a hardcoded outlet pressure of 1.0 bara and a flow range from 0 to 1,000,000 kg/hr. These defaults are intended for quick sensitivity analysis; for precise work, use findMaximumThroughput(double, double, double, double) with explicit bounds.

      Parameters:
      inletPressure - the inlet pressure in bara
      Returns:
      the maximum feasible flow in kg/hr
    • gradientDescentSearch

      public double gradientDescentSearch(double inletPressure, double outletPressure, double initialFlow)
      Performs gradient descent optimization to find maximum flow.

      Uses finite-difference gradient estimation with adaptive step size. More efficient than bracket-based methods when near the optimum.

      Parameters:
      inletPressure - inlet pressure in bara
      outletPressure - outlet pressure in bara
      initialFlow - starting flow rate in kg/hr
      Returns:
      optimal flow rate in kg/hr
    • estimateGradient

      private double estimateGradient(double inletPressure, double outletPressure, double flow)
      Estimates the gradient of the objective function using finite differences.
      Parameters:
      inletPressure - inlet pressure in bara
      outletPressure - outlet pressure in bara
      flow - current flow rate in kg/hr
      Returns:
      estimated gradient
    • evaluateConstrainedObjective

      private double evaluateConstrainedObjective(double inletPressure, double outletPressure, double flow)
      Evaluates the objective function with adaptive constraint penalty.

      The penalty magnitude scales with the flow rate so that the penalty always dominates the objective regardless of problem scale.

      Parameters:
      inletPressure - inlet pressure in bara
      outletPressure - outlet pressure in bara
      flow - flow rate in kg/hr
      Returns:
      objective value (flow rate with penalty for constraint violations)
    • calculateConstraintViolationMagnitude

      private double calculateConstraintViolationMagnitude()
      Calculates the total magnitude of constraint violations.
      Returns:
      sum of squared constraint violations
    • gradientDescentArmijoWolfeSearch

      public double gradientDescentArmijoWolfeSearch(double inletPressure, double outletPressure, double initialFlow)
      Performs gradient descent with Armijo-Wolfe line search conditions.

      The Armijo-Wolfe conditions ensure:

      • Sufficient decrease (Armijo): f(x + alpha*d) <= f(x) + c1*alpha*grad'*d
      • Curvature condition (Wolfe): |grad(x + alpha*d)'*d| <= c2*|grad'*d|

      These conditions guarantee convergence and avoid too-small or too-large steps.

      Parameters:
      inletPressure - inlet pressure in bara
      outletPressure - outlet pressure in bara
      initialFlow - starting flow rate in kg/hr
      Returns:
      optimal flow rate in kg/hr
    • armijoWolfeLineSearch

      private double armijoWolfeLineSearch(double inletPressure, double outletPressure, double flow, double direction, double f0, double directionalDerivative, double initialAlpha)
      Performs Armijo-Wolfe line search to find step size satisfying both conditions.
      Parameters:
      inletPressure - inlet pressure in bara
      outletPressure - outlet pressure in bara
      flow - current flow rate
      direction - search direction
      f0 - objective at current point
      directionalDerivative - gradient dot direction
      initialAlpha - initial step size guess
      Returns:
      step size satisfying Armijo-Wolfe conditions, or initial alpha if failed
    • bfgsSearch

      public double bfgsSearch(double inletPressure, double outletPressure, double initialFlow, double minFlow, double maxFlow)
      Performs BFGS (Broyden-Fletcher-Goldfarb-Shanno) quasi-Newton optimization.

      BFGS is a quasi-Newton method that approximates the inverse Hessian matrix using gradient information. This provides superlinear convergence near the optimum, typically much faster than steepest descent.

      For the 1D flow optimization problem, this simplifies to a scalar version that maintains an approximation of the inverse second derivative.

      Parameters:
      inletPressure - inlet pressure in bara
      outletPressure - outlet pressure in bara
      initialFlow - starting flow rate in kg/hr
      minFlow - minimum allowed flow in kg/hr
      maxFlow - maximum allowed flow in kg/hr
      Returns:
      optimal flow rate in kg/hr
    • setArmijoC1

      public void setArmijoC1(double c1)
      Sets the Armijo sufficient decrease parameter (c1).

      Typical values: 1e-4 (default). Must satisfy 0 < c1 < c2 < 1.

      Parameters:
      c1 - the Armijo parameter (default 1e-4)
    • setWolfeC2

      public void setWolfeC2(double c2)
      Sets the Wolfe curvature condition parameter (c2).

      Typical values: 0.9 for quasi-Newton methods (default), 0.1 for conjugate gradient. Must satisfy 0 < c1 < c2 < 1.

      Parameters:
      c2 - the Wolfe curvature parameter (default 0.9)
    • setBfgsGradientTolerance

      public void setBfgsGradientTolerance(double tolerance)
      Sets the BFGS gradient tolerance for convergence.
      Parameters:
      tolerance - gradient tolerance (default 1e-6)
    • setMaxLineSearchIterations

      public void setMaxLineSearchIterations(int iterations)
      Sets the maximum number of line search iterations.
      Parameters:
      iterations - maximum iterations (default 20)
    • analyzeSensitivity

      public ProcessOptimizationEngine.SensitivityResult analyzeSensitivity(double optimalFlow, double inletPressure, double outletPressure)
      Analyzes the sensitivity of the optimal solution to flow rate changes.
      Parameters:
      optimalFlow - the optimal flow rate in kg/hr
      inletPressure - inlet pressure in bara
      outletPressure - outlet pressure in bara
      Returns:
      sensitivity result with gradient and margin information
    • estimateFlowBuffer

      private double estimateFlowBuffer(double currentFlow, double inletPressure, double outletPressure)
      Estimates how much flow can increase before hitting a constraint.
      Parameters:
      currentFlow - current flow rate in kg/hr
      inletPressure - inlet pressure in bara
      outletPressure - outlet pressure in bara
      Returns:
      estimated flow buffer in kg/hr
    • calculateShadowPrices

      public Map<String,Double> calculateShadowPrices(double optimalFlow, double inletPressure, double outletPressure)
      Calculates shadow prices for each constraint using finite-difference perturbation.

      Shadow price indicates how much the objective (flow rate) would improve if the equipment's capacity constraint were relaxed by a small fraction. A positive shadow price means the constraint is binding and relaxing it would increase throughput.

      The method perturbs the flow rate slightly above the optimum and measures which equipment constraints become violated. The shadow price is estimated as the ratio of obtainable flow increase to the constraint relaxation needed, giving a dimensionless sensitivity. Equipment that is not near its capacity limit receives a shadow price of zero.

      Parameters:
      optimalFlow - the optimal flow rate in kg/hr
      inletPressure - inlet pressure in bara
      outletPressure - outlet pressure in bara
      Returns:
      map of equipment name to shadow price (higher means more binding)
    • createFlowRateOptimizer

      public FlowRateOptimizer createFlowRateOptimizer()
      Creates and configures a FlowRateOptimizer for this process system.

      This integrates the detailed FlowRateOptimizer with the ProcessOptimizationEngine, allowing for more sophisticated optimization scenarios including lift curve generation and reservoir integration.

      Returns:
      configured FlowRateOptimizer instance
    • generateComprehensiveLiftCurve

      public FlowRateOptimizer generateComprehensiveLiftCurve(String feedStreamName, double[] inletPressures, double outletPressure)
      Generates a comprehensive lift curve using FlowRateOptimizer.
      Parameters:
      feedStreamName - name of the feed stream
      inletPressures - array of inlet pressures to evaluate
      outletPressure - target outlet pressure
      Returns:
      FlowRateOptimizer configured with lift curve results
    • getConstraintEvaluator

      public ProcessConstraintEvaluator getConstraintEvaluator()
      Gets or creates the constraint evaluator.
      Returns:
      constraint evaluator instance
    • evaluateConstraintsWithCache

      public ProcessConstraintEvaluator.ConstraintEvaluationResult evaluateConstraintsWithCache()
      Evaluates constraints using cached evaluator for better performance.
      Returns:
      constraint evaluation result
    • calculateFlowSensitivities

      public Map<String,Double> calculateFlowSensitivities(double baseFlowRate, String flowUnit)
      Calculates flow sensitivities for all equipment.
      Parameters:
      baseFlowRate - base flow rate in kg/hr
      flowUnit - flow rate unit
      Returns:
      map of equipment name to sensitivity value
    • estimateMaximumFlow

      public double estimateMaximumFlow(double currentFlowRate, String flowUnit)
      Estimates maximum feasible flow rate.
      Parameters:
      currentFlowRate - current flow rate
      flowUnit - flow rate unit
      Returns:
      estimated maximum flow rate
    • setFeedFlowRate

      private void setFeedFlowRate(double flowKgPerHr)
      Sets the feed flow rate.

      If a feed stream name is specified via setFeedStreamName(String), that stream will be used. Otherwise, the first unit operation is assumed to be the feed stream.

      Parameters:
      flowKgPerHr - flow rate in kg/hr
    • setInletPressure

      private void setInletPressure(double pressureBara)
      Sets the inlet pressure.
      Parameters:
      pressureBara - pressure in bara
    • getFeedStream

      private ProcessEquipmentInterface getFeedStream()
      Gets the feed stream being used for optimization.

      If a feed stream name is specified, finds that stream by name. Otherwise, returns the first unit operation.

      Returns:
      the feed stream, or null if not found
    • setFeedStreamName

      public ProcessOptimizationEngine setFeedStreamName(String name)
      Sets the name of the feed stream to vary during optimization.

      Use this method to explicitly specify which stream should have its flow rate varied. If not set, the first unit operation in the process is used by default.

      Parameters:
      name - the name of the feed stream
      Returns:
      this engine for method chaining
    • getFeedStreamName

      public String getFeedStreamName()
      Gets the name of the feed stream being varied.
      Returns:
      the feed stream name, or null if using default (first unit)
    • setInletConditions

      private void setInletConditions(double pressure, double temperature, double waterCut, double gor)
      Sets inlet conditions.
    • getOutletStream

      private ProcessEquipmentInterface getOutletStream()
      Gets the outlet stream used for optimization.

      If setOutletStreamName(String) was called, returns that stream. Otherwise returns the last unit operation in the process.

      Returns:
      the outlet stream, or null if not found
    • setOutletStreamName

      public ProcessOptimizationEngine setOutletStreamName(String name)
      Sets the name of the outlet stream to monitor during optimization.

      Use this method to explicitly specify which stream should be monitored for outlet conditions (pressure, temperature, flow rate). If not set, the last unit operation in the process is used by default.

      Parameters:
      name - the name of the outlet stream
      Returns:
      this engine for method chaining
    • getOutletStreamName

      public String getOutletStreamName()
      Gets the name of the outlet stream being monitored.
      Returns:
      the outlet stream name, or null if using default (last unit)
    • getOutletPressure

      private double getOutletPressure()
      Gets the outlet pressure from the configured outlet stream.
      Returns:
      outlet pressure in bara, or 0.0 if no outlet stream found
    • getOutletTemperature

      public double getOutletTemperature()
      Gets the outlet temperature from the configured outlet stream.
      Returns:
      outlet temperature in Kelvin, or 0.0 if no outlet stream found
    • getOutletTemperature

      public double getOutletTemperature(String unit)
      Gets the outlet temperature from the configured outlet stream in specified unit.
      Parameters:
      unit - temperature unit ("K", "C", "R", "F")
      Returns:
      outlet temperature in specified unit, or 0.0 if no outlet stream found
    • getOutletFlowRate

      public double getOutletFlowRate(String flowUnit)
      Gets the outlet flow rate from the configured outlet stream.
      Parameters:
      flowUnit - flow rate unit (e.g., "kg/hr", "MSm3/day")
      Returns:
      outlet flow rate in specified unit, or 0.0 if no outlet stream found
    • getProcessSystem

      public ProcessSystem getProcessSystem()
      Gets the process system.
      Returns:
      process system
    • setProcessSystem

      public void setProcessSystem(ProcessSystem processSystem)
      Sets the process system.
      Parameters:
      processSystem - process system
    • getTolerance

      public double getTolerance()
      Gets the tolerance.
      Returns:
      tolerance
    • setTolerance

      public void setTolerance(double tolerance)
      Sets the tolerance.
      Parameters:
      tolerance - convergence tolerance
    • getMaxIterations

      public int getMaxIterations()
      Gets the max iterations.
      Returns:
      max iterations
    • setMaxIterations

      public void setMaxIterations(int maxIterations)
      Sets the max iterations.
      Parameters:
      maxIterations - max iterations
    • getSearchAlgorithm

      public ProcessOptimizationEngine.SearchAlgorithm getSearchAlgorithm()
      Gets the search algorithm.
      Returns:
      search algorithm
    • setSearchAlgorithm

      public void setSearchAlgorithm(ProcessOptimizationEngine.SearchAlgorithm algorithm)
      Sets the search algorithm.
      Parameters:
      algorithm - search algorithm
    • isEnforceConstraints

      public boolean isEnforceConstraints()
      Checks if constraints are enforced.
      Returns:
      true if enforced
    • setEnforceConstraints

      public void setEnforceConstraints(boolean enforce)
      Sets whether to enforce constraints.
      Parameters:
      enforce - true to enforce
    • clearCache

      public void clearCache()
      Clears the constraint cache.
    • getAdjusters

      public List<Adjuster> getAdjusters()
      Gets all Adjuster units in the process system.
      Returns:
      list of Adjuster units
    • disableAdjusters

      public List<Adjuster> disableAdjusters()
      Temporarily disables all Adjusters during optimization.

      Adjusters can interfere with optimization by trying to converge to their own targets. This method disables them and returns a list of the disabled adjusters for later re-enabling.

      Returns:
      list of adjusters that were disabled
    • enableAdjusters

      public void enableAdjusters(List<Adjuster> adjusters)
      Re-enables previously disabled Adjusters.
      Parameters:
      adjusters - list of adjusters to re-enable
    • optimizeWithAdjustersDisabled

      public ProcessOptimizationEngine.OptimizationResult optimizeWithAdjustersDisabled(double inletPressure, double outletPressure, double minFlow, double maxFlow)
      Optimizes with Adjusters temporarily disabled.

      This method disables all Adjusters during optimization, runs the optimization, and then re-enables them. This prevents the Adjusters from interfering with the optimization search.

      Parameters:
      inletPressure - inlet pressure in bara
      outletPressure - outlet pressure in bara
      minFlow - minimum flow rate in kg/hr
      maxFlow - maximum flow rate in kg/hr
      Returns:
      optimization result
    • createFlowAdjuster

      public Adjuster createFlowAdjuster(String name, String feedStreamName, String targetEquipmentName, String targetVariable, double targetValue, String targetUnit)
      Creates an Adjuster to optimize flow rate for a target variable.

      This method creates a new Adjuster that adjusts the feed stream flow rate to achieve a target value for a specified variable (e.g., outlet pressure, temperature).

      Parameters:
      name - name for the new Adjuster
      feedStreamName - name of the feed stream to adjust
      targetEquipmentName - name of the equipment with the target variable
      targetVariable - name of the target variable (e.g., "pressure", "temperature")
      targetValue - target value for the variable
      targetUnit - unit for the target value
      Returns:
      the created Adjuster, or null if creation fails
    • optimizeWithAdjusterTargets

      public ProcessOptimizationEngine.OptimizationResult optimizeWithAdjusterTargets(double inletPressure, double outletPressure, double minFlow, double maxFlow)
      Coordinates optimization with existing Adjusters.

      This method performs optimization while respecting the targets set by existing Adjusters. It finds the maximum flow rate that still allows all Adjusters to converge to their targets.

      Parameters:
      inletPressure - inlet pressure in bara
      outletPressure - outlet pressure in bara
      minFlow - minimum flow rate in kg/hr
      maxFlow - maximum flow rate in kg/hr
      Returns:
      optimization result with Adjuster-compatible flow rate
    • checkAdjusterConvergence

      private boolean checkAdjusterConvergence(double flowRate)
      Checks if all Adjusters can converge at the given flow rate.
      Parameters:
      flowRate - flow rate to test in kg/hr
      Returns:
      true if all Adjusters converge