OpenImpala
Image-based parallel transport property solver
Loading...
Searching...
No Matches
ResultsJSON.H
Go to the documentation of this file.
1
4// --- ResultsJSON.H ---
5//
6// Structured JSON output for OpenImpala transport property results.
7//
8// Implements the "Mimic and Passthrough" strategy for interoperability
9// with battery modelling standards (BPX, BattINFO, BDF):
10//
11// - "openimpala" block: native results with full solver provenance
12// - "units" block: SI unit annotations (BattINFO-aligned)
13// - "bpx" block: BPX-compatible electrode fragment for PyBaMM import
14// - "provenance" block: passthrough metadata (sample_id, provenance_uri)
15// for linking to external digital-twin databases (Faraday Engine, BDF)
16//
17// The JSON output is written alongside the existing results.txt file.
18//
19// Usage:
20// OpenImpala::ResultsJSON json;
21// json.setPhysicsConfig(physics_config);
22// json.setGridInfo(nx, ny, nz, box_size);
23// json.setSolverInfo("FlexGMRES", converged);
24// json.setProvenance(sample_id, provenance_uri);
25// json.setVolumeFraction(vf);
26// json.addDirectionResult("X", D_eff_ratio);
27// json.setBPXElectrode("negative"); // optional: enable BPX fragment
28// json.write("/path/to/results.json");
29
30#ifndef RESULTSJSON_H
31#define RESULTSJSON_H
32
33#include "PhysicsConfig.H"
34
35#ifndef OPENIMPALA_UNIT_TEST
36#include <AMReX_SPACE.H>
37#else
38#ifndef AMREX_SPACEDIM
39#define AMREX_SPACEDIM 3
40#endif
41#ifndef AMREX_D_DECL
42#define AMREX_D_DECL(a, b, c) a, b, c
43#endif
44#endif
45
46#include <nlohmann/json.hpp>
47
48#include <cmath>
49#include <fstream>
50#include <map>
51#include <string>
52#include <vector>
53
54namespace OpenImpala {
55
57public:
58 // --- Setters for each data category ---
59
61 m_physics = cfg;
62 }
63
64 void setInputFile(const std::string& filename) {
65 m_input_file = filename;
66 }
67
68 void setPhaseId(int phase_id) {
69 m_phase_id = phase_id;
70 }
71
72 void setGridInfo(int nx, int ny, int nz, int box_size) {
73 m_nx = nx;
74 m_ny = ny;
75 m_nz = nz;
76 m_box_size = box_size;
77 }
78
79 void setSolverInfo(const std::string& solver, bool converged) {
80 m_solver = solver;
81 m_converged = converged;
82 }
83
84 void setProvenance(const std::string& sample_id, const std::string& provenance_uri) {
85 m_sample_id = sample_id;
86 m_provenance_uri = provenance_uri;
87 }
88
90 m_volume_fraction = vf;
91 }
92
93 void addDirectionResult(const std::string& dir, Real D_eff_ratio) {
94 m_deff_ratios[dir] = D_eff_ratio;
95 }
96
99 void setBPXElectrode(const std::string& electrode) {
100 m_bpx_electrode = electrode;
101 }
102
103 // --- Microstructure parameter setters ---
104
107 m_ssa = ssa;
108 m_has_ssa = true;
109 }
110
113 m_ssa_raw = ssa_raw;
114 m_has_ssa_raw = true;
115 }
116
118 void setMultiPhaseVolumeFractions(const std::map<int, Real>& phase_vfs) {
119 m_phase_vfs = phase_vfs;
120 }
121
123 void setMacroGeometry(Real thickness, Real cross_section, Real total_volume) {
124 m_macro_thickness = thickness;
125 m_macro_cross_section = cross_section;
126 m_macro_volume = total_volume;
127 m_has_macro = true;
128 }
129
131 void setThroughThicknessProfile(const std::string& dir, const std::vector<Real>& vf_profile) {
132 m_tt_profiles[dir] = vf_profile;
133 }
134
137 m_solid_bruggeman = b_s;
138 m_has_solid_bruggeman = true;
139 }
140
142 void setParticleSizeDistribution(Real mean_radius, int num_particles,
143 const std::vector<Real>& radii) {
144 m_psd_mean_radius = mean_radius;
145 m_psd_num_particles = num_particles;
146 m_psd_radii = radii;
147 m_has_psd = true;
148 }
149
151 void setDeffTensor(const Real tensor[AMREX_SPACEDIM][AMREX_SPACEDIM]) {
152 for (int r = 0; r < AMREX_SPACEDIM; ++r) {
153 for (int c = 0; c < AMREX_SPACEDIM; ++c) {
154 m_deff_tensor[r][c] = tensor[r][c];
155 }
156 }
157 m_has_deff_tensor = true;
158 }
159
161 void setVoxelSize(Real voxel_size_m) {
162 m_voxel_size_m = voxel_size_m;
163 }
164
165 // --- Build the JSON object ---
166 nlohmann::ordered_json buildJSON() const {
167 nlohmann::ordered_json j;
168
169 // --- openimpala block: native results with full provenance ---
170 auto& oi = j["openimpala"];
171 oi["version"] = OPENIMPALA_VERSION;
172 oi["physics_type"] = m_physics.name;
173 oi["input_file"] = m_input_file;
174 oi["phase_id"] = m_phase_id;
175
176 if (m_physics.bulk_property != 1.0) {
177 oi["bulk_property"] = m_physics.bulk_property;
178 oi["bulk_property_label"] = m_physics.coeff_label + "_bulk";
179 }
180
181 oi["solver"] = m_solver;
182 oi["converged"] = m_converged;
183
184 auto& grid = oi["grid"];
185 grid["nx"] = m_nx;
186 grid["ny"] = m_ny;
187 grid["nz"] = m_nz;
188 grid["box_size"] = m_box_size;
189
190 oi["volume_fraction"] = m_volume_fraction;
191
192 // Per-direction results
193 auto& results = oi["results"];
194 for (const auto& [dir, ratio] : m_deff_ratios) {
195 auto& dir_obj = results[dir];
196 dir_obj[m_physics.ratio_label] = ratio;
197 dir_obj["tortuosity"] = m_physics.tortuosityFactor(ratio, m_volume_fraction);
198
199 if (m_physics.bulk_property != 1.0) {
200 dir_obj[m_physics.eff_property_label] = m_physics.effectiveProperty(ratio);
201 }
202 if (m_physics.type == PhysicsType::ElectricalConductivity) {
203 dir_obj["formation_factor"] = m_physics.formationFactor(ratio);
204 }
205 }
206
207 // D_eff tensor (from homogenization)
208 if (m_has_deff_tensor) {
209 auto& tensor_obj = oi["deff_tensor"];
210 const char* labels[AMREX_SPACEDIM] = {AMREX_D_DECL("X", "Y", "Z")};
211 for (int r = 0; r < AMREX_SPACEDIM; ++r) {
212 for (int c = 0; c < AMREX_SPACEDIM; ++c) {
213 std::string key = std::string(labels[r]) + std::string(labels[c]);
214 tensor_obj[key] = m_deff_tensor[r][c];
215 }
216 }
217 }
218
219 // --- microstructure block: additional geometric parameters ---
220 buildMicrostructureBlock(oi);
221
222 // --- units block: SI unit annotations (BattINFO-aligned) ---
223 buildUnitsBlock(j);
224
225 // --- bpx block: BPX-compatible electrode fragment ---
226 if (!m_bpx_electrode.empty()) {
227 buildBPXBlock(j);
228 }
229
230 // --- provenance block: metadata passthrough for BDF/Faraday Engine ---
231 if (!m_sample_id.empty() || !m_provenance_uri.empty()) {
232 auto& prov = j["provenance"];
233 if (!m_sample_id.empty()) {
234 prov["sample_id"] = m_sample_id;
235 }
236 if (!m_provenance_uri.empty()) {
237 prov["provenance_uri"] = m_provenance_uri;
238 }
239 }
240
241 return j;
242 }
243
244 // --- Write JSON to file ---
245 bool write(const std::string& filepath) const {
246 std::ofstream ofs(filepath);
247 if (!ofs.is_open()) {
248 return false;
249 }
250 ofs << buildJSON().dump(2) << "\n";
251 ofs.close();
252 return true;
253 }
254
255private:
256#ifndef OPENIMPALA_VERSION_STRING
257#define OPENIMPALA_VERSION_STRING "5.0.0"
258#endif
259 static constexpr const char* OPENIMPALA_VERSION = OPENIMPALA_VERSION_STRING;
260
261 // Physics configuration
262 PhysicsConfig m_physics;
263 std::string m_input_file;
264 int m_phase_id = 0;
265
266 // Grid info
267 int m_nx = 0;
268 int m_ny = 0;
269 int m_nz = 0;
270 int m_box_size = 0;
271
272 // Solver info
273 std::string m_solver;
274 bool m_converged = false;
275
276 // Provenance passthrough
277 std::string m_sample_id;
278 std::string m_provenance_uri;
279
280 // Results
281 Real m_volume_fraction = 0.0;
282 std::map<std::string, Real> m_deff_ratios;
283
284 // BPX electrode type (empty = no BPX fragment)
285 std::string m_bpx_electrode;
286
287 // Microstructure parameters
288 Real m_ssa = 0.0;
289 bool m_has_ssa = false;
290 Real m_ssa_raw = 0.0;
291 bool m_has_ssa_raw = false;
292 std::map<int, Real> m_phase_vfs;
293 Real m_macro_thickness = 0.0;
294 Real m_macro_cross_section = 0.0;
295 Real m_macro_volume = 0.0;
296 bool m_has_macro = false;
297 std::map<std::string, std::vector<Real>> m_tt_profiles;
298 Real m_solid_bruggeman = 0.0;
299 bool m_has_solid_bruggeman = false;
300 Real m_psd_mean_radius = 0.0;
301 int m_psd_num_particles = 0;
302 std::vector<Real> m_psd_radii;
303 bool m_has_psd = false;
304 Real m_voxel_size_m = 0.0;
305
306 // D_eff tensor (from homogenization)
307 Real m_deff_tensor[AMREX_SPACEDIM][AMREX_SPACEDIM] = {};
308 bool m_has_deff_tensor = false;
309
310 // --- Build microstructure parameters block ---
311 void buildMicrostructureBlock(nlohmann::ordered_json& oi) const {
312 if (!m_has_ssa && !m_has_ssa_raw && m_phase_vfs.empty() && !m_has_macro &&
313 m_tt_profiles.empty() && !m_has_solid_bruggeman && !m_has_psd) {
314 return;
315 }
316
317 auto& ms = oi["microstructure"];
318
319 if (m_has_ssa) {
320 ms["specific_surface_area"] = m_ssa;
321 }
322 if (m_has_ssa_raw) {
323 ms["specific_surface_area_raw"] = m_ssa_raw;
324 }
325
326 if (!m_phase_vfs.empty()) {
327 auto& pvf = ms["phase_volume_fractions"];
328 for (const auto& [pid, vf] : m_phase_vfs) {
329 pvf[std::to_string(pid)] = vf;
330 }
331 }
332
333 if (m_has_macro) {
334 auto& mg = ms["macro_geometry"];
335 mg["thickness_voxels"] = m_macro_thickness;
336 mg["cross_section_voxels"] = m_macro_cross_section;
337 mg["total_volume_voxels"] = m_macro_volume;
338 }
339
340 if (!m_tt_profiles.empty()) {
341 auto& ttp = ms["through_thickness_profiles"];
342 for (const auto& [dir, profile] : m_tt_profiles) {
343 ttp[dir]["volume_fraction"] = profile;
344 }
345 }
346
347 if (m_has_solid_bruggeman) {
348 ms["solid_phase_bruggeman"] = m_solid_bruggeman;
349 }
350
351 if (m_has_psd) {
352 auto& psd = ms["particle_size"];
353 psd["mean_radius_voxels"] = m_psd_mean_radius;
354 psd["num_particles"] = m_psd_num_particles;
355 psd["radii_voxels"] = m_psd_radii;
356 }
357
358 if (m_voxel_size_m > 0.0) {
359 ms["voxel_size_m"] = m_voxel_size_m;
360 }
361 }
362
363 // --- Build BattINFO-aligned SI unit annotations ---
364 void buildUnitsBlock(nlohmann::ordered_json& j) const {
365 auto& u = j["units"];
366 u["volume_fraction"] = "1";
367 u["tortuosity"] = "1";
368
369 if (m_physics.type == PhysicsType::Diffusion) {
370 u[m_physics.ratio_label] = "1";
371 } else if (m_physics.type == PhysicsType::ElectricalConductivity) {
372 u[m_physics.ratio_label] = "1";
373 u["formation_factor"] = "1";
374 if (m_physics.bulk_property != 1.0) {
375 u[m_physics.eff_property_label] = "S.m-1";
376 }
377 } else if (m_physics.type == PhysicsType::ThermalConductivity) {
378 u[m_physics.ratio_label] = "1";
379 if (m_physics.bulk_property != 1.0) {
380 u[m_physics.eff_property_label] = "W.m-1.K-1";
381 }
382 } else if (m_physics.type == PhysicsType::DielectricPermittivity) {
383 u[m_physics.ratio_label] = "1";
384 if (m_physics.bulk_property != 1.0) {
385 u[m_physics.eff_property_label] = "F.m-1";
386 }
387 } else if (m_physics.type == PhysicsType::MagneticPermeability) {
388 u[m_physics.ratio_label] = "1";
389 if (m_physics.bulk_property != 1.0) {
390 u[m_physics.eff_property_label] = "H.m-1";
391 }
392 }
393 }
394
396 Real meanDeffRatio() const {
397 if (m_deff_ratios.empty())
398 return 0.0;
399 Real sum = 0.0;
400 for (const auto& entry : m_deff_ratios) {
401 sum += entry.second;
402 }
403 return sum / static_cast<Real>(m_deff_ratios.size());
404 }
405
409 static Real bruggeman(Real transport_efficiency, Real porosity) {
410 if (porosity <= 0.0 || porosity >= 1.0 || transport_efficiency <= 0.0) {
411 return 0.0;
412 }
413 return std::log(transport_efficiency) / std::log(porosity);
414 }
415
417 static std::string capitalise(const std::string& s) {
418 if (s.empty())
419 return s;
420 std::string out = s;
421 out[0] = static_cast<char>(std::toupper(static_cast<unsigned char>(out[0])));
422 return out;
423 }
424
425 // --- Build BPX-compatible electrode fragment ---
426 //
427 // BPX key names follow the Faraday Institution BPX standard:
428 // https://github.com/FaradayInstitution/BPX
429 //
430 // Key relationships:
431 // transport_efficiency = D_eff / D_bulk = D_eff_ratio (OpenImpala output)
432 // Bruggeman exponent b: transport_efficiency = porosity^b
433 // porosity = volume_fraction (of the conducting/electrolyte phase)
434 //
435 // The fragment uses the *mean* transport efficiency across computed
436 // directions, since BPX is inherently isotropic. Per-direction values
437 // are available in the openimpala block for anisotropic workflows.
438 void buildBPXBlock(nlohmann::ordered_json& j) const {
439 std::string prefix = (m_bpx_electrode == "separator")
440 ? "Separator"
441 : (capitalise(m_bpx_electrode) + " electrode");
442
443 Real mean_te = meanDeffRatio();
444 Real mean_tau = m_physics.tortuosityFactor(mean_te, m_volume_fraction);
445 Real b = bruggeman(mean_te, m_volume_fraction);
446
447 auto& bpx = j["bpx"];
448 bpx["_comment"] = "BPX-compatible fragment. Merge into a full BPX file for PyBaMM import.";
449 bpx["electrode"] = m_bpx_electrode;
450
451 auto& params = bpx["Parameterisation"][prefix];
452 params["Porosity"] = m_volume_fraction;
453 params["Transport efficiency"] = mean_te;
454 params["Bruggeman coefficient (electrolyte)"] = b;
455
456 // Microstructure parameters in BPX
457 if (m_has_solid_bruggeman) {
458 params["Bruggeman coefficient (electrode)"] = m_solid_bruggeman;
459 }
460 if (m_has_psd && m_voxel_size_m > 0.0) {
461 params["Particle radius [m]"] = m_psd_mean_radius * m_voxel_size_m;
462 }
463 if (m_has_macro && m_voxel_size_m > 0.0) {
464 const char* thick_key =
465 (m_bpx_electrode == "separator") ? "Thickness [m]" : "Electrode thickness [m]";
466 params[thick_key] = m_macro_thickness * m_voxel_size_m;
467 }
468
469 // Per-direction transport efficiencies (BPX extension — not in base spec)
470 if (m_deff_ratios.size() > 1) {
471 auto& aniso = bpx["anisotropic"];
472 aniso["_comment"] = "Per-direction values (extension, not in base BPX spec)";
473 for (const auto& [dir, ratio] : m_deff_ratios) {
474 aniso["transport_efficiency"][dir] = ratio;
475 aniso["tortuosity"][dir] = m_physics.tortuosityFactor(ratio, m_volume_fraction);
476 }
477 aniso["mean_tortuosity"] = mean_tau;
478 }
479 }
480};
481
482} // namespace OpenImpala
483
484#endif // RESULTSJSON_H
Maps solver output to physical quantities (diffusion, conductivity, thermal, etc.).
#define OPENIMPALA_VERSION_STRING
Definition ResultsJSON.H:257
Definition ResultsJSON.H:56
void setMultiPhaseVolumeFractions(const std::map< int, Real > &phase_vfs)
Set multi-phase volume fractions (phase_id -> VF).
Definition ResultsJSON.H:118
void setSolidPhaseBruggeman(Real b_s)
Set solid-phase Bruggeman exponent.
Definition ResultsJSON.H:136
void setDeffTensor(const Real tensor[3][3])
Set the full effective diffusivity tensor (from homogenization).
Definition ResultsJSON.H:151
void setProvenance(const std::string &sample_id, const std::string &provenance_uri)
Definition ResultsJSON.H:84
bool write(const std::string &filepath) const
Definition ResultsJSON.H:245
void setVolumeFraction(Real vf)
Definition ResultsJSON.H:89
void setParticleSizeDistribution(Real mean_radius, int num_particles, const std::vector< Real > &radii)
Set particle size distribution results.
Definition ResultsJSON.H:142
nlohmann::ordered_json buildJSON() const
Definition ResultsJSON.H:166
void setGridInfo(int nx, int ny, int nz, int box_size)
Definition ResultsJSON.H:72
void setPhysicsConfig(const PhysicsConfig &cfg)
Definition ResultsJSON.H:60
void setVoxelSize(Real voxel_size_m)
Set voxel size in meters for unit conversion in BPX output.
Definition ResultsJSON.H:161
void setBPXElectrode(const std::string &electrode)
Definition ResultsJSON.H:99
void setInputFile(const std::string &filename)
Definition ResultsJSON.H:64
void setSpecificSurfaceArea(Real ssa)
Set corrected specific surface area (Cauchy-Crofton corrected, voxel units).
Definition ResultsJSON.H:106
void setSolverInfo(const std::string &solver, bool converged)
Definition ResultsJSON.H:79
void setPhaseId(int phase_id)
Definition ResultsJSON.H:68
void setSpecificSurfaceAreaRaw(Real ssa_raw)
Set raw specific surface area (uncorrected voxel face count per volume).
Definition ResultsJSON.H:112
void setThroughThicknessProfile(const std::string &dir, const std::vector< Real > &vf_profile)
Set through-thickness volume fraction profile for a direction.
Definition ResultsJSON.H:131
void addDirectionResult(const std::string &dir, Real D_eff_ratio)
Definition ResultsJSON.H:93
void setMacroGeometry(Real thickness, Real cross_section, Real total_volume)
Set macro-geometric parameters (thickness, cross-section, volume).
Definition ResultsJSON.H:123
Definition CathodeWrite.cpp:12
amrex::Real Real
Definition MacroGeometry.H:17
@ ElectricalConductivity
Definition PhysicsConfig.H:54
@ ThermalConductivity
Definition PhysicsConfig.H:55
@ MagneticPermeability
Definition PhysicsConfig.H:57
@ DielectricPermittivity
Definition PhysicsConfig.H:56
@ Diffusion
Definition PhysicsConfig.H:53
Definition PhysicsConfig.H:60