###############################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES).
#
# Copyright (c) 2018-2023 by the software owners: The Regents of the
# University of California, through Lawrence Berkeley National Laboratory,
# National Technology & Engineering Solutions of Sandia, LLC, Carnegie Mellon
# University, West Virginia University Research Corporation, et al.
# All rights reserved.  Please see the files COPYRIGHT.md and LICENSE.md
# for full copyright and license information.
###############################################################################

Parameter Estimation Using the NRTL State Block#

In this module, we use Pyomo’s parmest tool in conjunction with IDAES models for parameter estimation. We demonstrate these tools by estimating the parameters associated with the NRTL property model for a benzene-toluene mixture. The NRTL model has 2 sets of parameters: the non-randomness parameter (alpha_ij) and the binary interaction parameter (tau_ij), where i and j are the pure component species. In this example, we only estimate the binary interaction parameter (tau_ij) for a given dataset. When estimating parameters associated with the property package, IDAES provides the flexibility of doing the parameter estimation by just using the state block or by using a unit model with a specified property package. This module will demonstrate parameter estimation by using only the state block.

We will complete the following tasks:

  • Set up a method to return an initialized model

  • Set up the parameter estimation problem using parmest

  • Analyze the results

  • Demonstrate advanced features using parmest

Setting up an initialized model#

We need to provide a method that returns an initialized model to the parmest tool in Pyomo.

Inline Exercise: Using what you have learned from previous modules, fill in the missing code below to return an initialized IDAES model.
def NRTL_model(data):

    # Todo: Create a ConcreteModel object
    m = ConcreteModel()

    # Todo: Create FlowsheetBlock object
    m.fs = FlowsheetBlock(dynamic=False)

    # Todo: Create a properties parameter object with the following options:
    # "valid_phase": ('Liq', 'Vap')
    # "activity_coeff_model": 'NRTL'
    m.fs.properties = BTXParameterBlock(
        valid_phase=("Liq", "Vap"), activity_coeff_model="NRTL"
    )
    m.fs.state_block = m.fs.properties.build_state_block(defined_state=True)

    # Fix the state variables on the state block
    # hint: state variables exist on the state block i.e. on m.fs.state_block

    m.fs.state_block.flow_mol.fix(1)
    m.fs.state_block.temperature.fix(368)
    m.fs.state_block.pressure.fix(101325)
    m.fs.state_block.mole_frac_comp["benzene"].fix(0.5)
    m.fs.state_block.mole_frac_comp["toluene"].fix(0.5)

    # Fix NRTL specific parameters.

    # non-randomness parameter - alpha_ij (set at 0.3, 0 if i=j)
    m.fs.properties.alpha["benzene", "benzene"].fix(0)
    m.fs.properties.alpha["benzene", "toluene"].fix(0.3)
    m.fs.properties.alpha["toluene", "toluene"].fix(0)
    m.fs.properties.alpha["toluene", "benzene"].fix(0.3)

    # binary interaction parameter - tau_ij (0 if i=j, else to be estimated later but fixing to initialize)
    m.fs.properties.tau["benzene", "benzene"].fix(0)
    m.fs.properties.tau["benzene", "toluene"].fix(-0.9)
    m.fs.properties.tau["toluene", "toluene"].fix(0)
    m.fs.properties.tau["toluene", "benzene"].fix(1.4)

    # Initialize the flash unit
    m.fs.state_block.initialize(outlvl=idaeslog.INFO_LOW)

    # Fix at actual temperature
    m.fs.state_block.temperature.fix(float(data["temperature"]))

    # Set bounds on variables to be estimated
    m.fs.properties.tau["benzene", "toluene"].setlb(-5)
    m.fs.properties.tau["benzene", "toluene"].setub(5)

    m.fs.properties.tau["toluene", "benzene"].setlb(-5)
    m.fs.properties.tau["toluene", "benzene"].setub(5)

    # Return initialized flash model
    return m

Parameter estimation using parmest#

In addition to providing a method to return an initialized model, the parmest tool needs the following:

  • List of variable names to be estimated

  • Dataset

  • Expression to compute the sum of squared errors

In this example, we only estimate the binary interaction parameter (tau_ij). Given that this variable is usually indexed as tau_ij = Var(component_list, component_list), there are 2*2=4 degrees of freedom. However, when i=j, the binary interaction parameter is 0. Therefore, in this problem, we estimate the binary interaction parameter for the following variables only:

  • fs.properties.tau[‘benzene’, ‘toluene’]

  • fs.properties.tau[‘toluene’, ‘benzene’]

Inline Exercise: Create a list called `variable_name` with the above-mentioned variables declared as strings.
# Todo: Create a list of vars to estimate
variable_name = [
    "fs.properties.tau['benzene', 'toluene']",
    "fs.properties.tau['toluene', 'benzene']",
]

Pyomo’s parmest tool supports the following data formats:

  • pandas dataframe

  • list of dictionaries

  • list of json file names.

Please see the documentation for more details.

For this example, we load data from the csv file BT_NRTL_dataset.csv. The dataset consists of fifty data points which provide the mole fraction of benzene in the vapor and liquid phase as a function of temperature.

# Load data from csv
data = pd.read_csv("BT_NRTL_dataset.csv")

# Display the dataset
display(data)

We need to provide a method to return an expression to compute the sum of squared errors that will be used as the objective in solving the parameter estimation problem. For this problem, the error will be computed for the mole fraction of benzene in the vapor and liquid phase between the model prediction and data.

Inline Exercise: Complete the following cell by adding an expression to compute the sum of square errors.
# Create method to return an expression that computes the sum of squared error
def SSE(m, data):
    # Todo: Add expression for computing the sum of squared errors in mole fraction of benzene in the liquid
    # and vapor phase. For example, the squared error for the vapor phase is:
    # (float(data["vap_benzene"]) - m.fs.state_block.mole_frac_phase_comp["Vap", "benzene"])**2
    expr = (
        float(data["vap_benzene"])
        - m.fs.state_block.mole_frac_phase_comp["Vap", "benzene"]
    ) ** 2 + (
        float(data["liq_benzene"])
        - m.fs.state_block.mole_frac_phase_comp["Liq", "benzene"]
    ) ** 2
    return expr * 1e4
Note: Notice that we have scaled the expression up by a factor of 10000 as the SSE computed here will be an extremely small number given that we are using the difference in mole fraction in our expression. This will help in using a well-scaled objective to improve solve robustness when using IPOPT.

We are now ready to set up the parameter estimation problem. We will create a parameter estimation object called pest. As shown below, we pass the method that returns an initialized model, data, variable_name, and the SSE expression to the Estimator method. tee=True will print the solver output after solving the parameter estimation problem.

import logging

idaeslog.getIdaesLogger("core.property_meta").setLevel(logging.ERROR)
# Initialize a parameter estimation object
pest = parmest.Estimator(NRTL_model, data, variable_name, SSE, tee=True)

# Run parameter estimation using all data
obj_value, parameters = pest.theta_est()

You will notice that the resulting parameter estimation problem will have 1102 variables and 1100 constraints. Let us display the results by running the next cell.

print("The SSE at the optimal solution is %0.6f" % (obj_value * 1e-4))
print()
print("The values for the parameters are as follows:")
for k, v in parameters.items():
    print(k, "=", v)

Using the data that was provided, we have estimated the binary interaction parameters in the NRTL model for a benzene-toluene mixture. Although the dataset that was provided was temperature dependent, in this example we have estimated a single value that fits best for all temperatures.

Advanced options for parmest: bootstrapping#

Pyomo’s parmest tool allows for bootstrapping where the parameter estimation is repeated over n samples with resampling from the original data set. Parameter estimation with bootstrap resampling can be used to identify confidence regions around each parameter estimate. This analysis can be slow given the increased number of model instances that need to be solved. Please refer to https://pyomo.readthedocs.io/en/stable/contributed_packages/parmest/driver.html for more details.

For the example above, the bootstrapping can be run by uncommenting the code in the following cell:

# Run parameter estimation using bootstrap resample of the data (10 samples),
# plot results along with confidence regions

# Uncomment the following code:
# bootstrap_theta = pest.theta_est_bootstrap(4)
# display(bootstrap_theta)