zfactor

package module
v1.3.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 3 Imported by: 0

README

zfactor

zfactor is a comprehensive Go library designed for thermodynamic property calculations and visualization. It provides tools for solving Cubic Equations of State (EOS), estimating properties using correlations like Lee-Kesler, and generating Pressure-Volume (PV) diagrams.

Features

  • Cubic Equations of State (EOS): Support for major cubic EOS models:
    • van der Waals (vdW)
    • Redlich-Kwong (RK)
    • Soave-Redlich-Kwong (SRK)
    • Peng-Robinson (PR)
  • Lee-Kesler Correlation: Accurate estimation of compressibility factors (Z) and other derived properties.
  • Virial Equations: Solvers for 2-term and 3-term virial equations of state.
  • Abbott Correlations: Generalized correlations for the second virial coefficient ($B$).
  • Liquid Properties: Calculation of saturated liquid molar volumes using the Rackett equation and reduced density using Lydersen charts.
  • Antoine Equation: Calculation of saturation vapor pressures.
  • Thermodynamic State Management: Easy definition and validation of states ($T, P$).
  • Heat Capacity Data: Constants for Ideal Gases, Liquids, and Solids.
  • Visualization: Built-in generation of PV diagrams with:
    • Critical Isotherms
    • Saturation Domes (Two-phase regions)
    • Custom Isotherms
    • Customizable styling (colors, labels, dimensions)
  • Substance Database: Pre-defined properties for common substances (Critical properties, Acentric factor, MW, etc.).

Important Note on Lydersen Charts

The ReducedDensity function relies on digitized data from the Lydersen charts. While efforts have been made to ensure accuracy through smoothing and normalization, users should exercise caution.

  • Verification: Please review the generated Lydersen Chart Plot to ensure the curves meet the precision requirements of your specific use case.
  • Updates: Data values may be refined in future versions as digitization techniques improve or better data sources are integrated.

Lydersen Chart

Installation

go get github.com/rickykimani/zfactor

Usage

zfactor uses a unified argument structure zfactor.Args for most functions to ensure clarity and type safety.

Standard Units (unless otherwise customized or specified):

  • Temperature: Kelvin (K)
  • Pressure: bar
  • Volume: cm³/mol
  • Gas Constant (R): typically bar·cm³/(mol·K) (available as zfactor.RSI * 10)
1. General Property Calculation (Cubic EOS & Lee-Kesler)

Compare molar volume estimates using the Lee-Kesler correlation vs. the Soave-Redlich-Kwong (SRK) Equation of State.

For a full runnable example, see examples/problem_ethane_cylinder/main.go.

package main

import (
	"fmt"
	"log"

	"github.com/rickykimani/zfactor"
	"github.com/rickykimani/zfactor/cubic"
	leekesler "github.com/rickykimani/zfactor/lee-kesler"
	"github.com/rickykimani/zfactor/substance"
)

func main() {
	ethane := substance.Ethane
	args := zfactor.Args{
		T: 299.0, // Kelvin
		P: 32.0,  // bar
		R: 10 * zfactor.RSI, // bar*cm³/(mol*K)
	}

	// 1. Estimate Z using Lee-Kesler
	z, err := ethane.LeeKesler(args, leekesler.CompressibilityFactor)
	if err != nil {
		log.Fatal(err)
	}
	
	v_lk := z * args.R * args.T / args.P
	fmt.Printf("Volume (Lee-Kesler): %.2f cm³/mol\n", v_lk)

	// 2. Solve using SRK Equation of State
	// Create configuration for SRK
	cfg := ethane.CubicConfig(&cubic.SRK{}, args)
	
	// Solve for Volume (returns roots for liquid/vapor)
	volRes, err := cubic.SolveForVolume(cfg)
	if err != nil {
		log.Fatal(err)
	}
	
	fmt.Printf("Volume (SRK): %v\n", volRes.Clean())
}
2. Virial Equations

Solve for compressibility factors using 2-term or 3-term virial equations.

For a full runnable example, see examples/virial/main.go.

import "github.com/rickykimani/zfactor/virial"

// Isopropanol vapor example
args := zfactor.Args{
    T: 473.15, // K
    P: 10.0,   // bar
    R: 83.14,  // bar·cm³/(mol·K)
    B: -338.0, // Second virial coefficient (cm³/mol)
    C: -26000.0, // Third virial coefficient (cm⁶/mol²)
}

// 2-Term Virial (Z = 1 + BP/RT)
z2, _ := virial.CompressibilityTwoTerm(args)
fmt.Printf("Z (2-term): %.4f\n", z2)

// 3-Term Virial (Iterative solution)
// Returns complex roots for volume
roots, _ := virial.SolveForVolumeThreeTerm(args)
3. Saturation & Liquid Properties

For a full runnable example, see examples/liquids/main.go.

Calculate saturation pressure (Antoine) and liquid molar properties (Rackett/Lydersen).

import (
    "github.com/rickykimani/zfactor/antoine"
    "github.com/rickykimani/zfactor/substance"
)

// Saturation Pressure (Antoine Equation)
// Note: Antoine coefficients often use Celsius and specific pressure units (e.g., kPa)
pSat, _ := antoine.Ethanol.Pressure(25.0) // 25°C
fmt.Printf("Saturation Pressure (Ethanol @ 25C): %.2f kPa\n", pSat)

// Saturated Liquid Volume (Rackett Equation)
eth := substance.Ethane
vSat, _ := eth.Vsat(299.0) // T in Kelvin required
fmt.Printf("Saturated Liquid Volume: %.4f cm³/mol\n", vSat)

// Reduced Density (Lydersen Charts)
rhoR, _ := eth.ReducedDensity(zfactor.Args{T: 299.0, P: 50.0})
fmt.Printf("Reduced Density: %.4f\n", rhoR)
4. Residual Properties (Abbott/Virial & Lee-Kesler)

Calculate residual enthalpy ($H^R$) and entropy ($S^R$). You can use either the Abbott correlations (based on Virial coefficients) or the Lee-Kesler tables. Lee-Kesler is generally more accurate at higher pressures.

For a full runnable example, see examples/residual/main.go.

import (
    leekesler "github.com/rickykimani/zfactor/lee-kesler"
    "github.com/rickykimani/zfactor/substance"
)

eth := substance.Ethane
args := zfactor.Args{T: 299.0, P: 32.0}

// 1. Abbott Correlations (Virial)
hR, _ := eth.AbbottResidualEnthalpy(args)
sR, _ := eth.AbbottResidualEntropy(args)

// 2. Lee-Kesler (More accurate at high pressure)
hR_LK, _ := eth.LeeKesler(args, leekesler.ResidualEnthalpy)
sR_LK, _ := eth.LeeKesler(args, leekesler.ResidualEntropy)
5. Mixture Properties

Estimate properties for gas mixtures using Kay's Rule (linear pseudo-critical properties) and Lee-Kesler correlations.

For a full runnable example, see examples/problem_mixture/main.go.

// Define an equimolar mixture of CO2 and Propane
mixture, _ := substance.NewLinearMixture("Mixture", []substance.Component{
    {Substance: substance.CarbonDioxide, Fraction: 0.5},
    {Substance: substance.Propane, Fraction: 0.5},
})

// Use the mixture just like a pure substance
args := zfactor.Args{T: 450, P: 140}
z, _ := mixture.LeeKesler(args, leekesler.CompressibilityFactor)
6. Generating a PV Diagram

Visualize thermodynamic states on a PV diagram, including the saturation dome and critical isotherm.

package main

import (
	"log"

	"github.com/rickykimani/zfactor/cubic"
	"github.com/rickykimani/zfactor/state"
	"github.com/rickykimani/zfactor/substance"
)

func main() {
	// Define states
	s1, _ := state.NewState(substance.Ethane, 299, 32)
	s2, _ := state.NewState(substance.Ethane, 490, 70)

	// Configure the plot
	cfg := &state.PVConfig{
		Type:           *cubic.PR{}, // Use Peng-Robinson
		Title:          "PV Diagram for Ethane",
		NumberStates:   true,
		LabelIsotherms: true,
	}

	// Generate the diagram
	err := state.DrawPV(cfg, "ethane_pv.png", s1, s2)
	if err != nil {
		log.Fatal(err)
	}
}
Example Output

The following diagram was generated using the code in examples/main.go:

PV Diagram

7. Heat Capacity Data (cp)

The cp package provides standard heat capacity constants ($A, B, C, D$) for gases (Ideal Gas state), liquids, and solids. It supports the standard polynomial form:

$$ \frac{C_P}{R} = A + BT + CT^2 + DT^{-2} $$

It also implements integral methods for calculating property changes for Ideal Gases:

  • Enthalpy Change ($\Delta H^{ig}$)
  • Entropy Change ($\Delta S^{ig}$)
import "github.com/rickykimani/zfactor/cp"

gas := cp.MethaneGas
s1 := zfactor.Args{T: 300, P: 100000, R: zfactor.RSI}
s2 := zfactor.Args{T: 1000, P: 100000, R: zfactor.RSI}

// Calculate Delta H (Enthalpy Change)
dH, _ := gas.IdealGasEnthalpyChange(s1, s2)
fmt.Printf("Delta H: %.2f J/mol\n", dH)

// Calculate Delta S (Entropy Change)
dS, _ := gas.IdealGasEntropyChange(s1, s2)
fmt.Printf("Delta S: %.2f J/(mol·K)\n", dS)

Data is available via pre-defined variables:

  • cp.MethaneGas
  • cp.WaterLiquid
  • cp.CaOSolid etc.
8. Vapor Pressure & Acentric Factor (Lee-Kesler)

Estimate saturation vapor pressure ($P^{sat}$) and Acentric Factor ($\omega$) using the Lee-Kesler method.

The substance package provides convenient wrappers for these calculations if the substance has a defined Normal Boiling Point ($T_n$).

import (
    "fmt"
    "github.com/rickykimani/zfactor/substance"
)

// 1. Calculate Vapor Pressure for a specific substance
// Example: Methane at 150K
methane := substance.Methane
pSat, err := methane.LeeKeslerVaporPressure(150.0)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Vapor Pressure of %s at 150K: %.2f bar\n", methane.Name, pSat)

// 2. Estimate Acentric Factor
// If the substance is missing the Acentric Factor but has Tn defined:
omega, err := methane.LeeKeslerAcentric()
fmt.Printf("Estimated Acentric Factor: %.4f\n", omega)

You can also use the lee-kesler package directly if you don't have a Substance struct:

import leekesler "github.com/rickykimani/zfactor/lee-kesler"

// Estimate Vapor Pressure directly (T, Tn, Tc, Pc)
pSat, _ := leekesler.VaporPressure(150.0, 111.6, 190.6, 46.1)

Package Overview

  • zfactor: Root package, defines Args and physical constants.
  • substance: Database of chemical species and methods for substance-specific calculations (e.g., Ethane.LeeKesler(...)).
  • cubic: Solvers for cubic equations of state (vdW, RK, SRK, PR) for Volume, Pressure, and Z.
  • lee-kesler: Implementation of the Lee-Kesler generalized correlation tables.
  • virial: Solvers for 2-term and 3-term virial equations.
  • abbott: Generalized correlations for second virial coefficient ($B$) and residual properties.
  • antoine: Antoine equation parameters and solvers for saturation pressure.
  • cp: Heat capacity constants and thermodynamic property calculations ($\Delta H^{ig}$, $\Delta S^{ig}$) for ideal gases.
  • liquids: Correlations for liquid density (Rackett, Lydersen).
  • state: High-level plotting logic for generating Thermodynamic PV diagrams.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package zfactor provides a comprehensive library for thermodynamic property calculations and visualization. It includes tools for solving Cubic Equations of State (EOS), estimating properties using correlations like Lee-Kesler, calculating liquid properties, and generating Pressure-Volume (PV) diagrams.

Index

Constants

View Source
const (
	// RSI is the Universal Gas Constant in SI units [J/(mol·K)].
	RSI = 8.314

	// AtmPa is the standard atmospheric pressure in Pascals (Pa).
	AtmPa = 101_325.0

	// AtmKPa is the standard atmospheric pressure in Kilopascals (kPa).
	AtmKPa = AtmPa * 1e-3

	// AtmBar is the standard atmospheric pressure in Bars.
	AtmBar = AtmPa * 1e-5
)

Variables

View Source
var (
	// ErrTemp is returned when the absolute temperature is less than or equal to 0.
	ErrTemp = InputError{Msg: "absolute temperature (T) cannot be less than or equal to 0"}
	// ErrPressure is returned when the pressure is less than 0.
	ErrPressure = InputError{Msg: "pressure (P) cannot be less than 0"}
	// ErrCriticalProp is returned when a critical property (Tc or Pc) is less than or equal to 0.
	ErrCriticalProp = InputError{Msg: "critical property (Tc, Pc, Vc or Zc) cannot have a value less than or equal to 0"}
	// ErrUniversalConst is returned when the universal gas constant (R) is less than or equal to 0.
	ErrUniversalConst = InputError{Msg: "universal gas constant (R) value cannot be less than or equal to 0"}
	// ErrVirialCoeff is returned when a virial coefficient is 0.
	ErrVirialCoeff = InputError{Msg: "virial coefficient (B or C) cannot be 0"}
	// ErrVolume is returned when the molar volume is less than or equal to 0
	ErrVolume = InputError{Msg: "molar volume (V) cannot be less than or equal to 0"}
	// ErrHighPressureTwoTerm is returned when the pressure exceeds 15 bar for the two-term virial equation.
	ErrHighPressureTwoTerm = InputError{Msg: "pressure exceeds the validity limit (15 bar) for the two-term virial equation"}
	// ErrInvalidTr is returned when the reduced temperature (Tr) is less than or equal to 0.
	ErrInvalidTr = InputError{Msg: "reduced temperature (Tr) must be greater than 0"}
	// ErrInvalidPr is returned when the reduced pressure (Pr) is less than or equal to 0.
	ErrInvalidPr = InputError{Msg: "reduced pressure (Pr) must be greater than 0"}
)

Functions

func SolveCubic

func SolveCubic(a, b, c, d float64) ([3]complex128, error)

SolveCubic solves ax^3 + bx^2 + cx + d = 0 Returns all 3 roots (possibly complex).

Types

type Args added in v1.2.0

type Args struct {
	T float64 // Temperature
	P float64 // Pressure
	R float64 // Gas constant
	B float64 // Second virial coefficient
	C float64 // Third virial coefficient
}

Args holds the thermodynamic state arguments to prevent order-dependent errors. It is used to pass parameters like Temperature and Pressure safely.

type InputError added in v1.1.1

type InputError struct {
	Msg string
}

InputError represents an error resulting from invalid input parameters.

func (InputError) Error added in v1.1.1

func (e InputError) Error() string

Directories

Path Synopsis
Package abbott provides the generalized correlations for the second virial coefficient
Package abbott provides the generalized correlations for the second virial coefficient
Package antoine provides coefficients and calculation methods for the Antoine equation, which estimates the saturation vapor pressure of pure substances as a function of temperature.
Package antoine provides coefficients and calculation methods for the Antoine equation, which estimates the saturation vapor pressure of pure substances as a function of temperature.
gen command
cp
Package cp provides coefficients for the calculation of heat capacities of gases (in the ideal-gas state), solids, and liquids.
Package cp provides coefficients for the calculation of heat capacities of gases (in the ideal-gas state), solids, and liquids.
gen command
Package cubic provides implementations of cubic Equations of State (EOS) for calculating thermodynamic properties such as volume and pressure.
Package cubic provides implementations of cubic Equations of State (EOS) for calculating thermodynamic properties such as volume and pressure.
examples
liquids command
problem_mixture command
residual command
virial command
package leekesler contains the Lee/Kesler generalized correlation tables for the compressibility factor, residual enthalpy, residual entropy and the fugacity coefficient.
package leekesler contains the Lee/Kesler generalized correlation tables for the compressibility factor, residual enthalpy, residual entropy and the fugacity coefficient.
gen command
Package liquids provides correlations and data for calculating liquid properties.
Package liquids provides correlations and data for calculating liquid properties.
gen command
Package state provides functionality for defining thermodynamic states and generating visual representations such as PV diagrams.
Package state provides functionality for defining thermodynamic states and generating visual representations such as PV diagrams.
package substance contains the characteristic properties of pure species
package substance contains the characteristic properties of pure species
gen command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL