hdclass - Main Calculation Engine

The hdclass module contains the core HydDown class that manages the calculation engine, time-stepping integration, and thermodynamic state calculations.

Main calculation engine for pressure vessel filling and discharge simulations.

This module contains the HydDown class, which is the core of the HydDown package. It integrates mass and energy balances over time to simulate pressure vessel depressurization (discharge) and pressurization (filling) with heat transfer effects.

The HydDown class: - Reads and validates YAML input defining vessel geometry, initial conditions,

calculation type, valve parameters, and heat transfer settings

  • Initializes thermodynamic state using CoolProp for fluid properties

  • Integrates mass and energy balances using explicit Euler time stepping

  • Calculates heat transfer between fluid and vessel wall

  • Handles various thermodynamic paths: isothermal, isenthalpic, isentropic, constant internal energy, and full energy balance

  • Supports multiple valve types: orifice, control valve, relief valve, constant mass flow

  • Models fire heat loads using Stefan-Boltzmann approach

  • Tracks two-phase systems with separate gas/liquid temperatures

  • Can model 1-D transient heat conduction through vessel walls (composite materials)

  • Stores time-series results and provides plotting capabilities

Calculation types: - isothermal: Constant temperature (very slow process with large heat reservoir) - isenthalpic: Constant enthalpy (adiabatic, no work) - isentropic: Constant entropy (adiabatic with PV work) - specified_U: Constant internal energy - energybalance: Full energy balance with heat transfer and work

Heat transfer modes (for energybalance): - fixed_U: Fixed overall heat transfer coefficient - fixed_Q: Fixed heat input rate - specified_h: Specified internal/external heat transfer coefficients - detailed: 1-D transient conduction through vessel wall - fire: External fire heat load using Stefan-Boltzmann equation

Valve types: - orifice: Compressible flow through orifice (Yellow Book equation) - control_valve: Control valve with Cv characteristic - relief_valve: API 520/521 relief valve sizing - mdot: Constant mass flow rate

The integration scheme uses explicit Euler method with user-specified time step. Results are stored in numpy arrays for time, pressure, temperature, mass flow, etc.

Typical usage:

import yaml from hyddown import HydDown

with open(‘input.yml’) as f:

input_data = yaml.load(f, Loader=yaml.FullLoader)

hdown = HydDown(input_data) hdown.run() hdown.plot()

class hyddown.hdclass.HydDown(input)[source]

Bases: object

Main class to to hold problem definition, running problem, storing results etc.

__init__(input)[source]
Parameters:

input (dict) – Dict holding problem definition

validate_input()[source]

Validating the provided problem definition dict

Raises:

ValueError – If missing input is detected.

read_input()[source]

Reading in input/ problem definition dict and assigning to classs attributes.

initialize()[source]

Preparing for running problem by creating the fluid objects required instantiating arrays for storing time-dependent results, setting additional required class attributes.

calc_liquid_level()[source]

Calculate liquid level height based on current two-phase fluid state.

For two-phase systems (0 ≤ quality ≤ 1), calculates the height of liquid phase in the vessel based on vapor quality, phase densities, and vessel geometry. Uses vessel geometry from fluids.TANK to convert liquid volume to height.

Parameters:

fluid (CoolProp AbstractState) – Current fluid state

Returns:

Liquid level height from vessel bottom [m]. Returns 0.0 for single-phase gas (quality > 1 or subcooled liquid).

Return type:

float

PHres(T, P, H)[source]

Residual enthalpy function to be minimized during PH-problem.

Used by numerical optimizer (scipy.optimize.minimize) to find temperature that satisfies constant pressure-enthalpy constraints for multicomponent fluids. The optimizer adjusts T until residual approaches zero.

Parameters:
  • H (float) – Enthalpy at initial/final conditions [J/kg]

  • P (float) – Pressure at final conditions [Pa]

  • T (float) – Updated estimate for the final temperature at (P,H) [K]

Returns:

Squared normalized enthalpy residual (dimensionless). Zero when correct temperature is found.

Return type:

float

PHres_relief(T, P, H)[source]

Residual enthalpy function for PH-problem during relief valve calculations.

Used by numerical optimizer (scipy.optimize.root_scalar) to find temperature for relief valve discharge calculations. Similar to PHres() but uses the main fluid state instead of vent_fluid state.

Parameters:
  • H (float) – Enthalpy at initial/final conditions [J/kg]

  • P (float) – Pressure at final conditions [Pa]

  • T (float) – Updated estimate for the final temperature at (P,H) [K]

Returns:

Normalized enthalpy residual (dimensionless). Zero when correct temperature is found.

Return type:

float

PHproblem(H, P, Tguess, relief=False)[source]

Defining a constant pressure, constant enthalpy problem i.e. typical adiabatic problem like e.g. valve flow for the vented flow (during discharge). For multicomponent mixture the final temperature is changed/optimised until the residual enthalpy is near zero in an optimisation step. For single component fluid the coolprop built in methods are used for speed.

Parameters:
  • H (float) – Enthalpy at initial/final conditions

  • P (float) – Pressure at final conditions.

  • Tguess (float) – Initial guess for the final temperature at P,H

UDres(x, U, rho)[source]

Residual U-rho to be minimised during a U-rho/UV-problem

Parameters:
  • U (float) – Internal energy at final conditions

  • rho (float) – Density at final conditions

UDproblem(U, rho, Pguess, Tguess)[source]

Defining a constant UV problem i.e. constant internal energy and density/volume problem relevant for the 1. law of thermodynamics. For multicomponent mixture the final temperature/pressure is changed/optimised until the residual U/rho is near zero. For single component fluid the coolprop built in methods are used for speed.

Parameters:
  • U (float) – Internal energy at final conditions

  • rho (float) – Density at final conditions.

  • Pguess (float) – Initial guess for the final pressure at U, rho

  • Tguess (float) – Initial guess for the final temperature at U, rho

run(disable_pbar=True)[source]

Routine for running the actual problem defined i.e. integrating the mass and energy balances

get_dataframe()[source]

Export simulation results to pandas DataFrame for analysis and archiving.

Collects all time-series results from the simulation and organizes them into a pandas DataFrame with labeled columns. Useful for exporting to CSV/Excel, post-processing, or custom plotting.

Returns:

DataFrame with simulation results. Columns include: - Time (s) - Pressure (bar) - Fluid temperature (°C) - Wall temperature (°C) - Vent temperature (°C) - Fluid enthalpy (J/kg) - Fluid entropy (J/(kg·K)) - Fluid internal energy (J/kg) - Discharge mass rate (kg/s) - Fluid mass (kg) - Fluid density (kg/m³) - Inner heat transfer coefficient (W/(m²·K)) - Internal heat flux (W/m²) - External heat flux (W/m²) - Inner wall temperature (°C) - Outer wall temperature (°C)

Return type:

pd.DataFrame

Notes

Only returns data if simulation has been run (self.isrun == True). Temperature values are converted from Kelvin to Celsius. Pressure values are converted from Pa to bar.

plot(filename=None, verbose=True)[source]

Creating standard plots for the solved problem

Parameters:
  • filename (str) – Saving plots to filename if provideed (optional)

  • verbose (bool) – Plotting on screen if True (optional)

plot_envelope(filename=None, verbose=True)[source]

Creating standard plots for the solved problem

Parameters:
  • filename (str) – Saving plots to filename if provideed (optional)

  • verbose (bool) – Plotting on screen if True (optional)

plot_tprofile(filename=None, verbose=True)[source]

Creating standard plots for the solved problem

Parameters:
  • filename (str) – Saving plots to filename if provideed (optional)

  • verbose (bool) – Plotting on screen if True (optional)

analyze_rupture(filename=None)[source]

Analyze vessel rupture potential under fire exposure conditions.

Performs a simplified rupture analysis by calculating vessel wall temperatures under external fire heat load and comparing von Mises stress (from internal pressure) against temperature-dependent allowable tensile stress (ATS). Determines if and when vessel rupture may occur.

The analysis: 1. Calculates wall temperature evolution under fire exposure 2. Computes von Mises equivalent stress from internal pressure 3. Evaluates temperature-dependent material strength (ATS) 4. Identifies rupture time when stress exceeds strength 5. Generates diagnostic plots

Parameters:

filename (str, optional) – Base filename for saving plots. If None, plots are displayed on screen. Generates two plot files: - {filename}_peak_wall_temp.png - {filename}_ATS_vonmises.png

Returns:

Results are stored in instance variables: - self.rupture_time : float or None

Time when rupture occurs [s], or None if no rupture predicted

  • self.peak_timesndarray

    Time array for rupture analysis [s]

  • self.von_misesndarray

    von Mises equivalent stress history [Pa]

  • self.ATS_wettedndarray

    Allowable tensile stress for wetted region [Pa]

  • self.ATS_unwettedndarray

    Allowable tensile stress for unwetted region [Pa]

  • self.peak_T_wettedndarray

    Wall temperature history for wetted region [K]

  • self.peak_T_unwettedndarray

    Wall temperature history for unwetted region [K]

Return type:

None

Notes

Requires rupture analysis parameters in input: - self.rupture_fire: Fire type (e.g., ‘api_pool’, ‘scandpower_jet’) - self.rupture_material: Material type for ATS calculation

The method uses a simplified lumped capacitance model for wall heating. Time step for rupture analysis is fixed at 10 seconds.

generate_report()[source]

Generating a report summarising key features for the problem solved. Can be used for e.g. case studies, problem optimisation (external) etc.

Key Classes

HydDown

class hyddown.hdclass.HydDown(input)[source]

Bases: object

Main class to to hold problem definition, running problem, storing results etc.

__init__(input)[source]
Parameters:

input (dict) – Dict holding problem definition

validate_input()[source]

Validating the provided problem definition dict

Raises:

ValueError – If missing input is detected.

read_input()[source]

Reading in input/ problem definition dict and assigning to classs attributes.

initialize()[source]

Preparing for running problem by creating the fluid objects required instantiating arrays for storing time-dependent results, setting additional required class attributes.

calc_liquid_level()[source]

Calculate liquid level height based on current two-phase fluid state.

For two-phase systems (0 ≤ quality ≤ 1), calculates the height of liquid phase in the vessel based on vapor quality, phase densities, and vessel geometry. Uses vessel geometry from fluids.TANK to convert liquid volume to height.

Parameters:

fluid (CoolProp AbstractState) – Current fluid state

Returns:

Liquid level height from vessel bottom [m]. Returns 0.0 for single-phase gas (quality > 1 or subcooled liquid).

Return type:

float

PHres(T, P, H)[source]

Residual enthalpy function to be minimized during PH-problem.

Used by numerical optimizer (scipy.optimize.minimize) to find temperature that satisfies constant pressure-enthalpy constraints for multicomponent fluids. The optimizer adjusts T until residual approaches zero.

Parameters:
  • H (float) – Enthalpy at initial/final conditions [J/kg]

  • P (float) – Pressure at final conditions [Pa]

  • T (float) – Updated estimate for the final temperature at (P,H) [K]

Returns:

Squared normalized enthalpy residual (dimensionless). Zero when correct temperature is found.

Return type:

float

PHres_relief(T, P, H)[source]

Residual enthalpy function for PH-problem during relief valve calculations.

Used by numerical optimizer (scipy.optimize.root_scalar) to find temperature for relief valve discharge calculations. Similar to PHres() but uses the main fluid state instead of vent_fluid state.

Parameters:
  • H (float) – Enthalpy at initial/final conditions [J/kg]

  • P (float) – Pressure at final conditions [Pa]

  • T (float) – Updated estimate for the final temperature at (P,H) [K]

Returns:

Normalized enthalpy residual (dimensionless). Zero when correct temperature is found.

Return type:

float

PHproblem(H, P, Tguess, relief=False)[source]

Defining a constant pressure, constant enthalpy problem i.e. typical adiabatic problem like e.g. valve flow for the vented flow (during discharge). For multicomponent mixture the final temperature is changed/optimised until the residual enthalpy is near zero in an optimisation step. For single component fluid the coolprop built in methods are used for speed.

Parameters:
  • H (float) – Enthalpy at initial/final conditions

  • P (float) – Pressure at final conditions.

  • Tguess (float) – Initial guess for the final temperature at P,H

UDres(x, U, rho)[source]

Residual U-rho to be minimised during a U-rho/UV-problem

Parameters:
  • U (float) – Internal energy at final conditions

  • rho (float) – Density at final conditions

UDproblem(U, rho, Pguess, Tguess)[source]

Defining a constant UV problem i.e. constant internal energy and density/volume problem relevant for the 1. law of thermodynamics. For multicomponent mixture the final temperature/pressure is changed/optimised until the residual U/rho is near zero. For single component fluid the coolprop built in methods are used for speed.

Parameters:
  • U (float) – Internal energy at final conditions

  • rho (float) – Density at final conditions.

  • Pguess (float) – Initial guess for the final pressure at U, rho

  • Tguess (float) – Initial guess for the final temperature at U, rho

run(disable_pbar=True)[source]

Routine for running the actual problem defined i.e. integrating the mass and energy balances

get_dataframe()[source]

Export simulation results to pandas DataFrame for analysis and archiving.

Collects all time-series results from the simulation and organizes them into a pandas DataFrame with labeled columns. Useful for exporting to CSV/Excel, post-processing, or custom plotting.

Returns:

DataFrame with simulation results. Columns include: - Time (s) - Pressure (bar) - Fluid temperature (°C) - Wall temperature (°C) - Vent temperature (°C) - Fluid enthalpy (J/kg) - Fluid entropy (J/(kg·K)) - Fluid internal energy (J/kg) - Discharge mass rate (kg/s) - Fluid mass (kg) - Fluid density (kg/m³) - Inner heat transfer coefficient (W/(m²·K)) - Internal heat flux (W/m²) - External heat flux (W/m²) - Inner wall temperature (°C) - Outer wall temperature (°C)

Return type:

pd.DataFrame

Notes

Only returns data if simulation has been run (self.isrun == True). Temperature values are converted from Kelvin to Celsius. Pressure values are converted from Pa to bar.

plot(filename=None, verbose=True)[source]

Creating standard plots for the solved problem

Parameters:
  • filename (str) – Saving plots to filename if provideed (optional)

  • verbose (bool) – Plotting on screen if True (optional)

plot_envelope(filename=None, verbose=True)[source]

Creating standard plots for the solved problem

Parameters:
  • filename (str) – Saving plots to filename if provideed (optional)

  • verbose (bool) – Plotting on screen if True (optional)

plot_tprofile(filename=None, verbose=True)[source]

Creating standard plots for the solved problem

Parameters:
  • filename (str) – Saving plots to filename if provideed (optional)

  • verbose (bool) – Plotting on screen if True (optional)

analyze_rupture(filename=None)[source]

Analyze vessel rupture potential under fire exposure conditions.

Performs a simplified rupture analysis by calculating vessel wall temperatures under external fire heat load and comparing von Mises stress (from internal pressure) against temperature-dependent allowable tensile stress (ATS). Determines if and when vessel rupture may occur.

The analysis: 1. Calculates wall temperature evolution under fire exposure 2. Computes von Mises equivalent stress from internal pressure 3. Evaluates temperature-dependent material strength (ATS) 4. Identifies rupture time when stress exceeds strength 5. Generates diagnostic plots

Parameters:

filename (str, optional) – Base filename for saving plots. If None, plots are displayed on screen. Generates two plot files: - {filename}_peak_wall_temp.png - {filename}_ATS_vonmises.png

Returns:

Results are stored in instance variables: - self.rupture_time : float or None

Time when rupture occurs [s], or None if no rupture predicted

  • self.peak_timesndarray

    Time array for rupture analysis [s]

  • self.von_misesndarray

    von Mises equivalent stress history [Pa]

  • self.ATS_wettedndarray

    Allowable tensile stress for wetted region [Pa]

  • self.ATS_unwettedndarray

    Allowable tensile stress for unwetted region [Pa]

  • self.peak_T_wettedndarray

    Wall temperature history for wetted region [K]

  • self.peak_T_unwettedndarray

    Wall temperature history for unwetted region [K]

Return type:

None

Notes

Requires rupture analysis parameters in input: - self.rupture_fire: Fire type (e.g., ‘api_pool’, ‘scandpower_jet’) - self.rupture_material: Material type for ATS calculation

The method uses a simplified lumped capacitance model for wall heating. Time step for rupture analysis is fixed at 10 seconds.

generate_report()[source]

Generating a report summarising key features for the problem solved. Can be used for e.g. case studies, problem optimisation (external) etc.

Key Methods

The HydDown class implements the following key methods:

  • run(): Main integration loop for mass/energy balances

  • step(): Single time step calculation

  • PHproblem(): Solve thermodynamic state from pressure and enthalpy

  • UDproblem(): Solve thermodynamic state from internal energy and density

  • plot(): Generate results visualization

Implementation Notes

Time Integration

The code uses an explicit Euler method for mass balance integration. The time step dt must be small enough for numerical stability (typically 0.01-1 second).

Calculation Types

The calculation.type parameter determines the thermodynamic path:

  • isothermal: Constant temperature

  • isenthalpic: Constant enthalpy, adiabatic expansion without work

  • isentropic: Constant entropy, adiabatic expansion with PV work

  • specified_U: Constant internal energy

  • energybalance: Most general case with heat transfer