Sunday, November 24, 2024

Understanding the Psychrometric Chart python code

The psychrometric calculator is an essential tool in HVAC (Heating, Ventilation, and Air Conditioning) and other thermal systems to analyze air-water vapor mixtures. This blog post explains the fundamental concepts, formulas, and algorithms used in the given HTML-based psychrometric calculator.


How to Create a Psychrometric Chart Using Python

A psychrometric chart is a powerful tool used in HVAC, thermodynamics, and atmospheric sciences to represent the properties of moist air. This article explains how to generate a comprehensive psychrometric chart using Python with numpy, matplotlib, and the psychrolib library.

Refer this link to see full Python code: https://github.com/chemenggcalc/Psychrometric-Chart-using-Python


Libraries Used

  • NumPy: For efficient numerical computations.
  • Matplotlib: For visualizing the psychrometric chart.
  • PsychroLib: A library for psychrometric calculations, supporting SI and IP unit systems.

Setting Up the Environment

Before starting, ensure you have the required libraries installed. Use the following command to install them:

pip install numpy matplotlib psychrolib

The Code Breakdown

1. Initialization

The psychrometric calculations are based on the SI unit system (Celsius, kg/kg, Pa). Use the SetUnitSystem function from psychrolib to set the unit system:

from psychrolib import SI, SetUnitSystem
SetUnitSystem(SI)

2. Define Parameters

Define the ranges for dry-bulb temperature, humidity ratio, and atmospheric pressure:

import numpy as np

temperature_range = np.linspace(0, 50, 100)  # Dry-bulb temperature range (°C)
humidity_ratio_range = np.linspace(0, 0.01, 30)  # Humidity ratio range (kg/kg dry air)
pressure = 101325  # Atmospheric pressure (Pa)

3. Plotting the Psychrometric Chart

A. Saturation Line

The saturation line represents air that holds the maximum amount of water vapor at a given temperature:

from psychrolib import GetSatHumRatio

sat_hum_ratios = [GetSatHumRatio(t, pressure) for t in temperature_range]
plt.plot(temperature_range, sat_hum_ratios, color="blue", linewidth=4, label="Saturation Line")

B. Constant Relative Humidity Lines

Relative humidity lines (10%, 20%, ..., 100%) are plotted using GetHumRatioFromRelHum:

from psychrolib import GetHumRatioFromRelHum

relative_humidities = np.linspace(0.1, 1, 10)
for rh in relative_humidities:
    hum_ratios = [GetHumRatioFromRelHum(t, rh, pressure) for t in temperature_range]
    plt.plot(temperature_range, hum_ratios, linestyle="--", color="#32CD32", linewidth=2)

C. Constant Enthalpy Lines

Enthalpy lines (10, 20, ..., 250 kJ/kg) are derived from the equation:

h=1.006T+W(2501+1.86T)h = 1.006 \cdot T + W \cdot (2501 + 1.86 \cdot T)

Rearranged to find WW (humidity ratio):

enthalpy_lines = range(10, 250, 15)
for h in enthalpy_lines:
    hum_ratios = [(h - 1.006 * t) / (2501 + 1.86 * t) for t in temperature_range]
    plt.plot(temperature_range, hum_ratios, linestyle="-.", color="#FF4500", linewidth=2)

D. Constant Wet-Bulb Temperature Lines

Wet-bulb temperature lines are approximated using GetHumRatioFromRelHum:

wet_bulb_temps = range(5, 36, 5)
for twb in wet_bulb_temps:
    hum_ratios = []
    for t in temperature_range:
        try:
            hum_ratio = GetHumRatioFromRelHum(t, twb / 100.0, pressure)
            hum_ratios.append(hum_ratio)
        except:
            hum_ratios.append(np.nan)
    plt.plot(temperature_range, hum_ratios, linestyle=":", color="#9400D3", linewidth=2)

E. Constant Specific Volume Lines

Specific volume lines are calculated using an approximation formula:

v=1ρ=RTPv = \frac{1}{\rho} = \frac{R \cdot T}{P}
specific_volumes = np.linspace(0.75, 25, 20)
for vol in specific_volumes:
    hum_ratios = [vol / (t + 273.15) for t in temperature_range]
    plt.plot(temperature_range, hum_ratios, linestyle="-", color="#FFA500", linewidth=2)

4. Enhancing the Chart

Grid Lines

Vertical and horizontal grid lines improve readability:

for t in temperature_range:
    plt.axvline(t, color="gray", linestyle="--", linewidth=1, alpha=0.5)
for hr in np.linspace(humidity_ratio_range[0], humidity_ratio_range[1], 10):
    plt.axhline(hr, color="gray", linestyle=":", linewidth=1, alpha=0.5)

Labels and Title

Add descriptive labels, a title, and a legend:

plt.xlabel("Dry-Bulb Temperature (°C)", fontsize=20, weight="bold")
plt.ylabel("Humidity Ratio (kg water / kg dry air)", fontsize=20, weight="bold")
plt.text(15, 0.075, "Psychrometric Chart", fontsize=50, ha="center", color="black", weight="bold")
plt.legend(loc="center left", fontsize=18, frameon=True, shadow=True, fancybox=True)

Customization

Customize the layout with grid styling and appropriate figure size:

plt.figure(figsize=(20, 15))
plt.grid(True, which='both', linestyle="--", linewidth=1.5, alpha=0.7)

5. Display the Chart

Finally, render the chart using:

plt.show()

Key Outputs

The psychrometric chart includes:

  1. Saturation line.
  2. Constant relative humidity, enthalpy, wet-bulb temperature, and specific volume lines.
  3. Interactive labels and enhanced readability through grid lines.

Applications

  • HVAC Design: Analyze air-conditioning systems.
  • Environmental Science: Study humidity and temperature changes.
  • Industrial Processes: Understand air-water mixture dynamics in drying and humidification.

By leveraging Python's capabilities, this tool simplifies complex psychrometric calculations and makes air-property analysis accessible to engineers and researchers.

Saturday, November 23, 2024

Comprehensive Guide to Psychrometric Calculator and concepts Used

Psychrometrics deals with the physical and thermodynamic properties of air-vapor mixtures. The HTML-based psychrometric calculator presented here allows users to compute various properties of moist air, such as enthalpy, humidity ratio, relative humidity, dew point temperature, and others, based on inputs like Dry Bulb Temperature (DBT), Wet Bulb Temperature (WBT), or Relative Humidity (RH). This blog dives into the key formulas, concepts, and the logic used in the calculator.


Core Inputs and Their Significance

  1. Dry Bulb Temperature (DBT):
    The temperature of air measured using a standard thermometer without considering moisture content.

  2. Wet Bulb Temperature (WBT):
    The lowest temperature air can reach through evaporative cooling, measured with a thermometer covered by a wet cloth.

  3. Relative Humidity (RH):
    The ratio of the current vapor pressure of air to its saturation vapor pressure at a given temperature, expressed as a percentage.

  4. Altitude:
    The height above sea level affects atmospheric pressure, which in turn influences psychrometric properties.


Key Calculations and Formulas

1. Saturation Vapor Pressure

The saturation vapor pressure depends on the temperature and is determined using the Hyland-Wexler equation:

  • For T ≥ 0°C (Water):

    Psat, water=eC8Tk+C9+C10Tk+C11Tk2+C12Tk3+C13ln(Tk)P_{\text{sat, water}} = e^{\frac{C_8}{T_k} + C_9 + C_{10}T_k + C_{11}T_k^2 + C_{12}T_k^3 + C_{13}\ln(T_k)}
  • For T < 0°C (Ice):

    Psat, ice=eC1Tk+C2+C3Tk+C4Tk2+C5Tk3+C6Tk4+C7ln(Tk)P_{\text{sat, ice}} = e^{\frac{C_1}{T_k} + C_2 + C_3T_k + C_4T_k^2 + C_5T_k^3 + C_6T_k^4 + C_7\ln(T_k)}

    Here, Tk=T+273.15T_k = T + 273.15 (Kelvin).

2. Humidity Ratio (W):

The ratio of the mass of water vapor to the mass of dry air:

W=0.62198PvaporPatmPvaporW = 0.62198 \cdot \frac{P_{\text{vapor}}}{P_{\text{atm}} - P_{\text{vapor}}}

3. Partial Vapor Pressure (PvaporP_{\text{vapor}}):

Based on RH:

Pvapor=RH100PsatP_{\text{vapor}} = \frac{\text{RH}}{100} \cdot P_{\text{sat}}

4. Dew Point Temperature (TdewT_{\text{dew}}):

Using the logarithmic relation:

α=ln(Pvapor1000)\alpha = \ln\left(\frac{P_{\text{vapor}}}{1000}\right) Tdew={C14+C15α+C16α2+C17α3+C18Pvapor0.1984if Tdew06.09+12.608α+0.4959α2if Tdew<0T_{\text{dew}} = \begin{cases} C_{14} + C_{15}\alpha + C_{16}\alpha^2 + C_{17}\alpha^3 + C_{18}P_{\text{vapor}}^{0.1984} & \text{if } T_{\text{dew}} \geq 0 \\ 6.09 + 12.608\alpha + 0.4959\alpha^2 & \text{if } T_{\text{dew}} < 0 \end{cases}

5. Enthalpy (hh):

The total heat content of moist air:

h=Cp,airT+(Hfg+1.86T)Wh = C_{p, \text{air}}T + (H_{\text{fg}} + 1.86T)W

Where:

  • Cp,air=1.006kJ/kg\cdotpKC_{p, \text{air}} = 1.006 \, \text{kJ/kg·K} (specific heat of air)
  • Hfg=2501kJ/kgH_{\text{fg}} = 2501 \, \text{kJ/kg} (latent heat of vaporization)

6. Air Density (ρ\rho):

Using the ideal gas law:

ρ=PatmRspecific(T+273.15)(1+1.6078W)\rho = \frac{P_{\text{atm}}}{R_{\text{specific}}(T + 273.15)(1 + 1.6078W)}

7. Specific Volume (vv):

The volume occupied by 1 kg of moist air:

v=1ρv = \frac{1}{\rho}

Key Features of the Calculator

Input Types:

  • DBT & WBT: Calculates properties based on dry and wet bulb temperatures.
  • DBT & RH: Computes values using dry bulb temperature and relative humidity.

Altitude Adjustment:

Atmospheric pressure at altitude:

Patm=101325(12.25577×105altitude)5.2559P_{\text{atm}} = 101325 \cdot \left(1 - 2.25577 \times 10^{-5} \cdot \text{altitude}\right)^{5.2559}

Output Parameters Explained

  1. Enthalpy (kJ/kg): Total energy of air, combining sensible and latent heat.
  2. Humidity Ratio (kg/kg): Amount of moisture per unit mass of dry air.
  3. Air Density (kg/m³): Mass per unit volume of air.
  4. Partial Vapor Pressure (Pa): Pressure contributed by water vapor.
  5. Dew Point Temperature (°C): Temperature where air becomes saturated and water vapor condenses.
  6. Specific Volume (m³/kg): Volume occupied by a unit mass of moist air.
  7. Saturated Vapor Pressure (Pa): Maximum pressure water vapor can exert at a given temperature.
  8. Atmospheric Pressure (Pa): Ambient pressure adjusted for altitude.
  9. Calculated RH (%): Relative humidity derived from WBT.
  10. Calculated WBT (°C): Wet bulb temperature inferred from RH.

How It Works

  1. The user selects the input type and provides values for DBT, WBT/RH, and altitude.
  2. The calculator computes intermediate values like saturation pressure and partial vapor pressure.
  3. Core outputs like enthalpy, humidity ratio, and density are calculated.
  4. Results are dynamically displayed in a tabular format.

Advantages of This Calculator

  • User-friendly interface: Simple input forms with validation.
  • Dynamic adjustments: Fields toggle based on input type.
  • Real-world accuracy: Incorporates altitude effects on pressure.
  • Comprehensive outputs: Covers all significant psychrometric properties.

This psychrometric calculator simplifies the complex process of evaluating moist air properties, making it an indispensable tool for HVAC engineers, meteorologists, and anyone working with thermodynamic systems.

Resources

Thursday, November 21, 2024

Residence Time Distribution (RTD) for CSTR and PFR - Python Code Explanation

 

Explanation of the Code: Residence Time Distribution (RTD) for CSTR and PFR

This Python script models the Residence Time Distribution (RTD) for two types of chemical reactors: Continuous Stirred Tank Reactor (CSTR) and Plug Flow Reactor (PFR). It visualizes the response of these reactors to a pulse tracer input, helping to understand their behavior over time.


Key Concepts and Formulas

  1. Residence Time Distribution (RTD):
    • RTD, E(t)E(t), describes how long fluid elements spend in a reactor.
    • The mean residence time, τ\tau, is the average time the material stays in the reactor.

RTD for CSTR

Formula:

E(t)=1τetτE(t) = \frac{1}{\tau} e^{-\frac{t}{\tau}}

Explanation:

  • The RTD of a CSTR follows an exponential decay.
  • It assumes perfect mixing, meaning all fluid elements have an equal chance of leaving the reactor at any moment.
  • E(t)E(t) represents the probability density function of residence times.

Implementation in Code:

def rtd_cstr(t, tau):
    return (1 / tau) * np.exp(-t / tau)

RTD for PFR

Formula:

E(t)=δ(tτ)E(t) = \delta(t - \tau)

Where δ(tτ)\delta(t - \tau) is the Dirac delta function.

Explanation:

  • For a PFR, all fluid elements spend exactly the same time, τ\tau, in the reactor.
  • The Dirac delta function represents this instantaneous residence time.
  • In numerical simulations, the delta function is approximated as a sharp peak.

Implementation in Code:

def rtd_pfr(t, tau):
    E = np.zeros_like(t)
    E[np.argmin(np.abs(t - tau))] = 1  # Approximation of delta function
    return E

Pulse Tracer Input

Concept:

  • A pulse tracer is a sharp input signal at t=0t = 0 used to study RTD.
  • In the code, the pulse tracer is modeled as an array with a value of 1 at t=0t = 0 and 0 elsewhere.

Implementation in Code:

def pulse_tracer(t):
    pulse = np.zeros_like(t)
    pulse[0] = 1  # Sharp input at t=0
    return pulse

Visualization

The script uses Matplotlib to create plots comparing the RTD and pulse tracer input for both CSTR and PFR.

Key Elements:

  1. Subplots:

    • Two side-by-side plots for CSTR and PFR.
    • Pulse tracer input and RTD responses are plotted on the same axes.
  2. Styling:

    • Different colors and line styles for clarity.
    • Labels, titles, and legends for better interpretation.
  3. Time Range:

    • The time array spans from 00 to 3τ3\tau, capturing significant parts of the RTD curve.

Code Walkthrough

  1. Import Libraries:

    • math, numpy, and matplotlib for mathematical operations and plotting.
  2. Define Parameters:

    • Mean residence time, τ=1\tau = 1.
    • Time array, t, created using np.linspace.
  3. Define Functions:

    • rtd_cstr for CSTR RTD.
    • rtd_pfr for PFR RTD.
    • pulse_tracer for the pulse input.
  4. Plotting:

    • Two subplots for CSTR and PFR.
    • RTD curves and pulse input are overlaid for comparison.
  5. Display Results:

    • The plots are displayed using plt.show().

Output

  1. CSTR Plot:

    • Exponential decay RTD.
    • Smooth curve indicating a range of residence times due to perfect mixing.
  2. PFR Plot:

    • A sharp peak at t=τt = \tau.
    • Indicates all fluid elements exit the reactor simultaneously.



Significance of RTD Analysis

  1. Reactor Design:

    • RTD helps in understanding flow behavior, mixing, and reaction performance.
  2. Comparison:

    • CSTR: Suitable for reactions needing long residence times due to mixing.
    • PFR: Ideal for plug flow with uniform reaction time.
  3. Applications:

    • Chemical reaction engineering.
    • Troubleshooting flow maldistribution or bypassing in reactors.

By analyzing RTD, engineers can optimize reactor performance and ensure better process control.



Understanding the Psychrometric Chart python code

The psychrometric calculator is an essential tool in HVAC (Heating, Ventilation, and Air Conditioning) and other thermal systems to analyze ...