### Initial Simulation Optimization Setup Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/example_v0.1.ipynb Sets up the initial guess for the optimization variables (x0) and performs a test calculation using these values. It then prints the resulting simulation values and saves the flowsheet at the specified path. ```python # Initial simulation optimization setup # Initial guess of optimization x0 = np.array( [0.25/3600, 0.70/3600, 1.0/3600, 1.10/3600, 1.80/3600, 2.50e5, 50.0e5, -60+273.15] ) # Testing for simulation at x0 sim_smr.calculate_optProblem(1.0*x0) print(sim_smr.x_val, sim_smr.f_val, sim_smr.g_val) # Test saving simulation at x0 in 'savepath' sim_smr.interface.SaveFlowsheet(sim_smr.flowsheet,sim_smr.savepath,True) ``` -------------------------------- ### Locate DWSIM Installation Path in Python Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.1.ipynb This Python snippet demonstrates how to dynamically locate the DWSIM installation path from the system's environment variables. If DWSIM is not found in the path, it falls back to a manually specified default path. This ensures that the simulation can be run regardless of how DWSIM was installed or configured. ```python # Getting DWSIM path from system path for k,v in enumerate(os.environ['path'].split(';')): if v.find('\DWSIM')>-1: path2dwsim = os.path.join(v, '') if path2dwsim == None: path2dwsim = "C:\\Users\\lfsfr\\AppData\\Local\\DWSIM731\\" #insert manuall path2dwsim = "C:\\Users\\lfsfr\\AppData\\Local\\DWSIM731\\" #insert manuall print(path2dwsim) ``` -------------------------------- ### Set up DWSIM Environment and Load Simulation Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG_compositeCurve/example_PRICO_composite_v0.1.ipynb This snippet demonstrates how to set up the Python environment to interact with DWSIM. It involves adding the DWSIM installation directory to the system path, ensuring the necessary modules are imported correctly, and loading a DWSIM simulation file into a Python object for further manipulation. ```python import numpy as np from pprint import pprint import os from pathlib import Path from dwsimopt.utils import PATH2DWSIMOPT dir_path = str(Path(os.getcwd()).parent.absolute()) print(dir_path) import sys sys.path.append(dir_path) if 'dwsimopt.sim_opt' in sys.modules: # Is the module in the register? del sys.modules['dwsimopt.sim_opt'] # If so, remove it. # del SimulationOptimization # This line seems to be commented out in the original code, uncomment if needed from dwsimopt.sim_opt import SimulationOptimization ``` ```python # Getting DWSIM path from system path path2dwsim = None # Initialize to None for k,v in enumerate(os.environ['path'].split(';')): if v.find('\DWSIM')>-1: path2dwsim = os.path.join(v, '') if path2dwsim == None: path2dwsim = "C:\\Users\\lfsfr\\AppData\\Local\\DWSIM7\\" #insert manuall # The following line overwrites the previous logic, consider if this is intended path2dwsim = "C:\\Users\\lfsfr\\AppData\\Local\\DWSIM7\\" #insert manuall print(path2dwsim) # Loading DWSIM simulation into Python (Simulation object) sim = SimulationOptimization(dof=np.array([]), path2sim= os.path.join(dir_path, "PRICO_LNG_compositeCurve\\PRICO_composite.dwxmz"), path2dwsim = path2dwsim, savepath = os.path.join(dir_path, "PRICO_LNG_compositeCurve\\PRICO_composite2.dwxmz")) sim.add_refs() # Instanciate automation manager object from DWSIM.Automation import Automation2 if ('interf' not in locals()): # create automation manager interf = Automation2() # Connect simulation in sim.path2sim sim.connect(interf) ``` -------------------------------- ### Python: Setup DWSIM Environment and Load Simulation Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/example_v0.1.ipynb This snippet sets up the Python environment to interact with DWSIM by adding the project directory to the system path and dynamically importing the necessary `SimulationOptimization` class. It handles potential re-imports by removing the module from `sys.modules` if it already exists. This ensures a clean slate for loading the simulation. ```python import numpy as np from pprint import pprint import os from pathlib import Path from dwsimopt.utils import PATH2DWSIMOPT dir_path = str(Path(os.getcwd()).parent.absolute()) print(dir_path) import sys sys.path.append(dir_path) if 'dwsimopt.sim_opt' in sys.modules: del sys.modules['dwsimopt.sim_opt'] del SimulationOptimization from dwsimopt.sim_opt import SimulationOptimization ``` -------------------------------- ### Determine DWSIM Installation Path in Python Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.0.1.ipynb This Python code snippet iterates through the system's environment path to locate the DWSIM installation directory. If found, it constructs the path to the DWSIM executable. If not found, it defaults to a common installation path for DWSIM 7. This is often a prerequisite for integrating external simulation tools with Python scripts. ```python # Getting DWSIM path from system path for k,v in enumerate(os.environ['path'].split(';')): if v.find('\DWSIM')>-1: path2dwsim = os.path.join(v, '') if path2dwsim == None: path2dwsim = "C:\\Users\\lfsfr\\AppData\\Local\\DWSIM7\\" ``` -------------------------------- ### DWSIM Optimization Setup: Tolerances, Bounds, and Constraints Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.0.1.ipynb This section details the setup for DWSIM optimization, including defining convergence tolerances (xtol, ftol), maximum iterations, decision variable bounds (both raw and regularized), and setting up objective and constraint functions using lambda expressions and SciPy's optimization tools. ```python # Setup for optimization # convergence tolerances xtol=0.01 ftol=0.01 maxiter=5 # +- 20 seconds per iteration # decision variables bounds bounds_raw = np.array( [0.5*np.asarray(x0), 1.5*np.asarray(x0)] ) # 50 % around base case bounds_raw[0][-1] = 153 # precool temperature low limit manually bounds_raw[1][-1] = 253 # precool temperature upper limit manually # regularizer calculation regularizer = np.zeros(x0.size) import math for i in range(len(regularizer)): regularizer[i] = 10**(-1*math.floor(math.log(x0[i],10))) # regularizer for magnitude order of 1e0 # bounds regularized bounds_reg = regularizer*bounds_raw bounds = optimize.Bounds(bounds_reg[0], bounds_reg[1]) # objective and constraints lambda definitions f = lambda x: sim_smr.calculate_optProblem(np.asarray(x)/regularizer)[0:sim_smr.n_f] g = lambda x: sim_smr.calculate_optProblem(np.asarray(x)/regularizer)[sim_smr.n_f:(sim_smr.n_f+sim_smr.n_g)] nonlinear_constraint = optimize.NonlinearConstraint(g, -np.inf, 0, jac='2-point', hess=optimize.BFGS()) ``` -------------------------------- ### Initialize and Test DWSIM Optimization Problem Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG_compositeCurve/example_PRICO_composite_v0.1.ipynb This Python code sets up the initial conditions for a DWSIM optimization problem by defining an initial guess `x0` for the optimization variables. It then runs a simulation using `sim.calculate_optProblem` with this initial guess to test the setup and potentially observe initial simulation results. This is a foundational step in performing parameter optimization with DWSIM. ```python # Initial simulation optimization setup # Initial guess of optimization x0 = np.array( [1.3*1.12083333e-04, 1.3*2.20416667e-04, 1.3*1.42216680e-04, 1.3*7.54165016e-04, 3.45000000e+05, 7.20000000e+06] ) # Testing for simulation at x0 sim.calculate_optProblem(1.0*x0) # print(sim.x_val, # sim.f_val, # sim.g_val) ``` -------------------------------- ### Set DWSIM Path for Simulation Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/SMR_LNG/example_SMR_v0.0.1.ipynb This Python code snippet aims to locate the DWSIM installation directory. It iterates through the system's PATH environment variable to find a directory containing 'DWSIM'. If found, it constructs the path to the DWSIM executable. If not found, it defaults to a common installation path for DWSIM 7. This path is crucial for integrating DWSIM with optimization scripts. ```python # Getting DWSIM path from system path path2dwsim = None for k,v in enumerate(os.environ['path'].split(';')): if v.find('\DWSIM')>-1: path2dwsim = os.path.join(v, '') if path2dwsim == None: path2dwsim = "C:\\Users\\lfsfr\\AppData\\Local\\DWSIM7\\" ``` -------------------------------- ### Python: Configure DWSIM Path and Load Simulation Object Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/example_v0.1.ipynb This code configures the path to the DWSIM installation, either by reading from the system's PATH environment variable or prompting the user for manual input. It then loads a DWSIM simulation file (`.dwxmz`) into a `SimulationOptimization` object, specifying paths for the input simulation, DWSIM executable, and a save path for the modified simulation. Finally, it initializes the DWSIM automation interface and connects the loaded simulation to it. ```python # Getting DWSIM path from system path path2dwsim = [] for k,v in enumerate(os.environ['path'].split(';')): if v.find('\DWSIM')>-1: path2dwsim = os.path.join(v, '') if path2dwsim == []: path2dwsim = input(r"Please, input the path to your DWSIM installation, usually C:\\Users\\UserName\\AppData\\Local\\DWSIM7") #insert manuall if path2dwsim[-1] not in '\/': path2dwsim += r'/' # path2dwsim = "" #insert manuall print(path2dwsim) # Loading DWSIM simulation into Python (Simulation object) sim_smr = SimulationOptimization(dof=np.array([]), path2sim= os.path.join(dir_path, "examples\\SMR_LNG\\SMR.dwxmz"), path2dwsim = path2dwsim, savepath = os.path.join(dir_path, "examples\\SMR_LNG\\SMR2.dwxmz")) sim_smr.add_refs() # Instanciate automation manager object from DWSIM.Automation import Automation2 if ('interf' not in locals()): # create automation manager interf = Automation2() # Connect simulation in sim.path2sim sim_smr.connect(interf) ``` -------------------------------- ### Initial Guess for Optimization in Python Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.0.1.ipynb Provides an initial guess array (x0) for the optimization variables. This array contains starting values for each degree of freedom defined in the simulation, which helps the optimization algorithm converge more efficiently. ```python # Initial simulation optimization setup # Initial guess of optimization x0 = np.array( [0.269/3600, 0.529/3600, 0.619/3600, 2.847/3600, 2.3e5, 48.00e5] ) ``` -------------------------------- ### Initialize Simulation Optimization with DWSIM Path Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/SMR_LNG/example_SMR_v0.0.1.ipynb This Python script initializes the SimulationOptimization module for DWSIM. It dynamically determines the DWSIM installation path from the system environment variables and appends it to the Python path. It also ensures that the 'dwsimopt.sim_opt' module is reloaded if it has been imported previously, which is useful for development or when running scripts multiple times. ```python import numpy as np # from scipy import optimize from pprint import pprint import os from pathlib import Path dir_path = str(Path(os.getcwd()).parent.parent.absolute()) print(dir_path) import sys sys.path.append(dir_path) if 'dwsimopt.sim_opt' in sys.modules: # Is the module in the register? del sys.modules['dwsimopt.sim_opt'] # If so, remove it. del SimulationOptimization from dwsimopt.sim_opt import SimulationOptimization ``` -------------------------------- ### Load DWSIM Simulation (Python) Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/example_v0.2.ipynb Loads a DWSIM simulation file into a Python OptimiSim object. This involves specifying the path to the simulation file, the DWSIM installation directory, and a save path for modified simulations. It also initializes DWSIM. ```python # Loading DWSIM simulation into Python (Simulation object) sim_smr = OptimiSim(path2sim= os.path.join(dir_path, "examples\\SMR_LNG\\SMR_energy_recycle.dwxmz"), path2dwsim = "C:\\Users\\lfsfr\\AppData\\Local\\DWSIM8\\", savepath = os.path.join(dir_path, "examples\\SMR_LNG\\SMR_energy_recycle2.dwxmz"), init_dwsim=True) ``` -------------------------------- ### Setup Optimization Problem with Bounds and Regularization Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG_compositeCurve/example_PRICO_composite_v0.1.ipynb Configures parameters for an optimization problem, including convergence tolerances (xtol, ftol, maxiter), bounds for decision variables, and a regularizer for magnitude orders. It defines lambda functions for the objective (f) and constraints (g) based on a simulation calculation. ```python # Setup for optimization # convergence tolerances xtol=0.01 ftol=0.01 maxiter=5 # +- 20 seconds per iteration # decision variables bounds bounds_raw = np.array( [0.5*np.asarray(x0), 1.5*np.asarray(x0)] ) # 50 % around base case # regularizer calculation regularizer = np.zeros(x0.size) import math for i in range(len(regularizer)): regularizer[i] = 10**(-1*math.floor(math.log(x0[i],10))) # regularizer for magnitude order of 1e0 # bounds regularized bounds_reg = regularizer*bounds_raw # bounds = optimize.Bounds(bounds_reg[0], bounds_reg[1]) # objective and constraints lambda definitions f = lambda x: sim.calculate_optProblem(np.asarray(x)/regularizer)[0:sim.n_f] g = lambda x: sim.calculate_optProblem(np.asarray(x)/regularizer)[sim.n_f:(sim.n_f+sim.n_g)] # nonlinear_constraint = optimize.NonlinearConstraint(g, -np.inf, 0, jac='2-point', hess=optimize.BFGS()) ``` -------------------------------- ### Setup and Run RbfOpt Optimization Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/SMR_LNG/example_SMR_v0.0.1.ipynb Initializes and runs the RbfOpt optimization algorithm from the 'sbopt' library. It defines the objective function, bounds, initial design, and then calls the minimize method with various parameters controlling convergence and strategy. The results, including best design variables and function value, are printed. ```python optProb_sbo = sbopt.RbfOpt( lambda x: sim_smr.fpen_barrier(x/regularizer, pen=10), bounds_reg.T, initial_design='latin', initial_design_ndata=20) result = optProb_sbo.minimize(max_iter=100, # maximum number of iterations # (default) n_same_best=50, # number of iterations to run # without improving best function value (default) eps=1e-6, # minimum distance a new design point # may be from an existing design point (default) verbose=1, # number of iterations to go for # printing the status (default) initialize=True, # boolean, wether or not to # perform the initial sampling (default) strategy='local_best', # str, which minimize strategy # to use. strategy='local_best' (default) adds only # one design point per iteration, where this selection # first looks at the best local optimizer result. # strategy='all_local' adds the results from each of # the local optima in a single iteration. ) print('Best design variables:', result[0]) print('Best function value:', result[1]) print('Convergence by max iteration:', result[2]) print('Convergence by n_same_best:', result[3]) ``` -------------------------------- ### Local Optimization with Trust-Region (Commented Out) Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.0.1.ipynb This commented-out section demonstrates the setup for performing local optimization using the 'trust-constr' method from SciPy. It includes configurations for the objective function, constraints, bounds, and various solver options like Jacobian, Hessian, and tolerance. ```python # Local optimization with trust-region -> working to some extent # print("starting local optimization") # result = optimize.minimize( f, np.asarray(x0)*regularizer, # method='trust-constr', jac='2-point', hess=optimize.BFGS(), # constraints=[nonlinear_constraint], bounds=bounds, callback=None, # options={'verbose': 3, # 'xtol': xtol, # 'maxiter': 1*maxiter, # 'finite_diff_rel_step': None, # 'initial_tr_radius': 0.1} ) ``` -------------------------------- ### Setup Optimization Parameters in DWSIM (Python) Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/SMR_LNG/example_SMR_v0.0.1.ipynb This Python code sets up parameters for optimization within DWSIM. It defines convergence tolerances, decision variable bounds (with manual adjustments for specific variables), calculates a regularizer based on the order of magnitude of initial values, and defines lambda functions for the objective function ('f') and constraints ('g'). It utilizes NumPy and SciPy's optimization module. The output includes the number of objective functions and constraints, and the results of calculating the optimization problem with initial values. ```python # Setup for optimization # convergence tolerances xtol=0.01 ftol=0.01 maxiter=5 # +- 20 seconds per iteration # decision variables bounds bounds_raw = np.array( [0.5*np.asarray(x0), 1.5*np.asarray(x0)] ) # 50 % around base case bounds_raw[0][-1] = 153 # precool temperature low limit manually bounds_raw[1][-1] = 253 # precool temperature upper limit manually # regularizer calculation regularizer = np.zeros(x0.size) import math for i in range(len(regularizer)): regularizer[i] = 10**(-1*math.floor(math.log(x0[i],10))) # regularizer for magnitude order of 1e0 # bounds regularized bounds_reg = regularizer*bounds_raw bounds = optimize.Bounds(bounds_reg[0], bounds_reg[1]) # objective and constraints lambda definitions f = lambda x: sim_smr.calculate_optProblem(np.asarray(x)/regularizer)[0:sim_smr.n_f] g = lambda x: sim_smr.calculate_optProblem(np.asarray(x)/regularizer)[sim_smr.n_f:(sim_smr.n_f+sim_smr.n_g)] nonlinear_constraint = optimize.NonlinearConstraint(g, -np.inf, 0, jac='2-point', hess=optimize.BFGS()) ``` ```python print(sim_smr.n_f) print(sim_smr.n_g) res = sim_smr.calculate_optProblem(x0) print(res[0:sim_smr.n_f]) print(res[sim_smr.n_f:(sim_smr.n_f+sim_smr.n_g)]) ``` -------------------------------- ### Set Initial Optimization Guess in Python Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/example_v0.2.ipynb Defines the initial guess for the optimization variables. This NumPy array `x0` contains the starting values for each variable that the optimization algorithm will adjust to find the optimal solution. The values correspond to specific simulation parameters like flow rates, pressures, and temperatures. ```python # Setup for optimization # Initial guess of optimization x0 = np.array( [0.25/3600, 0.70/3600, 1.0/3600, 1.10/3600, 1.80/3600, 2.50e5, 50.0e5, -60+273.15] ) ``` -------------------------------- ### Python: Accessing DWSIM Simulation Degrees of Freedom Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.1.ipynb Retrieves a specific element from the 'dof' (degrees of freedom) attribute of the DWSIM simulation object. This allows inspection of individual degrees of freedom, which are often related to simulation variables or parameters. The output shows an example of accessing an element that describes a compound molar flow. ```python sim.dof[4] ``` -------------------------------- ### Load DWSIM Simulation and Connect Automation Manager Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.1.ipynb This snippet initializes a DWSIM simulation object, loads a specified .dwxmz file, and connects it to the DWSIM automation manager. It requires the `DWSIM.Automation` library and sets up the simulation for further manipulation. ```python from DWSIM.Automation import Automation2 sim = SimulationOptimization(dof=np.array([]), path2sim= os.path.join(dir_path, "PRICO_LNG\PRICO.dwxmz"), path2dwsim = path2dwsim, savepath = os.path.join(dir_path, "PRICO_LNG\PRICO2.dwxmz")) sim.add_refs() if ('interf' not in locals()): # create automation manager interf = Automation2() sim.connect(interf) ``` -------------------------------- ### Initialize sbopt Library Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/SMR_LNG/example_SMR_v0.0.1.ipynb This snippet shows the necessary imports to initialize the sbopt library for optimization tasks. It includes numpy for numerical operations and sbopt itself. ```python # test sbopt import numpy as np import sbopt ``` -------------------------------- ### Load and Connect DWSIM Simulation in Python Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.0.1.ipynb Loads a DWSIM simulation file and initializes the automation interface. It sets the save path for the simulation and adds necessary references for automation. This is the initial step before interacting with the simulation's parameters. ```python from DWSIM.Optimization import SimulationOptimization import numpy as np import os from DWSIM.Automation import Automation2 # Assuming dir_path and path2dwsim are defined elsewhere dir_path = os.getcwd() # Example: get current directory path2dwsim = 'C:\\Users\\lfsfr\\AppData\\Local\\DWSIM7\\' # Example path sim_smr = SimulationOptimization(dof=np.array([]), path2sim= os.path.join(dir_path, "examples\\PRICO_LNG\\PRICO.dwxmz"), path2dwsim = path2dwsim) sim_smr.savepath = str(os.path.join(dir_path, "examples\\PRICO_LNG\\PRICO2.dwxmz")) sim_smr.add_refs() # Instanciate automation manager object if ('interf' not in locals()): # create automation manager interf = Automation2() # Connect simulation in sim.path2sim sim_smr.connect(interf) ``` -------------------------------- ### Python: Global Optimization with GA Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/example_v0.1.ipynb This snippet shows how to initialize and run a Genetic Algorithm for global optimization. It defines the objective function, sets optimization bounds and parameters, and records the optimization history. It also includes basic error handling for the number of objective functions and saves the simulation flowsheet upon completion. ```python # Global optimization with GA from sko.GA import GA # f_pen = lambda x: fpen_barrier(sim_smr,x/regularizer) result_GA = GA(func= lambda x: sim_smr.fpen_barrier(x/regularizer), n_dim=sim_smr.n_dof, pop=sim_smr.n_dof, max_iter=2, lb=bounds_reg[0], ub=bounds_reg[1], verbose=True) result_GA.record_mode = True if sim_smr.n_f > 1: print("Multi-objective optimization not supported (yet)") elif sim_smr.n_f < 1: print("Invalid number of objective functions") else: print("Starting global optimization") result_GA.run() import matplotlib.pyplot as plt print(f(result_GA.gbest_x)) print(g(result_GA.gbest_x)) sim_smr.interface.SaveFlowsheet(sim_smr.flowsheet, sim_smr.savepath, True) print(result_GA.gbest_x) pprint(result_GA) plt.plot(result_GA.gbest_y_hist) plt.show() ``` -------------------------------- ### Import and Initialize Simulation Optimization Module in Python Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.0.1.ipynb This Python script imports necessary libraries like numpy and scipy for optimization. It sets up the environment by adding a directory to the system path and reloads the SimulationOptimization module from dwsimopt.sim_opt to ensure the latest version is used. This is crucial for custom simulation optimization tasks. ```python import numpy as np from scipy import optimize from pprint import pprint import os from pathlib import Path dir_path = str(Path(os.getcwd()).parent.parent.absolute()) print(dir_path) import sys sys.path.append(dir_path) if 'dwsimopt.sim_opt' in sys.modules: # Is the module in the register? del sys.modules['dwsimopt.sim_opt'] # If so, remove it. del SimulationOptimization from dwsimopt.sim_opt import SimulationOptimization ``` -------------------------------- ### Initialize SimulationOptimization in Python Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.1.ipynb This Python script initializes the SimulationOptimization class from the dwsimopt library. It sets up the necessary paths for DWSIM and the optimization module, ensuring that any previous instances of the module are removed to allow for a clean import. This is crucial for dynamic module reloading in development environments. ```python import numpy as np from pprint import pprint import os from pathlib import Path from dwsimopt.utils import PATH2DWSIMOPT dir_path = str(Path(os.getcwd()).parent.absolute()) print(dir_path) import sys sys.path.append(dir_path) if 'dwsimopt.sim_opt' in sys.modules: # Is the module in the register? del sys.modules['dwsimopt.sim_opt'] # If so, remove it. del SimulationOptimization from dwsimopt.sim_opt import SimulationOptimization ``` -------------------------------- ### Python: Initialize and Test DWSIM Simulation Optimization Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.1.ipynb Sets up the initial guess (x0) for DWSIM simulation optimization, performs a simulation calculation with this guess, prints the simulation results (x_val, f_val, g_val), and saves the simulation state to a specified path. It also includes code to inspect the simulation object's variables using pprint. Dependencies include numpy and the DWSIM.Automation library. ```python # Initial simulation optimization setup # Initial guess of optimization x0 = np.array( [0.269/3600, 0.529/3600, 0.619/3600, 2.847/3600, 2.3e5, 48.00e5] ) x0 = np.array( [0.81/3600, 0.6540356/3600, 1.0560176/3600, 3.7810566/3600, 3.97118e5, 94.8814e5] ) x0 = np.array( [0.269/3600, 0.529/3600, 0.619/3600, 2.847/3600, 3e-6, 2.3e5, 48.00e5] ) # Testing for simulation at x0 sim.calculate_optProblem(1.0*x0) print(sim.x_val, sim.f_val, sim.g_val) # Test saving simulation at x0 in 'savepath' sim.interface.SaveFlowsheet(sim.flowsheet,sim.savepath,True) # Inspecting simulation object pprint(vars(sim)) ``` -------------------------------- ### Initialize and Run PSO Optimization Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.0.1.ipynb This snippet shows the initialization of the Particle Swarm Optimization (PSO) algorithm with a custom objective function, dimension, population size, iteration limit, and bounds. It also includes logic to handle single-objective optimization and prints status messages. ```python f_pen = lambda x: fpen_barrier(sim_smr,x/regularizer) result_pso = PSO(func= lambda x: sim_smr.fpen_barrier(x/regularizer), n_dim=sim_smr.n_dof, pop=2*sim_smr.n_dof, max_iter=15, lb=bounds_reg[0], ub=bounds_reg[1], verbose=True) result_pso.record_mode = True if sim_smr.n_f > 1: print("Multi-objective optimization not supported (yet)") elif sim_smr.n_f < 1: print("Invalid number of objective functions") else: print("Starting global optimization") result_pso.run() ``` -------------------------------- ### Load DWSIM Simulation and Initialize Automation Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/SMR_LNG/example_SMR_v0.0.1.ipynb This snippet demonstrates how to load a DWSIM simulation file into a Python object for optimization. It initializes the DWSIM automation manager and connects the simulation. ```python sim_smr = SimulationOptimization(dof=np.array([]), path2sim= os.path.join(dir_path, "examples\SMR_LNG\SMR.dwxmz"), path2dwsim = path2dwsim) sim_smr.savepath = os.path.join(dir_path, "examples\SMR_LNG\SMR2.dwxmz") sim_smr.add_refs() from DWSIM.Automation import Automation2 if ('interf' not in locals()): # create automation manager interf = Automation2() sim_smr.connect(interf) ``` -------------------------------- ### Import DWSIM Python Interface (Python) Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/example_v0.2.ipynb Imports the Python to DWSIM interface functions, enabling Python scripts to interact with and control DWSIM simulations. ```python from dwsimopt.py2dwsim import * ``` -------------------------------- ### Run Black Box Optimization Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/SMR_LNG/example_SMR_v0.0.1.ipynb Utilizes the 'black_box' library to perform optimization. It defines an objective function 'fpen', sets the domain and budget for the search, and specifies an output file for results. The search_min function is called to execute the optimization process. ```python import black_box as bb def fpen(x): return sim_smr.fpen_barrier(x/regularizer, pen=10) f_pen = lambda x: fpen_barrier(sim_smr,x/regularizer) result = bb.search_min(f=fpen, domain = bounds_reg.T, budget = 20, # total number of function calls available batch = 1, # number of calls that will be evaluated in parallel resfile = 'output.csv') # text file where results will be savedin a single iteration. pprint(result) ``` -------------------------------- ### Import DWSIM Optimization Libraries (Python) Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/example_v0.2.ipynb Imports necessary libraries for DWSIM optimization, including numpy for numerical operations and specific modules from dwsimopt for simulation and optimization tasks. It also sets up directory paths. ```python import numpy as np from pprint import pprint import os from pathlib import Path dir_path = str(Path(os.getcwd()).parent.absolute()) from dwsimopt.solve_sim_opt import OptimiSim ``` -------------------------------- ### Run Simulation Calculation and Save State Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/SMR_LNG/example_SMR_v0.0.1.ipynb This snippet sets an initial guess for the optimization variables, runs a simulation calculation with these values, prints the results, and saves the simulation state to a specified file. ```python # Initial simulation optimization setup # Initial guess of optimization x0 = np.array( [0.25/3600, 0.70/3600, 1.0/3600, 1.10/3600, 1.80/3600, 2.50e5, 50.00e5, -60+273.15] ) # Testing for simulation at x0 sim_smr.calculate_optProblem(1.0*x0) print(sim_smr.x_val, sim_smr.f_val, sim_smr.g_val) # Test saving simulation at x0 in 'savepath' sim_smr.interface.SaveFlowsheet(sim_smr.flowsheet,sim_smr.savepath,True) ``` -------------------------------- ### Python: Initialize and Run PSO for Single-Objective Optimization Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/example_v0.1.ipynb Initializes and runs the Particle Swarm Optimization (PSO) algorithm for a single-objective optimization problem in DWSIM. It sets up the objective function, bounds, and optimization parameters. The code checks for the number of objective functions, proceeding only if it's a single-objective problem. The `run()` method executes the optimization, and `record_mode` is enabled to store results. ```python f_pen = lambda x: fpen_barrier(sim_smr,x/regularizer) result_pso = PSO(func= lambda x: sim_smr.fpen_barrier(x/regularizer), n_dim=sim_smr.n_dof, pop=2*sim_smr.n_dof, max_iter=50, lb=bounds_reg[0], ub=bounds_reg[1], verbose=True) result_pso.record_mode = True if sim_smr.n_f > 1: print("Multi-objective optimization not supported (yet)") elif sim_smr.n_f < 1: print("Invalid number of objective functions") else: print("Starting global optimization") result_pso.run() ``` -------------------------------- ### Python: Print and Save Optimization Results Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.0.1.ipynb This snippet shows how to print the results of a global optimization using Differential Evolution and save the flowsheet. It calculates optProblem using optimized parameters and saves the flowsheet to a specified path. ```python # printing results of global optimization with Differential Evolution # xpso = np.array([6.17810197e-05, 2.74573937e-04, 3.91942260e-04, 3.15410796e-04, # 2.66089439e-04, 1.96572335e+05, 4.53996283e+06, 2.45857440e+02]) xpso = result_pso.gbest_x/regularizer print(sim_smr.calculate_optProblem(xpso)) # saving results of local optimization with Differential Evolution sim_smr.interface.SaveFlowsheet(sim_smr.flowsheet, sim_smr.savepath,True) ``` -------------------------------- ### Inspect DWSIM Simulation Object Variables Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/example_v0.1.ipynb This snippet demonstrates how to inspect the variables of a DWSIM simulation object using the `pprint` function. It shows the structure of the simulation object, including degrees of freedom, objective functions, constraints, and paths to DWSIM and simulation files. This is useful for understanding the simulation's state and parameters. ```python # Setup for optimization # decision variables bounds bounds_raw = np.array( [0.75*np.asarray(x0), 1.25*np.asarray(x0)] ) # 50 % around base case bounds_raw[0][-1] = 153 # precool temperature low limit manually bounds_raw[1][-1] = 253 # precool temperature upper limit manually # regularizer calculation regularizer = np.ones(x0.size) # bounds regularized bounds_reg = regularizer*bounds_raw ``` -------------------------------- ### Python: Configure DWSIM Optimization Parameters Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.1.ipynb Configures parameters for DWSIM simulation optimization, including convergence tolerances (xtol, ftol) and maximum iterations (maxiter). It also sets up bounds for the decision variables by scaling an initial guess (x0) and calculates a regularizer based on the magnitude of x0 values to adjust these bounds. This code prepares the simulation for an optimization run. ```python # Setup for optimization # convergence tolerances xtol=0.01 ftol=0.01 maxiter=5 # +- 20 seconds per iteration # decision variables bounds bounds_raw = np.array( [0.5*np.asarray(x0), 1.5*np.asarray(x0)] ) # 50 % around base case # regularizer calculation regularizer = np.zeros(x0.size) import math for i in range(len(regularizer)): regularizer[i] = 10**(-1*math.floor(math.log(x0[i],10))) # regularizer for magnitude order of 1e0 # bounds regularized bounds_reg = regularizer*bounds_raw # bounds = optimize.Bounds(bounds_reg[0], bounds_reg[1]) ``` -------------------------------- ### Run PSO Optimization with Regularization in Python Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG_compositeCurve/example_PRICO_composite_v0.1.ipynb This Python snippet demonstrates how to configure and run a Particle Swarm Optimization (PSO) algorithm. It sets up the objective function using a lambda expression with regularization, defines search space bounds, and initializes PSO parameters like population size and maximum iterations. The code also includes checks for the number of objective functions, supporting only single-objective optimization. ```python f_pen = lambda x: fpen_barrier(sim,x/regularizer) result_pso = PSO(func= lambda x: sim.fpen_barrier(x/regularizer), n_dim=sim.n_dof, pop=2*sim.n_dof, max_iter=100, lb=bounds_reg[0], ub=bounds_reg[1], verbose=True) result_pso.record_mode = True if sim.n_f > 1: print("Multi-objective optimization not supported (yet)") elif sim.n_f < 1: print("Invalid number of objective functions") else: print("Starting global optimization") result_pso.run() ``` -------------------------------- ### Global Optimization with Particle Swarm Optimization (PSO) Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.0.1.ipynb This snippet imports the Particle Swarm Optimization (PSO) algorithm from the 'sko' (Scikit-Optimize) library, which is used for global optimization tasks within the DWSIM project. ```python # Global optimization with PSO from sko.PSO import PSO ``` -------------------------------- ### Print Simulation Variables in Python Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/example_v0.2.ipynb Prints the variables of a simulation object using the `pprint` function. This is useful for debugging and inspecting the state of the simulation model and its associated optimization parameters. ```python pprint(vars(sim_smr)) ``` -------------------------------- ### DWSIM File Paths Configuration Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/data/2021-12-22_11-42-59/sim.txt Configuration for DWSIM file paths, specifying the location of the DWSIM executable directory and the target flowsheet file. These paths are essential for the automation script to load and interact with the simulation. ```python 'path2sim': 'c:\Users\lfsfr\Desktop\dwsimopt\examples\SMR_LNG\SMR.dwxmz', 'path2dwsim': 'C:\Users\lfsfr\AppData\Local\DWSIM7\', 'savepath': 'c:\Users\lfsfr\Desktop\dwsimopt\examples\SMR_LNG\SMR2.dwxmz' ``` -------------------------------- ### Run DWSIM Simulation and Compare Output Variables Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG_compositeCurve/example_PRICO_composite_v0.1.ipynb This snippet showcases running a DWSIM simulation with a modified input parameter (`1.1*x0`) and then comparing an output variable from the simulation with a reference value. It retrieves a specific object from the DWSIM flowsheet, accesses its output variables, and prints the difference and the actual output variable value. This is useful for verifying simulation results and checking constraint satisfaction. ```python sim.calculate_optProblem(1.1*x0) obj = sim.flowsheet.GetFlowsheetSimulationObject("MITA1-Calc") print(obj.OutputVariables["tt_0"]-tt[0]()) print(TT[0]()) print(tt[0]()) print(sim.g[0][0]()) TT ``` -------------------------------- ### Define Optimization Variables, Objective, and Constraints in Python Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.0.1.ipynb Configures the simulation for optimization by defining degrees of freedom (variables to be changed), the objective function (what to minimize/maximize), and constraints (conditions that must be met). This snippet shows how to add these elements to the SimulationOptimization object. ```python # Add dof def set_comp_massflow(x, simobj): ms = sim_smr.flowsheet.SimulationObjects[simobj.Name] def set_property(x, obj, property=None): if property==None: obj = x # ACCESS PROPERTY CORRECTLY sim_smr.add_dof(lambda x: sim_smr.flowsheet.GetFlowsheetSimulationObject("MR-1").SetOverallCompoundMassFlow(7,x)) sim_smr.add_dof(lambda x: sim_smr.flowsheet.GetFlowsheetSimulationObject("MR-1").SetOverallCompoundMassFlow(0,x)) sim_smr.add_dof(lambda x: sim_smr.flowsheet.GetFlowsheetSimulationObject("MR-1").SetOverallCompoundMassFlow(1,x)) sim_smr.add_dof(lambda x: sim_smr.flowsheet.GetFlowsheetSimulationObject("MR-1").SetOverallCompoundMassFlow(2,x)) sim_smr.add_dof( lambda x: set_property(x, sim_smr.flowsheet.GetFlowsheetSimulationObject("VALV-01").OutletPressure) ) sim_smr.add_dof( lambda x: set_property(x, sim_smr.flowsheet.GetFlowsheetSimulationObject("COMP-4").POut) ) # adding objective function (f_i): sim_smr.add_fobj(lambda : sim_smr.flowsheet.GetFlowsheetSimulationObject("Sum_W").EnergyFlow) # adding constraints (g_i <= 0): sim_smr.add_constraint(np.array([ lambda : 3 - sim_smr.flowsheet.GetFlowsheetSimulationObject("MITA1-Calc").OutputVariables['mita'], lambda : 10*sim_smr.flowsheet.GetFlowsheetSimulationObject("MSTR-27").Phases[1].Properties.massfraction, # no phase separation in the cycle lambda : 10*sim_smr.flowsheet.GetFlowsheetSimulationObject("MR-1").Phases[1].Properties.massfraction, # no phase separation in the cycle lambda : 10*sim_smr.flowsheet.GetFlowsheetSimulationObject("MSTR-03").Phases[1].Properties.massfraction, # no phase separation in the cycle lambda : 10*sim_smr.flowsheet.GetFlowsheetSimulationObject("MSTR-05").Phases[1].Properties.massfraction, # phase separation before MSHE ])) # Displaying simulation object variables (for debugging/inspection) from pprint import pprint pprint(vars(sim_smr)) ``` -------------------------------- ### Retrieve DWSIM Optimization Problem Parameters Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.0.1.ipynb This snippet shows how to retrieve the number of objective functions (n_f) and constraints (n_g) from the DWSIM simulation manager. It then calls the optimization problem calculation with 'x0' and prints the objective and constraint values. ```python print(sim_smr.n_f) print(sim_smr.n_g) res = sim_smr.calculate_optProblem(x0) print(res[0:sim_smr.n_f]) print(res[sim_smr.n_f:(sim_smr.n_f+sim_smr.n_g)]) ``` -------------------------------- ### Calculate and Inspect DWSIM Simulation at x0 Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG/example_PRICO_v0.0.1.ipynb This snippet demonstrates how to calculate a DWSIM simulation at a specific point 'x0', print the objective function (f_val) and constraint values (g_val), and save the simulation state. It also shows how to inspect the simulation object's variables. ```python # Testing for simulation at x0 sim_smr.calculate_optProblem(1.0*x0) print(sim_smr.x_val, sim_smr.f_val, sim_smr.g_val) # Test saving simulation at x0 in 'savepath' sim_smr.interface.SaveFlowsheet(sim_smr.flowsheet,sim_smr.savepath,True) # Inspecting simulation object pprint(vars(sim_smr)) ``` -------------------------------- ### Run DWSIM Simulation and Print Output Variables Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/PRICO_LNG_compositeCurve/example_PRICO_composite_v0.1.ipynb This Python code iterates through a set of calculated results (presumably from an optimization or simulation process) and prints specific output variables. It utilizes a `sim.calculate_optProblem` function, which likely triggers a simulation run, followed by printing values from a list `TT`. This is essential for observing the outcome of simulation runs at different parameter values. ```python sim.calculate_optProblem(1.0*x0) for i in range(kk): print(TT[i]()) sim.calculate_optProblem(1.2*x0) for i in range(kk): print(TT[i]()) ``` -------------------------------- ### Python Optimization and Simulation Workflow Source: https://github.com/lf-santos/dwsimopt/blob/master/examples/example_v0.1.ipynb This Python code snippet performs optimization using a Particle Swarm Optimization (PSO) algorithm. It prints objective function (f) and gradient (g) values, saves the simulation state, and plots the history of the best objective function found during optimization. Dependencies include matplotlib.pyplot and pprint. ```python import matplotlib.pyplot as plt print(f(result_pso.gbest_x)) print(g(result_pso.gbest_x)) sim_smr.interface.SaveFlowsheet(sim_smr.flowsheet, sim_smr.savepath, True) print(result_pso.gbest_x) pprint(result_pso) plt.plot(result_pso.gbest_y_hist) plt.show() ```