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:
objectMain class to to hold problem definition, running problem, storing results etc.
- validate_input()[source]
Validating the provided problem definition dict
- Raises:
ValueError – If missing input is detected.
- 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:
- 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:
- Returns:
Squared normalized enthalpy residual (dimensionless). Zero when correct temperature is found.
- Return type:
- 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.
- 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.
- 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.
- 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.
- 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.
Key Classes
HydDown
- class hyddown.hdclass.HydDown(input)[source]
Bases:
objectMain class to to hold problem definition, running problem, storing results etc.
- validate_input()[source]
Validating the provided problem definition dict
- Raises:
ValueError – If missing input is detected.
- 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:
- 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:
- Returns:
Squared normalized enthalpy residual (dimensionless). Zero when correct temperature is found.
- Return type:
- 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.
- 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.
- 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.
- 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.
- 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.
Key Methods
The HydDown class implements the following key methods:
run(): Main integration loop for mass/energy balancesstep(): Single time step calculationPHproblem(): Solve thermodynamic state from pressure and enthalpyUDproblem(): Solve thermodynamic state from internal energy and densityplot(): 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 temperatureisenthalpic: Constant enthalpy, adiabatic expansion without workisentropic: Constant entropy, adiabatic expansion with PV workspecified_U: Constant internal energyenergybalance: Most general case with heat transfer