Repository navigation
Expand file tree
/
Copy pathoutput_data_processing.py
More file actions
157 lines (130 loc) · 7.29 KB
/
Copy pathoutput_data_processing.py
File metadata and controls
157 lines (130 loc) · 7.29 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
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.interpolate import interp1d
from datetime import datetime
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
comp = ['BDO', '3B2OL+BD', '3H2B+DMP', 'MEK+2BOL', '2MPAL+iBOL']
colors = ['black', 'green', 'darkorange', 'purple', 'blue']
comp_colors = {c: colors[i] for i, c in enumerate(comp)}
def calculate_conversion_and_selectivity(F, F_0, comp):
selectivity = np.zeros((len(F), len(comp)))
conversion = np.divide((F_0[:, 0] - F[:, 0]), F_0[:, 0])*100
for i in range(1, len(comp)):
selectivity[:, i] = np.divide(F[:, i], (F_0[:, 0] - F[:, 0]))*100
return conversion, selectivity
def visualize_parity(F, f_model, comp):
if not (F.shape[1] == f_model.shape[1] == len(comp)):
raise ValueError("Inputs F, f_model, and comp must have the same length.")
combined_fig, combined_ax = plt.subplots(1, 1, figsize = (10, 8))
global_max_value = max(np.max(F), np.max(f_model))
for i, component in enumerate(comp):
exp_flow = F[:, i]
model_flow = f_model[:, i]
max_value = max(np.max(exp_flow), np.max(model_flow))
fig, ax = plt.subplots(1, 1, figsize=(10, 8))
ax.scatter(exp_flow, model_flow, label = component)
ax.plot([0, max_value], [0, max_value], color="red", linestyle = '-')
ax.set_xlabel(f"Experimental_flow_rate_{component})")
ax.set_ylabel(f"Model_flow_rate_{component})")
ax.set_title(f"Parity Plot_{component}")
ax.grid(True)
ax.set_xlim([0, max([0, max_value])])
ax.set_ylim([0, max([0, max_value])])
ax.legend()
#plt.tight_layout()
# Save the figure
# save_path = os.path.join('output_data', f"parity_plot_{component}_{timestamp}.png")
# plt.savefig(save_path, dpi=300, bbox_inches="tight")
# print(f"Saved: {save_path}")
#plt.show()
plt.close(fig)
#Add the combined plot
combined_ax.scatter(exp_flow, model_flow, label = component, color = comp_colors[component])
#Finalize the combined plot
combined_ax.plot([0, global_max_value], [0, global_max_value], color = 'red', linestyle = '-')
combined_ax.set_xlabel("Experimental flow rate (mol/s)")
combined_ax.set_ylabel("Model flow rate (mol/s)")
combined_ax.grid(True)
combined_ax.set_xlim([0, global_max_value])
combined_ax.set_ylim([0, global_max_value])
combined_ax.legend()
combined_save_path = os.path.join('output_data', f"combined_parity_plot_{timestamp}.png")
plt.savefig(combined_save_path, dpi=300, bbox_inches="tight")
print(f"Saved: {combined_save_path}")
plt.show()
def visualize_dataVsmodel(comp, data, T_unique, p_tot):
"""Visualize the data using plots. """
# Check if data is empty
if data.empty:
raise ValueError("Input data is empty.")
# Define a color map for components
colors = ['black', 'green', 'darkorange', 'purple', 'blue'] #plt.cm.tab10.colors # Use a colormap with 10 distinct colors
comp_colors = {c: colors[i] for i, c in enumerate(comp)}
# Helper function to aggregate and plot data
def plot_data(ax, x_values, conv, model_conv, sel, model_sel, x_label):
"""Helper function to plot conversion and selectivity."""
ax.plot(x_values, conv, '*', ms = 10, color=comp_colors['BDO'], label=f"Conv_BDO")
if len(x_values) > 1:
f_conv = interp1d(x_values, model_conv, kind='linear', fill_value='extrapolate')
x_smooth = np.linspace(min(x_values), max(x_values), 3)
ax.plot(x_smooth, f_conv(x_smooth), '--', color=comp_colors['BDO'], label=f"Model_Conv")
for j, c in enumerate(comp):
if j != 0:
color = comp_colors.get(c, 'red')
ax.plot(x_values, sel[:, j], '*', ms = 10, color=color, label=f"Sel_{comp[j]}")
if len(x_values) > 1:
f_sel = interp1d(x_values, model_sel[:, j], kind='linear', fill_value='extrapolate')
ax.plot(x_smooth, f_sel(x_smooth), '--', color=color, label=f"Model_Sel_{comp[j]}")
plt.tight_layout()
ax.set_xlabel(x_label)
ax.set_ylabel("Conversion / Selectivity (%)")
#ax.set_title(title)
plt.legend(bbox_to_anchor = (0.5, -0.2), loc="upper center", ncol = len(comp))
#ax.grid(True)
ax.set_ylim(0, 100)
# save_path = os.path.join('output_data', f"performance_plot_{Tval}_{timestamp}.png")
# plt.savefig(save_path, dpi=300, bbox_inches="tight")
# print(f"Saved: {save_path}")
# Iterate over each unique temperature
for Tval in T_unique:
# Filter data for the current temperature
data_T = data[data["T"] == Tval]
# Check if data for the current temperature is empty
if data_T.empty:
print(f"No data found for T = {Tval}. Skipping.")
continue
# Create subplots for each temperature
fig, ax1 = plt.subplots(1, 1, figsize=(8, 6))
fig.suptitle(f"Temperature = {Tval} K", fontsize=14)
# Extract relevant data
FN2_T = data_T.iloc[:, 0].to_numpy() # FN2 column
F_0_T = data_T.iloc[:, 5].to_numpy() # F_0 column
# Calculate spacetime and inlet partial pressure
w_T = data_T.iloc[:, 2].to_numpy() # w column
spacetime = np.round((w_T / F_0_T) / 1000, 1) # Convert to kg.s/mol
ST_unique = np.unique(spacetime) # Unique spacetime values
pBDOin_unique = np.unique(np.round((F_0_T / (FN2_T + F_0_T)) * p_tot, 2)) # Unique partial pressure of BDO
# Calculate conversion and selectivity
conv = data_T['BDO_conversion'].to_numpy() # Experimental conversion
model_conv = data_T['BDO_conversion_model'].to_numpy() # Model conversion
sel = data_T[[f"S_{c}" for c in comp]].to_numpy() # Experimental selectivity
model_sel = data_T[[f"SM_{c}" for c in comp]].to_numpy() # Model selectivity
# Aggregate data for partial pressure of BDO
conv_agg_p = [conv[np.round((F_0_T / (FN2_T + F_0_T)) * p_tot, 2) == pBDO].mean() for pBDO in pBDOin_unique]
model_conv_agg_p = [model_conv[np.round((F_0_T / (FN2_T + F_0_T)) * p_tot, 2) == pBDO].mean() for pBDO in pBDOin_unique]
sel_agg_p = np.array([sel[np.round((F_0_T / (FN2_T + F_0_T)) * p_tot, 2) == pBDO].mean(axis=0) for pBDO in pBDOin_unique])
model_sel_agg_p = np.array([model_sel[np.round((F_0_T / (FN2_T + F_0_T)) * p_tot, 2) == pBDO].mean(axis=0) for pBDO in pBDOin_unique])
# Plot conversion and selectivity vs partial pressure of BDO
#plot_data(ax2, pBDOin_unique, conv_agg_p, model_conv_agg_p, sel_agg_p, model_sel_agg_p,"Partial Pressure of BDO (bar)")
# Aggregate data for space-time plotting
conv_agg = [conv[spacetime == ST].mean() for ST in ST_unique]
model_conv_agg = [model_conv[spacetime == ST].mean() for ST in ST_unique]
sel_agg = np.array([sel[spacetime == ST].mean(axis=0) for ST in ST_unique])
model_sel_agg = np.array([model_sel[spacetime == ST].mean(axis=0) for ST in ST_unique])
# Plot conversion and selectivity vs spacetime
plot_data(ax1, ST_unique, conv_agg, model_conv_agg, sel_agg, model_sel_agg,"Space time (kg.s/mol)")
# Adjust layout and display the plot
plt.tight_layout()
plt.show()