ryujin 2.1.1 revision 0348cbb53a3e4b1da2a4c037e81f88f2d21ce219
quantities.template.h
Go to the documentation of this file.
1//
2// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3// Copyright (C) 2020 - 2024 by the ryujin authors
4//
5
6#pragma once
7
8#include "openmp.h"
9#include "quantities.h"
10
11#include <deal.II/base/function_parser.h>
12#include <deal.II/base/mpi.templates.h>
13#include <deal.II/base/work_stream.h>
14#include <deal.II/dofs/dof_tools.h>
15
16#include <fstream>
17
18DEAL_II_NAMESPACE_OPEN
19template <int rank, int dim, typename Number>
20bool operator<(const Tensor<rank, dim, Number> &left,
21 const Tensor<rank, dim, Number> &right)
22{
23 return std::lexicographical_compare(
24 left.begin_raw(), left.end_raw(), right.begin_raw(), right.end_raw());
25}
26DEAL_II_NAMESPACE_CLOSE
27
28namespace ryujin
29{
30 using namespace dealii;
31
32 namespace
33 {
34 template <typename T>
35 const std::string &get_options_from_name(const T &manifolds,
36 const std::string &name)
37 {
38 const auto it =
39 std::find_if(manifolds.begin(),
40 manifolds.end(),
41 [&, name = std::cref(name)](const auto &element) {
42 return std::get<0>(element) == name.get();
43 });
44 Assert(it != manifolds.end(), dealii::ExcInternalError());
45 return std::get<2>(*it);
46 }
47 } // namespace
48
49
50 template <typename Description, int dim, typename Number>
52 const MPIEnsemble &mpi_ensemble,
53 const OfflineData<dim, Number> &offline_data,
54 const HyperbolicSystem &hyperbolic_system,
55 const ParabolicSystem &parabolic_system,
56 const std::string &subsection /*= "Quantities"*/)
57 : ParameterAcceptor(subsection)
58 , mpi_ensemble_(mpi_ensemble)
59 , offline_data_(&offline_data)
60 , hyperbolic_system_(&hyperbolic_system)
61 , parabolic_system_(&parabolic_system)
62 , base_name_("")
63 , mesh_files_have_been_written_(false)
64 {
65 add_parameter("interior manifolds",
66 interior_manifolds_,
67 "List of level set functions describing interior manifolds. "
68 "The description is used to only output point values for "
69 "vertices belonging to a certain level set. "
70 "Format: '<name> : <level set formula> : <options> , [...] "
71 "(options: time_averaged, space_averaged, instantaneous)");
72
73 add_parameter("boundary manifolds",
74 boundary_manifolds_,
75 "List of level set functions describing boundary. The "
76 "description is used to only output point values for "
77 "boundary vertices belonging to a certain level set. "
78 "Format: '<name> : <level set formula> : <options> , [...] "
79 "(options: time_averaged, space_averaged, instantaneous)");
81 clear_temporal_statistics_on_writeout_ = true;
82 add_parameter("clear statistics on writeout",
83 clear_temporal_statistics_on_writeout_,
84 "If set to true then all temporal statistics (for "
85 "\"time_averaged\" quantities) accumulated so far are reset "
86 "each time a writeout of quantities is performed");
87 }
88
89
90 template <typename Description, int dim, typename Number>
92 {
93#ifdef DEBUG_OUTPUT
94 std::cout << "Quantities<dim, Number>::prepare()" << std::endl;
95#endif
96
97 base_name_ = name;
98
99 /* Force to write to a new time series file: */
100 time_series_cycle_.reset();
101
102 const unsigned int n_owned = offline_data_->n_locally_owned();
103 const auto &sparsity_simd = offline_data_->sparsity_pattern_simd();
104
105 /*
106 * Create interior maps and allocate statistics.
107 *
108 * We have to loop over the cells and populate the std::map interior_maps_.
109 */
110
111 interior_maps_.clear();
112 std::transform(
113 interior_manifolds_.begin(),
114 interior_manifolds_.end(),
115 std::inserter(interior_maps_, interior_maps_.end()),
116 [this, n_owned, &sparsity_simd](auto it) {
117 const auto &[name, expression, option] = it;
118 FunctionParser<dim> level_set_function(expression);
119
120 std::vector<interior_point> map;
121 std::map<int, interior_point> preliminary_map;
122
123 const auto &discretization = offline_data_->discretization();
124 const auto &dof_handler = offline_data_->dof_handler();
125
126 const unsigned int dofs_per_cell = dof_handler.get_fe().dofs_per_cell;
127
128 const auto support_points =
129 dof_handler.get_fe().get_unit_support_points();
130
131 std::vector<dealii::types::global_dof_index> local_dof_indices(
132 dofs_per_cell);
133
134 /* Loop over cells */
135 for (auto cell : dof_handler.active_cell_iterators()) {
136
137 /* skip if not locally owned */
138 if (!cell->is_locally_owned())
139 continue;
140
141 cell->get_active_or_mg_dof_indices(local_dof_indices);
142
143 for (unsigned int j = 0; j < dofs_per_cell; ++j) {
144
145 Point<dim> position =
146 discretization.mapping().transform_unit_to_real_cell(
147 cell, support_points[j]);
148
149 /*
150 * Insert index, interior mass value and position into
151 * a preliminary map if we satisfy level set condition.
152 */
153
154 if (std::abs(level_set_function.value(position)) > 1.e-12)
155 continue;
156
157 const auto global_index = local_dof_indices[j];
158 const auto index =
159 offline_data_->scalar_partitioner()->global_to_local(
160 global_index);
161
162 /* Skip constrained degrees of freedom: */
163 const unsigned int row_length = sparsity_simd.row_length(index);
164 if (row_length == 1)
165 continue;
166
167 if (index >= n_owned)
168 continue;
169
170 const Number interior_mass =
171 offline_data_->lumped_mass_matrix().local_element(index);
172 // FIXME: change to std::set
173 preliminary_map[index] = {index, interior_mass, position};
174 }
175 }
176
177 /*
178 * Now we populate the std::vector(interior_point) object called map.
179 */
180 // FIXME: use std::copy
181 for (const auto &[index, tuple] : preliminary_map) {
182 map.push_back(tuple);
183 }
184
185 return std::make_pair(name, map);
186 });
187
188 /*
189 * Create boundary maps and allocate statistics vector:
190 *
191 * We want to loop over the boundary_map() once and populate the map
192 * object boundary_maps_. We have to create a vector of
193 * boundary_manifolds.size() that holds a std::vector<boundary_point>
194 * for each map entry.
195 */
196
197 boundary_maps_.clear();
198 std::transform(
199 boundary_manifolds_.begin(),
200 boundary_manifolds_.end(),
201 std::inserter(boundary_maps_, boundary_maps_.end()),
202 [this, n_owned](auto it) {
203 const auto &[name, expression, option] = it;
204 FunctionParser<dim> level_set_function(expression);
205
206 std::vector<boundary_point> map;
207
208 for (const auto &entry : offline_data_->boundary_map()) {
209 // [i, normal, normal_mass, boundary_mass, id, position] = entry
210 const auto &i = std::get<0>(entry);
211
212 /* skip nonlocal */
213 if (i >= n_owned)
214 continue;
215
216 /* skip constrained */
217 if (offline_data_->affine_constraints().is_constrained(
218 offline_data_->scalar_partitioner()->local_to_global(i)))
219 continue;
220
221 const auto &position = std::get<5>(entry);
222 if (std::abs(level_set_function.value(position)) < 1.e-12)
223 map.push_back(entry);
224 }
225 return std::make_pair(name, map);
226 });
227
228 /* Clear statistics: */
229 clear_statistics();
230
231 /* Make sure we output new mesh files: */
232 mesh_files_have_been_written_ = false;
233
234 /* Prepare header string: */
235 const auto &names = View::primitive_component_names;
236 header_ = std::accumulate(
237 std::begin(names),
238 std::end(names),
239 std::string(),
240 [](const std::string &description, const std::string &name) {
241 return description.empty()
242 ? (std::string("primitive state (") + name)
243 : (description + ", " + name);
244 }) +
245 ")\t and 2nd moments\n";
246 }
247
248
249 template <typename Description, int dim, typename Number>
250 void
251 Quantities<Description, dim, Number>::write_mesh_files(unsigned int cycle)
252 {
253 /*
254 * Output interior maps:
255 */
256
257 for (const auto &[name, interior_map] : interior_maps_) {
258 /* Skip outputting the boundary map for spatial averages. */
259 const auto &options = get_options_from_name(interior_manifolds_, name);
260 if (options.find("instantaneous") == std::string::npos &&
261 options.find("time_averaged") == std::string::npos)
262 continue;
263
264 /*
265 * FIXME: This currently distributes boundary maps to all MPI ranks.
266 * This is unnecessarily wasteful. Ideally, we should do MPI IO with
267 * only MPI ranks participating who actually have boundary values.
268 */
269
270 const auto received = Utilities::MPI::gather(
271 mpi_ensemble_.ensemble_communicator(), interior_map);
272
273 if (Utilities::MPI::this_mpi_process(
274 mpi_ensemble_.ensemble_communicator()) == 0) {
275
276 std::ofstream output(base_name_ + "-" + name + "-R" +
277 Utilities::to_string(cycle, 4) + "-points.dat");
278
279 output << std::scientific << std::setprecision(14);
280
281 output << "#\n# position\tinterior mass\n";
282
283 unsigned int rank = 0;
284 for (const auto &entries : received) {
285 output << "# rank " << rank++ << "\n";
286 for (const auto &entry : entries) {
287 const auto &[index, mass_i, x_i] = entry;
288 output << x_i << "\t" << mass_i << "\n";
289 } /*entry*/
290 } /*entries*/
291
292 output << std::flush;
293 }
294 }
295
296 /*
297 * Output boundary maps:
298 */
299
300 for (const auto &[name, boundary_map] : boundary_maps_) {
301 /* Skip outputting the boundary map for spatial averages. */
302 const auto &options = get_options_from_name(boundary_manifolds_, name);
303 if (options.find("instantaneous") == std::string::npos &&
304 options.find("time_averaged") == std::string::npos)
305 continue;
306
307 /*
308 * FIXME: This currently distributes boundary maps to all MPI ranks.
309 * This is unnecessarily wasteful. Ideally, we should do MPI IO with
310 * only MPI ranks participating who actually have boundary values.
311 */
312
313 const auto received = Utilities::MPI::gather(
314 mpi_ensemble_.ensemble_communicator(), boundary_map);
315
316 if (Utilities::MPI::this_mpi_process(
317 mpi_ensemble_.ensemble_communicator()) == 0) {
318
319 std::ofstream output(base_name_ + "-" + name + "-R" +
320 Utilities::to_string(cycle, 4) + "-points.dat");
321
322 output << std::scientific << std::setprecision(14);
323
324 output << "#\n# position\tnormal\tnormal mass\tboundary mass\n";
325
326 unsigned int rank = 0;
327 for (const auto &entries : received) {
328 output << "# rank " << rank++ << "\n";
329 for (const auto &entry : entries) {
330 const auto &[index, n_i, nm_i, bm_i, id, x_i] = entry;
331 output << x_i << "\t" << n_i << "\t" << nm_i << "\t" << bm_i
332 << "\n";
333 } /*entry*/
334 } /*entries*/
335
336 output << std::flush;
337 }
338 }
339 }
340
341
342 template <typename Description, int dim, typename Number>
343 void Quantities<Description, dim, Number>::clear_statistics()
344 {
345 const auto reset = [](const auto &manifold_map, auto &statistics_map) {
346 for (const auto &[name, data_map] : manifold_map) {
347 const auto n_entries = data_map.size();
348 auto &[val_old, val_new, val_sum, t_old, t_new, t_sum] =
349 statistics_map[name];
350 val_old.resize(n_entries);
351 val_new.resize(n_entries);
352 val_sum.resize(n_entries);
353 t_old = t_new = t_sum = 0.;
354 }
355 };
356
357 /* Clear statistics and time series: */
358
359 interior_statistics_.clear();
360 reset(interior_maps_, interior_statistics_);
361 interior_time_series_.clear();
362
363 boundary_statistics_.clear();
364 reset(boundary_maps_, boundary_statistics_);
365 boundary_time_series_.clear();
366 }
367
368
369 template <typename Description, int dim, typename Number>
370 template <typename point_type, typename value_type>
371 value_type Quantities<Description, dim, Number>::internal_accumulate(
372 const StateVector &state_vector,
373 const std::vector<point_type> &points_vector,
374 std::vector<value_type> &val_new)
375 {
376 const auto &U = std::get<0>(state_vector);
377
378 value_type spatial_average;
379 Number mass_sum = Number(0.);
380
381 std::transform(
382 points_vector.begin(),
383 points_vector.end(),
384 val_new.begin(),
385 [&](auto point) -> value_type {
386 const auto i = std::get<0>(point);
387 /*
388 * Small trick to get the correct index for retrieving the
389 * boundary mass.
390 */
391 constexpr auto index =
392 std::is_same_v<point_type, interior_point> ? 1 : 3;
393 const auto mass_i = std::get<index>(point);
394
395 const auto U_i = U.get_tensor(i);
396 const auto view = hyperbolic_system_->template view<dim, Number>();
397 const auto primitive_state = view.to_primitive_state(U_i);
398
399 value_type result;
400 std::get<0>(result) = primitive_state;
401 /* Compute second moments of the primitive state: */
402 std::get<1>(result) = schur_product(primitive_state, primitive_state);
403
404 mass_sum += mass_i;
405 std::get<0>(spatial_average) += mass_i * std::get<0>(result);
406 std::get<1>(spatial_average) += mass_i * std::get<1>(result);
407
408 return result;
409 });
410
411 /* synchronize MPI ranks (MPI Barrier): */
412
413 mass_sum =
414 Utilities::MPI::sum(mass_sum, mpi_ensemble_.ensemble_communicator());
415
416 std::get<0>(spatial_average) = Utilities::MPI::sum(
417 std::get<0>(spatial_average), mpi_ensemble_.ensemble_communicator());
418 std::get<1>(spatial_average) = Utilities::MPI::sum(
419 std::get<1>(spatial_average), mpi_ensemble_.ensemble_communicator());
420
421 /* take average: */
422
423 std::get<0>(spatial_average) /= mass_sum;
424 std::get<1>(spatial_average) /= mass_sum;
425
426 return spatial_average;
427 }
428
429
430 template <typename Description, int dim, typename Number>
431 template <typename value_type>
432 void Quantities<Description, dim, Number>::internal_write_out(
433 const std::string &file_name,
434 const std::string &time_stamp,
435 const std::vector<value_type> &values,
436 const Number scale)
437 {
438 /*
439 * FIXME: This currently distributes interior maps to all MPI ranks.
440 * This is unnecessarily wasteful. Ideally, we should do MPI IO with
441 * only MPI ranks participating who actually have interior values.
442 */
443
444 const auto received =
445 Utilities::MPI::gather(mpi_ensemble_.ensemble_communicator(), values);
446
447 if (Utilities::MPI::this_mpi_process(
448 mpi_ensemble_.ensemble_communicator()) == 0) {
449
450 std::ofstream output(file_name);
451 output << std::scientific << std::setprecision(14);
452 output << time_stamp << "# " << header_;
453
454 unsigned int rank = 0;
455 for (const auto &entries : received) {
456 output << "# rank " << rank++ << "\n";
457 for (const auto &entry : entries) {
458 const auto &[state, state_square] = entry;
459 output << scale * state << "\t" << scale * state_square << "\n";
460 } /*entry*/
461 } /*entries*/
462
463 output << std::flush;
464 }
465 }
466
467
468 template <typename Description, int dim, typename Number>
469 template <typename value_type>
470 void Quantities<Description, dim, Number>::internal_write_out_time_series(
471 const std::string &file_name,
472 const std::vector<std::tuple<Number, value_type>> &values,
473 bool append)
474 {
475 if (Utilities::MPI::this_mpi_process(
476 mpi_ensemble_.ensemble_communicator()) == 0) {
477 std::ofstream output;
478 output << std::scientific << std::setprecision(14);
479
480 if (append) {
481 output.open(file_name, std::ofstream::out | std::ofstream::app);
482 } else {
483 output.open(file_name, std::ofstream::out | std::ofstream::trunc);
484 output << "# time t\t" << header_;
485 }
486
487 for (const auto &entry : values) {
488 const auto t = std::get<0>(entry);
489 const auto &[state, state_square] = std::get<1>(entry);
490
491 output << t << "\t" << state << "\t" << state_square << "\n";
492 }
493
494 output << std::flush;
495 output.close();
496 }
497 }
498
499
500 template <typename Description, int dim, typename Number>
502 const StateVector &state_vector, const Number t)
503 {
504#ifdef DEBUG_OUTPUT
505 std::cout << "Quantities<dim, Number>::accumulate()" << std::endl;
506#endif
507
508 const auto accumulate = [&](const auto &point_maps,
509 const auto &manifolds,
510 auto &statistics,
511 auto &time_series) {
512 for (const auto &[name, point_map] : point_maps) {
513
514 /* Find the correct option string in manifolds */
515 const auto &options = get_options_from_name(manifolds, name);
516
517 /* skip if we don't average in space or time: */
518 if (options.find("time_averaged") == std::string::npos &&
519 options.find("space_averaged") == std::string::npos)
520 continue;
521
522 auto &[val_old, val_new, val_sum, t_old, t_new, t_sum] =
523 statistics[name];
524
525 std::swap(t_old, t_new);
526 std::swap(val_old, val_new);
527
528 /* accumulate new values */
529
530 const auto spatial_average =
531 internal_accumulate(state_vector, point_map, val_new);
532
533 /* Average in time with trapezoidal rule: */
534
535 if (RYUJIN_UNLIKELY(t_old == Number(0.) && t_new == Number(0.))) {
536 /* We have not accumulated any statistics yet: */
537 t_old = t - 1.;
538 t_new = t;
539
540 } else {
541
542 t_new = t;
543 const Number tau = t_new - t_old;
544
545 for (std::size_t i = 0; i < val_sum.size(); ++i) {
546 std::get<0>(val_sum[i]) += 0.5 * tau * std::get<0>(val_old[i]);
547 std::get<0>(val_sum[i]) += 0.5 * tau * std::get<0>(val_new[i]);
548 std::get<1>(val_sum[i]) += 0.5 * tau * std::get<1>(val_old[i]);
549 std::get<1>(val_sum[i]) += 0.5 * tau * std::get<1>(val_new[i]);
550 }
551 t_sum += tau;
552 }
553
554 /* Record average in space: */
555 time_series[name].push_back({t, spatial_average});
556 }
557 };
558
559 accumulate(interior_maps_,
560 interior_manifolds_,
561 interior_statistics_,
562 interior_time_series_);
563
564 accumulate(boundary_maps_,
565 boundary_manifolds_,
566 boundary_statistics_,
567 boundary_time_series_);
568 }
569
570
571 template <typename Description, int dim, typename Number>
573 const StateVector &state_vector, const Number t, unsigned int cycle)
574 {
575#ifdef DEBUG_OUTPUT
576 std::cout << "Quantities<dim, Number>::write_out()" << std::endl;
577#endif
578
579 /*
580 * First, write out mesh files if this hasn't happened yet.
581 */
582 if (!mesh_files_have_been_written_) {
583 write_mesh_files(cycle);
584 mesh_files_have_been_written_ = true;
585 }
586
587 /*
588 * Next write out instantaneous and time_averaged maps, and flush the
589 * space_averaged values to the corresponding log files:
590 */
591
592 const auto write_out = [&](const auto &point_maps,
593 const auto &manifolds,
594 auto &statistics,
595 auto &time_series) {
596 for (const auto &[name, point_map] : point_maps) {
597
598 /* Find the correct option string in manifolds */
599 const auto &options = get_options_from_name(manifolds, name);
600
601 const auto prefix =
602 base_name_ + "-" + name + "-R" + Utilities::to_string(cycle, 4);
603
604 /*
605 * Compute and output instantaneous field:
606 */
607
608 if (options.find("instantaneous") != std::string::npos) {
609
610 const std::string file_name = prefix + "-instantaneous.dat";
611
612 auto &[val_old, val_new, val_sum, t_old, t_new, t_sum] =
613 statistics[name];
614
615 std::stringstream time_stamp;
616 time_stamp << std::scientific << std::setprecision(14);
617 time_stamp << "# at t = " << t << std::endl;
618
619 /* We have not computed any updated statistics yet: */
620
621 if (options.find("time_averaged") == std::string::npos &&
622 options.find("space_averaged") == std::string::npos)
623 internal_accumulate(state_vector, point_map, val_new);
624 else
625 AssertThrow(t_new == t, dealii::ExcInternalError());
626
627 internal_write_out(file_name, time_stamp.str(), val_new, Number(1.));
628 }
629
630 /*
631 * Output time averaged field:
632 */
633
634 if (options.find("time_averaged") != std::string::npos) {
635
636 const std::string file_name = prefix + "-time_averaged.dat";
637
638 auto &[val_old, val_new, val_sum, t_old, t_new, t_sum] =
639 statistics[name];
640
641 /* Check whether we have accumulated any statistics yet: */
642 if (t_sum != Number(0.)) {
643 std::stringstream time_stamp;
644 time_stamp << std::scientific << std::setprecision(14);
645 time_stamp << "# averaged from t = " << t_new - t_sum
646 << " to t = " << t_new << std::endl;
647
648 internal_write_out(
649 file_name, time_stamp.str(), val_sum, Number(1.) / t_sum);
650 }
651 }
652
653 /*
654 * Output space averaged field:
655 */
656
657 if (options.find("space_averaged") != std::string::npos) {
658 bool append = true;
659 if (!time_series_cycle_.has_value()) {
660 time_series_cycle_ = cycle;
661 append = false;
662 }
663
664 const auto file_name =
665 base_name_ + "-" + name + "-R" +
666 Utilities::to_string(time_series_cycle_.value(), 4) +
667 "-space_averaged_time_series.dat";
668
669 auto &series = time_series[name];
670 internal_write_out_time_series(file_name, series, /*append*/ append);
671 series.clear();
672 }
673 }
674 };
675
676 write_out(interior_maps_,
677 interior_manifolds_,
678 interior_statistics_,
679 interior_time_series_);
680
681 write_out(boundary_maps_,
682 boundary_manifolds_,
683 boundary_statistics_,
684 boundary_time_series_);
685
686 if (clear_temporal_statistics_on_writeout_)
687 clear_statistics();
688 }
689
690} /* namespace ryujin */
typename Description::HyperbolicSystem HyperbolicSystem
Definition: quantities.h:38
typename Description::ParabolicSystem ParabolicSystem
Definition: quantities.h:39
typename View::StateVector StateVector
Definition: quantities.h:46
Quantities(const MPIEnsemble &mpi_ensemble, const OfflineData< dim, Number > &offline_data, const HyperbolicSystem &hyperbolic_system, const ParabolicSystem &parabolic_system, const std::string &subsection="/Quantities")
#define RYUJIN_UNLIKELY(x)
Definition: openmp.h:132
std::tuple< MultiComponentVector< Number, problem_dim >, MultiComponentVector< Number, prec_dim >, BlockVector< Number > > StateVector
Definition: state_vector.h:51
DEAL_II_NAMESPACE_OPEN bool operator<(const Tensor< rank, dim, Number > &left, const Tensor< rank, dim, Number > &right)