glitchfilter commited on
Commit
8530e85
Β·
verified Β·
1 Parent(s): ac4d8a1

refactor: GPU sim merged into reactor_sim.py

Browse files
Files changed (1) hide show
  1. server/reactor_sim.py +536 -0
server/reactor_sim.py CHANGED
@@ -426,6 +426,16 @@ def simulate_step(
426
  cooling_water_temp = state.cooling_water_temp
427
  if disturbance:
428
  cooling_water_temp = disturbance.get("cooling_water_temp", cooling_water_temp)
 
 
 
 
 
 
 
 
 
 
429
 
430
  # ------------------------------------------------------------------
431
  # 1. MASS BALANCE β€” 3 simultaneous reactions (Fogler Ch. 1, LeBlanc Ch.3.2)
@@ -814,3 +824,529 @@ def calculate_economics(
814
  "flare_penalty": flare_penalty,
815
  "profit": profit,
816
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426
  cooling_water_temp = state.cooling_water_temp
427
  if disturbance:
428
  cooling_water_temp = disturbance.get("cooling_water_temp", cooling_water_temp)
429
+ # Feed composition upset: shift H2/CO ratio by adjusting feed rates
430
+ # Simulates upstream reformer fluctuation (e.g., S/C ratio change)
431
+ if "feed_h2_factor" in disturbance:
432
+ new_h2 *= disturbance["feed_h2_factor"]
433
+ if "feed_co_factor" in disturbance:
434
+ new_co *= disturbance["feed_co_factor"]
435
+ # Pressure loss: reduce compressor effectiveness
436
+ # Simulates mechanical failure (bearing wear, seal leak)
437
+ if "compressor_power_factor" in disturbance:
438
+ new_compressor *= disturbance["compressor_power_factor"]
439
 
440
  # ------------------------------------------------------------------
441
  # 1. MASS BALANCE β€” 3 simultaneous reactions (Fogler Ch. 1, LeBlanc Ch.3.2)
 
824
  "flare_penalty": flare_penalty,
825
  "profit": profit,
826
  }
827
+
828
+
829
+
830
+ # ---------------------------------------------------------------------------
831
+ # GPU-ACCELERATED BATCHED SIMULATION (PyTorch)
832
+ # ---------------------------------------------------------------------------
833
+
834
+ try:
835
+ import torch
836
+
837
+ # SRK critical properties tensors for vectorized fugacity
838
+ _TC = torch.tensor([33.2, 132.9, 304.2, 512.6, 647.1])
839
+ _PC = torch.tensor([13.0, 35.0, 73.8, 80.9, 220.6])
840
+ _OMEGA = torch.tensor([-0.22, 0.066, 0.228, 0.566, 0.344])
841
+
842
+ # Adsorption constants for LHHW (same as CPU version)
843
+ K_ADS_CO = 0.5
844
+ K_ADS_H2 = 0.3
845
+ K_ADS_H2O = 0.1
846
+
847
+ class BatchedReactorSim:
848
+ """GPU-accelerated batched methanol reactor simulation.
849
+
850
+ Runs N independent reactor simulations in parallel using PyTorch
851
+ tensor operations. All physics equations are identical to the CPU
852
+ version (reactor_sim.py) but operate on (N,) shaped tensors.
853
+
854
+ Args:
855
+ n_envs: Number of parallel environments
856
+ device: "cuda" for GPU, "cpu" for CPU
857
+ dtype: Float precision (float32 for GPU, float64 for CPU validation)
858
+ """
859
+
860
+ # State tensor indices
861
+ IDX_TEMP = 0
862
+ IDX_PRESSURE = 1
863
+ IDX_H2 = 2
864
+ IDX_CO = 3
865
+ IDX_COOLING = 4
866
+ IDX_CW_TEMP = 5
867
+ IDX_CAT_HEALTH = 6
868
+ IDX_MEOH_PRODUCED = 7
869
+ IDX_COMPRESSOR = 8
870
+ IDX_RATE = 9
871
+ IDX_H2CO = 10
872
+ IDX_PROFIT_STEP = 11
873
+ IDX_CUM_PROFIT = 12
874
+ IDX_STEP = 13
875
+ IDX_SHUTDOWN = 14
876
+ IDX_SELECTIVITY = 15
877
+ IDX_PURITY = 16
878
+ IDX_CO2_EMISSIONS = 17
879
+ IDX_INERT_FRAC = 18
880
+ IDX_CARBON_EFF = 19
881
+ N_STATE = 20
882
+
883
+ # Action tensor indices
884
+ ACT_H2 = 0
885
+ ACT_CO = 1
886
+ ACT_COOLING = 2
887
+ ACT_COMPRESSOR = 3
888
+ ACT_PURGE = 4
889
+ ACT_RECYCLE = 5
890
+ N_ACTION = 6 # minimum required actions
891
+
892
+ def __init__(
893
+ self,
894
+ n_envs: int = 1,
895
+ device: str = "cuda" if torch.cuda.is_available() else "cpu",
896
+ dtype: torch.dtype = torch.float32,
897
+ ):
898
+ self.n_envs = n_envs
899
+ self.device = torch.device(device)
900
+ self.dtype = dtype
901
+
902
+ # Pre-compute SRK constants on device
903
+ self._tc = _TC.to(self.device, self.dtype)
904
+ self._pc = _PC.to(self.device, self.dtype)
905
+ self._omega = _OMEGA.to(self.device, self.dtype)
906
+
907
+ # State buffer: (n_envs, N_STATE)
908
+ self.state = torch.zeros(n_envs, self.N_STATE, device=self.device, dtype=self.dtype)
909
+
910
+ def reset(self, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
911
+ """Reset environments. If mask given, only reset those envs.
912
+
913
+ Args:
914
+ mask: Boolean tensor (n_envs,). True = reset that env.
915
+
916
+ Returns:
917
+ State tensor (n_envs, N_STATE)
918
+ """
919
+ if mask is None:
920
+ mask = torch.ones(self.n_envs, dtype=torch.bool, device=self.device)
921
+
922
+ # Domain randomization for initial conditions
923
+ n_reset = mask.sum().item()
924
+ if n_reset == 0:
925
+ return self.state
926
+
927
+ # Randomized initial temperatures (220-260Β°C)
928
+ init_temp = 240.0 + torch.randn(n_reset, device=self.device, dtype=self.dtype) * 10.0
929
+ init_pressure = 60.0 + torch.randn(n_reset, device=self.device, dtype=self.dtype) * 5.0
930
+ init_cw_temp = 25.0 + torch.randn(n_reset, device=self.device, dtype=self.dtype) * 2.0
931
+
932
+ self.state[mask, self.IDX_TEMP] = init_temp
933
+ self.state[mask, self.IDX_PRESSURE] = init_pressure.clamp(P_MIN, P_MAX)
934
+ self.state[mask, self.IDX_H2] = 4.0
935
+ self.state[mask, self.IDX_CO] = 2.0
936
+ self.state[mask, self.IDX_COOLING] = 50.0
937
+ self.state[mask, self.IDX_CW_TEMP] = init_cw_temp
938
+ self.state[mask, self.IDX_CAT_HEALTH] = 1.0 - torch.rand(n_reset, device=self.device, dtype=self.dtype) * 0.02
939
+ self.state[mask, self.IDX_MEOH_PRODUCED] = 0.0
940
+ self.state[mask, self.IDX_COMPRESSOR] = 50.0
941
+ self.state[mask, self.IDX_RATE] = 0.0
942
+ self.state[mask, self.IDX_H2CO] = 2.0
943
+ self.state[mask, self.IDX_PROFIT_STEP] = 0.0
944
+ self.state[mask, self.IDX_CUM_PROFIT] = 0.0
945
+ self.state[mask, self.IDX_STEP] = 0.0
946
+ self.state[mask, self.IDX_SHUTDOWN] = 0.0
947
+ self.state[mask, self.IDX_SELECTIVITY] = 0.995
948
+ self.state[mask, self.IDX_PURITY] = 0.995
949
+ self.state[mask, self.IDX_CO2_EMISSIONS] = 0.0
950
+ self.state[mask, self.IDX_INERT_FRAC] = 0.044
951
+ self.state[mask, self.IDX_CARBON_EFF] = 0.0
952
+
953
+ return self.state
954
+
955
+ def _fugacity_batch(self, T_K: torch.Tensor, P_bar: torch.Tensor) -> torch.Tensor:
956
+ """Vectorized SRK fugacity coefficients for all 5 species.
957
+
958
+ Args:
959
+ T_K: Temperature in Kelvin, shape (N,)
960
+ P_bar: Pressure in bar, shape (N,)
961
+
962
+ Returns:
963
+ Fugacity coefficients, shape (N, 5) for [H2, CO, CO2, CH3OH, H2O]
964
+ """
965
+ N = T_K.shape[0]
966
+ Tc = self._tc.unsqueeze(0).expand(N, -1) # (N, 5)
967
+ Pc = self._pc.unsqueeze(0).expand(N, -1)
968
+ omega = self._omega.unsqueeze(0).expand(N, -1)
969
+
970
+ Tr = T_K.unsqueeze(1) / Tc # (N, 5)
971
+ Pr = P_bar.unsqueeze(1) / Pc
972
+
973
+ m = 0.48 + 1.574 * omega - 0.176 * omega ** 2
974
+ alpha = (1.0 + m * (1.0 - Tr.sqrt())) ** 2
975
+
976
+ a = 0.42748 * (R_GAS * Tc) ** 2 / (Pc * 1e5) * alpha
977
+ b = 0.08664 * R_GAS * Tc / (Pc * 1e5)
978
+
979
+ A = a * P_bar.unsqueeze(1) * 1e5 / (R_GAS * T_K.unsqueeze(1)) ** 2
980
+ B = b * P_bar.unsqueeze(1) * 1e5 / (R_GAS * T_K.unsqueeze(1))
981
+
982
+ Z = (1.0 + B - A / (1.0 + B).clamp(min=0.1)).clamp(min=0.5)
983
+ phi = torch.exp(Z - 1.0 - torch.log((Z - B).clamp(min=0.01)))
984
+ return phi.clamp(0.3, 1.0)
985
+
986
+ def _lhhw_kinetics(
987
+ self,
988
+ T_K: torch.Tensor,
989
+ P_CO: torch.Tensor,
990
+ P_H2: torch.Tensor,
991
+ P_CO2: torch.Tensor,
992
+ P_CH3OH: torch.Tensor,
993
+ P_H2O: torch.Tensor,
994
+ cat_health: torch.Tensor,
995
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
996
+ """Vectorized LHHW kinetics for 3 reactions.
997
+
998
+ All inputs shape (N,), all outputs shape (N,).
999
+ """
1000
+ # Arrhenius terms
1001
+ arr_R1 = k0_R1 * torch.exp(-Ea_R1 / (R_GAS * T_K))
1002
+ arr_R2 = k0_R2 * torch.exp(-Ea_R2 / (R_GAS * T_K))
1003
+ arr_R3 = k0_R3 * torch.exp(-Ea_R3 / (R_GAS * T_K))
1004
+
1005
+ # Equilibrium factors (Van't Hoff)
1006
+ dH1_R = abs(DELTA_H_R1_298) / R_GAS
1007
+ K_eq_R1 = K_EQ_R1_REF * torch.exp(dH1_R * (1.0 / T_K - 1.0 / T_REF_EQ))
1008
+ eq_factor_R1 = (1.0 - 1.0 / K_eq_R1.clamp(min=0.01)).clamp(min=0.0)
1009
+
1010
+ dH2_R = abs(DELTA_H_R2_298) / R_GAS
1011
+ K_eq_R2 = K_EQ_R2_REF * torch.exp(dH2_R * (1.0 / T_K - 1.0 / T_REF_EQ))
1012
+ eq_factor_R2 = (1.0 - 1.0 / K_eq_R2.clamp(min=0.01)).clamp(min=0.0)
1013
+
1014
+ dH3_R = abs(DELTA_H_R3_298) / R_GAS
1015
+ K_eq_R3 = K_EQ_R3_REF * torch.exp(-dH3_R * (1.0 / T_K - 1.0 / T_REF_EQ))
1016
+
1017
+ # Driving forces
1018
+ driving_R1 = (P_CO * P_H2 ** 2 - P_CH3OH / K_eq_R1.clamp(min=1e-6)).clamp(min=0.0)
1019
+ driving_R2 = (P_CO2 * P_H2 ** 3 - P_CH3OH * P_H2O / K_eq_R2.clamp(min=1e-6)).clamp(min=0.0)
1020
+ driving_R3 = (P_CO2 * P_H2 - P_CO * P_H2O / K_eq_R3.clamp(min=1e-6)).clamp(min=0.0)
1021
+
1022
+ # LHHW adsorption denominator
1023
+ denom = (1.0 + K_ADS_CO * P_CO + K_ADS_H2 * P_H2.sqrt() + K_ADS_H2O * P_H2O) ** 2
1024
+
1025
+ rate_R1 = arr_R1 * driving_R1 / denom * cat_health * ETA
1026
+ rate_R2 = arr_R2 * driving_R2 / denom * cat_health * ETA
1027
+ rate_R3 = arr_R3 * driving_R3 / denom * cat_health * ETA
1028
+
1029
+ return rate_R1, rate_R2, rate_R3
1030
+
1031
+ def step(self, actions: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
1032
+ """Step all environments simultaneously.
1033
+
1034
+ Args:
1035
+ actions: (n_envs, N_ACTION) tensor of agent actions
1036
+ [feed_h2, feed_co, cooling_water, compressor, purge, recycle]
1037
+
1038
+ Returns:
1039
+ state: (n_envs, N_STATE) next state
1040
+ reward: (n_envs,) reward signal
1041
+ done: (n_envs,) boolean done flags
1042
+ """
1043
+ s = self.state
1044
+ N = self.n_envs
1045
+
1046
+ # Extract current state
1047
+ T = s[:, self.IDX_TEMP]
1048
+ pressure = s[:, self.IDX_PRESSURE]
1049
+ cur_h2 = s[:, self.IDX_H2]
1050
+ cur_co = s[:, self.IDX_CO]
1051
+ cur_cooling = s[:, self.IDX_COOLING]
1052
+ cw_temp = s[:, self.IDX_CW_TEMP]
1053
+ cat_health = s[:, self.IDX_CAT_HEALTH]
1054
+ cum_meoh = s[:, self.IDX_MEOH_PRODUCED]
1055
+ cur_comp = s[:, self.IDX_COMPRESSOR]
1056
+ cum_profit = s[:, self.IDX_CUM_PROFIT]
1057
+ step_num = s[:, self.IDX_STEP]
1058
+ shutdown = s[:, self.IDX_SHUTDOWN]
1059
+
1060
+ # Already shutdown? No-op
1061
+ is_shutdown = shutdown > 0.5
1062
+
1063
+ # ── 0. Apply rate limits to actions ──
1064
+ tgt_h2 = actions[:, self.ACT_H2].clamp(0.0, FEED_H2_MAX)
1065
+ tgt_co = actions[:, self.ACT_CO].clamp(0.0, FEED_CO_MAX)
1066
+ tgt_cool = actions[:, self.ACT_COOLING].clamp(0.0, MAX_COOLING_FLOW)
1067
+ tgt_comp = actions[:, self.ACT_COMPRESSOR].clamp(0.0, COMPRESSOR_MAX)
1068
+
1069
+ new_h2 = cur_h2 + (tgt_h2 - cur_h2).clamp(-VALVE_RATE_LIMIT, VALVE_RATE_LIMIT)
1070
+ new_co = cur_co + (tgt_co - cur_co).clamp(-VALVE_RATE_LIMIT, VALVE_RATE_LIMIT)
1071
+ new_cooling = cur_cooling + (tgt_cool - cur_cooling).clamp(-COOLING_RATE_LIMIT, COOLING_RATE_LIMIT)
1072
+ new_comp = cur_comp + (tgt_comp - cur_comp).clamp(-COMPRESSOR_RATE_LIMIT, COMPRESSOR_RATE_LIMIT)
1073
+
1074
+ # Purge and recycle
1075
+ purge_frac = (actions[:, self.ACT_PURGE] / 100.0).clamp(0.001, 1.0) if actions.shape[1] > self.ACT_PURGE else torch.full((N,), 0.02, device=self.device, dtype=self.dtype)
1076
+ recycle_ratio = actions[:, self.ACT_RECYCLE].clamp(0.0, 8.0) if actions.shape[1] > self.ACT_RECYCLE else torch.full((N,), 3.5, device=self.device, dtype=self.dtype)
1077
+
1078
+ # ── 1. Mass balance ──
1079
+ T_kelvin = T + 273.15
1080
+ h2_co_ratio = new_h2 / new_co.clamp(min=1e-6)
1081
+
1082
+ # Recycle loop
1083
+ prev_conv = (s[:, self.IDX_RATE] / (new_h2 + new_co).clamp(min=1e-6)).clamp(0.0, 0.5)
1084
+ recycle_factor = recycle_ratio / (1.0 + recycle_ratio)
1085
+ eff_h2 = (new_h2 * (1.0 + recycle_factor * (1.0 - prev_conv * 2.0))).clamp(min=0.0)
1086
+ eff_co = (new_co * (1.0 + recycle_factor * (1.0 - prev_conv))).clamp(min=0.0)
1087
+
1088
+ # Inert buildup
1089
+ inert_frac = 0.044
1090
+ inert_buildup = (inert_frac * recycle_ratio / (1.0 + purge_frac * recycle_ratio)).clamp(max=0.15)
1091
+ dilution = 1.0 - inert_buildup
1092
+ eff_h2 = eff_h2 * dilution
1093
+ eff_co = eff_co * dilution
1094
+
1095
+ # CO/CO2 split
1096
+ co2_frac = 0.3
1097
+ est_co2 = eff_co * co2_frac
1098
+ est_co_net = eff_co * (1.0 - co2_frac)
1099
+
1100
+ # Pressure dynamics
1101
+ P_target = P_MIN + (new_comp / 100.0) * (P_MAX - P_MIN)
1102
+ P_tau = 300.0
1103
+ pressure = pressure + (P_target - pressure) * (1.0 - torch.exp(torch.tensor(-DT_SECONDS / P_tau, device=self.device)))
1104
+
1105
+ # Partial pressures with fugacity correction
1106
+ F_total = eff_h2 + eff_co + est_co2 + 0.5
1107
+ y_H2 = eff_h2 / F_total.clamp(min=1e-6)
1108
+ y_CO = est_co_net / F_total.clamp(min=1e-6)
1109
+ y_CO2 = est_co2 / F_total.clamp(min=1e-6)
1110
+ y_CH3OH = torch.full((N,), 0.02, device=self.device, dtype=self.dtype)
1111
+ y_H2O = torch.full((N,), 0.01, device=self.device, dtype=self.dtype)
1112
+
1113
+ phi = self._fugacity_batch(T_kelvin, pressure) # (N, 5)
1114
+ P_H2 = y_H2 * pressure * phi[:, 0]
1115
+ P_CO = y_CO * pressure * phi[:, 1]
1116
+ P_CO2 = y_CO2 * pressure * phi[:, 2]
1117
+ P_CH3OH = y_CH3OH * pressure * phi[:, 3]
1118
+ P_H2O = y_H2O * pressure * phi[:, 4]
1119
+
1120
+ # ── Kinetics ──
1121
+ rate_R1, rate_R2, rate_R3 = self._lhhw_kinetics(
1122
+ T_kelvin, P_CO, P_H2, P_CO2, P_CH3OH, P_H2O, cat_health
1123
+ )
1124
+
1125
+ # Stoichiometric efficiency
1126
+ stoich_eff = (1.0 - 0.3 * (h2_co_ratio - 2.0).abs() / 2.0).clamp(0.1, 1.0)
1127
+ rate_R1 = rate_R1 * stoich_eff
1128
+
1129
+ # Michaelis-Menten feed saturation
1130
+ Km_co, Km_h2 = 0.5, 1.0
1131
+ feed_sat = (est_co_net / (est_co_net + Km_co)) * (eff_h2 / (eff_h2 + Km_h2))
1132
+ rate_R1 = rate_R1 * feed_sat
1133
+ rate_R2 = rate_R2 * feed_sat
1134
+ rate_R3 = rate_R3 * feed_sat
1135
+
1136
+ # Selectivity
1137
+ selectivity = (1.0 - 0.005 * (T - 250.0).clamp(min=0.0) / 50.0).clamp(0.95, 1.0)
1138
+ reaction_rate = (rate_R1 + rate_R2) * selectivity
1139
+
1140
+ # Methanol production
1141
+ meoh_step = (rate_R1 + rate_R2) * MW_CH3OH * DT_SECONDS * 0.96 # 96% condensation
1142
+
1143
+ # Pressure drop (Ergun)
1144
+ cross_area = 10.0 / BED_LENGTH
1145
+ sup_vel = ((new_h2 + new_co) * R_GAS * T_kelvin / (pressure * 1e5 * cross_area)).clamp(max=2.0)
1146
+ dp_visc = 150.0 * GAS_VISCOSITY * (1.0 - BED_POROSITY) ** 2 / (BED_POROSITY ** 3 * PELLET_DIAMETER ** 2) * sup_vel * BED_LENGTH
1147
+ dp_inert = 1.75 * GAS_DENSITY * (1.0 - BED_POROSITY) / (BED_POROSITY ** 3 * PELLET_DIAMETER) * sup_vel ** 2 * BED_LENGTH
1148
+ dp_bar = ((dp_visc + dp_inert) / 1e5).clamp(max=pressure * 0.15)
1149
+ pressure = pressure - dp_bar
1150
+
1151
+ # ── 2. Energy balance (RK4) ──
1152
+ dH_R1 = DELTA_H_R1_298 + (-43.0) * (T_kelvin - 298.15)
1153
+ dH_R2 = DELTA_H_R2_298 + (-30.0) * (T_kelvin - 298.15)
1154
+ dH_R3 = DELTA_H_R3_298 + (5.0) * (T_kelvin - 298.15)
1155
+
1156
+ u_eff = U_BASE * (new_cooling / MAX_COOLING_FLOW) ** 0.8
1157
+
1158
+ def dTdt(T_cur: torch.Tensor) -> torch.Tensor:
1159
+ T_k = T_cur + 273.15
1160
+ scale = torch.exp(-Ea_R1 / (R_GAS * T_k)) / torch.exp(-Ea_R1 / (R_GAS * T_kelvin)).clamp(min=1e-30)
1161
+ q_gen = (rate_R1 * dH_R1.abs() + rate_R2 * dH_R2.abs() - rate_R3 * dH_R3.abs()) * scale
1162
+ q_rem = u_eff * A_HX * (T_cur - cw_temp)
1163
+ return (q_gen - q_rem) / (M_REACTOR * CP_REACTOR)
1164
+
1165
+ # RK4 integration (4 sub-steps)
1166
+ dt_sub = DT_SECONDS / 4.0
1167
+ T_rk = T.clone()
1168
+ for _ in range(4):
1169
+ k1 = dTdt(T_rk)
1170
+ k2 = dTdt(T_rk + 0.5 * dt_sub * k1)
1171
+ k3 = dTdt(T_rk + 0.5 * dt_sub * k2)
1172
+ k4 = dTdt(T_rk + dt_sub * k3)
1173
+ T_rk = T_rk + dt_sub * (k1 + 2 * k2 + 2 * k3 + k4) / 6.0
1174
+
1175
+ dT = (T_rk - T).clamp(-MAX_DT_PER_STEP, MAX_DT_PER_STEP)
1176
+ new_temp = T + dT
1177
+
1178
+ # Process noise (GPU-native)
1179
+ new_temp = new_temp + torch.randn(N, device=self.device, dtype=self.dtype) * 1.0
1180
+ pressure = pressure + torch.randn(N, device=self.device, dtype=self.dtype) * 0.3
1181
+ reaction_rate = reaction_rate * (1.0 + torch.randn(N, device=self.device, dtype=self.dtype) * 0.05).clamp(min=0.0)
1182
+ cw_temp = cw_temp + torch.randn(N, device=self.device, dtype=self.dtype) * 0.5
1183
+
1184
+ # ── 3. Catalyst deactivation (3-zone sintering) ──
1185
+ # Zone 1: thermal sintering (>270Β°C)
1186
+ thermal_rate = 1e-4 * torch.exp(0.05 * (new_temp - 270.0).clamp(min=0.0))
1187
+ # Zone 2: poison (CO2 at >5 bar partial pressure)
1188
+ poison_rate = 5e-5 * (P_CO2 - 5.0).clamp(min=0.0)
1189
+ # Zone 3: mechanical (high pressure cycles)
1190
+ mech_rate = torch.full((N,), 1e-5, device=self.device, dtype=self.dtype)
1191
+
1192
+ new_cat = (cat_health - (thermal_rate + poison_rate + mech_rate) * DT_SECONDS / 3600.0).clamp(0.0, 1.0)
1193
+
1194
+ # ── 4. Emergency shutdown ──
1195
+ new_shutdown = (new_temp > EMERGENCY_SHUTDOWN_TEMP).float()
1196
+ # If shutdown, force zero production
1197
+ reaction_rate = reaction_rate * (1.0 - new_shutdown)
1198
+ meoh_step = meoh_step * (1.0 - new_shutdown)
1199
+
1200
+ # ── 5. Economics ──
1201
+ meoh_price = 350.0 # $/tonne
1202
+ gas_cost = 3.5 # $/GJ
1203
+ elec_cost = 0.08 # $/kWh
1204
+ profit = (meoh_step * meoh_price / 1000.0
1205
+ - (new_h2 + new_co) * gas_cost * 0.001
1206
+ - new_comp * elec_cost * DT_SECONDS / 3600.0)
1207
+
1208
+ # ── 6. Reward (6-component dense signal) ──
1209
+ # Production reward
1210
+ rw_prod = (reaction_rate / 5.0).clamp(0.0, 1.0) * 0.3
1211
+ # Safety reward
1212
+ rw_safe = torch.where(new_temp < 280, torch.ones_like(new_temp),
1213
+ (1.0 - (new_temp - 280) / 20.0).clamp(0.0, 1.0)) * 0.25
1214
+ # Stability reward (small temperature changes)
1215
+ rw_stab = (1.0 - dT.abs() / MAX_DT_PER_STEP).clamp(0.0, 1.0) * 0.15
1216
+ # Catalyst preservation
1217
+ rw_cat = new_cat * 0.1
1218
+ # Economic reward
1219
+ rw_econ = torch.sigmoid(profit * 10.0) * 0.15
1220
+ # Shutdown penalty
1221
+ rw_shut = -new_shutdown * 0.5
1222
+
1223
+ raw_reward = rw_prod + rw_safe + rw_stab + rw_cat + rw_econ + rw_shut
1224
+ # Sigmoid map to (0.01, 0.99)
1225
+ reward = 0.01 + 0.98 * torch.sigmoid((raw_reward - 0.5) * 5.0)
1226
+
1227
+ # ── 7. Update state buffer ──
1228
+ # Don't update shutdown envs
1229
+ active = (1.0 - is_shutdown.float())
1230
+
1231
+ self.state[:, self.IDX_TEMP] = torch.where(is_shutdown, T, new_temp)
1232
+ self.state[:, self.IDX_PRESSURE] = pressure.clamp(P_MIN, P_MAX)
1233
+ self.state[:, self.IDX_H2] = new_h2
1234
+ self.state[:, self.IDX_CO] = new_co
1235
+ self.state[:, self.IDX_COOLING] = new_cooling
1236
+ self.state[:, self.IDX_CW_TEMP] = cw_temp
1237
+ self.state[:, self.IDX_CAT_HEALTH] = new_cat
1238
+ self.state[:, self.IDX_MEOH_PRODUCED] = cum_meoh + meoh_step
1239
+ self.state[:, self.IDX_COMPRESSOR] = new_comp
1240
+ self.state[:, self.IDX_RATE] = reaction_rate
1241
+ self.state[:, self.IDX_H2CO] = h2_co_ratio
1242
+ self.state[:, self.IDX_PROFIT_STEP] = profit
1243
+ self.state[:, self.IDX_CUM_PROFIT] = cum_profit + profit
1244
+ self.state[:, self.IDX_STEP] = step_num + 1
1245
+ self.state[:, self.IDX_SHUTDOWN] = torch.max(shutdown, new_shutdown)
1246
+ self.state[:, self.IDX_SELECTIVITY] = selectivity
1247
+ self.state[:, self.IDX_PURITY] = selectivity # simplified
1248
+ self.state[:, self.IDX_INERT_FRAC] = inert_buildup
1249
+ self.state[:, self.IDX_CARBON_EFF] = (rate_R1 + rate_R2) / (est_co_net + est_co2).clamp(min=1e-6)
1250
+
1251
+ done = self.state[:, self.IDX_SHUTDOWN] > 0.5
1252
+
1253
+ return self.state.clone(), reward, done
1254
+
1255
+ def get_obs_dict(self, idx: int = 0) -> Dict[str, float]:
1256
+ """Get observation as dictionary (for compatibility with CPU version)."""
1257
+ s = self.state[idx]
1258
+ return {
1259
+ "temperature": s[self.IDX_TEMP].item(),
1260
+ "pressure": s[self.IDX_PRESSURE].item(),
1261
+ "feed_rate_h2": s[self.IDX_H2].item(),
1262
+ "feed_rate_co": s[self.IDX_CO].item(),
1263
+ "cooling_water_flow": s[self.IDX_COOLING].item(),
1264
+ "cooling_water_temp": s[self.IDX_CW_TEMP].item(),
1265
+ "catalyst_health": s[self.IDX_CAT_HEALTH].item(),
1266
+ "methanol_produced": s[self.IDX_MEOH_PRODUCED].item(),
1267
+ "compressor_power": s[self.IDX_COMPRESSOR].item(),
1268
+ "reaction_rate": s[self.IDX_RATE].item(),
1269
+ "h2_co_ratio": s[self.IDX_H2CO].item(),
1270
+ "profit_this_step": s[self.IDX_PROFIT_STEP].item(),
1271
+ "cumulative_profit": s[self.IDX_CUM_PROFIT].item(),
1272
+ "step_number": int(s[self.IDX_STEP].item()),
1273
+ "selectivity": s[self.IDX_SELECTIVITY].item(),
1274
+ "product_purity": s[self.IDX_PURITY].item(),
1275
+ "inert_fraction": s[self.IDX_INERT_FRAC].item(),
1276
+ "carbon_efficiency": s[self.IDX_CARBON_EFF].item(),
1277
+ }
1278
+
1279
+
1280
+ def benchmark(n_envs: int = 256, n_steps: int = 100, device: str = "auto"):
1281
+ """Benchmark GPU vs CPU throughput."""
1282
+ import time
1283
+
1284
+ if device == "auto":
1285
+ device = "cuda" if torch.cuda.is_available() else "cpu"
1286
+
1287
+ print(f"Benchmarking {n_envs} envs Γ— {n_steps} steps on {device}...")
1288
+ sim = BatchedReactorSim(n_envs=n_envs, device=device)
1289
+ sim.reset()
1290
+
1291
+ # Random actions
1292
+ actions = torch.rand(n_envs, 6, device=sim.device, dtype=sim.dtype)
1293
+ actions[:, 0] *= FEED_H2_MAX
1294
+ actions[:, 1] *= FEED_CO_MAX
1295
+ actions[:, 2] *= MAX_COOLING_FLOW
1296
+ actions[:, 3] *= COMPRESSOR_MAX
1297
+ actions[:, 4] *= 10.0 # purge %
1298
+ actions[:, 5] = 3.5 # recycle ratio
1299
+
1300
+ # Warmup
1301
+ for _ in range(5):
1302
+ sim.step(actions)
1303
+ if device == "cuda":
1304
+ torch.cuda.synchronize()
1305
+
1306
+ t0 = time.perf_counter()
1307
+ for _ in range(n_steps):
1308
+ state, reward, done = sim.step(actions)
1309
+ # Auto-reset done envs
1310
+ if done.any():
1311
+ sim.reset(mask=done)
1312
+ if device == "cuda":
1313
+ torch.cuda.synchronize()
1314
+ elapsed = time.perf_counter() - t0
1315
+
1316
+ total_steps = n_envs * n_steps
1317
+ print(f" Total env steps: {total_steps:,}")
1318
+ print(f" Wall time: {elapsed:.3f}s")
1319
+ print(f" Throughput: {total_steps / elapsed:,.0f} steps/sec")
1320
+ print(f" Per env-step: {elapsed / total_steps * 1e6:.1f} Β΅s")
1321
+ print(f" Final temp range: [{state[:, 0].min():.1f}, {state[:, 0].max():.1f}] Β°C")
1322
+ print(f" Mean reward: {reward.mean():.4f}")
1323
+ print(f" Shutdowns: {done.sum().item()}/{n_envs}")
1324
+
1325
+ return total_steps / elapsed
1326
+
1327
+
1328
+ if __name__ == "__main__":
1329
+ # Run benchmark on best available device
1330
+ print("=" * 60)
1331
+ print("Methanol APC β€” GPU-Accelerated Reactor Simulation Benchmark")
1332
+ print("=" * 60)
1333
+
1334
+ # CPU baseline
1335
+ cpu_throughput = benchmark(n_envs=1, n_steps=100, device="cpu")
1336
+ print()
1337
+
1338
+ # CPU batched
1339
+ cpu_batch_throughput = benchmark(n_envs=256, n_steps=100, device="cpu")
1340
+ print()
1341
+
1342
+ # GPU batched (if available)
1343
+ if torch.cuda.is_available():
1344
+ gpu_throughput = benchmark(n_envs=256, n_steps=100, device="cuda")
1345
+ print(f"\nSpeedup vs single CPU: {gpu_throughput / cpu_throughput:.0f}x")
1346
+ else:
1347
+ print("No CUDA GPU available β€” skipping GPU benchmark")
1348
+
1349
+ _GPU_AVAILABLE = True
1350
+ except ImportError:
1351
+ _GPU_AVAILABLE = False
1352
+ BatchedReactorSim = None # type: ignore