Okay, this is a great conceptual problem that highlights the differences between Sequential Modular (SM) and Equation Oriented (EO) modeling approaches.
Let's define a simplified crude furnace and fractionator:
System Description:
- Crude Feed: Known flow rate and inlet temperature.
- Furnace: Heats the crude oil to a target outlet temperature (for SM) or is supplied with a certain heat duty (for EO). We'll need the specific heat capacity of crude.
- Fractionator: Takes the hot crude and separates it into several products (e.g., LPG, Naphtha, Kerosene, Diesel, Residue) based on specified split fractions (yields). For simplicity, we'll assume product temperatures are also specified or can be derived.
Simplifications:
- No complex thermodynamics (VLE, enthalpy models). We'll use simple heat capacity for the furnace and direct split fractions for the fractionator.
- No pressure drops.
- Steady-state operation.
- Crude is treated as a single pseudo-component for furnace heating, then "magically" split into products in the fractionator.
1. Sequential Modular (SM) Approach
In SM, each unit operation is a "module" or black box. The output of one module becomes the input to the next. Calculations proceed sequentially.
import collections
# --- Define Unit Operation Modules (Classes) ---
class FurnaceSM:
def __init__(self, target_outlet_temp_C, cp_crude_kJ_kgC):
"""
Initializes the furnace module.
Args:
target_outlet_temp_C (float): Desired outlet temperature of crude from furnace.
cp_crude_kJ_kgC (float): Specific heat capacity of crude (kJ/kg.C).
"""
self.target_outlet_temp_C = target_outlet_temp_C
self.cp_crude_kJ_kgC = cp_crude_kJ_kgC
print(f"[SM Furnace Module] Initialized: Target T_out={target_outlet_temp_C}°C, Cp_crude={cp_crude_kJ_kgC} kJ/kg.°C")
def calculate(self, feed_stream):
"""
Calculates the furnace outlet stream and heat duty.
Args:
feed_stream (dict): {'flow_rate_kg_s': float, 'temperature_C': float}
Returns:
tuple: (outlet_stream, heat_duty_kW)
outlet_stream (dict): {'flow_rate_kg_s': float, 'temperature_C': float}
heat_duty_kW (float): Heat added in the furnace (kJ/s).
"""
inlet_flow_kg_s = feed_stream['flow_rate_kg_s']
inlet_temp_C = feed_stream['temperature_C']
outlet_temp_C = self.target_outlet_temp_C
# Q = m * Cp * deltaT
heat_duty_kW = inlet_flow_kg_s * self.cp_crude_kJ_kgC * (outlet_temp_C - inlet_temp_C)
outlet_stream = {
'flow_rate_kg_s': inlet_flow_kg_s, # Assuming no mass loss
'temperature_C': outlet_temp_C
}
print(f"[SM Furnace Module] Input: Flow={inlet_flow_kg_s} kg/s, T_in={inlet_temp_C}°C")
print(f"[SM Furnace Module] Output: T_out={outlet_temp_C}°C, Heat Duty={heat_duty_kW:.2f} kW")
return outlet_stream, heat_duty_kW
class FractionatorSM:
def __init__(self, product_splits, product_temperatures_C):
"""
Initializes the fractionator module.
Args:
product_splits (dict): {'product_name': split_fraction, ...}
e.g., {'LPG': 0.1, 'Naphtha': 0.25, ...}
Split fractions should sum to 1.0.
product_temperatures_C (dict): {'product_name': temperature_C, ...}
"""
if not abs(sum(product_splits.values()) - 1.0) < 1e-6:
raise ValueError(f"Product splits must sum to 1.0. Current sum: {sum(product_splits.values())}")
self.product_splits = product_splits
self.product_temperatures_C = product_temperatures_C
print(f"[SM Fractionator Module] Initialized with products: {list(product_splits.keys())}")
def calculate(self, feed_stream):
"""
Calculates the product streams from the fractionator.
Args:
feed_stream (dict): {'flow_rate_kg_s': float, 'temperature_C': float} (hot crude)
Returns:
dict: {'product_name': {'flow_rate_kg_s': float, 'temperature_C': float}, ...}
"""
total_feed_flow_kg_s = feed_stream['flow_rate_kg_s']
# feed_temp_C = feed_stream['temperature_C'] # Feed temp might be used for some product temps
product_streams = collections.OrderedDict() # Keep order for nice printing
print(f"[SM Fractionator Module] Input: Flow={total_feed_flow_kg_s} kg/s, T_in={feed_stream['temperature_C']}°C")
for name, split in self.product_splits.items():
product_flow_kg_s = total_feed_flow_kg_s * split
# Use specified product temperature, or default to feed temperature if not specified
product_temp_C = self.product_temperatures_C.get(name, feed_stream['temperature_C'])
product_streams[name] = {
'flow_rate_kg_s': product_flow_kg_s,
'temperature_C': product_temp_C
}
print(f" [SM Fractionator Module] Product '{name}': Flow={product_flow_kg_s:.2f} kg/s, T={product_temp_C}°C")
return product_streams
# --- SM Simulation ---
def run_sm_simulation():
print("\n--- Running Sequential Modular Simulation ---")
# Define Feed
crude_feed = {
'flow_rate_kg_s': 100.0, # kg/s
'temperature_C': 25.0 # Celsius
}
print(f"Initial Crude Feed: {crude_feed}")
# Parameters
furnace_target_outlet_temp_C = 350.0
cp_crude_kJ_kgC = 2.1 # kJ/kg.C
product_splits = collections.OrderedDict([
('LPG', 0.05),
('Naphtha', 0.15),
('Kerosene', 0.20),
('Diesel', 0.30),
('Residue', 0.30) # 1 - (0.05+0.15+0.20+0.30)
])
product_temperatures_C = { # Example temperatures
'LPG': 40.0,
'Naphtha': 100.0,
'Kerosene': 180.0,
'Diesel': 280.0,
'Residue': 340.0 # Close to furnace outlet temp
}
# Instantiate Modules
furnace = FurnaceSM(target_outlet_temp_C, cp_crude_kJ_kgC)
fractionator = FractionatorSM(product_splits, product_temperatures_C)
# Execute Simulation Sequentially
print("\nExecuting Furnace...")
hot_crude_stream, furnace_heat_duty_kW = furnace.calculate(crude_feed)
print("\nExecuting Fractionator...")
product_streams_sm = fractionator.calculate(hot_crude_stream)
print("\n--- SM Simulation Results ---")
print(f"Furnace Heat Duty: {furnace_heat_duty_kW:.2f} kW")
print(f"Hot Crude to Fractionator: {hot_crude_stream}")
print("Fractionator Products:")
for name, stream_data in product_streams_sm.items():
print(f" {name}: Flow={stream_data['flow_rate_kg_s']:.2f} kg/s, Temp={stream_data['temperature_C']}°C")
return furnace_heat_duty_kW # Return this to use as input for EO comparison
2. Equation Oriented (EO) Approach
In EO, all equations describing the system are gathered and solved simultaneously. We'll use scipy.optimize.fsolve for this.
from scipy.optimize import fsolve
import numpy as np
# --- EO Model Equations ---
def eo_model_equations(variables, params):
"""
Defines the system of equations for the EO model.
Variables are solved for simultaneously.
Args:
variables (list/array): Values of the unknown variables.
Order:
[0] T_furnace_out_C (Furnace outlet temperature)
[1] F_LPG_kg_s (LPG flow rate)
[2] F_Naphtha_kg_s
[3] F_Kerosene_kg_s
[4] F_Diesel_kg_s
[5] F_Residue_kg_s
(Note: Q_furnace_kW is also an unknown but related to T_furnace_out,
or T_furnace_out is unknown if Q_furnace_kW is specified.
Here, we specify Q_furnace_kW and solve for T_furnace_out.)
params (dict): Known parameters.
'F_crude_in_kg_s', 'T_crude_in_C', 'Cp_crude_kJ_kgC',
'Q_furnace_target_kW' (Target heat duty, e.g., from SM calc for comparison),
'product_splits' (dict from SM),
'product_names_ordered' (list of product names in order of variables)
Returns:
list: Residuals of the equations (should be zero at solution).
"""
# Unpack variables
T_furnace_out_C = variables[0]
product_flows_kg_s = {name: variables[i+1] for i, name in enumerate(params['product_names_ordered'])}
# Unpack parameters
F_crude_in_kg_s = params['F_crude_in_kg_s']
T_crude_in_C = params['T_crude_in_C']
Cp_crude_kJ_kgC = params['Cp_crude_kJ_kgC']
Q_furnace_target_kW = params['Q_furnace_target_kW'] # Specified heat duty
product_splits = params['product_splits']
residuals = []
# Equation 1: Furnace Energy Balance
# Q_target = m_crude * Cp_crude * (T_furnace_out - T_crude_in)
# Residual: Q_target - m_crude * Cp_crude * (T_furnace_out - T_crude_in) = 0
calculated_Q_furnace_kW = F_crude_in_kg_s * Cp_crude_kJ_kgC * (T_furnace_out_C - T_crude_in_C)
residuals.append(Q_furnace_target_kW - calculated_Q_furnace_kW)
# Equations 2 to N: Fractionator Mass Balances (Product Flows)
# F_product = split_product * F_crude_in
# Residual: F_product - split_product * F_crude_in = 0
for name in params['product_names_ordered']:
residuals.append(product_flows_kg_s[name] - product_splits[name] * F_crude_in_kg_s)
# (Optional) Overall mass balance for fractionator (often used as a check or constraint)
# If splits sum to 1, this is implicitly satisfied by the individual product equations.
# If splits don't sum to 1 and residue is by difference, then one product flow is dependent.
# Here, we assume splits sum to 1, so this is more of a check for consistency
# total_product_flow = sum(product_flows_kg_s.values())
# residuals.append(total_product_flow - F_crude_in_kg_s) # Add if one variable is dependent
return residuals
# --- EO Simulation ---
def run_eo_simulation(q_furnace_target_kW_from_sm):
print("\n--- Running Equation Oriented Simulation ---")
# Define Feed and Parameters (same as SM for comparison)
F_crude_in_kg_s = 100.0
T_crude_in_C = 25.0
Cp_crude_kJ_kgC = 2.1
# Use the heat duty calculated from SM to see if we get the same T_furnace_out
Q_furnace_target_kW = q_furnace_target_kW_from_sm
print(f"Target Furnace Heat Duty (from SM or specified): {Q_furnace_target_kW:.2f} kW")
product_splits_eo = collections.OrderedDict([ # Ensure same order for variables
('LPG', 0.05),
('Naphtha', 0.15),
('Kerosene', 0.20),
('Diesel', 0.30),
('Residue', 0.30)
])
# Product temperatures are not part of the EO *solver* here,
# as they don't affect other equations in this simplified model.
# They would be reported afterwards.
product_temperatures_C_eo = {
'LPG': 40.0, 'Naphtha': 100.0, 'Kerosene': 180.0,
'Diesel': 280.0, 'Residue': 340.0
}
product_names_ordered = list(product_splits_eo.keys())
params_eo = {
'F_crude_in_kg_s': F_crude_in_kg_s,
'T_crude_in_C': T_crude_in_C,
'Cp_crude_kJ_kgC': Cp_crude_kJ_kgC,
'Q_furnace_target_kW': Q_furnace_target_kW,
'product_splits': product_splits_eo,
'product_names_ordered': product_names_ordered
}
# Initial Guesses for variables:
# [T_furnace_out_C, F_LPG, F_Naphtha, F_Kerosene, F_Diesel, F_Residue]
# A good guess for T_furnace_out_C can be derived from Q_furnace_target_kW
t_furnace_out_guess = T_crude_in_C + Q_furnace_target_kW / (F_crude_in_kg_s * Cp_crude_kJ_kgC)
initial_guesses = [t_furnace_out_guess]
for name in product_names_ordered:
initial_guesses.append(product_splits_eo[name] * F_crude_in_kg_s * 0.9) # Slightly off guess
print(f"Initial Guesses for EO solver: {initial_guesses}")
# Solve the system of equations
solution_vars, infodict, ier, mesg = fsolve(eo_model_equations, initial_guesses, args=(params_eo,), full_output=True)
print(f"Solver converged: {'Yes' if ier==1 else 'No'}")
if ier != 1:
print(f"Solver message: {mesg}")
return
# Extract results
solved_T_furnace_out_C = solution_vars[0]
solved_product_flows_kg_s = {name: solution_vars[i+1] for i, name in enumerate(product_names_ordered)}
print("\n--- EO Simulation Results ---")
print(f"Solved Furnace Outlet Temperature: {solved_T_furnace_out_C:.2f}°C")
print("Solved Fractionator Product Flows:")
product_streams_eo = collections.OrderedDict()
for name in product_names_ordered:
flow = solved_product_flows_kg_s[name]
temp = product_temperatures_C_eo.get(name, solved_T_furnace_out_C) # Report temp
product_streams_eo[name] = {'flow_rate_kg_s': flow, 'temperature_C': temp}
print(f" {name}: Flow={flow:.2f} kg/s, Temp={temp}°C")
# Verify residuals (should be close to zero)
residuals_check = eo_model_equations(solution_vars, params_eo)
print(f"Final Residuals Check: {residuals_check}")
print(f" Max absolute residual: {np.max(np.abs(residuals_check)):.2e}")
Running the Simulations
if __name__ == "__main__":
# Run SM Simulation first
sm_furnace_heat_duty = run_sm_simulation()
# Run EO Simulation using the heat duty from SM as a target for fair comparison
# (or you could specify an arbitrary Q_furnace_target_kW)
if sm_furnace_heat_duty is not None:
run_eo_simulation(q_furnace_target_kW_from_sm=sm_furnace_heat_duty)
else:
print("\nSM simulation did not complete successfully, cannot run EO with its output.")
# Example: Run EO with an arbitrary heat duty if SM fails or is not run
# print("\nRunning EO with an arbitrary Q_furnace_target_kW = 68250 kW")
# run_eo_simulation(q_furnace_target_kW_from_sm=68250.0)
Explanation of Differences:
-
Structure:
- SM: Code is organized into classes representing physical units. Each class has a
calculate method. The main script calls these methods in sequence, passing data (streams) between them.
- EO: Code is centered around a function (
eo_model_equations) that returns the residuals of all defining equations. A numerical solver (fsolve) is used to find variable values that make all residuals zero.
-
Information Flow:
- SM: Explicit, unidirectional flow of information. Output of furnace is input to fractionator. Easy to trace.
- EO: Implicit. All variables are potentially interconnected through the system of equations. The solver figures out the dependencies.
-
Solving:
- SM: Each module solves its own relatively simple set of equations. No complex simultaneous solver needed for the overall flowsheet (unless there are recycles, which would require iterative tearing).
- EO: Requires a robust numerical solver for systems of non-linear (or linear) algebraic equations. Initial guesses are important for convergence.
-
Flexibility & Complexity:
- SM: Easier to develop and debug individual modules. Adding new units is straightforward. Handling recycles requires specific tear stream algorithms and convergence loops.
- EO: Can be more powerful for highly integrated processes with many recycles or complex interactions, as all equations are solved together. However, formulating the equations and ensuring solver convergence can be more challenging. For this simple linear flowsheet, EO is a bit like using a sledgehammer to crack a nut, but it demonstrates the principle.
-
Example Specifics:
- In our SM furnace, we specified
target_outlet_temp_C and calculated heat_duty_kW.
- In our EO model, to make it a solvable system and comparable, we used the
heat_duty_kW (obtained from SM or specified) as a known parameter and solved for T_furnace_out_C (among other variables). If we had specified T_furnace_out_C directly in EO, the first equation would just be T_furnace_out_C - T_target = 0, and Q_furnace would be a calculated result rather than an input.
This example should give you a clear, practical understanding of the two approaches for this specific system.