|
| 1 | +from datetime import datetime |
| 2 | +from pathlib import Path |
| 3 | +from sparging import ( |
| 4 | + LIBRA_PI_GEOM, |
| 5 | + LIBRA_PI_MAT, |
| 6 | + LIBRA_PI_OPERATING_PARAMS, |
| 7 | + LIBRA_PI_SPARGING_PARAMS, |
| 8 | + SimulationInput, |
| 9 | + ureg, |
| 10 | + all_correlations, |
| 11 | + CorrelationType, |
| 12 | +) |
| 13 | +import logging |
| 14 | +from autoemulate.simulations.base import Simulator |
| 15 | +from autoemulate import AutoEmulate |
| 16 | +from autoemulate.core.sensitivity_analysis import SensitivityAnalysis |
| 17 | +import torch |
| 18 | +import pandas as pd |
| 19 | +import json |
| 20 | +import networkx as nx |
| 21 | + |
| 22 | +COMPUTE_SOBOL = False |
| 23 | + |
| 24 | +logger = logging.getLogger(__name__) |
| 25 | +logging.basicConfig(level=logging.WARNING) |
| 26 | + |
| 27 | +FOLDER = Path("datasets") / datetime.now().strftime("%Y%m%d_%H%M%S") |
| 28 | +FOLDER.mkdir(exist_ok=True, parents=True) |
| 29 | +FOLDER_SAMPLES = FOLDER / "samples" |
| 30 | +FOLDER_SAMPLES.mkdir(exist_ok=True, parents=True) |
| 31 | +FOLDER_PP = FOLDER / "postprocessing" |
| 32 | +FOLDER_PP.mkdir(exist_ok=True) |
| 33 | + |
| 34 | +outputs = [] |
| 35 | +h_l_corrs = all_correlations.get_list(CorrelationType.MASS_TRANSFER_COEFF) |
| 36 | +D_l_corrs = all_correlations.get_list(CorrelationType.DIFFUSIVITY) |
| 37 | + |
| 38 | + |
| 39 | +class SpargingProblem(Simulator): |
| 40 | + def __init__(self, parameters_range, output_names): |
| 41 | + self.counter = 0 |
| 42 | + super().__init__(parameters_range, output_names) |
| 43 | + |
| 44 | + def _forward(self, x: torch.Tensor) -> torch.Tensor: |
| 45 | + # construct simulation input |
| 46 | + LIBRA_PI_OPERATING_PARAMS.temperature = x[0, 0].item() * ureg.celsius |
| 47 | + LIBRA_PI_OPERATING_PARAMS.P_top = x[0, 1].item() * ureg.bar |
| 48 | + LIBRA_PI_OPERATING_PARAMS.flow_g_mol = x[0, 2].item() * ureg.sccm |
| 49 | + LIBRA_PI_GEOM.nozzle_diameter = x[0, 3].item() * ureg.m |
| 50 | + # LIBRA_PI_SPARGING_PARAMS.h_l = h_l_corrs[int(x[0, 4].item())] |
| 51 | + LIBRA_PI_MAT.D_l = D_l_corrs[int(x[0, 4].item())] |
| 52 | + # breakpoint() |
| 53 | + |
| 54 | + graph = nx.Graph() |
| 55 | + sim_input = SimulationInput.from_parameters( |
| 56 | + LIBRA_PI_GEOM, |
| 57 | + LIBRA_PI_MAT, |
| 58 | + LIBRA_PI_OPERATING_PARAMS, |
| 59 | + LIBRA_PI_SPARGING_PARAMS, |
| 60 | + graph=graph, |
| 61 | + ) |
| 62 | + tau = sim_input.get_tau() |
| 63 | + h_l = sim_input.h_l |
| 64 | + a = sim_input.a |
| 65 | + eps_g = sim_input.eps_g |
| 66 | + sim_input.to_json( |
| 67 | + FOLDER_SAMPLES / f"sample_{self.counter}.json" |
| 68 | + ) # for debugging and postprocessing |
| 69 | + self.counter += 1 |
| 70 | + |
| 71 | + # for post processing |
| 72 | + Pi = sim_input.get_Pi_number().to("dimensionless").magnitude |
| 73 | + PP_numbers.append( |
| 74 | + [ |
| 75 | + Pi, |
| 76 | + tau.to("s").magnitude, |
| 77 | + h_l.to("m/s").magnitude, |
| 78 | + a.to("1/m").magnitude, |
| 79 | + eps_g.to("dimensionless").magnitude, |
| 80 | + graph.nodes["d_b"]["value"].to("m").magnitude, |
| 81 | + graph.nodes["u_g0"]["value"].to("m/s").magnitude, |
| 82 | + graph.nodes["h_l"]["origin"], |
| 83 | + graph.nodes["D_l"]["origin"], |
| 84 | + ] |
| 85 | + ) |
| 86 | + y = torch.tensor( |
| 87 | + [[tau.to("s").magnitude]], |
| 88 | + dtype=torch.float64, |
| 89 | + ) |
| 90 | + return y |
| 91 | + |
| 92 | + |
| 93 | +simulator = SpargingProblem( |
| 94 | + parameters_range={ # realistic (wide) parameters range for LIBRA |
| 95 | + "temperature": (500, 600), # celsius |
| 96 | + "P_top": (1, 2), # bar |
| 97 | + "flow_g_mol": (100, 500), # sccm |
| 98 | + "nozzle_diameter": (1e-3, 5e-3), # m |
| 99 | + "D_l_corr": (0, 0), # index for selecting diffusivity correlation |
| 100 | + }, |
| 101 | + output_names=["tau"], |
| 102 | +) |
| 103 | + |
| 104 | +n_samples = 5000 |
| 105 | + |
| 106 | +X = simulator.sample_inputs(n_samples) |
| 107 | + |
| 108 | +PP_numbers = [] |
| 109 | +Y, _ = simulator.forward_batch(X, allow_failures=False) |
| 110 | + |
| 111 | +# save training data |
| 112 | +pd.DataFrame(Y, columns=simulator.output_names).to_csv( |
| 113 | + FOLDER / "simulator_outputs.csv", index=False |
| 114 | +) |
| 115 | +pd.DataFrame(X, columns=simulator.param_names).to_csv( |
| 116 | + FOLDER / "simulator_inputs.csv", index=False |
| 117 | +) |
| 118 | +pd.DataFrame( |
| 119 | + PP_numbers, |
| 120 | + columns=["Pi", "tau", "h_l", "a", "eps_g", "d_b", "u_g0", "h_l_corr", "D_l_corr"], |
| 121 | +).to_csv(FOLDER / "PP_data.csv", index=False) |
| 122 | + |
| 123 | +# sensitivity analysis problem |
| 124 | +problem = { |
| 125 | + "num_vars": simulator.in_dim, |
| 126 | + "names": simulator.param_names, |
| 127 | + "bounds": simulator.param_bounds, |
| 128 | + "output_names": simulator.output_names, |
| 129 | +} |
| 130 | + |
| 131 | +with open(FOLDER / "problem.json", "w") as f: |
| 132 | + json.dump(problem, f, indent=4) |
| 133 | + |
| 134 | +if COMPUTE_SOBOL: |
| 135 | + # Run AutoEmulate with default settings |
| 136 | + ae = AutoEmulate(X, Y, log_level="WARNING", models=["GaussianProcessRBF"]) |
| 137 | + ae.summarise() |
| 138 | + |
| 139 | + # pick best model |
| 140 | + emulator = ae.best_result() |
| 141 | + print(f"Selected model: {emulator.model_name} with id: {emulator.id}") |
| 142 | + |
| 143 | + # The use_timestamp paramater ensures a new result is saved each time the save method is called |
| 144 | + best_result_filepath = ae.save(emulator, FOLDER, use_timestamp=False) |
| 145 | + print("Model and metadata saved to: ", best_result_filepath) |
| 146 | + |
| 147 | + ae.plot_preds( |
| 148 | + emulator, |
| 149 | + output_names=simulator.output_names, |
| 150 | + fname=FOLDER_PP / "predictions.png", |
| 151 | + ) |
| 152 | + |
| 153 | + # === Sensitivity analysis === |
| 154 | + sa = SensitivityAnalysis(emulator.model, problem=problem) |
| 155 | + sobol_df = sa.run("sobol") |
| 156 | + sa.plot_sobol(sobol_df, index="ST", fname=FOLDER_PP / "sobolTot.png") |
0 commit comments