Example 06: Gas metering station uncertainty calculations

This notebook demonstrates uncertainty calculations for a gas metering station consisting of an Ultrasonic Flowmeter (USM), a Gas Chromatograph (GC) and dual pressure and temperature measurements. Evaluations are done using both standard uncertainty calculations (based on sensitivity coefficients and input uncertainties), as well as the Monte Carlo Method.

# Import Required Libraries
import pvtlib
from uncertaintylib import uncertainty_functions, plot_functions
import pandas as pd
import matplotlib.pyplot as plt
import os
import numpy as np

np.random.seed(42)  # Fixed seed so that the Monte Carlo results in this notebook are reproducible

Read inputs from CSV file

The inputs to the uncertainty calculation is given in a csv file.

The input contains:

  • Pressure

  • Temperature

  • Actual volume flowrate measured by the USM

  • The calibration curve for the USM

  • Gas composition measured by the GC

The following features should be noted:

  • Uncertainty can be provided either as an absolute value (standard_uncertainty) or a a percentage (standard_uncertainty_percent)

  • If both standard_uncertainty and standard_uncertainty_percent are given, the code will use the larger of the two (useful for parameters that are dominated by noise in the low range for instance)

  • Distribution, min and max are only used by the Monte Carlo simulation. The min and max values are used to avoid non-physical distributions (such as mol% of a component going below 0)

  • Unit is not required, just for information

notebook_dir = os.path.dirname(os.path.abspath(__file__)) if '__file__' in globals() else os.getcwd()
data_path = os.path.join(notebook_dir, 'data.csv')
df = pd.read_csv(data_path)

df # Display the dataframe
input_name unit mean standard_uncertainty standard_uncertainty_percent distribution min max
0 USM_pressure_A bara 140.00 0.150 NaN normal NaN NaN
1 USM_pressure_B bara 140.00 0.150 NaN normal NaN NaN
2 USM_temperature_A C 50.00 0.150 NaN normal NaN NaN
3 USM_temperature_B C 50.00 0.150 NaN normal NaN NaN
4 USM_volflow m3/h 14700.00 0.300 0.05 normal NaN NaN
5 USM_calib_volflow_01 m3/h 2332.00 NaN 0.16 normal NaN NaN
6 USM_calib_volflow_02 m3/h 3888.00 NaN 0.10 normal NaN NaN
7 USM_calib_volflow_03 m3/h 6480.00 NaN 0.09 normal NaN NaN
8 USM_calib_volflow_04 m3/h 10800.00 NaN 0.07 normal NaN NaN
9 USM_calib_volflow_05 m3/h 18000.00 NaN 0.07 normal NaN NaN
10 USM_calib_volflow_06 m3/h 30000.00 NaN 0.07 normal NaN NaN
11 USM_calib_error_01 % -0.07 0.220 NaN normal NaN NaN
12 USM_calib_error_02 % 0.04 0.120 NaN normal NaN NaN
13 USM_calib_error_03 % 0.07 0.100 NaN normal NaN NaN
14 USM_calib_error_04 % 0.08 0.090 NaN normal NaN NaN
15 USM_calib_error_05 % 0.02 0.090 NaN normal NaN NaN
16 USM_calib_error_06 % -0.28 0.080 NaN normal NaN NaN
17 N2 mol% 1.00 0.050 NaN normal 0.0 100.0
18 CO2 mol% 1.00 0.050 NaN normal 0.0 100.0
19 C1 mol% 90.00 0.075 NaN normal 0.0 100.0
20 C2 mol% 5.00 0.060 NaN normal 0.0 100.0
21 C3 mol% 2.00 0.050 NaN normal 0.0 100.0
22 iC4 mol% 0.50 0.035 NaN normal 0.0 100.0
23 nC4 mol% 0.50 0.035 NaN normal 0.0 100.0
24 GERG_uncertainty_factor - 1.00 NaN 0.05 normal NaN NaN

Convert dataframe to dictionary

Input to uncertaintylib must be a dictionary. Convert the dataframe to a dictionary

df=df.set_index('input_name')

inputs = df.to_dict() # Convert dataframe to dictionary, which is the required format for uncertaintylib

Define the function performing the gas metering station calculations

def calculate_gas_metering_station(inarray):
    """
    Function to calculate the gas metering station output parameters.
    Inputs is a dictionary with all input parameters.
    Outputs is a dictionary with all output parameters.
    """

    outarray = {}   # Create an empty dictionary to store output parameters. 

    # Set up AGA8 object for GERG-2008 equation. This process runs the setup for the given equation
    gerg = pvtlib.AGA8('GERG-2008')

    composition = {
        'N2' : inarray['N2'],
        'CO2' : inarray['CO2'],
        'C1' : inarray['C1'],
        'C2' : inarray['C2'],
        'C3' : inarray['C3'],
        'iC4' : inarray['iC4'],
        'nC4' : inarray['nC4'],
    }

    outarray['USM_Pressure_used'] = (inarray['USM_pressure_A']+inarray['USM_pressure_B'])/2 # Calculate average pressure
    outarray['USM_Temperature_used'] = (inarray['USM_temperature_A']+inarray['USM_temperature_B'])/2 # Calculate average temperature

    # Calculate gas properties
    gas_properties = gerg.calculate_from_PT(
        composition=composition,
        pressure=outarray['USM_Pressure_used'],
        temperature=outarray['USM_Temperature_used'],
        pressure_unit='bara',
        temperature_unit='C',
    )

    # Store results in output dictionary
    # Gas density is multiplied with an uncertainty factor to account for uncertainty in the GERG-2008 equation of state. The value of the factor is 1, but the uncertainty is +/- 0.1 % (k=2)
    outarray['Gas_Density'] = gas_properties['rho']*inarray['GERG_uncertainty_factor']  # Gas density in kg/m3
    outarray['Gas_Compressibility'] = gas_properties['z']  # Gas compressibility factor
    outarray['Gas_Molar_Mass'] = gas_properties['mm']  # Gas molar mass in kg/kmol

    # Get calibration curves from inarray
    USM_calib_volflow = [
        inarray['USM_calib_volflow_01'],
        inarray['USM_calib_volflow_02'],
        inarray['USM_calib_volflow_03'],
        inarray['USM_calib_volflow_04'],
        inarray['USM_calib_volflow_05'],
        inarray['USM_calib_volflow_06'],
    ]

    USM_calib_error = [
        inarray['USM_calib_error_01'],
        inarray['USM_calib_error_02'],
        inarray['USM_calib_error_03'],
        inarray['USM_calib_error_04'],
        inarray['USM_calib_error_05'],
        inarray['USM_calib_error_06'],
    ]

    # Retrieve the calibration error for the measured volume flow, using linear interpolation
    outarray['USM_calib_error_used'] = pvtlib.utilities.linear_interpolation(
        x=inarray['USM_volflow'],
        x_values=USM_calib_volflow,
        y_values=USM_calib_error
    )

    # Calculate volume flowrate corrected for calibration error
    outarray['USM_volflow_corrected'] = inarray['USM_volflow']/((outarray['USM_calib_error_used']/100)+1)  # Corrected volume flow in m3/h

    # Calculate mass flowrate
    outarray['USM_massflow'] = outarray['USM_volflow_corrected'] * outarray['Gas_Density'] # Mass flow in kg/h

    # Calculate gas properties at standard conditions (288.15 K (15.00 °C) and 101.325 kPa according to ISO 13443)
    gas_properties_std = gerg.calculate_from_PT(
        composition=composition,
        pressure=101.325,
        temperature=288.15,
        pressure_unit='kPa',
        temperature_unit='K',
    )

    # Calculate volume flowrate at standard conditions
    outarray['USM_volflow_std'] = outarray['USM_massflow'] / gas_properties_std['rho']  # Standard volume flow in Sm3/h

    return outarray

Calculate uncertainty using sensitivity coefficients and input uncertainties

Uncertainty is calculated using the function calculate_uncertainty, which returns a dictionary with the following results:

Key

Description

value

The actual output values returned from the function (based on the ‘mean’ input values)

variance

The variance for each input parameter for each output parameter

contribution

The percentage contribution of each input variable to the uncertainty in each output variable

u

Combined Standard Uncertainty (u) for each output parameter

U

Expanded Uncertainty (95% confidence level, k=2) for each output parameter

U_perc

Relative Expanded Uncertainty (95% confidence level, k=2) for each output parameter, in %

This allows you to see both the calculated values and the detailed breakdown of uncertainty contributions for each output variable.

uncertainty_results = uncertainty_functions.calculate_uncertainty(
    indata=inputs,
    function=calculate_gas_metering_station
)

Plot contributions to uncertainty in Standard Volumetric Flowrate

fig1=plot_functions.plot_uncertainty_contribution(
    res=uncertainty_results,
    property_id='USM_volflow_std',
    plot_title='Contributions to Uncertainty in Standard Volumetric Flowrate',
    filter_top_x=10
)
../../_images/6c858c32e005ea7e99484ceeefb3881c116489a61df9ebc823cb78da79c9024f.png

Plot calibration curve and the operating point

# Get the calibration data from inputs (from calibration point 01 to 06)
USM_calib_volflow = [inputs['mean'][f'USM_calib_volflow_0{i}'] for i in range(1, 7)]
USM_calib_error = [inputs['mean'][f'USM_calib_error_0{i}'] for i in range(1, 7)]
USM_calib_error_uncertainty = [2 * inputs['standard_uncertainty'][f'USM_calib_error_0{i}'] for i in range(1, 7)] # k=2 uncertainty

# Plot the calibration curve with error bars
plt.figure(figsize=(9, 6))
plt.style.use('seaborn-v0_8-darkgrid')

# Calibration curve with error bars
plt.errorbar(
    USM_calib_volflow,
    USM_calib_error,
    yerr=USM_calib_error_uncertainty,
    fmt='o-',
    color='#008080',
    ecolor='gray',
    elinewidth=2,
    capsize=6,
    capthick=2,
    markersize=8,
    label='Calibration Curve'
)
# Highlight the operating point
plt.scatter(
    inputs['mean']['USM_volflow'],
    uncertainty_results['value']['USM_calib_error_used'],
    marker='X',
    color='#d62728',
    s=120,
    zorder=5,
    label='Operating Point'
)
plt.xlabel('Volume Flow Rate (m³/h)', fontsize=13)
plt.ylabel('Calibration Error (%)', fontsize=13)
plt.title('USM Calibration Curve', fontsize=15, weight='bold')
plt.ylim([-1.0, 1.0])
plt.xlim(left=0)
plt.legend(fontsize=12, loc='best', frameon=True)
plt.grid(True, which='both', linestyle='--', linewidth=0.7, alpha=0.7)
plt.tight_layout()
plt.show()

# Print calibration error for the given point
print(f"Calibration error at {inputs['mean']['USM_volflow']:,.1f} m3/h: {uncertainty_results['value']['USM_calib_error_used']:.2f} % ± {uncertainty_results['U']['USM_calib_error_used']:.2f} % (k=2)")
../../_images/3f24a1b6621da575391dafc7002cc5ffb2edb2b19e6779ccb9c96d75df30f629.png
Calibration error at 14,700.0 m3/h: 0.05 % ± 0.13 % (k=2)

Run Monte Carlo simulation

Uncertainties can also be determined by using the Monte Carlo method. In this method, uncertainty distributions for each input variable is generated randomly, and then the outputs are calculated from the input distributions. The standard deviation of the resulting output distribution will reflect the uncertainty of that given output parameter.

monte_carlo_results = uncertainty_functions.monte_carlo_simulation(
    mc_input=inputs,
    function=calculate_gas_metering_station,
    n=10000
)

# The monte_carlo_results is a dataframe with the results of the Monte Carlo simulation
# The 'calculate_monte_carlo_statistics' is used to calculate the mean, standard deviations and relative standard deviations of the results
monte_carlo_statistics = uncertainty_functions.calculate_monte_carlo_statistics(monte_carlo_results)

# Display the Monte Carlo statistics
monte_carlo_statistics
mean std_dev std_dev_percent std_dev_k2 std_dev_percent_k2
USM_Pressure_used 1.400009e+02 0.105848 0.075605 0.211695 0.151210
USM_Temperature_used 4.999850e+01 0.105985 0.211976 0.211970 0.423952
Gas_Density 1.130953e+02 0.286000 0.252884 0.572000 0.505768
Gas_Compressibility 8.350692e-01 0.000683 0.081816 0.001366 0.163632
Gas_Molar_Mass 1.812489e+01 0.028595 0.157766 0.057190 0.315532
USM_calib_error_used 4.747910e-02 0.063052 132.798556 0.126103 265.597111
USM_volflow_corrected 1.469308e+04 11.827887 0.080500 23.655774 0.160999
USM_massflow 1.661718e+06 4411.015412 0.265449 8822.030824 0.530898
USM_volflow_std 2.162415e+06 3376.647228 0.156152 6753.294456 0.312303

Plot the distribution for the Standard Volumetric Flowrate

fig2 = plot_functions.montecarlo_property_plot_and_table(
    data=monte_carlo_results,
    property_id='USM_volflow_std',
    xlim=[-1,1],
    property_name='Standard Volumetric Flowrate (Sm3/h)',
    property_unit='Sm3/h',
    round_props={'mean': 1, 'std': 2, 'stdperc': 2}
)
../../_images/bb24f56aaf7bb32338b91744b32e37fc419bc87414ea9850b216467e330eca42.png