MoCSI API Reference
Loading...
Searching...
No Matches
SimulationClassDefault.h
Go to the documentation of this file.
1#ifndef SIMULATION_CLASS_DEFAULT_H
2#define SIMULATION_CLASS_DEFAULT_H
3
4#include <iostream>
5#include <map>
6#include <memory>
7#include <string>
8#include <valarray>
9#include <vector>
10
11#include "ChainManager.h"
12#include "CsvParser.h"
13#include "ElementManager.h"
14#include "GenericSolver.h"
15#include "GridFactory.h"
16#include "InputManager.h"
17#include "MatrixFactory.h"
18#include "MatrixManager.h"
19#include "ModuleFactory.h"
20#include "SetupRunner.h"
21#include "ShapeFactory.h"
22#include "SimulationClassBase.h"
23#include "SnapshotCreator.h"
24#include "SnapshotLoader.h"
27
28#ifdef MPI_PRESENT
29#include <mpi.h>
30
33#endif
34
35template <typename T>
37{
38 public:
39 std::string m_dependent_variable_name{"Temperature"};
40 std::string m_dependent_variable_initial_state{"initial_temperature"};
41
42 std::vector<std::shared_ptr<GenericManagingModule<T>>> m_all_modules{};
43 std::vector<std::shared_ptr<GenericSubmodule<T>>> m_all_submodules{};
44
46 SimulationClassDefault(int argc, const char* argv[]);
47 SimulationClassDefault(const std::string& user_ini);
48
49 int run() override;
50
51 ~SimulationClassDefault() override = default;
52};
53
54template <typename T>
58
59template <typename T>
64
65template <typename T>
70
71template <typename T>
73{
75 snapshot_data.overwriteSimConfig(this);
76
77 // Loading of the shape model so that all the mesh info is available at grid creation.
78 std::unique_ptr<ShapeFactory<T>> shape_creator;
79 std::shared_ptr<ShapeBase<T>> simulation_shape;
80 try
81 {
82 shape_creator = std::make_unique<ShapeFactory<T>>(
83 this, this->m_simulation_config.getBoolParameters("use_shape_file"),
84 this->m_simulation_config.getStringParameters("spatial_dimension"));
85 simulation_shape = shape_creator->getShapePtr();
86 }
87 catch (const BadInput& e)
88 {
89 // Map access errors.
90 std::cerr << "[SimulationClassDefault]: Failed creating ShapeBase object from ShapeFactory "
91 << e.what() << '\n';
92 throw BadInput(
93 static_cast<std::string>(
94 "[SimulationClassDefault]: Failed creating ShapeBase object from ShapeFactory ")
95 + static_cast<std::string>(e.what()));
96 }
97 catch (const std::runtime_error& e)
98 {
99 // ShapeFactory internal errors.
100 std::cerr << "[SimulationClassDefault]: Failed creating ShapeBase object from ShapeFactory "
101 << e.what() << '\n';
102 throw std::runtime_error(
103 static_cast<std::string>(
104 "[SimulationClassDefault]: Failed creating ShapeBase object from ShapeFactory ")
105 + static_cast<std::string>(e.what()));
106 }
107
108#ifdef MPI_PRESENT
110#endif
111
112 std::unique_ptr<GridFactory<T>> grid_creator;
113 std::shared_ptr<GridBase<T>> simulation_grid;
114 try
115 {
116 grid_creator = std::make_unique<GridFactory<T>>(
117 this, simulation_shape,
118 this->m_simulation_config.getStringParameters("spatial_dimension"));
119 simulation_grid = grid_creator->getGridPtr();
120 }
121 catch (const BadInput& e)
122 {
123 // Map access errors or GridBase internal errors.
124 std::cerr << "[SimulationClassDefault]: Failed creating GridBase object from GridFactory "
125 << e.what() << '\n';
126 throw BadInput(
127 static_cast<std::string>(
128 "[SimulationClassDefault]: Failed creating GridBase object from GridFactory ")
129 + static_cast<std::string>(e.what()));
130 }
131 catch (const std::runtime_error& e)
132 {
133 // GridFactory internal errors.
134 std::cerr << "[SimulationClassDefault]: Failed creating GridBase object from GridFactory "
135 << e.what() << '\n';
136 throw std::runtime_error(
137 static_cast<std::string>(
138 "[SimulationClassDefault]: Failed creating GridBase object from GridFactory ")
139 + static_cast<std::string>(e.what()));
140 }
141
142#ifdef MPI_PRESENT
143 // After (potentially) updating the numerical layers, the final splitting point of larger to
144 // smaller processes can be calculated.
145 try
146 {
148 * (this->min_number_facets_per_proc + 1)
149 * this->m_simulation_config.getIntParameters("numerical_layers");
150 }
151 catch (const BadInput& e)
152 {
153 std::cerr << "[SimulationClassDefault]: Failed creating GridBase object from GridFactory "
154 << e.what() << '\n';
155 throw BadInput(
156 static_cast<std::string>(
157 "[SimulationClassDefault]: Failed creating GridBase object from GridFactory ")
158 + static_cast<std::string>(e.what()));
159 }
160#endif
161
162 try
163 {
164 this->m_field_map.insert(
165 {m_dependent_variable_name,
166 std::valarray<T>(
167 this->m_simulation_config.getDoubleParameters(m_dependent_variable_initial_state),
168 this->m_simulation_config.getIntParameters("numerical_layers")
169 * this->m_simulation_config.getIntParameters("number_of_facets"))});
170 }
171 catch (const BadInput& e)
172 {
173 std::cerr << "[SimulationClassDefault]: Failed to create main independent variable field "
174 "(usually temperature) "
175 << e.what() << '\n';
176 throw BadInput(static_cast<std::string>("[SimulationClassDefault]: Failed to create main "
177 "independent variable field (usually temperature) ")
178 + static_cast<std::string>(e.what()));
179 }
180
181 std::shared_ptr<MatrixFactory<T>> matrix_factory;
182 std::shared_ptr<ElementManager<T>> element_manager;
183 std::shared_ptr<MatrixManager<T>> matrix_manager;
184 try
185 {
186 matrix_factory = std::make_shared<MatrixFactory<T>>("Csr");
187
188 element_manager = std::make_shared<ElementManager<T>>(
189 simulation_grid->getGridSize(), simulation_grid->getCells(), matrix_factory);
190
191 matrix_manager = std::make_shared<MatrixManager<T>>(simulation_grid->getGridSize(), this,
193 }
194 catch (const BadInput& e)
195 {
196 // Map access errors or MatrixManager internal errors.
197 std::cerr << "[SimulationClassDefault]: Failed matrix build step " << e.what() << '\n';
198 throw BadInput(
199 static_cast<std::string>("[SimulationClassDefault]: Failed matrix build step ")
200 + static_cast<std::string>(e.what()));
201 }
202 catch (const std::runtime_error& e)
203 {
204 // ElementManager internal errors.
205 std::cerr << "[SimulationClassDefault]: Failed matrix build step at ElementManager "
206 << e.what() << '\n';
207 throw std::runtime_error(
208 static_cast<std::string>(
209 "[SimulationClassDefault]: Failed matrix build step at ElementManager ")
210 + static_cast<std::string>(e.what()));
211 }
212 catch (const std::invalid_argument& e)
213 {
214 // MatrixFactory internal errors.
215 std::cerr << "[SimulationClassDefault]: Failed matrix build step at MatrixFactory "
216 << e.what() << '\n';
217 throw std::runtime_error(
218 static_cast<std::string>(
219 "[SimulationClassDefault]: Failed matrix build step at MatrixFactory ")
220 + static_cast<std::string>(e.what()));
221 }
222
224
225 try
226 {
227 // Create the modules and allow static access
231 }
232 catch (const std::runtime_error& e)
233 {
234 std::cerr << "[SimulationClassDefault]: Failed at module or submodule creation step "
235 << e.what() << '\n';
236 throw std::runtime_error(
237 static_cast<std::string>(
238 "[SimulationClassDefault]: Failed at module or submodule creation step ")
239 + static_cast<std::string>(e.what()));
240 }
241
242 try
243 {
244 snapshot_data.overwriteIniFiles(this, m_all_modules, m_all_submodules);
245 }
246 catch (const std::runtime_error& e)
247 {
248 // This branch gets triggered when a module is in the snapshot but it was not loaded in this
249 // simulation/ModuleFactory.cpp.
250 std::cerr << "[SimulationClassDefault]: Failed at loading snapshot ini values due do "
251 "unloaded module that was requested in snapshot "
252 << e.what() << '\n';
253 throw std::runtime_error(
254 static_cast<std::string>(
255 "[SimulationClassDefault]: Failed at loading snapshot ini values ")
256 + static_cast<std::string>(e.what()));
257 }
258 catch (const BadInput& e)
259 {
260 // This branch should only be triggered when some sort of corruption occured to the snapshot
261 // data.
262 std::cerr << "[SimulationClassDefault]: Failed at loading snapshot ini values " << e.what()
263 << '\n';
264 throw std::runtime_error(
265 static_cast<std::string>(
266 "[SimulationClassDefault]: Failed at loading snapshot ini values ")
267 + static_cast<std::string>(e.what()));
268 }
269
270 try
271 {
272 // If a user supplied managing module list is present, use this
273 global_chain.autoLoader(
274 m_all_modules, this->m_simulation_config.getStringVectorParameters("managing_modules"));
275 }
277 {
278 std::cerr
279 << "[SimulationClassDefault]: Failed to resolve dependencies for selected modules "
280 << e.what() << '\n';
281 throw std::runtime_error(
282 static_cast<std::string>("[SimulationClassDefault]: (DependencyError) Failed to "
283 "resolve dependencies for selected modules ")
284 + static_cast<std::string>(e.what()));
285 }
286 catch (const BadInput& e)
287 {
288 std::cerr
289 << "[SimulationClassDefault]: Warning - Failed to load managing modules from config: "
290 << e.what() << "\n"
291 << "Falling back to loading all modules.\n";
292 try
293 {
294 global_chain.autoLoader(m_all_modules);
295 }
297 {
298 std::cerr << "[SimulationClassDefault]: Failed to resolve dependencies for all modules "
299 << e.what() << '\n';
300 throw std::runtime_error(
301 static_cast<std::string>("[SimulationClassDefault]: (DependencyError) Failed to "
302 "resolve dependencies for all modules ")
303 + static_cast<std::string>(e.what()));
304 }
305 }
306 try
307 {
308 runSetup<T>(m_all_modules, m_all_submodules, global_chain.getManagingModuleNames());
309 }
310 catch (const BadInput& e)
311 {
312 // runSetup itself does not throw an error but has a high chance to trigger a BadInput
313 // within the setup functions of the modules.
314 std::cerr << "[SimulationClassDefault]: Failed at setting up the modules " << e.what()
315 << '\n';
316 throw std::runtime_error(
317 static_cast<std::string>("[SimulationClassDefault]: Failed at setting up the modules ")
318 + static_cast<std::string>(e.what()));
319 }
320
321 try
322 {
323 snapshot_data.overwriteSimFields(this);
324 }
325 catch (const BadInput& e)
326 {
327 // This branch should only be triggered when some sort of corruption occured to the snapshot
328 // data.
329 std::cerr << "[SimulationClassDefault]: Failed at loading snapshot field values "
330 << e.what() << '\n';
331 throw std::runtime_error(
332 static_cast<std::string>(
333 "[SimulationClassDefault]: Failed at loading snapshot field values ")
334 + static_cast<std::string>(e.what()));
335 }
336
337 // Insertion point "Init"
338 this->setInitChainStr();
339 global_chain.runChain(this->m_current_position);
340
341 // this->printField("HeliocentricDistance");
342
343 // Solver reads matrix size from sim class, so has to be created after matrix size is set.
344 std::shared_ptr<SolverInterface<T>> solver;
345 try
346 {
347 solver = std::make_shared<TridiagonalMatrixSolver<T>>(this, matrix_manager);
348 }
349 catch (const MatrixOutOfBoundsError& e)
350 {
351 // If there somehow was a mismatch between elements and matrix size this would trigger.
352 std::cerr << "[SimulationClassDefault]: Failed at creating Solver " << e.what() << '\n';
353 throw std::runtime_error(
354 static_cast<std::string>(
355 "[SimulationClassDefault]: (MatrixOutOfBoundsError) Failed at creating Solver ")
356 + static_cast<std::string>(e.what()));
357 }
358 catch (const StaticSparseMatrixAccessError& e)
359 {
360 // This should only trigger if there is a mismatch of solver type and grid type.
361 std::cerr << "[SimulationClassDefault]: Failed at creating Solver " << e.what() << '\n';
362 throw std::runtime_error(
363 static_cast<std::string>("[SimulationClassDefault]: (StaticSparseMatrixAccessError) "
364 "Failed at creating Solver ")
365 + static_cast<std::string>(e.what()));
366 }
367
370#ifdef MPI_PRESENT
373#endif
374 try
375 {
376 timesteps = static_cast<int>(this->m_simulation_config.getDoubleParameters("time_max")
377 / this->m_simulation_config.getDoubleParameters("time_delta"));
378 inner_iterations = this->m_simulation_config.getIntParameters("inner_iterations");
379 epsilon_abs = this->m_simulation_config.getDoubleParameters("epsilon_inner_iterations");
381 this->m_simulation_config.getDoubleParameters("relative_epsilon_inner_iterations");
382 delta_t = this->m_simulation_config.getDoubleParameters("time_delta");
383 }
384 catch (const BadInput& e)
385 {
386 std::cerr << "[SimulationClassDefault]" << e.what() << '\n';
387 throw BadInput(static_cast<std::string>("[SimulationClassDefault]")
388 + static_cast<std::string>(e.what()));
389 }
390
391 while (this->time_step * delta_t < this->m_simulation_config.getDoubleParameters("time_max"))
392 {
394 this->m_field_map[m_dependent_variable_name]};
396 this->m_field_map[m_dependent_variable_name]};
397 this->elapsed_time += delta_t;
398 this->time_step++;
399
400 // this->m_field_map["SolarVector"][0] = cos(this->time_step * 0.36 * std::numbers::pi /
401 // 180); this->m_field_map["SolarVector"][2] = sin(this->time_step * 0.36 * std::numbers::pi
402 // / 180);
403 for (int iter{0}; iter < inner_iterations; iter++)
404 {
405 // Insertion point "PreTimeStep"
406 this->setPreTimeStepChainStr();
407 global_chain.runChain(this->m_current_position);
408
410 {
411 // Change temperature field after the module run, so they use the updated
412 // temperatures!
413 this->m_field_map[m_dependent_variable_name] = dependent_variable_previous_timestep;
414 }
415
416 // Do something with the temperature field
417 element_manager->assembleFemMatrices();
418 matrix_manager->assembleGlobalLse(element_manager->m_capacitance_matrix,
419 element_manager->m_stiffness_matrix,
420 element_manager->m_forcing_vector);
421 solver->solveMatrixSystem(m_dependent_variable_name);
422
423 // Insertion point "PostNonLinIter"
424 this->setPostNonLinIterChainStr();
425 global_chain.runChain(this->m_current_position);
426
427#ifdef MPI_PRESENT
429 - this->m_field_map[m_dependent_variable_name]))
430 .max();
431 MPI_Iallreduce(&this->local_convergence_diff, &this->global_convergence_diff, 1,
434 max_var_local = (this->m_field_map[m_dependent_variable_name]).max();
436 {
438 }
442 if (this->global_convergence_diff < epsilon_abs || inner_iterations == 1)
443 {
444 break;
445 }
446 else if (this->global_convergence_diff / this->max_var_value < epsilon_rel)
447 {
448 break;
449 }
450#else
451 this->global_convergence_diff = abs(dependent_variable_previous_iteration
452 - this->m_field_map[m_dependent_variable_name])
453 .max();
454 if (this->global_convergence_diff < epsilon_abs || inner_iterations == 1)
455 {
456 break;
457 }
458 // Relative criterion: normalise the inter-iteration difference by the
459 // larger of the previous and current field maxima. This matches the
460 // MPI path, where max_var_value is reduced with MPI_MAX.
461 else if (this->global_convergence_diff
463 (this->m_field_map[m_dependent_variable_name]).max())
464 < epsilon_rel)
465 {
466 break;
467 }
468#endif
469 if (iter < inner_iterations - 1)
470 {
472 this->m_field_map[m_dependent_variable_name];
473 }
474 else
475 {
476 std::cerr << "[SimulationClassDefault]: Warning - Reached specified inner "
477 "iterations limit without fullfilling the "
478 "requested convergence criterion.\n";
479 }
480 }
481 // this->time_step++;
482 // Insertion point "PostTimeStep"
483 this->setPostTimeStepChainStr();
484 global_chain.runChain(this->m_current_position);
485
486 delta_t = this->m_simulation_config.getDoubleParameters("time_delta");
487
488 // this->printField(m_dependent_variable_name);
489 }
490
491 // Insertion point "Output"
492 this->setOutputChainStr();
493 global_chain.runChain(this->m_current_position);
494
495#ifdef MPI_PRESENT
496 if (this->world_size > 1)
497 {
498 std::valarray<T> global_temperature(
499 this->m_simulation_config.getIntParameters("numerical_layers")
500 * this->m_simulation_config.getIntParameters("global_number_of_facets"));
501 commPatternAllDataToAll(global_temperature, this->getField("Temperature"), this);
502 if (this->my_rank == 0)
503 {
504 std::cout << "Full temperature:\n";
505 for (const auto& val : global_temperature)
506 {
507 std::cout << val << " ";
508 }
509 std::cout << "\n";
510 }
511 }
512 else
513 {
514 this->printField(m_dependent_variable_name);
515 }
516#else
517 this->printField(m_dependent_variable_name);
518#endif
519
520 SnapshotCreator{this, m_all_modules, m_all_submodules};
521 // this->printField("HeatConductivity");
522 // this->printField("HeatCapacity");
523 // this->printField("Density");
524
525 return 0;
526}
527
528#endif
This error class inherits from std::exception and marks faulty parameter or CL inputs....
Definition IniParser.h:71
Concrete implementation of a matrix class representing a Compressed Sparse Rows (CSR) matrix....
Definition CsrMatrix.h:37
CsrSparseMatrix()
Constructor for an empty CsrSparseMatrix object. Leaves all storage arrays empty but sets the flag to...
Definition CsrMatrix.h:94
Error class to throw when a module chain has circular or missing dependencies. Inherits from std::exc...
Definition ChainManager.h:28
Error class to throw when the matrix is accessed out of bounds. Inherits from std::exception.
Definition GenericMatrix.h:152
Definition SimulationClassBase.h:19
Definition SimulationClassDefault.h:37
std::vector< std::shared_ptr< GenericSubmodule< T > > > m_all_submodules
Definition SimulationClassDefault.h:43
std::string m_dependent_variable_initial_state
Definition SimulationClassDefault.h:40
SimulationClassDefault()
Definition SimulationClassDefault.h:55
std::vector< std::shared_ptr< GenericManagingModule< T > > > m_all_modules
Definition SimulationClassDefault.h:42
int run() override
Definition SimulationClassDefault.h:72
~SimulationClassDefault() override=default
std::string m_dependent_variable_name
Definition SimulationClassDefault.h:39
Class which creates MoCSI snapshot files. Saves all the specified fields from m_save_fields and all t...
Definition SnapshotCreator.h:27
static std::vector< std::shared_ptr< GenericSubmodule< T > > > & getAllSelectedSubmodules()
Get all selected submodules (static).
Definition StaticModuleContainer.h:82
static std::vector< std::shared_ptr< GenericManagingModule< T > > > & getAllSelectedManagingModules()
Get all selected managing modules (static).
Definition StaticModuleContainer.h:72
Error class to be thrown when a zero element is tried to be accessed as a reference.
Definition CsrMatrix.h:17