Repository navigation
Expand file tree
/
Copy pathmodel_plotting.py
More file actions
184 lines (153 loc) · 7.59 KB
/
Copy pathmodel_plotting.py
File metadata and controls
184 lines (153 loc) · 7.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import numpy as np
import time
from scipy.optimize import least_squares, root
import logging
import matplotlib.pyplot as plt
from scipy.optimize import root_scalar
R: float = 8.314 # J/mol.K
kB: float = 1.38e-23 # Joules/K
h: float = 6.62e-34 # Joules.sec
Tavg: float = 298.15 # K
def calc_ktm(kB: float, T: float, h: float, Sint: np.ndarray) -> list:
"""Calculate kinetic prefactors (ktm) for adsorption."""
return [(kB*T/h)*np.exp(S/R) for S in Sint]
def calc_Kadcoef(elem: list, surface_entropies: list, p_tot: float) -> dict:
"""Calculate adsorption equilibrium constants (Kad) for components."""
if len(elem) != len(surface_entropies):
raise ValueError("Component count must match surface entropy count.")
entropies = [R * np.log(p_tot) + S for S in surface_entropies]
Kadcoef = {elem[i]: np.exp(entropies[i] / R) for i in range(len(elem))}
return Kadcoef
def solve_rxn_model_operating_conditions(spacetime: float, T: float, pBDOin: float, w: float, par: list, Nbrxn: int, elem: list[str], comp: list[str],
surface_entropies: list[float], Sint: np.ndarray, p_tot: int) -> tuple:
w /= 1000 # Convert w to kg
FBDOin = (w/spacetime)*3600 # Convert to mol/hr
ntot = FBDOin*p_tot/pBDOin
f = np.zeros(5)
def equations(f):
E = par[:Nbrxn]
H = par[Nbrxn:]
# claculation of intermediate constants
ktm_g = calc_ktm(kB, Tavg, h, Sint)
KTadc = calc_Kadcoef(elem, surface_entropies, p_tot)
k = [ktm_g[i] * np.exp(-E[i] * 1000 / R * (1 / T - 1 / Tavg))
for i in range(Nbrxn)]
KTad = {elem[i]: KTadc[elem[i]] *
np.exp(-H[i] * 1000 / R * (1 / T - 1 / Tavg)) for i in range(len(elem))}
pBDO = f[0]/ntot * p_tot
p3B2OL = f[1]/ntot * p_tot
p3H2B = f[2]/ntot * p_tot
pMEK = f[3]/ntot * p_tot
piBOL = f[4]/ntot * p_tot
# Acid site balance
# + KTad['MEK_acid'] * pw
den_acid = 1 + KTad['BDO_acid'] * \
pBDO + KTad['MEK_acid'] * pMEK + 1e-10
theta_free_acid = 1 / den_acid
theta_BDO_acid = KTad['BDO_acid'] * pBDO * theta_free_acid
theta_MEK_acid = KTad['MEK_acid'] * pMEK * theta_free_acid
# base balance
den_base = 1 + KTad['BDO_base'] * pBDO + KTad['3B2OL_base'] * p3B2OL + \
KTad['lump_base'] * (p3H2B + piBOL) + \
1e-10 # + KTad['MEK_acid'] * pw
theta_free_base = 1 / den_base
theta_BDO_base = KTad['BDO_base'] * pBDO * theta_free_base
theta_3B2OL_base = KTad['3B2OL_base'] * p3B2OL * theta_free_base
theta_iBOL_base = KTad['lump_base'] * piBOL * theta_free_base
theta_3H2B_base = KTad['lump_base'] * p3H2B * theta_free_base
assert np.isclose(theta_free_base + theta_BDO_base + theta_3B2OL_base +
theta_iBOL_base + theta_3H2B_base, 1.0, atol=1e-6)
assert np.isclose(theta_free_acid + theta_BDO_acid +
theta_MEK_acid, 1.0, atol=1e-6)
# REACTION RATES
r_3B2OL = k[0] * (theta_BDO_base * theta_free_base) # 3B2OL formation
r_3H2B = k[1] * (theta_BDO_base * theta_free_base) # 3H2B formation
r_MEK = k[2] * (theta_BDO_acid * theta_free_acid) # MEK formation
r_iBOL = k[3] * (theta_BDO_base * theta_free_base) # 2MPAL formation
r_BDO_total = r_3B2OL + r_3H2B + r_MEK + r_iBOL
Fconv = FBDOin - f[0]
# Fcalc = r_BDO_total*w
if f[0] < 0 or f[0] > FBDOin*1.01:
return 1e20
# mol balance equations
residuals = np.zeros(5)
# residuals[0] = FBDOin - f.sum() # BDO balance
residuals[0] = f[0] - (FBDOin - r_BDO_total *
w) # optional alternative
residuals[1] = f[1] - (r_3B2OL/r_BDO_total)*Fconv # 3B2OL balance
residuals[2] = f[2] - (r_3H2B/r_BDO_total)*Fconv # 3H2B balance
residuals[3] = f[3] - (r_MEK/r_BDO_total)*Fconv # MEK balance
residuals[4] = f[4] - (r_iBOL/r_BDO_total)*Fconv # IBOL balance
# Physical constraint
if np.any(f < 0) or np.any(f > FBDOin*1.01):
return np.ones_like(residuals) * 1e20
# Verify site balances
if not (0.95 <= (theta_free_acid + theta_BDO_acid + theta_MEK_acid) <= 1.01):
return np.ones_like(residuals) * 1e10
if not (0.95 <= theta_free_base + theta_BDO_base + theta_3B2OL_base + theta_3H2B_base + theta_iBOL_base) <= 1.05:
return np.ones_like(residuals) * 1e10
return residuals
# Initial guess (feed comp with slight conversion)
f0 = np.array([FBDOin*0.5, FBDOin*0.2, FBDOin *
0.05, FBDOin*0.1, FBDOin*0.05])
# bounds
bounds = (np.zeros(5), np.array([FBDOin]*5))
# Solve using constrained root_finding
sol = least_squares(equations, f0, bounds=bounds,
method='trf', xtol=1e-6, max_nfev=1000)
if not sol.success:
logging.warning(
f"Solution not converged at spacetime: {spacetime}: {sol.message}")
logging.debug(f"Residuals: {equations(sol.x)}")
return FBDOin, sol.x
return FBDOin, sol.x
def calculate_conversion_and_selectivity(FBDOin: float, f: np.ndarray, comp: list[str]) -> tuple:
selectivity = np.zeros(len(comp)-1)
conversion = ((FBDOin - f[0]) / FBDOin) * 100
for i in range(1, len(comp)):
selectivity[i-1] = f[i] / (FBDOin - f[0]) * \
100 if (FBDOin - f[0]) > 1e-10 else 0
return conversion, selectivity
def simulate():
global comp, spacetime, conv, start_time, sele
comp = ['BDO', '3B2OL+BD', '3H2B+DMP', 'MEK+2BOL', '2MPAL+iBOL']
Nbrxn = 4
elem = ['BDO_acid', 'BDO_base', '3B2OL_base', 'MEK_acid', 'lump_base']
surface_entropies = [10.0, 15.0, 30.0, 40.0, 30.0]
Sint = np.array([-200.0, -210.0, -210.0, -250])
# 89, 112, 54, 238, -35.3, -354.0, -92.0, -177.0
n_optimized_params = [113, 154, 16, 26, -110.0, -188.0, -130.0, -125.0, -174.0]
spacetime = np.linspace(100, 1000, 50)
conv = np.zeros(len(spacetime))
start_time = time.time()
sele = np.zeros((len(spacetime), len(comp) - 1))
for i, st in enumerate(spacetime):
FBDOin, f_model = solve_rxn_model_operating_conditions(spacetime=st, T=398, pBDOin=0.1, w=2,
par=n_optimized_params, Nbrxn=Nbrxn,
elem=elem, comp=comp,
surface_entropies=surface_entropies, Sint=Sint, p_tot=10)
conv[i], sele[i, :] = calculate_conversion_and_selectivity(
FBDOin, f_model, comp)
print(conv[i], sele[i, :])
def plot():
colors = ['black', 'green', 'darkorange', 'purple', 'blue']
comp_colors = {c: colors[i] for i, c in enumerate(comp)}
fig, ax = plt.subplots(figsize=(8, 6))
plt.rcParams['axes.labelsize'] = 14 # Font size for x-label and y-label
plt.rcParams['xtick.labelsize'] = 12 # Font size for x-axis tick labels
plt.rcParams['ytick.labelsize'] = 12 # Font size for y-axis tick labels
ax.plot(spacetime, conv, '-', color=comp_colors['BDO'], label=f"Conv_BDO")
for j, product in enumerate(comp[1:]):
ax.plot(spacetime, sele[:, j], '-',
color=comp_colors[product], label=f"Sel_{product}")
ax.set_xlabel('Spacetime (kg.s/mol)')
ax.set_ylabel('XBDO (%), Si(%)')
# ax.set_ylim(0, 100)
ax.legend()
plt.grid(True)
plt.show()
if __name__ == "__main__":
simulate()
plot()
end_time = time.time()
print(f"Execution time: {(end_time - start_time):.2f} seconds")