Modeling a crude furnace and fractionator involves complex thermodynamics, mass, and energy balances. Both "sequential modular" and "equation-oriented" approaches have their strengths.
- Sequential Modular (SM): Units are solved one by one, and streams are passed between them. Iteration is often required for recycle loops or when units are interdependent (e.g., the furnace output depends on the fractionator's performance if there's a recycle, or simply for convergence). This is conceptually closer to how process engineers design unit operations in commercial simulators like Aspen Plus or Hysys.
- Equation-Oriented (EO): All equations for all units are formulated simultaneously and solved as a single, large system of non-linear equations. This requires a robust solver and good initial guesses but can offer faster convergence for highly integrated systems and is well-suited for optimization.
We'll use the thermo library for thermodynamic calculations (VLE, enthalpy).
Key Concepts & Assumptions:
- Components: We'll use a simplified set of pseudo-components or representative hydrocarbons. A real crude assay has hundreds.
- Thermodynamics: We'll use the Peng-Robinson (PR) Equation of State for Vapor-Liquid Equilibrium (VLE) and enthalpy calculations.
- Furnace: Modeled as a heater that raises the crude temperature, followed by a flash drum where the heated crude separates into vapor and liquid phases.
- Fractionator (Simplified):
- Sequential Modular: We'll simplify the fractionator to a "black box" splitter for demonstration. A full rigorous tray-by-tray model is too extensive for this example but would involve MESH (Mass, Energy, Summation, Equilibrium) equations for each tray. Our simplified version will just split the feed based on specified recovery fractions.
- Equation-Oriented: We'll demonstrate the EO approach primarily for the furnace/flash unit. A full rigorous tray-by-tray fractionator in EO would involve thousands of equations, making it impractical for a simple self-contained example without a specialized modeling framework like Pyomo or GAMS. However, the principles shown for the flash apply directly.
1. Common Setup (Thermodynamics, Stream Class)
import numpy as np
from scipy.optimize import root
from thermo.chemical import Chemical
from thermo.eos import PR
from thermo.mixture import Mixture
# --- 1. Define Components and Thermodynamic Model ---
# Using representative hydrocarbons for crude oil
# A real crude assay would use pseudo-components derived from TBP curves.
components_list = ['n-pentane', 'n-hexane', 'n-heptane', 'n-octane',
'n-nonane', 'n-decane', 'n-undecane', 'n-dodecane',
'n-tridecane', 'n-tetradecane', 'n-pentadecane']
# Initialize the thermodynamic system with Peng-Robinson EOS
# We'll use this for VLE and property calculations
pr_thermo_system = PR(components=components_list)
# Get component molar masses for mass calculations (kg/kmol)
molar_masses = np.array([Chemical(c).MW for c in components_list])
# --- 2. Stream Class (Helper for both approaches) ---
class Stream:
def __init__(self, T, P, compositions, total_flow_mol=0.0):
"""
Represents a process stream.
T: Temperature (K)
P: Pressure (Pa)
compositions: Molar compositions (array-like, will be normalized)
total_flow_mol: Total molar flow rate (kmol/s)
"""
self.T = T
self.P = P
self.compositions = np.array(compositions) / np.sum(compositions) if np.sum(compositions) > 0 else np.zeros_like(compositions)
self.total_flow_mol = total_flow_mol
# Calculate properties (lazy loading)
self._mixture = None
self._H = None # Molar enthalpy
self._mass_flow = None # Total mass flow (kg/s)
@property
def mixture(self):
if self._mixture is None:
self._mixture = Mixture(zs=self.compositions, T=self.T, P=self.P, eos=pr_thermo_system.eos)
return self._mixture
@property
def H_mol(self):
"""Molar enthalpy (J/kmol)"""
if self._H is None:
self._H = pr_thermo_system.H_mixture(zs=self.compositions, T=self.T, P=self.P)
return self._H
@property
def mass_flow(self):
"""Total mass flow (kg/s)"""
if self._mass_flow is None:
self._mass_flow = self.total_flow_mol * np.sum(self.compositions * molar_masses)
return self._mass_flow
def __str__(self):
comp_str = ', '.join([f'{c}: {z*100:.1f}%' for c, z in zip(components_list, self.compositions)])
return (f"Stream:\n"
f" T: {self.T - 273.15:.2f} C ({self.T:.2f} K)\n"
f" P: {self.P / 1e5:.2f} bar ({self.P:.2f} Pa)\n"
f" Total Molar Flow: {self.total_flow_mol:.2f} kmol/s\n"
f" Total Mass Flow: {self.mass_flow:.2f} kg/s\n"
f" Compositions: {comp_str}\n"
f" Molar Enthalpy: {self.H_mol/1e6:.2f} MJ/kmol")
# --- Example Crude Feed Stream ---
# Composition (example, sum to 1.0)
# A typical crude might have C5: 0.05, C6: 0.10, C7: 0.15, C8: 0.15, C9: 0.10, C10: 0.10, C11-C15+: remaining
feed_compositions_example = np.array([0.05, 0.10, 0.12, 0.13, 0.10, 0.10, 0.09, 0.08, 0.07, 0.08, 0.08])
feed_compositions_example = feed_compositions_example / np.sum(feed_compositions_example) # Normalize
feed_T_K = 300.0 # K (approx 27 C)
feed_P_Pa = 3e5 # Pa (3 bar absolute)
feed_flow_kmol_s = 10.0 # kmol/s
crude_feed = Stream(feed_T_K, feed_P_Pa, feed_compositions_example, feed_flow_kmol_s)
print("--- Crude Feed Stream ---")
print(crude_feed)
print("\n" + "="*50 + "\n")
2. Sequential Modular Approach
In this approach, we define functions for each unit operation.
# --- 3. Unit Operations for Sequential Modular Approach ---
def heater_unit(input_stream: Stream, outlet_T_K: float) -> Stream:
"""
Simulates a furnace (heater) unit.
Calculates the heat duty required to raise the temperature of the stream.
Assumes constant pressure.
"""
if outlet_T_K <= input_stream.T:
raise ValueError("Outlet temperature must be higher than inlet temperature for a heater.")
# Calculate enthalpy at inlet and outlet conditions
H_in = input_stream.H_mol
H_out = pr_thermo_system.H_mixture(
zs=input_stream.compositions,
T=outlet_T_K,
P=input_stream.P
)
heat_duty_kW = input_stream.total_flow_mol * (H_out - H_in) / 1000 # Convert J/s to kW
print(f"Heater Unit:\n"
f" Inlet T: {input_stream.T-273.15:.2f} C, Outlet T: {outlet_T_K-273.15:.2f} C\n"
f" Heat Duty Required: {heat_duty_kW:.2f} kW")
# Create the outlet stream with updated temperature
heated_stream = Stream(outlet_T_K, input_stream.P,
input_stream.compositions, input_stream.total_flow_mol)
return heated_stream
def flash_drum_unit(input_stream: Stream, flash_T_K: float, flash_P_Pa: float):
"""
Simulates a flash drum.
Separates an input stream into vapor and liquid phases at specified T and P.
"""
print(f"\nFlash Drum Unit (at T={flash_T_K-273.15:.2f} C, P={flash_P_Pa/1e5:.2f} bar):")
# Perform flash calculation using the thermodynamic system
try:
# pr_thermo_system.flash returns:
# beta (vapor mole fraction), y (vapor compositions), x (liquid compositions)
beta, y_flash, x_flash = pr_thermo_system.flash(T=flash_T_K, P=flash_P_Pa, zs=input_stream.compositions)
if beta is None: # Indicates single phase
if pr_thermo_system.is_supercritical(T=flash_T_K, P=flash_P_Pa, zs=input_stream.compositions):
print(" Stream is supercritical (single phase fluid).")
return Stream(flash_T_K, flash_P_Pa, input_stream.compositions, input_stream.total_flow_mol), None
elif pr_thermo_system.is_single_phase_liquid(T=flash_T_K, P=flash_P_Pa, zs=input_stream.compositions):
print(" Stream is subcooled liquid (single phase liquid).")
return None, Stream(flash_T_K, flash_P_Pa, input_stream.compositions, input_stream.total_flow_mol)
else:
print(" Flash calculation failed or resulted in a single phase not explicitly identified.")
# Fallback to single phase if flash didn't give beta (shouldn't happen with proper PR)
return Stream(flash_T_K, flash_P_Pa, input_stream.compositions, input_stream.total_flow_mol), None
except Exception as e:
print(f" Flash calculation error: {e}")
# In a real simulator, this might raise an error or try another solver
return None, None # Indicate failure
vapor_flow = input_stream.total_flow_mol * beta
liquid_flow = input_stream.total_flow_mol * (1.0 - beta)
vapor_stream = Stream(flash_T_K, flash_P_Pa, y_flash, vapor_flow)
liquid_stream = Stream(flash_T_K, flash_P_Pa, x_flash, liquid_flow)
print(f" Vapor Fraction (Beta): {beta:.3f}")
print(f" Vapor Flow: {vapor_flow:.2f} kmol/s, Liquid Flow: {liquid_flow:.2f} kmol/s")
return vapor_stream, liquid_stream
def crude_fractionator_simplified(flashed_vapor: Stream, flashed_liquid: Stream):
"""
Simplified crude fractionator.
This is NOT a rigorous tray-by-tray model. It simulates a black-box splitter
based on approximate recovery for demonstration of sequential modularity.
A rigorous model would solve MESH equations for each tray.
Products: Naphtha (top), Kerosene (side), Diesel (side), Residue (bottom)
"""
print("\nCrude Fractionator (Simplified Black Box Splitter):")
if flashed_vapor is None or flashed_liquid is None:
print(" Warning: One or both flash streams are None. Cannot process.")
return None, None, None, None
# Combine flashed streams to get total feed to fractionator
total_feed_flow = flashed_vapor.total_flow_mol + flashed_liquid.total_flow_mol
total_feed_compositions = (flashed_vapor.compositions * flashed_vapor.total_flow_mol +
flashed_liquid.compositions * flashed_liquid.total_flow_mol) / total_feed_flow
# Define simplified component distribution factors (example values)
# These would be derived from rigorous simulation or operating data.
# For a given component, what fraction goes to which product? Sum for each component must be 1.0.
# 'n-pentane', 'n-hexane', 'n-heptane', 'n-octane', 'n-nonane', 'n-decane', 'n-undecane', 'n-dodecane', 'n-tridecane', 'n-tetradecane', 'n-pentadecane'
product_distribution = {
'Naphtha': [0.95, 0.85, 0.50, 0.20, 0.05, 0.01, 0.00, 0.00, 0.00, 0.00, 0.00],
'Kerosene': [0.05, 0.15, 0.45, 0.60, 0.30, 0.10, 0.05, 0.02, 0.01, 0.00, 0.00],
'Diesel': [0.00, 0.00, 0.05, 0.20, 0.60, 0.70, 0.50, 0.30, 0.15, 0.05, 0.02],
'AtmGasOil': [0.00, 0.00, 0.00, 0.00, 0.05, 0.19, 0.45, 0.68, 0.84, 0.95, 0.18], # Heavier than diesel, lighter than residue
'Residue': [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.80], # Heaviest components
}
product_streams = {}
product_keys = ['Naphtha', 'Kerosene', 'Diesel', 'AtmGasOil', 'Residue']
# Initialize product stream compositions and flows
for prod_name in product_keys:
product_streams[prod_name] = {'compositions': np.zeros_like(total_feed_compositions),
'flow_mol': 0.0}
# Distribute components
for i, comp_name in enumerate(components_list):
for prod_name in product_keys:
comp_flow_to_prod = total_feed_compositions[i] * total_feed_flow * product_distribution[prod_name][i]
product_streams[prod_name]['compositions'][i] += comp_flow_to_prod
product_streams[prod_name]['flow_mol'] += comp_flow_to_prod
# Create Stream objects for products
naphtha_stream = Stream(flashed_vapor.T - 50, flashed_vapor.P, # Approx lower T for top product
product_streams['Naphtha']['compositions'], product_streams['Naphtha']['flow_mol'])
kerosene_stream = Stream(flashed_vapor.T - 20, flashed_vapor.P, # Approx T
product_streams['Kerosene']['compositions'], product_streams['Kerosene']['flow_mol'])
diesel_stream = Stream(flashed_vapor.T, flashed_vapor.P, # Approx T
product_streams['Diesel']['compositions'], product_streams['Diesel']['flow_mol'])
atm_gas_oil_stream = Stream(flashed_liquid.T, flashed_liquid.P, # Approx T
product_streams['AtmGasOil']['compositions'], product_streams['AtmGasOil']['flow_mol'])
residue_stream = Stream(flashed_liquid.T + 20, flashed_liquid.P, # Approx higher T for bottom product
product_streams['Residue']['compositions'], product_streams['Residue']['flow_mol'])
print(f" Total Feed to Fractionator: {total_feed_flow:.2f} kmol/s")
print(f" Naphtha Flow: {naphtha_stream.total_flow_mol:.2f} kmol/s")
print(f" Kerosene Flow: {kerosene_stream.total_flow_mol:.2f} kmol/s")
print(f" Diesel Flow: {diesel_stream.total_flow_mol:.2f} kmol/s")
print(f" Atmospheric Gas Oil Flow: {atm_gas_oil_stream.total_flow_mol:.2f} kmol/s")
print(f" Residue Flow: {residue_stream.total_flow_mol:.2f} kmol/s")
# Return products in a tuple for clarity
return naphtha_stream, kerosene_stream, diesel_stream, atm_gas_oil_stream, residue_stream
# --- 4. Sequential Modular Simulation Orchestration ---
def run_sequential_modular_simulation(crude_feed_stream: Stream, furnace_outlet_T_K: float, flash_P_Pa: float):
print("\n" + "="*20 + " Sequential Modular Simulation " + "="*20 + "\n")
# Step 1: Crude Furnace
print("\n--- Step 1: Crude Furnace (Heater) ---")
heated_crude = heater_unit(crude_feed_stream, furnace_outlet_T_K)
print("\nHeated Crude Stream:")
print(heated_crude)
# Step 2: Furnace Outlet Flash
print("\n--- Step 2: Furnace Outlet Flash Drum ---")
flashed_vapor, flashed_liquid = flash_drum_unit(heated_crude, furnace_outlet_T_K, flash_P_Pa)
if flashed_vapor is None and flashed_liquid is None:
print(" Flash calculation failed. Aborting SM simulation.")
return
print("\nFlashed Vapor Stream:")
if flashed_vapor: print(flashed_vapor) else print(" (None)")
print("\nFlashed Liquid Stream:")
if flashed_liquid: print(flashed_liquid) else print(" (None)")
# Step 3: Crude Fractionator
print("\n--- Step 3: Crude Fractionator ---")
naphtha, kerosene, diesel, atm_gas_oil, residue = \
crude_fractionator_simplified(flashed_vapor, flashed_liquid)
print("\n--- Final Product Streams (Sequential Modular) ---")
print("\nNaphtha Product:")
if naphtha: print(naphtha)
print("\nKerosene Product:")
if kerosene: print(kerosene)
print("\nDiesel Product:")
if diesel: print(diesel)
print("\nAtmospheric Gas Oil Product:")
if atm_gas_oil: print(atm_gas_oil)
print("\nResidue Product:")
if residue: print(residue)
print("\n" + "="*50 + "\n")
# --- Run Sequential Modular Simulation ---
# Parameters for the simulation
furnace_outlet_temp_C_sm = 370.0 # Target temperature for crude entering flash
flash_pressure_bar_sm = 1.5 # Pressure at which flash occurs
run_sequential_modular_simulation(
crude_feed,
furnace_outlet_temp_C_sm + 273.15, # Convert to K
flash_pressure_bar_sm * 1e5 # Convert to Pa
)
3. Equation-Oriented Approach
For the Equation-Oriented approach, we define a single function that encapsulates all the governing equations for the system (or a part of it). The solver then finds the variables that make all equations equal to zero.
Here, we will model the Furnace Outlet Flash rigorously using the equation-oriented approach. A full fractionator in EO is very extensive (hundreds/thousands of equations).
Variables to Solve for (x):
T_flash: Flash Temperature (K)
beta: Vapor mole fraction (V/F)
y_flash: Molar compositions of the vapor phase (for each component)
x_flash: Molar compositions of the liquid phase (for each component)
Equations (Residuals, set to zero):
- Material Balances (Component-wise):
z_i - beta * y_i - (1-beta) * x_i = 0 (for each component i)
- Equilibrium (VLE):
y_i - K_i * x_i = 0 (for each component i, where K_i is the equilibrium constant)
- Summation Equations:
sum(y_i) - 1 = 0 and sum(x_i) - 1 = 0
- Energy Balance:
F * H_feed + Q_duty - V * H_vapor - L * H_liquid = 0 (where V = beta * F, L = (1-beta) * F)
Constraint: We will fix the heat duty (Q_duty) and the flash pressure, and solve for T_flash, beta, x, and y.
# --- 5. Equation-Oriented Approach (Focus on Furnace Flash) ---
def furnace_flash_equations(x, feed_stream: Stream, Q_duty_kW: float, flash_P_Pa: float):
"""
System of equations for a rigorous isothermal-isobaric flash,
including an energy balance from a heater.
x: Array of unknowns [T_flash, beta, y1..yn, x1..xn]
feed_stream: Inlet stream to the furnace/flash
Q_duty_kW: Heat supplied by the furnace (kW)
flash_P_Pa: Pressure of the flash drum (Pa)
"""
num_components = len(components_list)
# Unpack variables from x
T_flash = x[0]
beta = x[1] # Vapor mole fraction (V/F)
y_flash = x[2 : 2 + num_components] # Vapor phase compositions
x_flash = x[2 + num_components : 2 + 2 * num_components] # Liquid phase compositions
# Ensure compositions sum to 1 to avoid numerical issues with K_values
y_flash_norm = y_flash / np.sum(y_flash) if np.sum(y_flash) > 0 else np.ones_like(y_flash) / num_components
x_flash_norm = x_flash / np.sum(x_flash) if np.sum(x_flash) > 0 else np.ones_like(x_flash) / num_components
# --- Equations (Residuals) ---
residuals = []
# 1. K-values for VLE at current T_flash, P_flash
try:
K_values = pr_thermo_system.K_values(T=T_flash, P=flash_P_Pa, zs=feed_stream.compositions,
V_mol_fraction=beta, # Provide initial guess for V_mol_fraction
gamma_v=np.ones(num_components), gamma_l=np.ones(num_components) # Ideal for PR
)
# K_values might return nan if T/P is outside valid range, handle gracefully
if np.any(np.isnan(K_values)):
return np.ones_like(x) * 1e10 # Return large residuals if K values are invalid
except Exception:
return np.ones_like(x) * 1e10 # Return large residuals on thermo error
# 2. Component Material Balance (Rachford-Rice type implicit)
# zi - beta*yi - (1-beta)*xi = 0
# yi = Ki * xi
# => zi - beta * Ki*xi - (1-beta)*xi = 0
# => xi = zi / (beta*Ki + (1-beta))
# => yi = Ki * zi / (beta*Ki + (1-beta))
# This is often done by solving for beta using Rachford-Rice,
# but for EO we'll use the explicit relations with xi and yi as variables.
# 2a. Component Material Balances: zi - beta*yi - (1-beta)*xi = 0
for i in range(num_components):
residual_material_balance = (feed_stream.compositions[i] -
beta * y_flash[i] -
(1.0 - beta) * x_flash[i])
residuals.append(residual_material_balance)
# 2b. VLE Equilibrium: yi - Ki*xi = 0
for i in range(num_components):
residual_vle = y_flash[i] - K_values[i] * x_flash[i]
residuals.append(residual_vle)
# 2c. Summation Equations: sum(yi) - 1 = 0, sum(xi) - 1 = 0
residuals.append(np.sum(y_flash) - 1.0)
residuals.append(np.sum(x_flash) - 1.0)
# Ensure beta is between 0 and 1
# Adding bounds as soft constraints or using a bounded solver is better,
# but for fsolve, we can make residuals large if violated.
if not (0 <= beta <= 1):
residuals.append(1e6 * (beta < 0) - 1e6 * (beta > 1))
# 3. Energy Balance
# F * H_feed + Q_duty = V * H_vapor + L * H_liquid
# where H_feed is molar enthalpy of inlet stream, H_vapor/liquid are molar enthalpies of outlet streams
# V = beta * F_total, L = (1-beta) * F_total
F_total = feed_stream.total_flow_mol
H_feed_mol = feed_stream.H_mol
# Calculate outlet stream enthalpies
H_vapor_mol = pr_thermo_system.H_mixture(T=T_flash, P=flash_P_Pa, zs=y_flash_norm)
H_liquid_mol = pr_thermo_system.H_mixture(T=T_flash, P=flash_P_Pa, zs=x_flash_norm)
energy_balance_residual = (
F_total * H_feed_mol + Q_duty_kW * 1000 # Q_duty in J/s, H in J/kmol, F in kmol/s
- (beta * F_total * H_vapor_mol)
- ((1.0 - beta) * F_total * H_liquid_mol)
)
residuals.append(energy_balance_residual)
return np.array(residuals)
def run_equation_oriented_simulation(crude_feed_stream: Stream, Q_duty_kW: float, flash_P_Pa: float):
print("\n" + "="*20 + " Equation-Oriented Simulation " + "="*20 + "\n")
print(f"Solving for Furnace Flash with Q_duty={Q_duty_kW:.2f} kW and P={flash_P_Pa/1e5:.2f} bar.")
num_components = len(components_list)
# --- Initial Guess for Solver ---
# This is crucial for non-linear solvers.
# A good guess for flash T, and ideal flash (K=Pv/P) for y and x.
initial_T = crude_feed_stream.T + (Q_duty_kW * 1000 / (crude_feed_stream.total_flow_mol * pr_thermo_system.Cp_mixture(crude_feed_stream.T, crude_feed_stream.P, crude_feed_stream.compositions))) # Simple heat capacity based guess for T
if initial_T > 600: initial_T = 600 # Cap reasonable T
if initial_T < crude_feed_stream.T: initial_T = crude_feed_stream.T + 50 # Ensure increase
initial_beta = 0.5 # Start with 50% vapor
initial_y = crude_feed_stream.compositions.copy()
initial_x = crude_feed_stream.compositions.copy()
# Normalize initial compositions if needed, though fsolve generally handles this.
initial_y /= np.sum(initial_y)
initial_x /= np.sum(initial_x)
# Construct the initial guess vector
x0 = [initial_T, initial_beta]
x0.extend(initial_y)
x0.extend(initial_x)
x0 = np.array(x0)
# --- Solve the System of Equations ---
print(f"Initial Guess T: {initial_T-273.15:.2f} C, Beta: {initial_beta:.2f}")
try:
# Use root instead of fsolve for more control over method and Jacobian if needed
# 'lm' (Levenberg-Marquardt) is a good general-purpose method
# 'hybr' (hybrid Powell method) is also common
solution = root(furnace_flash_equations, x0,
args=(crude_feed_stream, Q_duty_kW, flash_P_Pa),
method='hybr',
options={'xtol': 1e-6, 'maxfev': 2000}) # Adjust tolerance and max function evaluations
if solution.success:
print("\nSolver converged successfully!")
T_flash_solved = solution.x[0]
beta_solved = solution.x[1]
y_flash_solved = solution.x[2 : 2 + num_components]
x_flash_solved = solution.x[2 + num_components : 2 + 2 * num_components]
# Normalize final compositions for Stream objects
y_flash_solved /= np.sum(y_flash_solved)
x_flash_solved /= np.sum(x_flash_solved)
# Create outlet streams
vapor_flow_solved = crude_feed_stream.total_flow_mol * beta_solved
liquid_flow_solved = crude_feed_stream.total_flow_mol * (1.0 - beta_solved)
vapor_stream_eo = Stream(T_flash_solved, flash_P_Pa, y_flash_solved, vapor_flow_solved)
liquid_stream_eo = Stream(T_flash_solved, flash_P_Pa, x_flash_solved, liquid_flow_solved)
print(f"\n--- Furnace Flash Results (Equation-Oriented) ---")
print(f" Solved Flash T: {T_flash_solved - 273.15:.2f} C")
print(f" Solved Vapor Fraction (Beta): {beta_solved:.3f}")
print("\nFlashed Vapor Stream (EO):")
print(vapor_stream_eo)
print("\nFlashed Liquid Stream (EO):")
print(liquid_stream_eo)
# Check mass balance:
total_mass_out = vapor_stream_eo.mass_flow + liquid_stream_eo.mass_flow
print(f"\nInput Mass Flow: {crude_feed_stream.mass_flow:.2f} kg/s")
print(f"Output Mass Flow: {total_mass_out:.2f} kg/s (Difference: {total_mass_out - crude_feed_stream.mass_flow:.4e})")
else:
print(f"\nSolver FAILED to converge: {solution.message}")
print(f"Last residuals: {solution.fun}")
except Exception as e:
print(f"\nAn error occurred during solving: {e}")
print("\n" + "="*50 + "\n")
# --- Run Equation-Oriented Simulation ---
# Parameters for the simulation
furnace_heat_duty_kW_eo = 25000.0 # Example heat duty for the furnace (kW)
flash_pressure_bar_eo = 1.5 # Pressure of the flash drum (bar)
run_equation_oriented_simulation(
crude_feed,
furnace_heat_duty_kW_eo,
flash_pressure_bar_eo * 1e5 # Convert to Pa
)
Explanation and Comparison:
Sequential Modular Output:
You will see the steps executed:
- Heater: Takes
crude_feed, heats it to a specified temperature (e.g., 370 C). It calculates the required heat duty.
- Flash Drum: Takes the
heated_crude and separates it into vapor and liquid at the specified temperature and pressure. thermo handles the VLE calculations internally.
- Simplified Fractionator: Takes the vapor and liquid from the flash. It then applies pre-defined "splitting factors" to distribute components into the various product streams (Naphtha, Kerosene, Diesel, etc.). This is a major simplification. In a real SM simulator, this would be a complex tray-by-tray model that calculates internal reflux, reboiler duty, and precise cut points based on vapor-liquid traffic.
Equation-Oriented Output:
This output focuses on the furnace outlet flash:
- System of Equations: All equations for mass, energy, and VLE are put into a single function (
furnace_flash_equations).
- Solver:
scipy.optimize.root takes an initial guess for all unknowns (T_flash, beta, y, x) and iteratively finds the values that make all equations in furnace_flash_equations equal to zero.
- Results: It will output the solved
T_flash, beta, and the compositions/flows of the vapor and liquid streams exiting the furnace.
Why the Fractionator is simplified/omitted in EO demo:
A rigorous tray-by-tray fractionator model for N trays and C components in an equation-oriented framework would involve:
N * C component material balance equations
N total mass balance equations
N energy balance equations
N * C VLE equilibrium equations
2 * N summation equations (sum(y_i)=1, sum(x_i)=1 for each tray)
- Equations for condenser, reboiler, side draws, pumps, etc.
This quickly adds up to hundreds or thousands of non-linear equations, requiring specialized frameworks like Pyomo or GAMS for efficient formulation and solution, often with sparse Jacobian calculations. The core principles, however, are the same as demonstrated for the flash: define variables, define equations, and solve.
This code provides a strong foundation for understanding both approaches for a crude furnace and fractionator modeling.