Flow123d  release_3.0.0-1264-g45bfb2a
balance.cc
Go to the documentation of this file.
1 /*!
2  *
3  * Copyright (C) 2015 Technical University of Liberec. All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or modify it under
6  * the terms of the GNU General Public License version 3 as published by the
7  * Free Software Foundation. (http://www.gnu.org/licenses/gpl-3.0.en.html)
8  *
9  * This program is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12  *
13  *
14  * @file balance.cc
15  * @ingroup transport
16  * @brief Mass balance
17  */
18 
19 #include <iostream>
20 #include <iomanip>
21 #include <unordered_map>
22 
23 #include "system/system.hh"
24 #include "system/sys_profiler.hh"
25 
26 #include <petscmat.h>
27 #include "mesh/mesh.h"
28 #include "mesh/long_idx.hh"
29 #include "mesh/accessors.hh"
30 #include "io/output_time_set.hh"
31 #include "coupling/balance.hh"
32 #include "tools/unit_si.hh"
33 #include "tools/time_governor.hh"
34 #include "la/distribution.hh"
35 
36 using namespace Input::Type;
37 
38 bool Balance::do_yaml_output_ = true;
39 
41  return Selection("Balance_output_format", "Format of output file for balance.")
42  .add_value(Balance::legacy, "legacy", "Legacy format used by previous program versions.")
43  .add_value(Balance::txt, "txt", "Excel format with tab delimiter.")
44  .add_value(Balance::gnuplot, "gnuplot", "Format compatible with GnuPlot datafile with fixed column width.")
45  .close();
46 }
47 
49  return Record("Balance", "Balance of a conservative quantity, boundary fluxes and sources.")
50  .declare_key("times", OutputTimeSet::get_input_type(), Default("[]"), "" )
51  .declare_key("add_output_times", Bool(), Default("true"), "Add all output times of the balanced equation to the balance output times set. "
52  "Note that this is not the time set of the output stream.")
53  //.declare_key("balance_on", Bool(), Default("true"), "Balance is computed if the value is true.")
54  .declare_key("format", Balance::get_format_selection_input_type(), Default("\"txt\""), "Format of output file.")
55  .declare_key("cumulative", Bool(), Default("false"), "Compute cumulative balance over time. "
56  "If true, then balance is calculated at each computational time step, which can slow down the program.")
57  .declare_key("file", FileName::output(), Default::read_time("File name generated from the balanced quantity: <quantity_name>_balance.*"), "File name for output of balance.")
58  .close();
59 }
60 
63 }
64 
65 /*
66 std::shared_ptr<Balance> Balance::make_balance(
67  const std::string &file_prefix,
68  const Mesh *mesh,
69  const Input::Record &in_rec,
70  TimeGovernor &tg)
71 {
72  auto ptr = make_shared<Balance>(file_prefix, mesh, in_rec, tg);
73  auto &marks = TimeGovernor::marks();
74  auto balance_output_type = tg.equation_mark_type() | TimeGovernor::marks().type_balance_output();
75  if (marks.begin(balance_output_type) == marks.end(balance_output_type) ) {
76  // no balance output time => force balance off
77  ptr.reset();
78  }
79  return ptr;
80 }*/
81 
82 
83 
84 Balance::Balance(const std::string &file_prefix, const Mesh *mesh)
85  : file_prefix_(file_prefix),
86  mesh_(mesh),
87  last_time_(),
88  initial_(true),
89  allocation_done_(false),
90  balance_on_(true),
91  output_line_counter_(0),
92  output_yaml_header_(false)
93 
94 {
95  MPI_Comm_rank(PETSC_COMM_WORLD, &rank_);
97 }
98 
99 
100 
102 {
103  if (rank_ == 0) {
104  output_.close();
105  if (do_yaml_output_) output_yaml_.close();
106  }
107  if (! allocation_done_) return;
108 
109  for (unsigned int c=0; c<quantities_.size(); ++c)
110  {
111  chkerr(MatDestroy(&(region_mass_matrix_[c])));
112  chkerr(MatDestroy(&(be_flux_matrix_[c])));
113  chkerr(MatDestroy(&(region_source_matrix_[c])));
114  chkerr(MatDestroy(&(region_source_rhs_[c])));
115  chkerr(VecDestroy(&(be_flux_vec_[c])));
116  chkerr(VecDestroy(&(region_mass_vec_[c])));
117  }
118  delete[] region_mass_matrix_;
119  delete[] be_flux_matrix_;
120  delete[] be_flux_vec_;
121  delete[] region_source_matrix_;
122  delete[] region_source_rhs_;
123  delete[] region_mass_vec_;
124 }
125 
126 
128  const Input::Record &in_rec,
129  TimeGovernor &tg)
130 {
132 
133  time_ = &tg;
134 
135  auto &marks = TimeGovernor::marks();
136 
137  output_mark_type_ = tg.equation_mark_type() | marks.type_output(),
138  balance_output_type_ = tg.equation_fixed_mark_type() | marks.type_balance_output();
139 
140  cumulative_ = in_rec.val<bool>("cumulative");
141  output_format_ = in_rec.val<OutputFormat>("format");
142 
143  OutputTimeSet time_set;
144  time_set.read_from_input( in_rec.val<Input::Array>("times"), tg, balance_output_type_);
145  add_output_times_ = in_rec.val<bool>("add_output_times");
146 
147  input_record_ = in_rec;
148 
149 }
150 
151 
152 void Balance::units(const UnitSI &unit)
153 {
155 
156  units_ = unit;
157  units_.undef(false);
158 }
159 
160 unsigned int Balance::add_quantity(const string &name)
161 {
163 
164  Quantity q(quantities_.size(), name);
165  quantities_.push_back(q);
166 
167  return q.index_;
168 }
169 
170 
172 {
173  vector<unsigned int> indices;
174  for (auto name : names)
175  indices.push_back(add_quantity(name));
176  return indices;
177 }
178 
179 
180 void Balance::allocate(unsigned int n_loc_dofs,
181  unsigned int max_dofs_per_boundary)
182 {
184  n_loc_dofs_ = n_loc_dofs;
185  max_dofs_per_boundary_ = max_dofs_per_boundary;
186 }
187 
189 {
190  if (allocation_done_) return;
191 
192  auto &marks = TimeGovernor::marks();
193  if (add_output_times_)
194  marks.add_to_type_all(output_mark_type_, balance_output_type_);
195  // if there are no balance marks turn balance off
196  if (marks.begin(balance_output_type_) == marks.end(balance_output_type_) )
197  {
198  balance_on_ = false;
199  cumulative_ = false;
200  return;
201  }
202 
203  // Max. number of regions to which a single dof can contribute.
204  // TODO: estimate or compute this number directly (from mesh or dof handler).
205  const int n_bulk_regs_per_dof = min(10, (int)mesh_->region_db().bulk_size());
206  const unsigned int n_quant = quantities_.size();
207  const unsigned int n_bdr_reg = mesh_->region_db().boundary_size();
208  const unsigned int n_blk_reg = mesh_->region_db().bulk_size();
209 
210 
211  // enumerate boundary edges by unique id and
212  // create map: (local bulk ele idx, side idx) -> boundary edge id
213  // create vector that maps: boundary edge id -> region boundary index
214  unsigned int be_id = 0;
215  for (unsigned int loc_el = 0; loc_el < mesh_->get_el_ds()->lsize(); loc_el++)
216  {
218  if (elm->boundary_idx_ != nullptr)
219  {
220  for(unsigned int si=0; si<elm->n_sides(); si++)
221  {
222  if (elm.side(si)->is_boundary()){
223  Boundary bcd = elm.side(si)->cond();
224  LongIdx ele_side_uid = get_boundary_edge_uid(elm.side(si));
225  be_id_map_[ele_side_uid] = be_id;
226  be_regions_.push_back(bcd.region().boundary_idx());
227  be_id++;
228  }
229  }
230  }
231  }
232 
233 
234  fluxes_ .resize(n_quant, vector<double>(n_bdr_reg, 0));
235  fluxes_in_ .resize(n_quant, vector<double>(n_bdr_reg, 0));
236  fluxes_out_.resize(n_quant, vector<double>(n_bdr_reg, 0));
237 
238  masses_ .resize(n_quant, vector<double>(n_blk_reg, 0));
239  sources_in_ .resize(n_quant, vector<double>(n_blk_reg, 0));
240  sources_out_.resize(n_quant, vector<double>(n_blk_reg, 0));
241 
242  sum_fluxes_ .resize(n_quant, 0);
243  sum_fluxes_in_ .resize(n_quant, 0);
244  sum_fluxes_out_ .resize(n_quant, 0);
245  sum_masses_ .resize(n_quant, 0);
246  sum_sources_ .resize(n_quant, 0);
247  sum_sources_in_ .resize(n_quant, 0);
248  sum_sources_out_.resize(n_quant, 0);
249 
250  if (cumulative_)
251  {
252  initial_mass_ .resize(n_quant, 0);
253  integrated_fluxes_ .resize(n_quant, 0);
254  integrated_sources_.resize(n_quant, 0);
255  increment_sources_.resize(n_quant, 0);
256  increment_fluxes_.resize(n_quant, 0);
257  }
258 
259 
260 
261  region_mass_matrix_ = new Mat[n_quant];
262  be_flux_matrix_ = new Mat[n_quant];
263  region_source_matrix_ = new Mat[n_quant];
264  region_source_rhs_ = new Mat[n_quant];
265  region_mass_vec_ = new Vec[n_quant];
266  be_flux_vec_ = new Vec[n_quant];
267 
268  for (unsigned int c=0; c<n_quant; ++c)
269  {
270  chkerr(MatCreateAIJ(PETSC_COMM_WORLD,
271  n_loc_dofs_,
272  (rank_==0)?mesh_->region_db().bulk_size():0,
273  PETSC_DECIDE,
274  PETSC_DECIDE,
275  (rank_==0)?n_bulk_regs_per_dof:0,
276  0,
277  (rank_==0)?0:n_bulk_regs_per_dof,
278  0,
279  &(region_mass_matrix_[c])));
280 
281  chkerr(MatCreateSeqAIJ(PETSC_COMM_SELF,
282  n_loc_dofs_,
284  n_bulk_regs_per_dof,
285  NULL,
286  &(region_source_matrix_[c])));
287 
288  chkerr(MatCreateSeqAIJ(PETSC_COMM_SELF,
289  n_loc_dofs_,
291  n_bulk_regs_per_dof,
292  NULL,
293  &(region_source_rhs_[c])));
294 
295  chkerr(MatCreateAIJ(PETSC_COMM_WORLD,
296  be_regions_.size(), // n local rows, number of local boundary edges
297  n_loc_dofs_, // n local cols (local rows of multiplying vector)
298  PETSC_DECIDE, // n global rows
299  PETSC_DECIDE, // n global cols
300  max_dofs_per_boundary_, // allocation, local poriton
301  0,
302  0,
303  0,
304  &(be_flux_matrix_[c])));
305 
306  chkerr(VecCreateMPI(PETSC_COMM_WORLD,
307  (rank_==0)?mesh_->region_db().bulk_size():0,
308  PETSC_DECIDE,
309  &(region_mass_vec_[c])));
310 
311  chkerr(VecCreateMPI(PETSC_COMM_WORLD,
312  be_regions_.size(),
313  PETSC_DECIDE,
314  &(be_flux_vec_[c])));
315  }
316 
317  // set be_offset_, used in add_flux_matrix_values()
318  chkerr(VecGetOwnershipRange(be_flux_vec_[0], &be_offset_, NULL));
319 
320  if (rank_ == 0) {
321  // set default value by output_format_
322  std::string default_file_name;
323  switch (output_format_)
324  {
325  case txt:
326  default_file_name = file_prefix_ + "_balance.txt";
327  break;
328  case gnuplot:
329  default_file_name = file_prefix_ + "_balance.dat";
330  break;
331  case legacy:
332  default_file_name = file_prefix_ + "_balance.txt";
333  break;
334  }
335 
337  try {
339  } INPUT_CATCH(FilePath::ExcFileOpen, FilePath::EI_Address_String, input_record_)
340 
341 
342  // set file name of YAML output
343  if (do_yaml_output_) {
344  string yaml_file_name = file_prefix_ + "_balance.yaml";
346  }
347  }
348 
349  allocation_done_ = true;
350 }
351 
352 
353 
355 {
356  if (! balance_on_) return false;
357 
358  auto &marks = TimeGovernor::marks();
359  bool res = marks.current(time_->step(), balance_output_type_) != marks.end(balance_output_type_);
360 
361  //cout << "flag: " << res << " time: " << step.end() << " type:" << hex << balance_output_type_ << endl;
362  return res;
363 }
364 
365 void Balance::start_mass_assembly(unsigned int quantity_idx)
366 {
367  lazy_initialize();
368  if (! balance_on_) return;
369  chkerr(MatZeroEntries(region_mass_matrix_[quantity_idx]));
370  chkerr(VecZeroEntries(region_mass_vec_[quantity_idx]));
371 }
372 
373 
374 void Balance::start_flux_assembly(unsigned int quantity_idx)
375 {
376  lazy_initialize();
377  if (! balance_on_) return;
378  chkerr(MatZeroEntries(be_flux_matrix_[quantity_idx]));
379  chkerr(VecZeroEntries(be_flux_vec_[quantity_idx]));
380 }
381 
382 
383 void Balance::start_source_assembly(unsigned int quantity_idx)
384 {
385  lazy_initialize();
386  if (! balance_on_) return;
387  chkerr(MatZeroEntries(region_source_matrix_[quantity_idx]));
388  chkerr(MatZeroEntries(region_source_rhs_[quantity_idx]));
389 }
390 
391 
392 void Balance::finish_mass_assembly(unsigned int quantity_idx)
393 {
395  if (! balance_on_) return;
396 
397  chkerr(MatAssemblyBegin(region_mass_matrix_[quantity_idx], MAT_FINAL_ASSEMBLY));
398  chkerr(MatAssemblyEnd(region_mass_matrix_[quantity_idx], MAT_FINAL_ASSEMBLY));
399  chkerr(VecAssemblyBegin(region_mass_vec_[quantity_idx]));
400  chkerr(VecAssemblyEnd(region_mass_vec_[quantity_idx]));
401 }
402 
403 void Balance::finish_flux_assembly(unsigned int quantity_idx)
404 {
406  if (! balance_on_) return;
407 
408  chkerr(MatAssemblyBegin(be_flux_matrix_[quantity_idx], MAT_FINAL_ASSEMBLY));
409  chkerr(MatAssemblyEnd(be_flux_matrix_[quantity_idx], MAT_FINAL_ASSEMBLY));
410  chkerr(VecAssemblyBegin(be_flux_vec_[quantity_idx]));
411  chkerr(VecAssemblyEnd(be_flux_vec_[quantity_idx]));
412 }
413 
414 void Balance::finish_source_assembly(unsigned int quantity_idx)
415 {
417  if (! balance_on_) return;
418 
419  chkerr(MatAssemblyBegin(region_source_matrix_[quantity_idx], MAT_FINAL_ASSEMBLY));
420  chkerr(MatAssemblyEnd(region_source_matrix_[quantity_idx], MAT_FINAL_ASSEMBLY));
421  chkerr(MatAssemblyBegin(region_source_rhs_[quantity_idx], MAT_FINAL_ASSEMBLY));
422  chkerr(MatAssemblyEnd(region_source_rhs_[quantity_idx], MAT_FINAL_ASSEMBLY));
423 }
424 
425 
426 
427 
428 void Balance::add_mass_matrix_values(unsigned int quantity_idx,
429  unsigned int region_idx,
430  const vector<LongIdx> &dof_indices,
431  const vector<double> &values)
432 {
434  if (! balance_on_) return;
435 
436  PetscInt reg_array[1] = { (int)region_idx };
437 
438  chkerr_assert(MatSetValues(region_mass_matrix_[quantity_idx],
439  dof_indices.size(),
440  &(dof_indices[0]),
441  1,
442  reg_array,
443  &(values[0]),
444  ADD_VALUES));
445 }
446 
447 
448 void Balance::add_flux_matrix_values(unsigned int quantity_idx,
449  SideIter side,
450  const vector<LongIdx> &dof_indices,
451  const vector<double> &values)
452 {
454  if (! balance_on_) return;
455 
456  PetscInt elem_array[1] = { int(be_offset_ + be_id_map_[get_boundary_edge_uid(side)]) };
457  chkerr_assert(MatSetValues(be_flux_matrix_[quantity_idx],
458  1,
459  elem_array,
460  dof_indices.size(),
461  &(dof_indices[0]),
462  &(values[0]),
463  ADD_VALUES));
464 }
465 
466 void Balance::add_source_values(unsigned int quantity_idx,
467  unsigned int region_idx,
468  const vector<LongIdx> &loc_dof_indices,
469  const vector<double> &mat_values,
470  const vector<double> &vec_values)
471 {
473  if (! balance_on_) return;
474 
475  PetscInt reg_array[1] = { (int)region_idx };
476 
477  chkerr_assert(MatSetValues(region_source_matrix_[quantity_idx],
478  loc_dof_indices.size(),
479  &(loc_dof_indices[0]),
480  1,
481  reg_array,
482  &(mat_values[0]),
483  ADD_VALUES));
484 
485  chkerr_assert(MatSetValues(region_source_rhs_[quantity_idx],
486  loc_dof_indices.size(),
487  &(loc_dof_indices[0]),
488  1,
489  reg_array,
490  &(vec_values[0]),
491  ADD_VALUES));
492 }
493 
494 void Balance::add_mass_vec_value(unsigned int quantity_idx,
495  unsigned int region_idx,
496  double value)
497 {
498  chkerr_assert(VecSetValue(region_mass_vec_[quantity_idx],
499  region_idx,
500  value,
501  ADD_VALUES));
502 }
503 
504 
505 void Balance::add_flux_vec_value(unsigned int quantity_idx,
506  SideIter side,
507  double value)
508 {
510  if (! balance_on_) return;
511 
512  chkerr_assert(VecSetValue(be_flux_vec_[quantity_idx],
514  value,
515  ADD_VALUES));
516 }
517 
518 
519 void Balance::add_cumulative_source(unsigned int quantity_idx, double source)
520 {
522  if (!cumulative_) return;
523 
524  if (rank_ == 0)
525  increment_sources_[quantity_idx] += source;
526 }
527 
528 
529 void Balance::calculate_cumulative(unsigned int quantity_idx,
530  const Vec &solution)
531 {
533  if (!cumulative_) return;
534  if (time_->tlevel() <= 0) return;
535 
536  // sources
537  double temp_source = 0;
538  int lsize, n_cols_mat, n_cols_rhs;
539  //const int *cols;
540  const double *vals_mat, *vals_rhs, *sol_array;
541  chkerr(VecGetLocalSize(solution, &lsize));
542  chkerr(VecGetArrayRead(solution, &sol_array));
543 
544  // computes transpose multiplication and sums region_source_rhs_ over dofs
545  // resulting in a vector of sources for each region
546  // transpose(region_source_matrix_) * solution + region_source_rhs_*ones(n_blk_reg)
547  // the region vector is then summed up to temp_source
548  for (int i=0; i<lsize; ++i){
549  chkerr(MatGetRow(region_source_matrix_[quantity_idx], i, &n_cols_mat, NULL, &vals_mat));
550  chkerr(MatGetRow(region_source_rhs_[quantity_idx], i, &n_cols_rhs, NULL, &vals_rhs));
551 
552  ASSERT_DBG(n_cols_mat == n_cols_rhs);
553 
554  for (int j=0; j<n_cols_mat; ++j)
555  temp_source += vals_mat[j]*sol_array[i] + vals_rhs[j];
556 
557  chkerr(MatRestoreRow(region_source_matrix_[quantity_idx], i, &n_cols_mat, NULL, &vals_mat));
558  chkerr(MatRestoreRow(region_source_rhs_[quantity_idx], i, &n_cols_rhs, NULL, &vals_rhs));
559  }
560  chkerr(VecRestoreArrayRead(solution, &sol_array));
561 
562  increment_sources_[quantity_idx] += temp_source*time_->dt();
563 
564 
565  // fluxes
566  Vec temp;
567  chkerr(VecCreateMPI(PETSC_COMM_WORLD,
568  be_regions_.size(),
569  PETSC_DECIDE,
570  &temp));
571 
572  chkerr(MatMultAdd(be_flux_matrix_[quantity_idx], solution, be_flux_vec_[quantity_idx], temp));
573 
574  double sum_fluxes;
575  chkerr(VecSum(temp, &sum_fluxes));
576  chkerr(VecDestroy(&temp));
577 
578  if (rank_ == 0)
579  // sum fluxes in one step
580  // Since internally we keep outgoing fluxes, we change sign
581  // to write to output _incoming_ fluxes.
582  increment_fluxes_[quantity_idx] += -1.0 * sum_fluxes*time_->dt();
583 }
584 
585 
586 void Balance::calculate_mass(unsigned int quantity_idx,
587  const Vec &solution,
588  vector<double> &output_array)
589 {
591  if (! balance_on_) return;
592 
593  Vec bulk_vec;
594 
595  chkerr(VecCreateMPIWithArray(PETSC_COMM_WORLD,
596  1,
597  (rank_==0)?mesh_->region_db().bulk_size():0,
598  PETSC_DECIDE,
599  &(output_array[0]),
600  &bulk_vec));
601 
602  // compute mass on regions: M'.u
603  chkerr(VecZeroEntries(bulk_vec));
604  chkerr(MatMultTransposeAdd(region_mass_matrix_[quantity_idx],
605  solution,
606  region_mass_vec_[quantity_idx],
607  bulk_vec));
608  chkerr(VecDestroy(&bulk_vec));
609 }
610 
611 void Balance::calculate_instant(unsigned int quantity_idx, const Vec& solution)
612 {
613  if ( !is_current() ) return;
614 
615  calculate_mass(quantity_idx, solution, masses_[quantity_idx]);
616 
617  // compute positive/negative sources
618  for (unsigned int r=0; r<mesh_->region_db().bulk_size(); ++r)
619  {
620  sources_in_[quantity_idx][r] = 0;
621  sources_out_[quantity_idx][r] = 0;
622  }
623 
624  int lsize, n_cols_mat, n_cols_rhs;
625  const int *cols; // the columns must be same - matrices created and filled in the same way
626  const double *vals_mat, *vals_rhs, *sol_array;
627  chkerr(VecGetLocalSize(solution, &lsize));
628  chkerr(VecGetArrayRead(solution, &sol_array));
629 
630  // computes transpose multiplication and sums region_source_rhs_ over dofs
631  // resulting in a vector of sources for each region, one positive, one negative
632  // transpose(region_source_matrix_) * solution + region_source_rhs_*ones(n_blk_reg)
633  for (int i=0; i<lsize; ++i)
634  {
635  int row = i;
636  chkerr(MatGetRow(region_source_matrix_[quantity_idx], row, &n_cols_mat, &cols, &vals_mat));
637  chkerr(MatGetRow(region_source_rhs_[quantity_idx], row, &n_cols_rhs, NULL, &vals_rhs));
638 
639  ASSERT_DBG(n_cols_mat == n_cols_rhs);
640 
641  for (int j=0; j<n_cols_mat; ++j)
642  {
643  int col = cols[j];
644 
645  double f = vals_mat[j]*sol_array[i] + vals_rhs[j];
646  if (f > 0) sources_in_[quantity_idx][col] += f;
647  else sources_out_[quantity_idx][col] += f;
648  }
649  }
650  chkerr(VecRestoreArrayRead(solution, &sol_array));
651 
652  // calculate flux
653  Vec temp;
654  chkerr(VecCreateMPI(PETSC_COMM_WORLD,
655  be_regions_.size(),
656  PETSC_DECIDE,
657  &temp));
658 
659  chkerr(MatMultAdd(be_flux_matrix_[quantity_idx], solution, be_flux_vec_[quantity_idx], temp));
660  // Since internally we keep outgoing fluxes, we change sign
661  // to write to output _incoming_ fluxes.
662  chkerr(VecScale(temp, -1));
663 
664  // compute positive/negative fluxes
665  fluxes_in_[quantity_idx].assign(mesh_->region_db().boundary_size(), 0);
666  fluxes_out_[quantity_idx].assign(mesh_->region_db().boundary_size(), 0);
667  const double *flux_array;
668 // int lsize;
669  chkerr(VecGetArrayRead(temp, &flux_array));
670  chkerr(VecGetLocalSize(temp, &lsize));
671  for (int e=0; e<lsize; ++e)
672  {
673  if (flux_array[e] < 0)
674  fluxes_out_[quantity_idx][be_regions_[e]] += flux_array[e];
675  else
676  fluxes_in_[quantity_idx][be_regions_[e]] += flux_array[e];
677  }
678  chkerr(VecRestoreArrayRead(temp, &flux_array));
679  chkerr(VecDestroy(&temp));
680 }
681 
682 
683 
684 
685 
687 {
689  if (! balance_on_) return;
690  if (! is_current() ) return;
691 
692  // gather results from processes and sum them up
693  const unsigned int n_quant = quantities_.size();
694  const unsigned int n_blk_reg = mesh_->region_db().bulk_size();
695  const unsigned int n_bdr_reg = mesh_->region_db().boundary_size();
696  const int buf_size = n_quant*2*n_blk_reg + n_quant*2*n_bdr_reg + n_quant;
697  double sendbuffer[buf_size], recvbuffer[buf_size];
698  for (unsigned int qi=0; qi<n_quant; qi++)
699  {
700  for (unsigned int ri=0; ri<n_blk_reg; ri++)
701  {
702  sendbuffer[qi*2*n_blk_reg + + ri] = sources_in_[qi][ri];
703  sendbuffer[qi*2*n_blk_reg + n_blk_reg + ri] = sources_out_[qi][ri];
704  }
705  for (unsigned int ri=0; ri<n_bdr_reg; ri++)
706  {
707  sendbuffer[n_quant*2*n_blk_reg + qi*2*n_bdr_reg + + ri] = fluxes_in_[qi][ri];
708  sendbuffer[n_quant*2*n_blk_reg + qi*2*n_bdr_reg + n_bdr_reg + ri] = fluxes_out_[qi][ri];
709  }
710  if (cumulative_)
711  {
712  sendbuffer[n_quant*2*n_blk_reg + n_quant*2*n_bdr_reg + qi] = increment_sources_[qi];
713  }
714  }
715 
716  MPI_Reduce(&sendbuffer,recvbuffer,buf_size,MPI_DOUBLE,MPI_SUM,0,PETSC_COMM_WORLD);
717  // for other than 0th process update last_time and finish,
718  // on process #0 sum balances over all regions and calculate
719  // cumulative balance over time.
720  if (rank_ == 0)
721  {
722  // update balance vectors
723  for (unsigned int qi=0; qi<n_quant; qi++)
724  {
725  for (unsigned int ri=0; ri<n_blk_reg; ri++)
726  {
727  sources_in_[qi][ri] = recvbuffer[qi*2*n_blk_reg + + ri];
728  sources_out_[qi][ri] = recvbuffer[qi*2*n_blk_reg + n_blk_reg + ri];
729  }
730  for (unsigned int ri=0; ri<n_bdr_reg; ri++)
731  {
732  fluxes_in_[qi][ri] = recvbuffer[n_quant*2*n_blk_reg + qi*2*n_bdr_reg + + ri];
733  fluxes_out_[qi][ri] = recvbuffer[n_quant*2*n_blk_reg + qi*2*n_bdr_reg + n_bdr_reg + ri];
734  }
735  if (cumulative_)
736  {
737  increment_sources_[qi] = recvbuffer[n_quant*2*n_blk_reg + n_quant*2*n_bdr_reg + qi];
738  }
739  }
740  }
741 
742 
743  // The convention for input/output of fluxes is that positive means inward.
744  // Therefore in the following code we switch sign of fluxes.
745  if (rank_ == 0)
746  {
747  sum_fluxes_.assign(n_quant, 0);
748  sum_fluxes_in_.assign(n_quant, 0);
749  sum_fluxes_out_.assign(n_quant, 0);
750  sum_masses_.assign(n_quant, 0);
751  sum_sources_.assign(n_quant, 0);
752  sum_sources_in_.assign(n_quant, 0);
753  sum_sources_out_.assign(n_quant, 0);
754 
755  // sum all boundary fluxes
756  const RegionSet & b_set = mesh_->region_db().get_region_set(".BOUNDARY");
757  for( RegionSet::const_iterator reg = b_set.begin(); reg != b_set.end(); ++reg)
758  {
759  for (unsigned int qi=0; qi<n_quant; qi++)
760  {
761  sum_fluxes_[qi] += fluxes_in_ [qi][reg->boundary_idx()] + fluxes_out_[qi][reg->boundary_idx()];
762  sum_fluxes_in_[qi] += fluxes_in_ [qi][reg->boundary_idx()];
763  sum_fluxes_out_[qi] += fluxes_out_[qi][reg->boundary_idx()];
764  }
765  }
766 
767  // sum all volume sources
768  const RegionSet & bulk_set = mesh_->region_db().get_region_set("BULK");
769  for( RegionSet::const_iterator reg = bulk_set.begin(); reg != bulk_set.end(); ++reg)
770  {
771  for (unsigned int qi=0; qi<n_quant; qi++)
772  {
773  sum_masses_[qi] += masses_[qi][reg->bulk_idx()];
774  sum_sources_[qi] += sources_in_[qi][reg->bulk_idx()] + sources_out_[qi][reg->bulk_idx()];
775  sum_sources_in_[qi] += sources_in_[qi][reg->bulk_idx()];
776  sum_sources_out_[qi] += sources_out_[qi][reg->bulk_idx()];
777  }
778  }
779 
780  // cumulative balance over time
781  if (cumulative_)
782  {
783  // save initial time and mass
784  if (initial_)
785  {
787  for (unsigned int qi=0; qi<n_quant; qi++)
788  initial_mass_[qi] = sum_masses_[qi];
789  initial_ = false;
790  }
791 
792  for (unsigned int qi=0; qi<n_quant; qi++)
793  {
796  }
797  }
798  }
799 
800  last_time_ = time_->t();
801 
802 
803  // perform actual output
804  switch (output_format_)
805  {
806  case txt:
807  output_csv(time_->t(), '\t', "");
808  break;
809  case gnuplot:
810  output_csv(time_->t(), ' ', "#", 30);
811  break;
812  case legacy:
813  output_legacy(time_->t());
814  break;
815  }
816  // output in YAML format
817  output_yaml(time_->t());
818 
819  if (rank_ == 0)
820  {
821  sum_fluxes_.assign(n_quant, 0);
822  sum_sources_.assign(n_quant, 0);
823  increment_fluxes_.assign(n_quant, 0);
824  }
825  increment_sources_.assign(n_quant, 0);
826 }
827 
828 
829 void Balance::output_legacy(double time)
830 {
831  // write output only on process #0
832  if (rank_ != 0) return;
833 
834  const unsigned int n_quant = quantities_.size();
835 
836  // print the head of mass balance file
837  unsigned int c = 6; //column number without label
838  unsigned int w = 14; //column width
839  unsigned int wl = 2*(w-5)+7; //label column width
840  string bc_head_format = "# %-*s%-*s%-*s%-*s%-*s%-*s\n",
841  bc_format = "%*s%-*d%-*s%-*s%-*g%-*g%-*g\n",
842  bc_total_format = "# %-*s%-*s%-*g%-*g%-*g\n";
843 
844  output_ << "# " << setw((w*c+wl-14)/2) << setfill('-') << "--"
845  << " MASS BALANCE "
846  << setw((w*c+wl-14)/2) << setfill('-') << "" << endl
847  << "# Time: " << (time / time_->get_coef()) << "[" << time_->get_unit_string() << "]\n\n\n";
848 
849  // header for table of boundary fluxes
850  output_ << "# Mass flux through boundary [M/T]:\n# "
851  << setiosflags(ios::left) << setfill(' ')
852  << setw(w) << "[boundary_id]"
853  << setw(wl) << "[label]"
854  << setw(w) << "[substance]"
855  << setw(w) << "[total flux]"
856  << setw(w) << "[outward flux]"
857  << setw(w) << "[inward flux]"
858  << endl;
859 
860  // draw long line
861  output_ << "# " << setw(w*c+wl) << setfill('-') << "" << setfill(' ') << endl;
862 
863  // print mass fluxes over boundaries
864  const RegionSet & b_set = mesh_->region_db().get_region_set(".BOUNDARY");
865  for( RegionSet::const_iterator reg = b_set.begin(); reg != b_set.end(); ++reg) {
866  for (unsigned int qi=0; qi<n_quant; qi++) {
867  output_ << setw(2) << ""
868  << setw(w) << (int)reg->id()
869  << setw(wl) << reg->label().c_str()
870  << setw(w) << quantities_[qi].name_.c_str()
871  << setw(w) << fluxes_in_[qi][reg->boundary_idx()] + fluxes_out_[qi][reg->boundary_idx()]
872  << setw(w) << fluxes_out_[qi][reg->boundary_idx()]
873  << setw(w) << fluxes_in_[qi][reg->boundary_idx()]
874  << endl;
875  }
876  }
877 
878  // draw long line
879  output_ << "# " << setw(w*c+wl) << setfill('-') << "" << setfill(' ') << endl;
880 
881  // total boundary balance
882  for (unsigned int qi=0; qi<n_quant; qi++)
883  output_ << "# " << setiosflags(ios::left)
884  << setw(w+wl) << "Total mass flux of substance [M/T]"
885  << setw(w) << quantities_[qi].name_.c_str()
886  << setw(w) << sum_fluxes_[qi]
887  << setw(w) << sum_fluxes_out_[qi]
888  << setw(w) << sum_fluxes_in_[qi]
889  << endl;
890  output_ << "\n\n";
891 
892 
893  // header for table of volume sources and masses
894  string src_head_format = "# %-*s%-*s%-*s%-*s%-*s\n",
895  src_format = "%*s%-*d%-*s%-*s%-*g%-*g\n",
896  src_total_format = "# %-*s%-*s%-*g%-*g\n";
897  output_ << "# Mass [M] and sources [M/T] on regions:\n"
898  << "# " << setiosflags(ios::left)
899  << setw(w) << "[region_id]"
900  << setw(wl) << "[label]"
901  << setw(w) << "[substance]"
902  << setw(w) << "[total_mass]"
903  << setw(w) << "[total_source]"
904  << endl;
905 
906  // draw long line
907  output_ << "# " << setw(w*c+wl) << setfill('-') << "" << setfill(' ') << endl;
908 
909  // print balance of volume sources and masses
910  const RegionSet & bulk_set = mesh_->region_db().get_region_set("BULK");
911  for( RegionSet::const_iterator reg = bulk_set.begin(); reg != bulk_set.end(); ++reg)
912  {
913  for (unsigned int qi=0; qi<n_quant; qi++)
914  {
915  output_ << setw(2) << ""
916  << setw(w) << (int)reg->id()
917  << setw(wl) << reg->label().c_str()
918  << setw(w) << quantities_[qi].name_.c_str()
919  << setw(w) << masses_[qi][reg->bulk_idx()]
920  << setw(w) << sources_in_[qi][reg->bulk_idx()] + sources_out_[qi][reg->bulk_idx()]
921  << endl;
922  }
923  }
924 
925  // draw long line
926  output_ << "# " << setw(w*c+wl) << setfill('-') << "" << setfill(' ') << endl;
927 
928  // total sources balance
929  for (unsigned int qi=0; qi<n_quant; qi++)
930  output_ << "# " << setiosflags(ios::left) << setw(w+wl) << "Total mass [M] and sources [M/T]"
931  << setw(w) << quantities_[qi].name_.c_str()
932  << setw(w) << sum_masses_[qi]
933  << setw(w) << sum_sources_[qi]
934  << endl;
935 
936  if (cumulative_)
937  {
938  // Print cumulative sources
939  output_ << "\n\n# Cumulative mass balance on time interval ["
940  << setiosflags(ios::left) << time_->init_time() << ","
941  << setiosflags(ios::left) << time << "]\n"
942  << "# Initial mass [M] + sources integrated over time [M] - flux integrated over time [M] = current mass [M]\n"
943  << "# " << setiosflags(ios::left)
944  << setw(w) << "[substance]"
945  << setw(w) << "[A=init. mass]"
946  << setw(w) << "[B=source]"
947  << setw(w) << "[C=flux]"
948  << setw(w) << "[A+B-C]"
949  << setw(w) << "[D=curr. mass]"
950  << setw(w) << "[A+B-C-D=err.]"
951  << setw(w) << "[rel. error]"
952  << endl;
953 
954  for (unsigned int qi=0; qi<n_quant; qi++)
955  {
956  double denominator = max(fabs(initial_mass_[qi]+integrated_sources_[qi]-integrated_fluxes_[qi]),fabs(sum_masses_[qi]));
957  output_ << " " << setiosflags(ios::left)
958  << setw(w) << quantities_[qi].name_.c_str()
959  << setw(w) << initial_mass_[qi]
960  << setw(w) << integrated_sources_[qi]
961  << setw(w) << integrated_fluxes_[qi]
962  << setw(w) << initial_mass_[qi]+integrated_sources_[qi]-integrated_fluxes_[qi]
963  << setw(w) << sum_masses_[qi]
965  << setw(w) << fabs(initial_mass_[qi]+integrated_sources_[qi]+integrated_fluxes_[qi]-sum_masses_[qi])/(denominator==0?1:denominator)
966  << endl;
967  }
968  }
969 
970  output_ << endl << endl;
971 }
972 
973 
974 std::string Balance::csv_zero_vals(unsigned int cnt, char delimiter)
975 {
976  std::stringstream ss;
977  for (unsigned int i=0; i<cnt; i++) ss << format_csv_val(0, delimiter);
978  return ss.str();
979 }
980 
981 
982 void Balance::output_csv(double time, char delimiter, const std::string& comment_string, unsigned int repeat)
983 {
984  // write output only on process #0
985  if (rank_ != 0) return;
986 
987  const unsigned int n_quant = quantities_.size();
988 
989  // print data header only on first line
990  if (repeat==0 && output_line_counter_==0) format_csv_output_header(delimiter, comment_string);
991 
992  // print sources and masses over bulk regions
993  const RegionSet & bulk_set = mesh_->region_db().get_region_set("BULK");
994  for( RegionSet::const_iterator reg = bulk_set.begin(); reg != bulk_set.end(); ++reg)
995  {
996  for (unsigned int qi=0; qi<n_quant; qi++)
997  {
998  // print data header (repeat header after every "repeat" lines)
999  if (repeat && (output_line_counter_%repeat == 0)) format_csv_output_header(delimiter, comment_string);
1000 
1001  output_ << format_csv_val(time / time_->get_coef(), delimiter, true)
1002  << format_csv_val(reg->label(), delimiter)
1003  << format_csv_val(quantities_[qi].name_, delimiter)
1004  << csv_zero_vals(3, delimiter)
1005  << format_csv_val(masses_[qi][reg->bulk_idx()], delimiter)
1006  << format_csv_val(sources_in_[qi][reg->bulk_idx()] + sources_out_[qi][reg->bulk_idx()], delimiter)
1007  << format_csv_val(sources_in_[qi][reg->bulk_idx()], delimiter)
1008  << format_csv_val(sources_out_[qi][reg->bulk_idx()], delimiter)
1009  << csv_zero_vals(5, delimiter) << endl;
1011  }
1012  }
1013 
1014  // print mass fluxes over boundaries
1015  const RegionSet & b_set = mesh_->region_db().get_region_set(".BOUNDARY");
1016  for( RegionSet::const_iterator reg = b_set.begin(); reg != b_set.end(); ++reg)
1017  {
1018  for (unsigned int qi=0; qi<n_quant; qi++) {
1019  // print data header (repeat header after every "repeat" lines)
1020  if (repeat && (output_line_counter_%repeat == 0)) format_csv_output_header(delimiter, comment_string);
1021 
1022  output_ << format_csv_val(time / time_->get_coef(), delimiter, true)
1023  << format_csv_val(reg->label(), delimiter)
1024  << format_csv_val(quantities_[qi].name_, delimiter)
1025  << format_csv_val(fluxes_in_[qi][reg->boundary_idx()] + fluxes_out_[qi][reg->boundary_idx()], delimiter)
1026  << format_csv_val(fluxes_in_[qi][reg->boundary_idx()], delimiter)
1027  << format_csv_val(fluxes_out_[qi][reg->boundary_idx()], delimiter)
1028  << csv_zero_vals(9, delimiter) << endl;
1030  }
1031  }
1032 
1033  if (cumulative_)
1034  {
1035  for (unsigned int qi=0; qi<n_quant; qi++)
1036  {
1037  // print data header (repeat header after every "repeat" lines)
1038  if (repeat && (output_line_counter_%repeat == 0)) format_csv_output_header(delimiter, comment_string);
1039 
1040  double error = sum_masses_[qi] - (initial_mass_[qi] + integrated_sources_[qi] + integrated_fluxes_[qi]);
1041  output_ << format_csv_val(time / time_->get_coef(), delimiter, true)
1042  << format_csv_val("ALL", delimiter)
1043  << format_csv_val(quantities_[qi].name_, delimiter)
1044  << format_csv_val(sum_fluxes_[qi], delimiter)
1045  << format_csv_val(sum_fluxes_in_[qi], delimiter)
1046  << format_csv_val(sum_fluxes_out_[qi], delimiter)
1047  << format_csv_val(sum_masses_[qi], delimiter)
1048  << format_csv_val(sum_sources_[qi], delimiter)
1049  << format_csv_val(sum_sources_in_[qi], delimiter)
1050  << format_csv_val(sum_sources_out_[qi], delimiter)
1051  << format_csv_val(increment_fluxes_[qi], delimiter)
1052  << format_csv_val(increment_sources_[qi], delimiter)
1053  << format_csv_val(integrated_fluxes_[qi], delimiter)
1054  << format_csv_val(integrated_sources_[qi], delimiter)
1055  << format_csv_val(error, delimiter) << endl;
1057  }
1058  }
1059 
1060 }
1061 
1062 
1063 void Balance::format_csv_output_header(char delimiter, const std::string& comment_string)
1064 {
1065  std::stringstream ss;
1066  if (delimiter == ' ') {
1067  ss << setw(output_column_width-comment_string.size()) << "\"time [" << time_->get_unit_string() << "]\"";
1068  } else {
1069  ss << "\"time [" << time_->get_unit_string() << "]\"";
1070  }
1071 
1072  output_ << comment_string << ss.str()
1073  << format_csv_val("region", delimiter)
1074  << format_csv_val("quantity [" + units_.format_text() + "]", delimiter)
1075  << format_csv_val("flux", delimiter)
1076  << format_csv_val("flux_in", delimiter)
1077  << format_csv_val("flux_out", delimiter)
1078  << format_csv_val("mass", delimiter)
1079  << format_csv_val("source", delimiter)
1080  << format_csv_val("source_in", delimiter)
1081  << format_csv_val("source_out", delimiter)
1082  << format_csv_val("flux_increment", delimiter)
1083  << format_csv_val("source_increment", delimiter)
1084  << format_csv_val("flux_cumulative", delimiter)
1085  << format_csv_val("source_cumulative", delimiter)
1086  << format_csv_val("error", delimiter)
1087  << endl;
1088 }
1089 
1090 std::string Balance::format_csv_val(std::string val, char delimiter, bool initial)
1091 {
1092  std::stringstream ss;
1093  std::replace( val.begin(), val.end(), '\"', '\'');
1094 
1095  if (!initial) ss << delimiter;
1096  if (delimiter == ' ') {
1097  std::stringstream sval;
1098  sval << "\"" << val << "\"";
1099  ss << " " << setw(output_column_width-1) << sval.str();
1100  } else {
1101  ss << "\"" << val << "\"";
1102  }
1103 
1104  return ss.str();
1105 }
1106 
1107 std::string Balance::format_csv_val(double val, char delimiter, bool initial)
1108 {
1109  std::stringstream ss;
1110 
1111  if (!initial) ss << delimiter;
1112  if (delimiter == ' ') {
1113  ss << " " << setw(output_column_width-1) << val;
1114  } else {
1115  ss << val;
1116  }
1117  return ss.str();
1118 }
1119 
1120 void Balance::output_yaml(double time)
1121 {
1122 
1123  // write output only on process #0
1124  if (!do_yaml_output_ || rank_ != 0) return;
1125 
1126  const unsigned int n_quant = quantities_.size();
1127 
1128  // print data header only once
1129  if (!output_yaml_header_) {
1130  output_yaml_ << "column_names: [ flux, flux_in, flux_out, mass, source, source_in, source_out, flux_increment, "
1131  << "source_increment, flux_cumulative, source_cumulative, error ]" << endl;
1132  output_yaml_ << "data:" << endl;
1133  output_yaml_header_ = true;
1134  }
1135 
1136  output_yaml_ << setfill(' ');
1137 
1138  // print sources and masses over bulk regions
1139  const RegionSet & bulk_set = mesh_->region_db().get_region_set("BULK");
1140  for( RegionSet::const_iterator reg = bulk_set.begin(); reg != bulk_set.end(); ++reg)
1141  {
1142  for (unsigned int qi=0; qi<n_quant; qi++)
1143  {
1144  output_yaml_ << " - time: " << (time / time_->get_coef()) << endl;
1145  output_yaml_ << setw(4) << "" << "region: " << reg->label() << endl;
1146  output_yaml_ << setw(4) << "" << "quantity: " << quantities_[qi].name_ << endl;
1147  output_yaml_ << setw(4) << "" << "data: " << "[ 0, 0, 0, " << masses_[qi][reg->bulk_idx()] << ", "
1148  << sources_in_[qi][reg->bulk_idx()] + sources_out_[qi][reg->bulk_idx()] << ", "
1149  << sources_in_[qi][reg->bulk_idx()] << ", " << sources_out_[qi][reg->bulk_idx()]
1150  << ", 0, 0, 0, 0, 0 ]" << endl;
1151  }
1152  }
1153 
1154  // print mass fluxes over boundaries
1155  const RegionSet & b_set = mesh_->region_db().get_region_set(".BOUNDARY");
1156  for( RegionSet::const_iterator reg = b_set.begin(); reg != b_set.end(); ++reg)
1157  {
1158  for (unsigned int qi=0; qi<n_quant; qi++) {
1159  output_yaml_ << " - time: " << (time / time_->get_coef()) << endl;
1160  output_yaml_ << setw(4) << "" << "region: " << reg->label() << endl;
1161  output_yaml_ << setw(4) << "" << "quantity: " << quantities_[qi].name_ << endl;
1162  output_yaml_ << setw(4) << "" << "data: " << "[ "
1163  << fluxes_in_[qi][reg->boundary_idx()] + fluxes_out_[qi][reg->boundary_idx()] << ", "
1164  << fluxes_in_[qi][reg->boundary_idx()] << ", " << fluxes_out_[qi][reg->boundary_idx()]
1165  << ", 0, 0, 0, 0, 0, 0, 0, 0, 0 ]" << endl;
1166  }
1167  }
1168 
1169  if (cumulative_)
1170  {
1171  for (unsigned int qi=0; qi<n_quant; qi++)
1172  {
1173  double error = sum_masses_[qi] - (initial_mass_[qi] + integrated_sources_[qi] + integrated_fluxes_[qi]);
1174  output_yaml_ << " - time: " << (time / time_->get_coef()) << endl;
1175  output_yaml_ << setw(4) << "" << "region: ALL" << endl;
1176  output_yaml_ << setw(4) << "" << "quantity: " << quantities_[qi].name_ << endl;
1177  output_yaml_ << setw(4) << "" << "data: " << "[ " << sum_fluxes_[qi] << ", "
1178  << sum_fluxes_in_[qi] << ", " << sum_fluxes_out_[qi] << ", "
1179  << sum_masses_[qi] << ", " << sum_sources_[qi] << ", "
1180  << sum_sources_in_[qi] << ", " << sum_sources_out_[qi] << ", "
1181  << increment_fluxes_[qi] << ", " << increment_sources_[qi] << ", "
1182  << integrated_fluxes_[qi] << ", " << integrated_sources_[qi] << ", "
1183  << error << " ]" << endl;
1184  }
1185  }
1186 }
1187 
1188 
1189 
1190 
1191 
1192 
int LongIdx
Define type that represents indices of large arrays (elements, nodes, dofs etc.)
Definition: long_idx.hh:22
UnitSI units_
Units of conserved quantities.
Definition: balance.hh:456
void lazy_initialize()
Definition: balance.cc:188
static const Input::Type::Record & get_input_type()
Main balance input record type.
Definition: balance.cc:48
std::vector< double > integrated_sources_
Definition: balance.hh:511
unsigned int add_quantity(const string &name)
Definition: balance.cc:160
std::vector< double > sum_fluxes_out_
Definition: balance.hh:503
void calculate_mass(unsigned int quantity_idx, const Vec &solution, vector< double > &output_array)
Definition: balance.cc:586
RegionSet get_region_set(const std::string &set_name) const
Definition: region.cc:329
LongIdx get_boundary_edge_uid(SideIter side)
Definition: balance.hh:423
TimeMark::Type output_mark_type_
TimeMark type for output of particular equation.
Definition: balance.hh:523
Accessor to input data conforming to declared Array.
Definition: accessors.hh:567
void allocate(unsigned int n_loc_dofs, unsigned int max_dofs_per_boundary)
Definition: balance.cc:180
TimeMark::Type balance_output_type_
TimeMark type for balance output of particular equation.
Definition: balance.hh:520
unsigned int * boundary_idx_
Definition: elements.h:82
std::string format_text() const
Definition: unit_si.cc:127
int tlevel() const
void finish_source_assembly(unsigned int quantity_idx)
This method must be called after assembling the matrix and vectors for computing source.
Definition: balance.cc:414
unsigned int bulk_size() const
Definition: region.cc:269
void add_mass_vec_value(unsigned int quantity_idx, unsigned int region_idx, double value)
Definition: balance.cc:494
Class Input::Type::Default specifies default value of keys of a Input::Type::Record.
Definition: type_record.hh:61
Class for declaration of the input of type Bool.
Definition: type_base.hh:459
gnuplot
Definition: balance.hh:147
bool initial_
true before calculating the mass at initial time, otherwise false
Definition: balance.hh:526
std::vector< std::vector< double > > sources_in_
Definition: balance.hh:497
void add_cumulative_source(unsigned int quantity_idx, double source)
Definition: balance.cc:519
std::vector< std::vector< double > > fluxes_in_
Definition: balance.hh:494
std::vector< double > sum_fluxes_in_
Definition: balance.hh:502
std::vector< std::vector< double > > fluxes_out_
Definition: balance.hh:495
#define INPUT_CATCH(ExceptionType, AddressEITag, input_accessor)
Definition: accessors.hh:64
const TimeGovernor * time_
Definition: balance.hh:553
#define MPI_SUM
Definition: mpi.h:196
Mat * region_source_rhs_
Matrices for calculation of signed source (n_dofs x n_bulk_regions).
Definition: balance.hh:469
Definition: mesh.h:76
Input::Record input_record_
Record for current balance.
Definition: balance.hh:551
ofstream output_
Handle for file for output in given OutputFormat of balance and total fluxes over individual regions ...
Definition: balance.hh:442
void read_from_input(Input::Array in_array, const TimeGovernor &tg)
void chkerr(unsigned int ierr)
Replacement of new/delete operator in the spirit of xmalloc.
Definition: system.hh:148
void output_legacy(double time)
Perform output in old format (for compatibility)
Definition: balance.cc:829
SideIter side(const unsigned int loc_index)
void add_mass_matrix_values(unsigned int quantity_idx, unsigned int region_idx, const std::vector< LongIdx > &dof_indices, const std::vector< double > &values)
Definition: balance.cc:428
const RegionDB & region_db() const
Definition: mesh.h:141
#define ASSERT(expr)
Allow use shorter versions of macro names if these names is not used with external library...
Definition: asserts.hh:347
Region region()
const TimeStep & step(int index=-1) const
bool allocation_done_
true before allocating necessary internal structures (Petsc matrices etc.)
Definition: balance.hh:532
double t() const
void calculate_cumulative(unsigned int quantity_idx, const Vec &solution)
Definition: balance.cc:529
Basic time management functionality for unsteady (and steady) solvers (class Equation).
static TimeMarks & marks()
#define MPI_Reduce(sendbuf, recvbuf, count, datatype, op, root, comm)
Definition: mpi.h:608
void calculate_instant(unsigned int quantity_idx, const Vec &solution)
Definition: balance.cc:611
Record & close() const
Close the Record for further declarations of keys.
Definition: type_record.cc:304
Basic time management class.
std::vector< double > sum_fluxes_
Definition: balance.hh:501
virtual ElementAccessor< 3 > element_accessor(unsigned int idx) const
Create and return ElementAccessor to element of given idx.
Definition: mesh.cc:739
bool balance_on_
If the balance is on. Balance is off in the case of no balance output time marks. ...
Definition: balance.hh:535
static constexpr bool value
Definition: json.hpp:87
std::vector< double > increment_sources_
Definition: balance.hh:514
Vec * be_flux_vec_
Vectors for calculation of flux (n_boundary_edges).
Definition: balance.hh:472
static void set_yaml_output()
Set global variable to output balance files into YAML format (in addition to the table format)...
Definition: balance.cc:61
static const Input::Type::Selection & get_format_selection_input_type()
Input selection for file format.
Definition: balance.cc:40
std::vector< double > integrated_fluxes_
Definition: balance.hh:512
unsigned int boundary_idx() const
Returns index of the region in the boundary set.
Definition: region.hh:86
std::vector< Quantity > quantities_
Names of conserved quantities.
Definition: balance.hh:451
std::string csv_zero_vals(unsigned int cnt, char delimiter)
Return part of output represented by zero values. Count of zero values is given by cnt parameter...
Definition: balance.cc:974
std::vector< std::vector< double > > sources_out_
Definition: balance.hh:498
Mat * be_flux_matrix_
Matrices for calculation of flux (n_boundary_edges x n_dofs).
Definition: balance.hh:463
double last_time_
time of last calculated balance
Definition: balance.hh:517
void open_stream(Stream &stream) const
Definition: file_path.cc:211
double init_time() const
std::vector< std::vector< double > > fluxes_
Definition: balance.hh:493
bool is_boundary() const
Returns true for side on the boundary.
void finish_mass_assembly(unsigned int quantity_idx)
This method must be called after assembling the matrix for computing mass.
Definition: balance.cc:392
TimeMark::Type equation_fixed_mark_type() const
void format_csv_output_header(char delimiter, const std::string &comment_string)
Print output header.
Definition: balance.cc:1063
int rank_
MPI rank.
Definition: balance.hh:542
Accessor to the data with type Type::Record.
Definition: accessors.hh:292
TimeMark::Type equation_mark_type() const
const Ret val(const string &key) const
unsigned int n_sides() const
Definition: elements.h:134
void init_from_input(const Input::Record &in_rec, TimeGovernor &tg)
Definition: balance.cc:127
Mat * region_mass_matrix_
Matrices for calculation of mass (n_dofs x n_bulk_regions).
Definition: balance.hh:460
Selection & add_value(const int value, const std::string &key, const std::string &description="", TypeBase::attribute_map attributes=TypeBase::attribute_map())
Adds one new value with name given by key to the Selection.
std::vector< double > sum_sources_out_
Definition: balance.hh:507
unsigned int max_dofs_per_boundary_
Definition: balance.hh:432
bool cumulative_
if true then cumulative balance is computed
Definition: balance.hh:529
Record & declare_key(const string &key, std::shared_ptr< TypeBase > type, const Default &default_value, const string &description, TypeBase::attribute_map key_attributes=TypeBase::attribute_map())
Declares a new key of the Record.
Definition: type_record.cc:503
Mat * region_source_matrix_
Matrices for calculation of source (n_dofs x n_bulk_regions).
Definition: balance.hh:466
std::vector< double > increment_fluxes_
Definition: balance.hh:513
void chkerr_assert(unsigned int ierr)
Definition: system.hh:159
bool is_current()
Returns true if the current time step is marked for the balance output.
Definition: balance.cc:354
Balance(const std::string &file_prefix, const Mesh *mesh)
Definition: balance.cc:84
void output_csv(double time, char delimiter, const std::string &comment_string, unsigned int repeat=0)
Perform output in csv format.
Definition: balance.cc:982
Distribution * get_el_ds() const
Definition: mesh.h:162
~Balance()
Definition: balance.cc:101
static bool do_yaml_output_
Definition: balance.hh:428
#define MPI_DOUBLE
Definition: mpi.h:156
#define MPI_Comm_rank
Definition: mpi.h:236
std::vector< unsigned int > add_quantities(const std::vector< string > &names)
Definition: balance.cc:171
Dedicated class for storing path to input and output files.
Definition: file_path.hh:54
const Mesh * mesh_
Definition: balance.hh:453
static Default read_time(const std::string &description)
The factory function to make an default value that will be specified at the time when a key will be r...
Definition: type_record.hh:97
Support classes for parallel programing.
void output_yaml(double time)
Perform output in yaml format.
Definition: balance.cc:1120
void output()
Perform output to file for given time instant.
Definition: balance.cc:686
std::vector< double > sum_sources_
Definition: balance.hh:505
std::string get_unit_string() const
void start_flux_assembly(unsigned int quantity_idx)
Definition: balance.cc:374
std::vector< double > initial_mass_
Definition: balance.hh:508
static const unsigned int output_column_width
Size of column in output (used if delimiter is space)
Definition: balance.hh:388
void add_source_values(unsigned int quantity_idx, unsigned int region_idx, const std::vector< LongIdx > &loc_dof_indices, const std::vector< double > &mat_values, const std::vector< double > &vec_values)
Definition: balance.cc:466
#define ASSERT_PTR(ptr)
Definition of assert macro checking non-null pointer (PTR)
Definition: asserts.hh:336
const Selection & close() const
Close the Selection, no more values can be added.
unsigned int boundary_size() const
Definition: region.cc:262
double dt() const
void finish_flux_assembly(unsigned int quantity_idx)
This method must be called after assembling the matrix and vector for computing flux.
Definition: balance.cc:403
std::vector< unsigned int > be_regions_
Maps local boundary edge to its region boundary index.
Definition: balance.hh:485
ofstream output_yaml_
Definition: balance.hh:445
OutputFormat output_format_
Format of output file.
Definition: balance.hh:448
#define ASSERT_DBG(expr)
std::unordered_map< LongIdx, unsigned int > be_id_map_
Definition: balance.hh:482
static const Input::Type::Array get_input_type()
void units(const UnitSI &unit)
Setter for units of conserved quantities.
Definition: balance.cc:152
int be_offset_
Offset for local part of vector of boundary edges.
Definition: balance.hh:488
std::vector< std::vector< double > > masses_
Definition: balance.hh:496
void start_mass_assembly(unsigned int quantity_idx)
Definition: balance.cc:365
Record type proxy class.
Definition: type_record.hh:182
std::vector< double > sum_masses_
Definition: balance.hh:504
Vec * region_mass_vec_
Vectors for calculation of mass (n_bulk_regions).
Definition: balance.hh:475
unsigned int output_line_counter_
hold count of line printed into output_
Definition: balance.hh:545
bool add_output_times_
Add output time marks to balance output time marks.
Definition: balance.hh:538
Class for representation SI units of Fields.
Definition: unit_si.hh:40
Boundary cond() const
unsigned int n_loc_dofs_
Allocation parameters. Set by the allocate method used in the lazy_initialize.
Definition: balance.hh:431
double get_coef() const
static FileName output()
The factory function for declaring type FileName for input files.
Definition: type_base.cc:533
OutputFormat
Definition: balance.hh:143
LongIdx * get_el_4_loc() const
Definition: mesh.h:168
void add_flux_matrix_values(unsigned int quantity_idx, SideIter side, const std::vector< LongIdx > &dof_indices, const std::vector< double > &values)
Definition: balance.cc:448
void undef(bool val=true)
Definition: unit_si.cc:197
void start_source_assembly(unsigned int quantity_idx)
Definition: balance.cc:383
Template for classes storing finite set of named values.
void add_flux_vec_value(unsigned int quantity_idx, SideIter side, double value)
Definition: balance.cc:505
FilePath balance_output_file_
File path for output_ stream.
Definition: balance.hh:439
std::string file_prefix_
Save prefix passed in in constructor.
Definition: balance.hh:436
bool output_yaml_header_
marks whether YAML output has printed header
Definition: balance.hh:548
std::string format_csv_val(std::string val, char delimiter, bool initial=false)
Format string value of csv output. Wrap string into quotes and if delimiter is space, align text to column.
Definition: balance.cc:1090
std::vector< double > sum_sources_in_
Definition: balance.hh:506
unsigned int lsize(int proc) const
get local size