Flow123d  release_3.0.0-506-g34af125
transport.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 transport.cc
15  * @ingroup transport
16  * @brief Transport
17  */
18 
19 #include <memory>
20 
21 #include "system/system.hh"
22 #include "system/sys_profiler.hh"
23 
24 #include "mesh/side_impl.hh"
25 #include "mesh/long_idx.hh"
26 #include "mesh/mesh.h"
27 #include "mesh/partitioning.hh"
28 #include "mesh/accessors.hh"
29 #include "mesh/range_wrapper.hh"
30 #include "mesh/neighbours.h"
31 #include "transport/transport.h"
32 
33 #include "la/distribution.hh"
34 
35 #include "la/sparse_graph.hh"
36 #include <iostream>
37 #include <iomanip>
38 #include <string>
39 
40 #include "io/output_time.hh"
41 #include "tools/time_governor.hh"
42 #include "coupling/balance.hh"
43 #include "input/accessors.hh"
44 #include "input/input_type.hh"
45 
47 #include "fields/field_values.hh"
48 #include "fields/field_fe.hh"
50 #include "fields/generic_field.hh"
51 
52 #include "reaction/isotherm.hh" // SorptionType enum
53 #include "flow/mh_dofhandler.hh"
54 
55 
56 FLOW123D_FORCE_LINK_IN_CHILD(convectionTransport);
57 
58 
59 namespace IT = Input::Type;
60 
61 const string _equation_name = "Solute_Advection_FV";
62 
64  Input::register_class< ConvectionTransport, Mesh &, const Input::Record >(_equation_name) +
66 
68 {
69  return IT::Record(_equation_name, "Explicit in time finite volume method for advection only solute transport.")
71  .declare_key("input_fields", IT::Array(
72  EqData().make_field_descriptor_type(_equation_name)),
74  "")
75  .declare_key("output",
76  EqData().output_fields.make_output_type(_equation_name, ""),
77  IT::Default("{ \"fields\": [ \"conc\" ] }"),
78  "Setting of the fields output.")
79  .close();
80 }
81 
82 
84 {
85  ADD_FIELD(bc_conc, "Boundary conditions for concentrations.", "0.0");
86  bc_conc.units( UnitSI().kg().m(-3) );
87  ADD_FIELD(init_conc, "Initial concentrations.", "0.0");
88  init_conc.units( UnitSI().kg().m(-3) );
89 
90  output_fields += *this;
91  output_fields += conc_mobile.name("conc")
92  .units( UnitSI().kg().m(-3) )
94  output_fields += region_id.name("region_id")
97  output_fields += subdomain.name("subdomain")
100 }
101 
102 
104 : ConcentrationTransportBase(init_mesh, in_rec),
105  is_mass_diag_changed(false),
106  input_rec(in_rec),
107  mh_dh(nullptr),
108  sources_corr(nullptr)
109 {
110  START_TIMER("ConvectionTransport");
111  this->eq_data_ = &data_;
112 
113  transport_matrix_time = -1.0; // or -infty
114  transport_bc_time = -1.0;
116  is_src_term_scaled = false;
117  is_bc_term_scaled = false;
118 }
119 
121 {
123 
125 
127  data_.set_input_list( input_rec.val<Input::Array>("input_fields"), *time_ );
128  data_.set_mesh(*mesh_);
129 
133 
134  // register output vectors
141  for (unsigned int sbi=0; sbi<n_substances(); sbi++)
142  {
143  // create shared pointer to a FieldFE and push this Field to output_field on all regions
144  output_field_ptr[sbi] = out_conc[sbi].create_field<3, FieldValue<3>::Scalar>(*mesh_, 1);
145  data_.conc_mobile[sbi].set_field(mesh_->region_db().get_region_set("ALL"), output_field_ptr[sbi], 0);
146  }
147  //output_stream_->add_admissible_field_names(input_rec.val<Input::Array>("output_fields"));
148  //output_stream_->mark_output_times(*time_);
149 
151  //cout << "Transport." << endl;
152  //cout << time().marks();
153 
154  balance_->allocate(el_ds->lsize(), 1);
155 
156 }
157 
158 
159 //=============================================================================
160 // MAKE TRANSPORT
161 //=============================================================================
163 
164 // int * id_4_old = new int[mesh_->n_elements()];
165 // int i = 0;
166 // for (auto ele : mesh_->elements_range()) id_4_old[i++] = ele.index();
167 // mesh_->get_part()->id_maps(mesh_->n_elements(), id_4_old, el_ds, el_4_loc, row_4_el);
168 // delete[] id_4_old;
169  el_ds = mesh_->get_el_ds();
172 
173  // TODO: make output of partitioning is usefull but makes outputs different
174  // on different number of processors, which breaks tests.
175  //
176  // Possible solution:
177  // - have flag in ini file to turn this output ON
178  // - possibility to have different ref_output for different num of proc.
179  // - or do not test such kind of output
180  //
181  //for (auto ele : mesh_->elements_range()) {
182  // ele->pid()=el_ds->get_proc(row_4_el[ele.index()]);
183  //}
184 
185 }
186 
187 
188 
190 {
191  unsigned int sbi;
192 
193  if (sources_corr) {
194  //Destroy mpi vectors at first
195  chkerr(MatDestroy(&tm));
196  chkerr(VecDestroy(&mass_diag));
197  chkerr(VecDestroy(&vpmass_diag));
198  chkerr(VecDestroy(&vcfl_flow_));
199  chkerr(VecDestroy(&vcfl_source_));
200  delete cfl_flow_;
201  delete cfl_source_;
202 
203  for (sbi = 0; sbi < n_substances(); sbi++) {
204  // mpi vectors
205  chkerr(VecDestroy(&vconc[sbi]));
206  chkerr(VecDestroy(&vpconc[sbi]));
207  chkerr(VecDestroy(&bcvcorr[sbi]));
208  chkerr(VecDestroy(&vcumulative_corr[sbi]));
209  chkerr(VecDestroy(&v_tm_diag[sbi]));
210  chkerr(VecDestroy(&v_sources_corr[sbi]));
211 
212  // arrays of arrays
213  delete conc[sbi];
214  delete cumulative_corr[sbi];
215  delete tm_diag[sbi];
216  delete sources_corr[sbi];
217  }
218 
219  // arrays of mpi vectors
220  delete vconc;
221  delete vpconc;
222  delete bcvcorr;
223  delete vcumulative_corr;
224  delete v_tm_diag;
225  delete v_sources_corr;
226 
227  // arrays of arrays
228  delete conc;
229  delete cumulative_corr;
230  delete tm_diag;
231  delete sources_corr;
232  }
233 }
234 
235 
236 
237 
238 
240 {
241  for (auto elem : mesh_->elements_range()) {
242  if (!el_ds->is_local(row_4_el[ elem.idx() ])) continue;
243 
244  LongIdx index = row_4_el[ elem.idx() ] - el_ds->begin();
245  ElementAccessor<3> ele_acc = mesh_->element_accessor( elem.idx() );
246 
247  for (unsigned int sbi=0; sbi<n_substances(); sbi++) // Optimize: SWAP LOOPS
248  conc[sbi][index] = data_.init_conc[sbi].value(elem.centre(), ele_acc);
249  }
250 
251 }
252 
253 //=============================================================================
254 // ALLOCATE OF TRANSPORT VARIABLES (ELEMENT & NODES)
255 //=============================================================================
257 
258  unsigned int i, sbi, n_subst;
259  n_subst = n_substances();
260 
261  sources_corr = new double*[n_subst];
262  tm_diag = new double*[n_subst];
263  cumulative_corr = new double*[n_subst];
264  for (sbi = 0; sbi < n_subst; sbi++) {
265  cumulative_corr[sbi] = new double[el_ds->lsize()];
266  sources_corr[sbi] = new double[el_ds->lsize()];
267  tm_diag[sbi] = new double[el_ds->lsize()];
268  }
269 
270  conc = new double*[n_subst];
271  out_conc.clear();
272  out_conc.resize(n_subst);
273  output_field_ptr.clear();
274  output_field_ptr.resize(n_subst);
275  for (sbi = 0; sbi < n_subst; sbi++) {
276  conc[sbi] = new double[el_ds->lsize()];
277  out_conc[sbi].resize( el_ds->size() );
278  for (i = 0; i < el_ds->lsize(); i++) {
279  conc[sbi][i] = 0.0;
280  }
281  }
282 
283  cfl_flow_ = new double[el_ds->lsize()];
284  cfl_source_ = new double[el_ds->lsize()];
285 }
286 
287 //=============================================================================
288 // ALLOCATION OF TRANSPORT VECTORS (MPI)
289 //=============================================================================
291 
292  int sbi, n_subst, rank, np;
293  n_subst = n_substances();
294 
295  MPI_Barrier(PETSC_COMM_WORLD);
296  MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
297  MPI_Comm_size(PETSC_COMM_WORLD, &np);
298 
299  vconc = new Vec[n_subst];
300  vpconc = new Vec[n_subst];
301  bcvcorr = new Vec[n_subst];
302  vcumulative_corr = new Vec[n_subst];
303  v_tm_diag = new Vec[n_subst];
304  v_sources_corr = new Vec[n_subst];
305 
306 
307  for (sbi = 0; sbi < n_subst; sbi++) {
308  VecCreateMPI(PETSC_COMM_WORLD, el_ds->lsize(), mesh_->n_elements(), &bcvcorr[sbi]);
309  VecZeroEntries(bcvcorr[sbi]);
310  VecCreateMPIWithArray(PETSC_COMM_WORLD,1, el_ds->lsize(), mesh_->n_elements(), conc[sbi],
311  &vconc[sbi]);
312 
313  VecCreateMPI(PETSC_COMM_WORLD, el_ds->lsize(), mesh_->n_elements(), &vpconc[sbi]);
314  VecZeroEntries(vconc[sbi]);
315  VecZeroEntries(vpconc[sbi]);
316 
317  // SOURCES
318  VecCreateMPIWithArray(PETSC_COMM_WORLD,1, el_ds->lsize(), mesh_->n_elements(),
319  cumulative_corr[sbi],&vcumulative_corr[sbi]);
320 
321  VecCreateMPIWithArray(PETSC_COMM_WORLD,1, el_ds->lsize(), mesh_->n_elements(),
322  sources_corr[sbi],&v_sources_corr[sbi]);
323 
324  VecCreateMPIWithArray(PETSC_COMM_WORLD,1, el_ds->lsize(), mesh_->n_elements(),
325  tm_diag[sbi],&v_tm_diag[sbi]);
326 
327  VecZeroEntries(vcumulative_corr[sbi]);
328  VecZeroEntries(out_conc[sbi].get_data_petsc());
329  }
330 
331 
332  MatCreateAIJ(PETSC_COMM_WORLD, el_ds->lsize(), el_ds->lsize(), mesh_->n_elements(),
333  mesh_->n_elements(), 16, PETSC_NULL, 4, PETSC_NULL, &tm);
334 
335  VecCreateMPI(PETSC_COMM_WORLD, el_ds->lsize(), mesh_->n_elements(), &mass_diag);
336  VecCreateMPI(PETSC_COMM_WORLD, el_ds->lsize(), mesh_->n_elements(), &vpmass_diag);
337 
338  VecCreateMPIWithArray(PETSC_COMM_WORLD,1, el_ds->lsize(), mesh_->n_elements(),
340  VecCreateMPIWithArray(PETSC_COMM_WORLD,1, el_ds->lsize(), mesh_->n_elements(),
342 }
343 
344 
346 {
347  START_TIMER ("set_boundary_conditions");
348 
349  ElementAccessor<3> elm;
350 
351  unsigned int sbi, loc_el, loc_b = 0;
352 
353  // Assembly bcvcorr vector
354  for(sbi=0; sbi < n_substances(); sbi++) VecZeroEntries(bcvcorr[sbi]);
355 
356  balance_->start_flux_assembly(subst_idx);
357 
358  for (loc_el = 0; loc_el < el_ds->lsize(); loc_el++) {
359  elm = mesh_->element_accessor( el_4_loc[loc_el] );
360  if (elm->boundary_idx_ != NULL) {
361  LongIdx new_i = row_4_el[ elm.idx() ];
362 
363  for (unsigned int si=0; si<elm->n_sides(); si++) {
364  Boundary *b = elm.side(si)->cond();
365  if (b != NULL) {
366  double flux = mh_dh->side_flux( *(elm.side(si)) );
367  if (flux < 0.0) {
368  double aij = -(flux / elm.measure() );
369 
370  for (sbi=0; sbi<n_substances(); sbi++)
371  {
372  double value = data_.bc_conc[sbi].value( b->element_accessor().centre(), b->element_accessor() );
373 
374  VecSetValue(bcvcorr[sbi], new_i, value * aij, ADD_VALUES);
375 
376  // CAUTION: It seems that PETSc possibly optimize allocated space during assembly.
377  // So we have to add also values that may be non-zero in future due to changing velocity field.
378  balance_->add_flux_matrix_values(subst_idx[sbi], loc_b, {row_4_el[el_4_loc[loc_el]]}, {0.});
379  balance_->add_flux_vec_value(subst_idx[sbi], loc_b, flux*value);
380  }
381  } else {
382  for (sbi=0; sbi<n_substances(); sbi++)
383  VecSetValue(bcvcorr[sbi], new_i, 0, ADD_VALUES);
384 
385  for (unsigned int sbi=0; sbi<n_substances(); sbi++)
386  {
387  balance_->add_flux_matrix_values(subst_idx[sbi], loc_b, {row_4_el[el_4_loc[loc_el]]}, {flux});
388  balance_->add_flux_vec_value(subst_idx[sbi], loc_b, 0);
389  }
390  }
391  ++loc_b;
392  }
393  }
394 
395  }
396  }
397 
398  balance_->finish_flux_assembly(subst_idx);
399 
400  for (sbi=0; sbi<n_substances(); sbi++) VecAssemblyBegin(bcvcorr[sbi]);
401  for (sbi=0; sbi<n_substances(); sbi++) VecAssemblyEnd(bcvcorr[sbi]);
402 
403  // we are calling set_boundary_conditions() after next_time() and
404  // we are using data from t() before, so we need to set corresponding bc time
406 }
407 
408 
409 //=============================================================================
410 // COMPUTE SOURCES
411 //=============================================================================
413 
414  //temporary variables
415  unsigned int loc_el, sbi;
416  double csection, source, diag;
417 
418  ElementAccessor<3> ele_acc;
419  arma::vec3 p;
420 
421  //TODO: would it be possible to check the change in data for chosen substance? (may be in multifields?)
422 
423  //checking if the data were changed
424  if( (data_.sources_density.changed() )
425  || (data_.sources_conc.changed() )
426  || (data_.sources_sigma.changed() )
427  || (data_.cross_section.changed()))
428  {
429  START_TIMER("sources_reinit");
430  balance_->start_source_assembly(subst_idx);
431 
432  for (loc_el = 0; loc_el < el_ds->lsize(); loc_el++)
433  {
434  ele_acc = mesh_->element_accessor( el_4_loc[loc_el] );
435  p = ele_acc.centre();
436  csection = data_.cross_section.value(p, ele_acc);
437 
438  // read for all substances
439  double max_cfl=0;
440  for (sbi = 0; sbi < n_substances(); sbi++)
441  {
442  double src_sigma = data_.sources_sigma[sbi].value(p, ele_acc);
443 
444  source = csection * (data_.sources_density[sbi].value(p, ele_acc) + src_sigma * data_.sources_conc[sbi].value(p, ele_acc));
445  // addition to RHS
446  sources_corr[sbi][loc_el] = source;
447  // addition to diagonal of the transport matrix
448  diag = src_sigma * csection;
449  tm_diag[sbi][loc_el] = - diag;
450 
451  // compute maximal cfl condition over all substances
452  max_cfl = std::max(max_cfl, fabs(diag));
453 
454  balance_->add_source_matrix_values(sbi, ele_acc.region().bulk_idx(), {row_4_el[el_4_loc[loc_el]]},
455  {- src_sigma * ele_acc.measure() * csection});
456  balance_->add_source_vec_values(sbi, ele_acc.region().bulk_idx(), {row_4_el[el_4_loc[loc_el]]},
457  {source * ele_acc.measure()});
458  }
459 
460  cfl_source_[loc_el] = max_cfl;
461  }
462 
463  balance_->finish_source_assembly(subst_idx);
464 
465  END_TIMER("sources_reinit");
466  }
467 }
468 
469 
470 
472 {
474 
477  std::stringstream ss; // print warning message with table of uninitialized fields
478  if ( FieldCommon::print_message_table(ss, "convection transport") ) {
479  WarningOut() << ss.str();
480  }
481 
484 
485  START_TIMER("Convection balance zero time step");
486 
490 
491  // write initial condition
492  output_data();
493 }
494 
495 
497 {
498  OLD_ASSERT(mh_dh, "Null MH object.\n" );
499  data_.set_time(time_->step(), LimitSide::right); // set to the last computed time
500 
501  START_TIMER("data reinit");
502 
503  bool cfl_changed = false;
504 
505  // if FLOW or DATA changed ---------------------> recompute transport matrix
507  {
510  cfl_changed = true;
511  DebugOut() << "CFL changed - flow.\n";
512  }
513 
515  {
517  cfl_changed = true;
518  DebugOut() << "CFL changed - mass matrix.\n";
519  }
520 
521  // if DATA changed ---------------------> recompute concentration sources (rhs and matrix diagonal)
524  {
526  is_src_term_scaled = false;
527  cfl_changed = true;
528  DebugOut() << "CFL changed - source.\n";
529  }
530 
531  // now resolve the CFL condition
532  if(cfl_changed)
533  {
534  // find maximum of sum of contribution from flow and sources: MAX(vcfl_flow_ + vcfl_source_)
535  Vec cfl;
536  VecCreateMPI(PETSC_COMM_WORLD, el_ds->lsize(),PETSC_DETERMINE, &cfl);
537  VecWAXPY(cfl, 1.0, vcfl_flow_, vcfl_source_);
538  VecMaxPointwiseDivide(cfl,mass_diag, &cfl_max_step);
539  // get a reciprocal value as a time constraint
541  DebugOut().fmt("CFL constraint (transport): {}\n", cfl_max_step);
542  }
543 
544  // although it does not influence CFL, compute BC so the full system is assembled
546  || data_.porosity.changed()
548  || data_.bc_conc.changed() )
549  {
551  is_bc_term_scaled = false;
552  }
553 
554  END_TIMER("data reinit");
555 
556  // return time constraint
557  time_constraint = cfl_max_step;
558  return cfl_changed;
559 }
560 
562 
563  START_TIMER("convection-one step");
564 
565  // proceed to next time - which we are about to compute
566  // explicit scheme looks one step back and uses data from previous time
567  // (data time set previously in assess_time_constraint())
568  time_->next_time();
569 
570  double dt_new = time_->dt(), // current time step we are about to compute
571  dt_scaled = dt_new / time_->last_dt(); // scaling ratio to previous time step
572 
573  START_TIMER("time step rescaling");
574 
575  // if FLOW or DATA or BC or DT changed ---------------------> rescale boundary condition
577  {
578  DebugOut() << "BC - rescale dt.\n";
579  //choose between fresh scaling with new dt or rescaling to a new dt
580  double dt = (!is_bc_term_scaled) ? dt_new : dt_scaled;
581  for (unsigned int sbi=0; sbi<n_substances(); sbi++)
582  VecScale(bcvcorr[sbi], dt);
583  is_bc_term_scaled = true;
584  }
585 
586 
587  // if DATA or TIME STEP changed -----------------------> rescale source term
589  DebugOut() << "SRC - rescale dt.\n";
590  //choose between fresh scaling with new dt or rescaling to a new dt
591  double dt = (!is_src_term_scaled) ? dt_new : dt_scaled;
592  for (unsigned int sbi=0; sbi<n_substances(); sbi++)
593  {
594  VecScale(v_sources_corr[sbi], dt);
595  VecScale(v_tm_diag[sbi], dt);
596  }
597  is_src_term_scaled = true;
598  }
599 
600  // if DATA or TIME STEP changed -----------------------> rescale transport matrix
602  DebugOut() << "TM - rescale dt.\n";
603  //choose between fresh scaling with new dt or rescaling to a new dt
604  double dt = (!is_convection_matrix_scaled) ? dt_new : dt_scaled;
605 
606  MatScale(tm, dt);
608  }
609 
610  END_TIMER("time step rescaling");
611 
612 
613  data_.set_time(time_->step(), LimitSide::right); // set to the last computed time
615  {
616  VecCopy(mass_diag, vpmass_diag);
618  } else is_mass_diag_changed = false;
619 
620 
621  // Compute new concentrations for every substance.
622 
623  for (unsigned int sbi = 0; sbi < n_substances(); sbi++) {
624  // one step in MOBILE phase
625  START_TIMER("mat mult");
626 
627  // tm_diag is a diagonal part of transport matrix, which depends on substance data (sources_sigma)
628  // Wwe need keep transport matrix independent of substance, therefore we keep this diagonal part
629  // separately in a vector tm_diag.
630  // Computation: first, we compute this diagonal addition D*pconc and save it temporaly into RHS
631 
632  // RHS = D*pconc, where D is diagonal matrix represented by a vector
633  VecPointwiseMult(vcumulative_corr[sbi], v_tm_diag[sbi], vconc[sbi]); //w = x.*y
634 
635  // Then we add boundary terms ans other source terms into RHS.
636  // RHS = 1.0 * bcvcorr + 1.0 * v_sources_corr + 1.0 * rhs
637  VecAXPBYPCZ(vcumulative_corr[sbi], 1.0, 1.0, 1.0, bcvcorr[sbi], v_sources_corr[sbi]); //z = ax + by + cz
638 
639  // Then we set the new previous concentration.
640  VecCopy(vconc[sbi], vpconc[sbi]); // pconc = conc
641  // And finally proceed with transport matrix multiplication.
642  if (is_mass_diag_changed) {
643  VecPointwiseMult(vconc[sbi], vconc[sbi], vpmass_diag); // vconc*=vpmass_diag
644  MatMultAdd(tm, vpconc[sbi], vconc[sbi], vconc[sbi]); // vconc+=tm*vpconc
645  VecAXPY(vconc[sbi], 1, vcumulative_corr[sbi]); // vconc+=vcumulative_corr
646  VecPointwiseDivide(vconc[sbi], vconc[sbi], mass_diag); // vconc/=mass_diag
647  } else {
648  MatMultAdd(tm, vpconc[sbi], vcumulative_corr[sbi], vconc[sbi]); // vconc =tm*vpconc+vcumulative_corr
649  VecPointwiseDivide(vconc[sbi], vconc[sbi], mass_diag); // vconc/=mass_diag
650  VecAXPY(vconc[sbi], 1, vpconc[sbi]); // vconc+=vpconc
651  }
652 
653  END_TIMER("mat mult");
654  }
655 
656  for (unsigned int sbi=0; sbi<n_substances(); ++sbi)
657  balance_->calculate_cumulative(sbi, vpconc[sbi]);
658 
659  END_TIMER("convection-one step");
660 }
661 
662 
663 void ConvectionTransport::set_target_time(double target_time)
664 {
665 
666  //sets target_mark_type (it is fixed) to be met in next_time()
667  time_->marks().add(TimeMark(target_time, target_mark_type));
668 
669  // This is done every time TOS calls update_solution.
670  // If CFL condition is changed, time fixation will change later from TOS.
671 
672  // Set the same constraint as was set last time.
673 
674  // TODO: fix this hack, remove this method completely, leaving just the first line at the calling point
675  // in TransportOperatorSplitting::update_solution()
676  // doing this directly leads to choose of large time step violationg CFL condition
677  if (cfl_max_step > time_->dt()*1e-10)
678  time_->set_upper_constraint(cfl_max_step, "CFL condition used from previous step.");
679 
680  // fixing convection time governor till next target_mark_type (got from TOS or other)
681  // may have marks for data changes
683 }
684 
685 
687 {
688  ElementAccessor<3> elm;
689 
690  VecZeroEntries(mass_diag);
691 
692  balance_->start_mass_assembly(subst_idx);
693 
694  for (unsigned int loc_el = 0; loc_el < el_ds->lsize(); loc_el++) {
695  elm = mesh_->element_accessor( el_4_loc[loc_el] );
696 
697  double csection = data_.cross_section.value(elm.centre(), elm);
698  //double por_m = data_.porosity.value(elm.centre(), elm->element_accessor());
699  double por_m = data_.water_content.value(elm.centre(), elm);
700 
701  for (unsigned int sbi=0; sbi<n_substances(); ++sbi)
702  balance_->add_mass_matrix_values(subst_idx[sbi], elm.region().bulk_idx(), {row_4_el[el_4_loc[loc_el]]}, {csection*por_m*elm.measure()} );
703 
704  VecSetValue(mass_diag, row_4_el[ elm.idx() ], csection*por_m, INSERT_VALUES);
705  }
706 
707  balance_->finish_mass_assembly(subst_idx);
708 
709  VecAssemblyBegin(mass_diag);
710  VecAssemblyEnd(mass_diag);
711 
712  is_mass_diag_changed = true;
713 }
714 
715 
716 //=============================================================================
717 // CREATE TRANSPORT MATRIX
718 //=============================================================================
720 
721  START_TIMER("convection_matrix_assembly");
722 
723  ElementAccessor<3> el2;
724  ElementAccessor<3> elm;
725  const Edge *edg;
726  int j, np, rank;
727  LongIdx new_j, new_i;
728  double aij, aii;
729 
730  MatZeroEntries(tm);
731 
732  MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
733  MPI_Comm_size(PETSC_COMM_WORLD, &np);
734 
735  double flux, flux2, edg_flux;
736 
737  aii = 0.0;
738 
739  for (unsigned int loc_el = 0; loc_el < el_ds->lsize(); loc_el++) {
740  elm = mesh_->element_accessor( el_4_loc[loc_el] );
741  new_i = row_4_el[ elm.idx() ];
742 
743  for (unsigned int si=0; si<elm->n_sides(); si++) {
744  // same dim
745  flux = mh_dh->side_flux( *(elm.side(si)) );
746  if (elm.side(si)->cond() == NULL) {
747  edg = elm.side(si)->edge();
748  edg_flux = 0;
749  for( int s=0; s < edg->n_sides; s++) {
750  flux2 = mh_dh->side_flux( *(edg->side(s)) );
751  if ( flux2 > 0) edg_flux+= flux2;
752  }
753  for(unsigned int s=0; s<edg->n_sides; s++)
754  // this test should also eliminate sides facing to lower dim. elements in comp. neighboring
755  // These edges on these sides should have just one side
756  if (edg->side(s) != elm.side(si)) {
757  j = edg->side(s)->element().idx();
758  new_j = row_4_el[j];
759 
760  flux2 = mh_dh->side_flux( *(edg->side(s)));
761  if ( flux2 > 0.0 && flux <0.0)
762  aij = -(flux * flux2 / ( edg_flux * elm.measure() ) );
763  else aij =0;
764  MatSetValue(tm, new_i, new_j, aij, INSERT_VALUES);
765  }
766  }
767  if (flux > 0.0)
768  aii -= (flux / elm.measure() );
769  } // end same dim //ELEMENT_SIDES
770 
771  for (unsigned int n=0; n<elm->n_neighs_vb(); n++) // comp model
772  {
773  el2 = mesh_->element_accessor( elm->neigh_vb[n]->side()->element().idx() ); // higher dim. el.
774  ASSERT( el2.idx() != elm.idx() ).error("Elm. same\n");
775  new_j = row_4_el[ el2.idx() ];
776  flux = mh_dh->side_flux( *(elm->neigh_vb[n]->side()) );
777 
778  // volume source - out-flow from higher dimension
779  if (flux > 0.0) aij = flux / elm.measure();
780  else aij=0;
781  MatSetValue(tm, new_i, new_j, aij, INSERT_VALUES);
782  // out flow from higher dim. already accounted
783 
784  // volume drain - in-flow to higher dimension
785  if (flux < 0.0) {
786  aii -= (-flux) / elm.measure(); // diagonal drain
787  aij = (-flux) / el2.measure();
788  } else aij=0;
789  MatSetValue(tm, new_j, new_i, aij, INSERT_VALUES);
790  }
791 
792  MatSetValue(tm, new_i, new_i, aii, INSERT_VALUES);
793 
794  cfl_flow_[loc_el] = fabs(aii);
795  aii = 0.0;
796  } // END ELEMENTS
797 
798  MatAssemblyBegin(tm, MAT_FINAL_ASSEMBLY);
799  MatAssemblyEnd(tm, MAT_FINAL_ASSEMBLY);
800 
802  END_TIMER("convection_matrix_assembly");
803 
805 }
806 
807 
808 
809 
810 
811 //=============================================================================
812 // OUTPUT VECTOR GATHER
813 //=============================================================================
815 
816  unsigned int sbi;
817  IS is;
818 
819  ISCreateGeneral(PETSC_COMM_SELF, mesh_->n_elements(), row_4_el, PETSC_COPY_VALUES, &is); //WithArray
820  VecScatterCreate(vconc[0], is, out_conc[0].get_data_petsc(), PETSC_NULL, &vconc_out_scatter);
821  for (sbi = 0; sbi < n_substances(); sbi++) {
822  VecScatterBegin(vconc_out_scatter, vconc[sbi], out_conc[sbi].get_data_petsc(), INSERT_VALUES, SCATTER_FORWARD);
823  VecScatterEnd(vconc_out_scatter, vconc[sbi], out_conc[sbi].get_data_petsc(), INSERT_VALUES, SCATTER_FORWARD);
824  }
825  chkerr(VecScatterDestroy(&(vconc_out_scatter)));
826  chkerr(ISDestroy(&(is)));
827 }
828 
829 
831  return conc;
832 }
833 
834 void ConvectionTransport::get_par_info(LongIdx * &el_4_loc_out, Distribution * &el_distribution_out){
835  el_4_loc_out = this->el_4_loc;
836  el_distribution_out = this->el_ds;
837  return;
838 }
839 
840 //int *ConvectionTransport::get_el_4_loc(){
841 // return el_4_loc;
842 //}
843 
845  return row_4_el;
846 }
847 
848 
849 
851 
853  //if ( data_.output_fields.is_field_output_time(data_.conc_mobile, time().step()) ) {
855  //}
856 
857  for (unsigned int sbi = 0; sbi < n_substances(); sbi++) {
858  out_conc[sbi].fill_output_data(output_field_ptr[sbi]);
859  }
860 
861  data_.output_fields.output(time().step());
862 
863  START_TIMER("TOS-balance");
864  for (unsigned int sbi=0; sbi<n_substances(); ++sbi)
865  balance_->calculate_instant(sbi, vconc[sbi]);
866  balance_->output();
867  END_TIMER("TOS-balance");
868 }
869 
870 void ConvectionTransport::set_balance_object(std::shared_ptr<Balance> balance)
871 {
872  balance_ = balance;
873  subst_idx = balance_->add_quantities(substances_.names());
874 }
TimeGovernor & time()
Definition: equation.hh:148
void output_type(OutputTime::DiscreteSpace rt)
Definition: field_set.hh:211
int LongIdx
Define type that represents indices of large arrays (elements, nodes, dofs etc.)
Definition: long_idx.hh:22
const Edge * edge() const
Definition: side_impl.hh:66
unsigned int size() const
get global size
FieldSet * eq_data_
Definition: equation.hh:232
static auto subdomain(Mesh &mesh) -> IndexField
std::vector< VectorSeqDouble > out_conc
Definition: transport.h:307
bool is_mass_diag_changed
Flag indicates that porosity or cross_section changed during last time.
Definition: transport.h:268
double time_changed() const
void update_solution() override
Definition: transport.cc:561
Accessor to input data conforming to declared Array.
Definition: accessors.hh:567
double end_time() const
End time.
unsigned int * boundary_idx_
Definition: elements.h:83
LongIdx * get_row_4_el() const
Definition: mesh.h:171
double transport_matrix_time
Definition: transport.h:293
unsigned int size() const
Returns number of keys in the Record.
Definition: type_record.hh:598
int tlevel() const
const std::vector< std::string > & names()
Definition: substance.hh:85
Class Input::Type::Default specifies default value of keys of a Input::Type::Record.
Definition: type_record.hh:61
void alloc_transport_vectors()
Definition: transport.cc:256
unsigned int n_substances() override
Returns number of transported substances.
Definition: transport.h:202
void output(TimeStep step)
Boundary * cond() const
Definition: side_impl.hh:71
double fix_dt_until_mark()
Fixing time step until fixed time mark.
MultiField< 3, FieldValue< 3 >::Scalar > conc_mobile
Calculated concentrations in the mobile zone.
Definition: transport.h:103
void create_mass_matrix()
Definition: transport.cc:686
void next_time()
Proceed to the next time according to current estimated time step.
void initialize() override
Definition: transport.cc:120
std::shared_ptr< OutputTime > output_stream_
Definition: transport.h:317
TimeMark::Type target_mark_type
TimeMark type for time marks denoting end of every time interval where transport matrix remains const...
Definition: transport.h:275
static Default obligatory()
The factory function to make an empty default value which is obligatory.
Definition: type_record.hh:110
void set_initial_condition()
Definition: transport.cc:239
Field< 3, FieldValue< 3 >::Scalar > region_id
Definition: transport.h:101
double transport_bc_time
Time of the last update of the boundary condition terms.
Definition: transport.h:294
double * cfl_flow_
Definition: transport.h:280
MultiField< 3, FieldValue< 3 >::Scalar > sources_density
Concentration sources - density of substance source, only positive part is used.
void set_boundary_conditions()
Definition: transport.cc:345
Definition: mesh.h:80
Fields computed from the mesh data.
EquationOutput output_fields
Fields indended for output, i.e. all input fields plus those representing solution.
Definition: transport.h:107
double ** sources_corr
Definition: transport.h:271
LongIdx * el_4_loc
Definition: transport.h:321
MultiField< 3, FieldValue< 3 >::Scalar > sources_conc
BCMultiField< 3, FieldValue< 3 >::Scalar > bc_conc
Definition: transport.h:96
void chkerr(unsigned int ierr)
Replacement of new/delete operator in the spirit of xmalloc.
Definition: system.hh:147
std::vector< std::shared_ptr< FieldFE< 3, FieldValue< 3 >::Scalar > > > output_field_ptr
Fields correspond with out_conc.
Definition: transport.h:312
int n_sides
Definition: edges.h:36
Definition: edges.h:26
SideIter side(const unsigned int loc_index)
Definition: accessors.hh:137
void set_balance_object(std::shared_ptr< Balance > balance) override
Definition: transport.cc:870
#define ASSERT(expr)
Allow use shorter versions of macro names if these names is not used with external library...
Definition: asserts.hh:346
double ** conc
Concentrations for phase, substance, element.
Definition: transport.h:299
const TimeStep & step(int index=-1) const
virtual ~ConvectionTransport()
Definition: transport.cc:189
static Input::Type::Abstract & get_input_type()
Common specification of the input record for secondary equations.
MultiField< 3, FieldValue< 3 >::Scalar > init_conc
Initial concentrations.
Definition: transport.h:99
double t() const
#define ADD_FIELD(name,...)
Definition: field_set.hh:279
FieldCommon & units(const UnitSI &units)
Set basic units of the field.
ElementAccessor< 3 > element() const
Definition: side_impl.hh:53
void zero_time_step() override
Definition: transport.cc:471
static TimeMarks & marks()
void output_vector_gather()
Definition: transport.cc:814
Basic time management class.
Class for declaration of inputs sequences.
Definition: type_base.hh:346
virtual ElementAccessor< 3 > element_accessor(unsigned int idx) const
Create and return ElementAccessor to element of given idx.
Definition: mesh.cc:719
const Input::Record input_rec
Record with input specification.
Definition: transport.h:315
static constexpr bool value
Definition: json.hpp:87
Field< 3, FieldValue< 3 >::Scalar > subdomain
Definition: transport.h:102
const string _equation_name
Definition: transport.cc:61
double last_t() const
const MH_DofHandler * mh_dh
Definition: transport.h:332
arma::vec::fixed< spacedim > centre() const
Computes the barycenter.
Definition: accessors.hh:285
static const Input::Type::Record & get_input_type()
Definition: transport.cc:67
virtual Record & derive_from(Abstract &parent)
Method to derive new Record from an AbstractRecord parent.
Definition: type_record.cc:195
#define OLD_ASSERT(...)
Definition: global_defs.h:131
void setup_components()
bool is_local(unsigned int idx) const
identify local index
static constexpr Mask equation_result
Match result fields. These are never given by input or copy of input.
Definition: field_flag.hh:55
Neighbour ** neigh_vb
Definition: elements.h:87
TimeMark::Type equation_fixed_mark_type() const
MultiField< 3, FieldValue< 3 >::Scalar > sources_sigma
Concentration sources - Robin type, in_flux = sources_sigma * (sources_conc - mobile_conc) ...
static constexpr Mask equation_external_output
Match an output field, that can be also copy of other field.
Definition: field_flag.hh:58
SideIter side()
Definition: neighbours.h:147
unsigned int begin(int proc) const
get starting local index
Accessor to the data with type Type::Record.
Definition: accessors.hh:292
const Ret val(const string &key) const
unsigned int n_sides() const
Definition: elements.h:135
static auto region_id(Mesh &mesh) -> IndexField
ConvectionTransport(Mesh &init_mesh, const Input::Record in_rec)
Definition: transport.cc:103
static const int registrar
Registrar of class to factory.
Definition: transport.h:252
bool is_changed_dt() const
#define START_TIMER(tag)
Starts a timer with specified tag.
SubstanceList substances_
Transported substances.
Definition: transport.h:325
Mesh * mesh_
Definition: equation.hh:223
LongIdx * get_row_4_el() override
Return global array of order of elements within parallel vector.
Definition: transport.cc:844
virtual Value::return_type const & value(const Point &p, const ElementAccessor< spacedim > &elm) const
Definition: field.hh:389
double ** get_concentration_matrix() override
Getter for array of concentrations per element.
Definition: transport.cc:830
Field< 3, FieldValue< 3 >::Scalar > porosity
Mobile porosity - usually saturated water content in the case of unsaturated flow model...
std::shared_ptr< Balance > balance_
object for calculation and writing the mass balance to file.
Definition: equation.hh:235
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:501
virtual Range< ElementAccessor< 3 > > elements_range() const
Returns range of bulk elements.
Definition: mesh.cc:1033
double measure() const
Computes the measure of the element.
Definition: accessors.hh:254
vector< unsigned int > subst_idx
List of indices used to call balance methods for a set of quantities.
Definition: transport.h:335
Distribution * get_el_ds() const
Definition: mesh.h:168
#define MPI_Comm_size
Definition: mpi.h:235
Field< 3, FieldValue< 3 >::Scalar > water_content
Water content - result of unsaturated water flow model or porosity.
Vec * vconc
Concentration vectors for mobile phase.
Definition: transport.h:297
Region region() const
Definition: accessors.hh:95
#define MPI_Comm_rank
Definition: mpi.h:236
void mark_input_times(const TimeGovernor &tg)
Definition: field_set.hh:218
TimeMark add(const TimeMark &mark)
Definition: time_marks.cc:81
void create_transport_matrix_mpi()
Definition: transport.cc:719
Support classes for parallel programing.
void alloc_transport_structs_mpi()
Definition: transport.cc:290
int set_upper_constraint(double upper, std::string message)
Sets upper constraint for the next time step estimating.
double side_flux(const Side &side) const
temporary replacement for DofHandler accessor, flux through given side
bool is_convection_matrix_scaled
Definition: transport.h:265
FLOW123D_FORCE_LINK_IN_CHILD(convectionTransport)
void set_input_list(Input::Array input_list, const TimeGovernor &tg)
Definition: field_set.hh:190
double * cfl_source_
Definition: transport.h:280
virtual unsigned int n_elements(bool boundary=false) const
Returns count of boundary or bulk elements.
Definition: mesh.h:346
void initialize(std::shared_ptr< OutputTime > stream, Mesh *mesh, Input::Record in_rec, const TimeGovernor &tg)
void set_components(const std::vector< string > &names)
Definition: field_set.hh:177
void compute_concentration_sources()
Assembles concentration sources for each substance. note: the source of concentration is multiplied b...
Definition: transport.cc:412
bool evaluate_time_constraint(double &time_constraint) override
Definition: transport.cc:496
VecScatter vconc_out_scatter
Definition: transport.h:283
double dt() const
Vec vcfl_flow_
Parallel vector for flow contribution to CFL condition.
Definition: transport.h:278
void set_target_time(double target_time) override
Definition: transport.cc:663
double ** tm_diag
Definition: transport.h:288
virtual void output_data() override
Write computed fields.
Definition: transport.cc:850
bool set_time(const TimeStep &time, LimitSide limit_side)
Definition: field_set.cc:157
void get_par_info(LongIdx *&el_4_loc, Distribution *&el_ds) override
Return array of indices of local elements and parallel distribution of elements.
Definition: transport.cc:834
Distributed sparse graphs, partitioning.
Vec vcfl_source_
Parallel vector for source term contribution to CFL condition.
Definition: transport.h:278
unsigned int bulk_idx() const
Returns index of the region in the bulk set.
Definition: region.hh:91
#define WarningOut()
Macro defining &#39;warning&#39; record of log.
Definition: logger.hh:246
FieldCommon & name(const string &name)
#define END_TIMER(tag)
Ends a timer with specified tag.
#define OLD_ASSERT_EQUAL(a, b)
Definition: global_defs.h:133
double ** cumulative_corr
Definition: transport.h:305
bool changed() const
void set_mesh(const Mesh &mesh)
Definition: field_set.hh:183
Class used for marking specified times at which some events occur.
Definition: time_marks.hh:45
Record type proxy class.
Definition: type_record.hh:182
FieldCommon & flags(FieldFlag::Flags::Mask mask)
Field< 3, FieldValue< 3 >::Scalar > cross_section
Pointer to DarcyFlow field cross_section.
Class for representation SI units of Fields.
Definition: unit_si.hh:40
#define MPI_Barrier(comm)
Definition: mpi.h:531
double last_dt() const
unsigned int n_neighs_vb() const
Return number of neighbours.
Definition: elements.h:70
static UnitSI & dimensionless()
Returns dimensionless unit.
Definition: unit_si.cc:55
#define DebugOut()
Macro defining &#39;debug&#39; record of log.
Definition: logger.hh:252
static bool print_message_table(ostream &stream, std::string equation_name)
Definition: field_common.cc:96
unsigned int idx() const
Return local idx of element in boundary / bulk part of element vector.
Definition: accessors.hh:111
Other possible transformation of coordinates:
LongIdx * get_el_4_loc() const
Definition: mesh.h:174
Distribution * el_ds
Definition: transport.h:322
SideIter side(const unsigned int i) const
Definition: edges.h:31
Implementation of range helper class.
ElementAccessor< 3 > element_accessor()
Definition: boundaries.cc:48
void make_transport_partitioning()
Definition: transport.cc:162
LongIdx * row_4_el
Definition: transport.h:320
double cfl_max_step
Time step constraint coming from CFL condition.
Definition: transport.h:276
TimeGovernor * time_
Definition: equation.hh:224
unsigned int lsize(int proc) const
get local size