Flow123d  JS_before_hm-1626-gde32303
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 #include "system/index_types.hh"
24 
25 #include "mesh/mesh.h"
26 #include "mesh/partitioning.hh"
27 #include "mesh/accessors.hh"
28 #include "mesh/range_wrapper.hh"
29 #include "mesh/neighbours.h"
30 #include "transport/transport.h"
31 
32 #include "la/distribution.hh"
33 
34 #include "la/sparse_graph.hh"
35 #include <iostream>
36 #include <iomanip>
37 #include <string>
38 
39 #include "io/output_time.hh"
40 #include "tools/time_governor.hh"
41 #include "tools/mixed.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 
54 #include "fem/fe_p.hh"
55 #include "fem/fe_values.hh"
57 
58 
59 FLOW123D_FORCE_LINK_IN_CHILD(convectionTransport)
60 
61 
62 namespace IT = Input::Type;
63 
64 /********************************************************************************
65  * Static methods and data members
66  */
67 const string _equation_name = "Solute_Advection_FV";
68 
69 const int ConvectionTransport::registrar =
71  ConvectionTransport::get_input_type().size();
72 
73 const IT::Record &ConvectionTransport::get_input_type()
74 {
75  return IT::Record(_equation_name, "Finite volume method, explicit in time, for advection only solute transport.")
77  .declare_key("input_fields", IT::Array(
78  EqData().make_field_descriptor_type(_equation_name)),
80  "")
81  .declare_key("output",
82  EqData().output_fields.make_output_type(_equation_name, ""),
83  IT::Default("{ \"fields\": [ \"conc\" ] }"),
84  "Specification of output fields and output times.")
85  .close();
86 }
87 
88 
90 {
91  *this += bc_conc.name("bc_conc")
92  .description("Boundary condition for concentration of substances.")
93  .input_default("0.0")
94  .units( UnitSI().kg().m(-3) );
95 
96  *this += init_conc.name("init_conc")
97  .description("Initial values for concentration of substances.")
98  .input_default("0.0")
99  .units( UnitSI().kg().m(-3) );
100 
101  output_fields += *this;
102  output_fields += conc_mobile.name("conc")
103  .units( UnitSI().kg().m(-3) )
105  .description("Concentration solution.");
106  output_fields += region_id.name("region_id")
109  .description("Region ids.");
110  output_fields += subdomain.name("subdomain")
113  .description("Subdomain ids of the domain decomposition.");
114 }
115 
116 
117 /********************************************************************************
118  * Helper class FETransportObjects
119  */
121 : q_(QGauss::make_array(0))
122 {
123  fe0_ = new FE_P_disc<0>(0);
124  fe1_ = new FE_P_disc<1>(0);
125  fe2_ = new FE_P_disc<2>(0);
126  fe3_ = new FE_P_disc<3>(0);
127 
128 
129  fe_values_[0].initialize(q(0), *fe1_,
131  fe_values_[1].initialize(q(1), *fe2_,
133  fe_values_[2].initialize(q(2), *fe3_,
135 }
136 
137 
139 {
140  delete fe0_;
141  delete fe1_;
142  delete fe2_;
143  delete fe3_;
144 }
145 
146 template<> FiniteElement<0> *FETransportObjects::fe<0>() { return fe0_; }
147 template<> FiniteElement<1> *FETransportObjects::fe<1>() { return fe1_; }
148 template<> FiniteElement<2> *FETransportObjects::fe<2>() { return fe2_; }
149 template<> FiniteElement<3> *FETransportObjects::fe<3>() { return fe3_; }
150 
151 Quadrature &FETransportObjects::q(unsigned int dim) { return q_[dim]; }
152 
153 
154 
155 /********************************************************************************
156  * ConvectionTransport
157  */
159 : ConcentrationTransportBase(init_mesh, in_rec),
160  is_mass_diag_changed(false),
161  tm_diag(nullptr),
162  input_rec(in_rec)
163 {
164  START_TIMER("ConvectionTransport");
165  this->eq_fieldset_ = &data_;
166 
167  transport_matrix_time = -1.0; // or -infty
168  transport_bc_time = -1.0;
170  is_src_term_scaled = false;
171  is_bc_term_scaled = false;
172 
173  //initialization of DOF handler
174  MixedPtr<FE_P_disc> fe(0);
175  dh_ = make_shared<DOFHandlerMultiDim>(init_mesh);
176  shared_ptr<DiscreteSpace> ds = make_shared<EqualOrderDiscreteSpace>( &init_mesh, fe);
177  dh_->distribute_dofs(ds);
178 
179 }
180 
182 {
184 
186 
188  data_.set_input_list( input_rec.val<Input::Array>("input_fields"), *time_ );
189  data_.set_mesh(*mesh_);
190 
194 
195  // register output vectors
202  for (unsigned int sbi=0; sbi<n_substances(); sbi++)
203  {
204  // create shared pointer to a FieldFE and push this Field to output_field on all regions
205  data_.conc_mobile_fe[sbi] = create_field_fe< 3, FieldValue<3>::Scalar >(dh_);
206  data_.conc_mobile[sbi].set(data_.conc_mobile_fe[sbi], 0);
207  }
208  //output_stream_->add_admissible_field_names(input_rec.val<Input::Array>("output_fields"));
209  //output_stream_->mark_output_times(*time_);
210 
212  //cout << "Transport." << endl;
213  //cout << time().marks();
214 
215  balance_->allocate(el_ds->lsize(), 1);
216 
217 }
218 
219 
221 {
222  return data_.conc_mobile_fe[sbi]->vec().petsc_vec();
223 }
224 
225 
226 //=============================================================================
227 // MAKE TRANSPORT
228 //=============================================================================
230 
231 // int * id_4_old = new int[mesh_->n_elements()];
232 // int i = 0;
233 // for (auto ele : mesh_->elements_range()) id_4_old[i++] = ele.index();
234 // mesh_->get_part()->id_maps(mesh_->n_elements(), id_4_old, el_ds, el_4_loc, row_4_el);
235 // delete[] id_4_old;
236  el_ds = mesh_->get_el_ds();
239 
240  // TODO: make output of partitioning is usefull but makes outputs different
241  // on different number of processors, which breaks tests.
242  //
243  // Possible solution:
244  // - have flag in ini file to turn this output ON
245  // - possibility to have different ref_output for different num of proc.
246  // - or do not test such kind of output
247  //
248  //for (auto ele : mesh_->elements_range()) {
249  // ele->pid()=el_ds->get_proc(row_4_el[ele.index()]);
250  //}
251 
252 }
253 
254 
255 
257 {
258  unsigned int sbi;
259 
260  if (tm_diag) {
261  //Destroy mpi vectors at first
262  chkerr(MatDestroy(&tm));
263  chkerr(VecDestroy(&mass_diag));
264  chkerr(VecDestroy(&vpmass_diag));
265  chkerr(VecDestroy(&vcfl_flow_));
266  chkerr(VecDestroy(&vcfl_source_));
267  delete cfl_flow_;
268  delete cfl_source_;
269 
270  for (sbi = 0; sbi < n_substances(); sbi++) {
271  // mpi vectors
272  chkerr(VecDestroy(&vpconc[sbi]));
273  chkerr(VecDestroy(&bcvcorr[sbi]));
274  chkerr(VecDestroy(&vcumulative_corr[sbi]));
275  chkerr(VecDestroy(&v_tm_diag[sbi]));
276 
277  // arrays of arrays
278  delete cumulative_corr[sbi];
279  delete tm_diag[sbi];
280  }
281 
282  // arrays of mpi vectors
283  delete vpconc;
284  delete bcvcorr;
285  delete vcumulative_corr;
286  delete v_tm_diag;
287 
288  // arrays of arrays
289  delete cumulative_corr;
290  delete tm_diag;
291  }
292 }
293 
294 
295 
296 
297 
299 {
300  DebugOut() << "ConvectionTransport::set_initial_condition()\n";
301  // get vecs
303  for (unsigned int sbi=0; sbi<n_substances(); sbi++)
304  vecs.push_back(data_.conc_mobile_fe[sbi]->vec());
305 
306  for ( DHCellAccessor dh_cell : dh_->own_range() ) {
307  LongIdx index = dh_cell.local_idx();
308  ElementAccessor<3> ele_acc = mesh_->element_accessor( dh_cell.elm_idx() );
309 
310  for (unsigned int sbi=0; sbi<n_substances(); sbi++) { // Optimize: SWAP LOOPS
311  vecs[sbi].set( index, data_.init_conc[sbi].value(ele_acc.centre(), ele_acc) );
312  }
313  }
314 }
315 
316 //=============================================================================
317 // ALLOCATE OF TRANSPORT VARIABLES (ELEMENT & NODES)
318 //=============================================================================
320 
321  unsigned int sbi, n_subst;
322  n_subst = n_substances();
323 
324  tm_diag = new double*[n_subst];
325  cumulative_corr = new double*[n_subst];
326  for (sbi = 0; sbi < n_subst; sbi++) {
327  cumulative_corr[sbi] = new double[el_ds->lsize()];
328  tm_diag[sbi] = new double[el_ds->lsize()];
329  }
330 
331  data_.conc_mobile_fe.resize(n_subst);
332 
333  cfl_flow_ = new double[el_ds->lsize()];
334  cfl_source_ = new double[el_ds->lsize()];
335 }
336 
337 //=============================================================================
338 // ALLOCATION OF TRANSPORT VECTORS (MPI)
339 //=============================================================================
341 
342  int sbi, n_subst;
343  n_subst = n_substances();
344 
345  MPI_Barrier(PETSC_COMM_WORLD);
346 
347  vpconc = new Vec[n_subst];
348  bcvcorr = new Vec[n_subst];
349  vcumulative_corr = new Vec[n_subst];
350  v_tm_diag = new Vec[n_subst];
351 
352 
353  for (sbi = 0; sbi < n_subst; sbi++) {
354  VecCreateMPI(PETSC_COMM_WORLD, el_ds->lsize(), mesh_->n_elements(), &bcvcorr[sbi]);
355  VecZeroEntries(bcvcorr[sbi]);
356 
357  VecCreateMPI(PETSC_COMM_WORLD, el_ds->lsize(), mesh_->n_elements(), &vpconc[sbi]);
358  VecZeroEntries(vpconc[sbi]);
359 
360  // SOURCES
361  VecCreateMPIWithArray(PETSC_COMM_WORLD,1, el_ds->lsize(), mesh_->n_elements(),
362  cumulative_corr[sbi],&vcumulative_corr[sbi]);
363 
364  corr_vec.emplace_back(el_ds->lsize(), PETSC_COMM_WORLD);
365 
366  VecCreateMPIWithArray(PETSC_COMM_WORLD,1, el_ds->lsize(), mesh_->n_elements(),
367  tm_diag[sbi],&v_tm_diag[sbi]);
368 
369  VecZeroEntries(vcumulative_corr[sbi]);
370  }
371 
372 
373  MatCreateAIJ(PETSC_COMM_WORLD, el_ds->lsize(), el_ds->lsize(), mesh_->n_elements(),
374  mesh_->n_elements(), 16, PETSC_NULL, 4, PETSC_NULL, &tm);
375 
376  VecCreateMPI(PETSC_COMM_WORLD, el_ds->lsize(), mesh_->n_elements(), &mass_diag);
377  VecCreateMPI(PETSC_COMM_WORLD, el_ds->lsize(), mesh_->n_elements(), &vpmass_diag);
378 
379  VecCreateMPIWithArray(PETSC_COMM_WORLD,1, el_ds->lsize(), mesh_->n_elements(),
381  VecCreateMPIWithArray(PETSC_COMM_WORLD,1, el_ds->lsize(), mesh_->n_elements(),
383 }
384 
385 
386 //=============================================================================
387 // COMPUTE SOURCES, SET BOUNDARY CONDITIONS
388 //=============================================================================
390 
391  //temporary variables
392  double csection, source, diag;
393  unsigned int sbi;
394  bool sources_changed = ( (data_.sources_density.changed() )
395  || (data_.sources_conc.changed() )
396  || (data_.sources_sigma.changed() )
397  || (data_.cross_section.changed()));
398 
399  //TODO: would it be possible to check the change in data for chosen substance? (may be in multifields?)
400 
401  START_TIMER("sources_reinit_set_bc");
402  if (sources_changed) balance_->start_source_assembly(subst_idx);
403  // Assembly bcvcorr vector
404  for(sbi=0; sbi < n_substances(); sbi++) VecZeroEntries(bcvcorr[sbi]);
405 
406  balance_->start_flux_assembly(subst_idx);
407 
408  for ( DHCellAccessor dh_cell : dh_->own_range() )
409  {
410  ElementAccessor<3> elm = dh_cell.elm();
411  // we have currently zero order P_Disc FE
412  ASSERT_DBG(dh_cell.get_loc_dof_indices().size() == 1);
413  IntIdx local_p0_dof = dh_cell.get_loc_dof_indices()[0];
414  LongIdx glob_p0_dof = dh_->get_local_to_global_map()[local_p0_dof];
415 
416  arma::vec3 center = elm.centre();
417  csection = data_.cross_section.value(center, elm);
418 
419  // SET SOURCES
420 
421  if (sources_changed) {
422  // read for all substances
423  double max_cfl=0;
424  for (sbi = 0; sbi < n_substances(); sbi++)
425  {
426  double src_sigma = data_.sources_sigma[sbi].value(center, elm);
427 
428  source = csection * (data_.sources_density[sbi].value(center, elm)
429  + src_sigma * data_.sources_conc[sbi].value(center, elm));
430  // addition to RHS
431  corr_vec[sbi].set(local_p0_dof, source);
432  // addition to diagonal of the transport matrix
433  diag = src_sigma * csection;
434  tm_diag[sbi][local_p0_dof] = - diag;
435 
436  // compute maximal cfl condition over all substances
437  max_cfl = std::max(max_cfl, fabs(diag));
438 
439  balance_->add_source_values(sbi, elm.region().bulk_idx(), {local_p0_dof},
440  {- src_sigma * elm.measure() * csection},
441  {source * elm.measure()});
442  }
443 
444  cfl_source_[local_p0_dof] = max_cfl;
445  }
446 
447  // BOUNDARY CONDITIONS
448 
449  for(DHCellSide dh_side: dh_cell.side_range()) {
450  if (dh_side.side().is_boundary()) {
451  ElementAccessor<3> bc_elm = dh_side.cond().element_accessor();
452  double flux = this->side_flux(dh_side);
453  if (flux < 0.0) {
454  double aij = -(flux / elm.measure() );
455 
456  for (sbi=0; sbi<n_substances(); sbi++)
457  {
458  double value = data_.bc_conc[sbi].value( bc_elm.centre(), bc_elm );
459 
460  VecSetValue(bcvcorr[sbi], glob_p0_dof, value * aij, ADD_VALUES);
461 
462  // CAUTION: It seems that PETSc possibly optimize allocated space during assembly.
463  // So we have to add also values that may be non-zero in future due to changing velocity field.
464  balance_->add_flux_values(subst_idx[sbi], dh_side,
465  {local_p0_dof}, {0.0}, flux*value);
466  }
467  } else {
468  for (sbi=0; sbi<n_substances(); sbi++)
469  VecSetValue(bcvcorr[sbi], glob_p0_dof, 0, ADD_VALUES);
470 
471  for (unsigned int sbi=0; sbi<n_substances(); sbi++)
472  balance_->add_flux_values(subst_idx[sbi], dh_side,
473  {local_p0_dof}, {flux}, 0.0);
474  }
475  }
476  }
477  }
478 
479  balance_->finish_flux_assembly(subst_idx);
480  if (sources_changed) balance_->finish_source_assembly(subst_idx);
481 
482  for (sbi=0; sbi<n_substances(); sbi++) VecAssemblyBegin(bcvcorr[sbi]);
483  for (sbi=0; sbi<n_substances(); sbi++) VecAssemblyEnd(bcvcorr[sbi]);
484 
485  // we are calling set_boundary_conditions() after next_time() and
486  // we are using data from t() before, so we need to set corresponding bc time
488  END_TIMER("sources_reinit_set_bc");
489 }
490 
491 
492 
494 {
496 
499  std::stringstream ss; // print warning message with table of uninitialized fields
500  if ( FieldCommon::print_message_table(ss, "convection transport") ) {
501  WarningOut() << ss.str();
502  }
503 
506 
507  START_TIMER("Convection balance zero time step");
508 
511 
512  // write initial condition
513  output_data();
514 }
515 
516 
518 {
519  ASSERT_PTR(dh_).error( "Null DOF handler object.\n" );
520  // read changed status before setting time
521  bool changed_flux = data_.flow_flux.changed();
522  data_.set_time(time_->step(), LimitSide::right); // set to the last computed time
523 
524  START_TIMER("data reinit");
525 
526  bool cfl_changed = false;
527 
528  // if FLOW or DATA changed ---------------------> recompute transport matrix
529  if (changed_flux)
530  {
533  cfl_changed = true;
534  DebugOut() << "CFL changed - flow.\n";
535  }
536 
538  {
540  cfl_changed = true;
541  DebugOut() << "CFL changed - mass matrix.\n";
542  }
543 
544  // if DATA changed ---------------------> recompute concentration sources (rhs and matrix diagonal)
548  {
551  || data_.cross_section.changed() ) {
552  is_src_term_scaled = false;
553  cfl_changed = true;
554  }
557  DebugOut() << "CFL changed - source.\n";
558  }
559 
560  // now resolve the CFL condition
561  if(cfl_changed)
562  {
563  // find maximum of sum of contribution from flow and sources: MAX(vcfl_flow_ + vcfl_source_)
564  Vec cfl;
565  VecCreateMPI(PETSC_COMM_WORLD, el_ds->lsize(),PETSC_DETERMINE, &cfl);
566  VecWAXPY(cfl, 1.0, vcfl_flow_, vcfl_source_);
567  VecMaxPointwiseDivide(cfl,mass_diag, &cfl_max_step);
568  // get a reciprocal value as a time constraint
570  DebugOut().fmt("CFL constraint (transport): {}\n", cfl_max_step);
571  }
572 
573  END_TIMER("data reinit");
574 
575  // return time constraint
576  time_constraint = cfl_max_step;
577  return cfl_changed;
578 }
579 
581 
582  START_TIMER("convection-one step");
583 
584  // proceed to next time - which we are about to compute
585  // explicit scheme looks one step back and uses data from previous time
586  // (data time set previously in assess_time_constraint())
587  time_->next_time();
588 
589  double dt_new = time_->dt(), // current time step we are about to compute
590  dt_scaled = dt_new / time_->last_dt(); // scaling ratio to previous time step
591 
592  START_TIMER("time step rescaling");
593 
594  // if FLOW or DATA or BC or DT changed ---------------------> rescale boundary condition
596  {
597  DebugOut() << "BC - rescale dt.\n";
598  //choose between fresh scaling with new dt or rescaling to a new dt
599  double dt = (!is_bc_term_scaled) ? dt_new : dt_scaled;
600  for (unsigned int sbi=0; sbi<n_substances(); sbi++)
601  VecScale(bcvcorr[sbi], dt);
602  is_bc_term_scaled = true;
603  }
604 
605 
606  // if DATA or TIME STEP changed -----------------------> rescale source term
608  DebugOut() << "SRC - rescale dt.\n";
609  //choose between fresh scaling with new dt or rescaling to a new dt
610  double dt = (!is_src_term_scaled) ? dt_new : dt_scaled;
611  for (unsigned int sbi=0; sbi<n_substances(); sbi++)
612  {
613  VecScale(corr_vec[sbi].petsc_vec(), dt);
614  VecScale(v_tm_diag[sbi], dt);
615  }
616  is_src_term_scaled = true;
617  }
618 
619  // if DATA or TIME STEP changed -----------------------> rescale transport matrix
621  DebugOut() << "TM - rescale dt.\n";
622  //choose between fresh scaling with new dt or rescaling to a new dt
623  double dt = (!is_convection_matrix_scaled) ? dt_new : dt_scaled;
624 
625  MatScale(tm, dt);
627  }
628 
629  END_TIMER("time step rescaling");
630 
631 
632  data_.set_time(time_->step(), LimitSide::right); // set to the last computed time
634  {
635  VecCopy(mass_diag, vpmass_diag);
637  } else is_mass_diag_changed = false;
638 
639 
640  // Compute new concentrations for every substance.
641 
642  for (unsigned int sbi = 0; sbi < n_substances(); sbi++) {
643  // one step in MOBILE phase
644  START_TIMER("mat mult");
645  Vec vconc = data_.conc_mobile_fe[sbi]->vec().petsc_vec();
646 
647  // tm_diag is a diagonal part of transport matrix, which depends on substance data (sources_sigma)
648  // Wwe need keep transport matrix independent of substance, therefore we keep this diagonal part
649  // separately in a vector tm_diag.
650  // Computation: first, we compute this diagonal addition D*pconc and save it temporaly into RHS
651 
652  // RHS = D*pconc, where D is diagonal matrix represented by a vector
653  VecPointwiseMult(vcumulative_corr[sbi], v_tm_diag[sbi], vconc); //w = x.*y
654 
655  // Then we add boundary terms ans other source terms into RHS.
656  // RHS = 1.0 * bcvcorr + 1.0 * corr_vec + 1.0 * rhs
657  VecAXPBYPCZ(vcumulative_corr[sbi], 1.0, 1.0, 1.0, bcvcorr[sbi], corr_vec[sbi].petsc_vec()); //z = ax + by + cz
658 
659  // Then we set the new previous concentration.
660  VecCopy(vconc, vpconc[sbi]); // pconc = conc
661  // And finally proceed with transport matrix multiplication.
662  if (is_mass_diag_changed) {
663  VecPointwiseMult(vconc, vconc, vpmass_diag); // vconc*=vpmass_diag
664  MatMultAdd(tm, vpconc[sbi], vconc, vconc); // vconc+=tm*vpconc
665  VecAXPY(vconc, 1, vcumulative_corr[sbi]); // vconc+=vcumulative_corr
666  VecPointwiseDivide(vconc, vconc, mass_diag); // vconc/=mass_diag
667  } else {
668  MatMultAdd(tm, vpconc[sbi], vcumulative_corr[sbi], vconc); // vconc =tm*vpconc+vcumulative_corr
669  VecPointwiseDivide(vconc, vconc, mass_diag); // vconc/=mass_diag
670  VecAXPY(vconc, 1, vpconc[sbi]); // vconc+=vpconc
671  }
672 
673  END_TIMER("mat mult");
674  }
675 
676  for (unsigned int sbi=0; sbi<n_substances(); ++sbi)
677  balance_->calculate_cumulative(sbi, vpconc[sbi]);
678 
679  END_TIMER("convection-one step");
680 }
681 
682 
683 void ConvectionTransport::set_target_time(double target_time)
684 {
685 
686  //sets target_mark_type (it is fixed) to be met in next_time()
687  time_->marks().add(TimeMark(target_time, target_mark_type));
688 
689  // This is done every time TOS calls update_solution.
690  // If CFL condition is changed, time fixation will change later from TOS.
691 
692  // Set the same constraint as was set last time.
693 
694  // TODO: fix this hack, remove this method completely, leaving just the first line at the calling point
695  // in TransportOperatorSplitting::update_solution()
696  // doing this directly leads to choose of large time step violationg CFL condition
697  if (cfl_max_step > time_->dt()*1e-10)
698  time_->set_upper_constraint(cfl_max_step, "CFL condition used from previous step.");
699 
700  // fixing convection time governor till next target_mark_type (got from TOS or other)
701  // may have marks for data changes
703 }
704 
705 
707 {
708  ElementAccessor<3> elm;
709 
710  VecZeroEntries(mass_diag);
711 
712  balance_->start_mass_assembly(subst_idx);
713 
714  for ( DHCellAccessor dh_cell : dh_->own_range() ) {
715  ElementAccessor<3> elm = dh_cell.elm();
716  // we have currently zero order P_Disc FE
717  ASSERT_DBG(dh_cell.get_loc_dof_indices().size() == 1);
718  IntIdx local_p0_dof = dh_cell.get_loc_dof_indices()[0];
719 
720  double csection = data_.cross_section.value(elm.centre(), elm);
721  //double por_m = data_.porosity.value(elm.centre(), elm->element_accessor());
722  double por_m = data_.water_content.value(elm.centre(), elm);
723 
724  for (unsigned int sbi=0; sbi<n_substances(); ++sbi)
725  balance_->add_mass_values(subst_idx[sbi], dh_cell, {local_p0_dof}, {csection*por_m*elm.measure()}, 0);
726 
727  VecSetValue(mass_diag, dh_->get_local_to_global_map()[local_p0_dof], csection*por_m, INSERT_VALUES);
728  }
729 
730  balance_->finish_mass_assembly(subst_idx);
731 
732  VecAssemblyBegin(mass_diag);
733  VecAssemblyEnd(mass_diag);
734 
735  is_mass_diag_changed = true;
736 }
737 
738 
739 //=============================================================================
740 // CREATE TRANSPORT MATRIX
741 //=============================================================================
743 
744  START_TIMER("convection_matrix_assembly");
745 
746  ElementAccessor<3> el2;
747  ElementAccessor<3> elm;
748  int j;
749  LongIdx new_j, new_i;
750  double aij, aii;
751 
752  MatZeroEntries(tm);
753 
754  double flux, flux2, edg_flux;
755 
756  aii = 0.0;
757 
758  unsigned int loc_el = 0;
759  for ( DHCellAccessor dh_cell : dh_->own_range() ) {
760  new_i = row_4_el[ dh_cell.elm_idx() ];
761  elm = dh_cell.elm();
762  for( DHCellSide cell_side : dh_cell.side_range() ) {
763  flux = this->side_flux(cell_side);
764  if (! cell_side.side().is_boundary()) {
765  edg_flux = 0;
766  for( DHCellSide edge_side : cell_side.edge_sides() ) {
767  el2 = edge_side.element();
768  flux2 = this->side_flux(edge_side);
769  if ( flux2 > 0) edg_flux+= flux2;
770  }
771  for( DHCellSide edge_side : cell_side.edge_sides() )
772  if (edge_side != cell_side) {
773  j = edge_side.element().idx();
774  new_j = row_4_el[j];
775 
776  el2 = edge_side.element();
777  flux2 = this->side_flux(edge_side);
778  if ( flux2 > 0.0 && flux <0.0)
779  aij = -(flux * flux2 / ( edg_flux * dh_cell.elm().measure() ) );
780  else aij =0;
781  MatSetValue(tm, new_i, new_j, aij, INSERT_VALUES);
782  }
783  }
784  if (flux > 0.0)
785  aii -= (flux / dh_cell.elm().measure() );
786  } // end same dim //ELEMENT_SIDES
787 
788  for( DHCellSide neighb_side : dh_cell.neighb_sides() ) // dh_cell lower dim
789  {
790  ASSERT( neighb_side.elem_idx() != dh_cell.elm_idx() ).error("Elm. same\n");
791  new_j = row_4_el[ neighb_side.elem_idx() ];
792  el2 = neighb_side.element();
793  flux = this->side_flux(neighb_side);
794 
795  // volume source - out-flow from higher dimension
796  if (flux > 0.0) aij = flux / dh_cell.elm().measure();
797  else aij=0;
798  MatSetValue(tm, new_i, new_j, aij, INSERT_VALUES);
799  // out flow from higher dim. already accounted
800 
801  // volume drain - in-flow to higher dimension
802  if (flux < 0.0) {
803  aii -= (-flux) / dh_cell.elm().measure(); // diagonal drain
804  aij = (-flux) / neighb_side.element().measure();
805  } else aij=0;
806  MatSetValue(tm, new_j, new_i, aij, INSERT_VALUES);
807  }
808 
809  MatSetValue(tm, new_i, new_i, aii, INSERT_VALUES);
810 
811  cfl_flow_[loc_el++] = fabs(aii);
812  aii = 0.0;
813  }
814 
815  MatAssemblyBegin(tm, MAT_FINAL_ASSEMBLY);
816  MatAssemblyEnd(tm, MAT_FINAL_ASSEMBLY);
817 
819  END_TIMER("convection_matrix_assembly");
820 
822 }
823 
824 
826  return data_.conc_mobile_fe;
827 }
828 
829 void ConvectionTransport::get_par_info(LongIdx * &el_4_loc_out, Distribution * &el_distribution_out){
830  el_4_loc_out = this->el_4_loc;
831  el_distribution_out = this->el_ds;
832  return;
833 }
834 
835 //int *ConvectionTransport::get_el_4_loc(){
836 // return el_4_loc;
837 //}
838 
840  return row_4_el;
841 }
842 
843 
844 
846 
848  data_.output_fields.output(time().step());
849 
850  START_TIMER("TOS-balance");
851  for (unsigned int sbi=0; sbi<n_substances(); ++sbi)
852  balance_->calculate_instant(sbi, data_.conc_mobile_fe[sbi]->vec().petsc_vec());
853  balance_->output();
854  END_TIMER("TOS-balance");
855 }
856 
857 void ConvectionTransport::set_balance_object(std::shared_ptr<Balance> balance)
858 {
859  balance_ = balance;
860  subst_idx = balance_->add_quantities(substances_.names());
861 }
862 
864 {
865  if (cell_side.dim()==3) return calculate_side_flux<3>(cell_side);
866  else if (cell_side.dim()==2) return calculate_side_flux<2>(cell_side);
867  else return calculate_side_flux<1>(cell_side);
868 }
869 
870 template<unsigned int dim>
872 {
873  ASSERT_EQ(cell_side.dim(), dim).error("Element dimension mismatch!");
874 
875  feo_.fe_values(dim).reinit(cell_side.side());
876  auto vel = data_.flow_flux.value(cell_side.centre(), cell_side.element());
877  double side_flux = arma::dot(vel, feo_.fe_values(dim).normal_vector(0)) * feo_.fe_values(dim).JxW(0);
878  return side_flux;
879 }
TimeGovernor & time()
Definition: equation.hh:149
void output_type(OutputTime::DiscreteSpace rt)
Definition: field_set.hh:303
MultiField< 3, FieldValue< 3 >::Scalar > sources_conc
Shape function values.
Definition: update_flags.hh:87
const Element * element() const
Definition: accessors.hh:160
static auto subdomain(Mesh &mesh) -> IndexField
Quadrature & q(unsigned int dim)
Definition: transport.cc:151
bool is_mass_diag_changed
Flag indicates that porosity or cross_section changed during last time.
Definition: transport.h:311
Transformed quadrature weight for cell sides.
void update_solution() override
Definition: transport.cc:580
Accessor to input data conforming to declared Array.
Definition: accessors.hh:566
double end_time() const
End time.
LongIdx * get_row_4_el() const
Definition: mesh.h:174
double transport_matrix_time
Definition: transport.h:335
Field< 3, FieldValue< 3 >::VectorFixed > flow_flux
Flow flux, can be result of water flow model.
int tlevel() const
double calculate_side_flux(const DHCellSide &cell)
Calculate flux on side of given element specified by dimension.
Definition: transport.cc:871
unsigned int dim() const
Return dimension of element appropriate to the side.
Field< 3, FieldValue< 3 >::Scalar > water_content
Water content - result of unsaturated water flow model or porosity.
const std::vector< std::string > & names()
Definition: substance.hh:85
QGauss::array q_
Quadratures used in assembling methods.
Definition: transport.h:108
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:319
unsigned int n_substances() override
Returns number of transported substances.
Definition: transport.h:240
int IntIdx
Definition: index_types.hh:25
void output(TimeStep step)
double fix_dt_until_mark()
Fixing time step until fixed time mark.
Abstract linear system class.
Definition: balance.hh:40
MultiField< 3, FieldValue< 3 >::Scalar > conc_mobile
Calculated concentrations in the mobile zone.
Definition: transport.h:142
void create_mass_matrix()
Definition: transport.cc:706
MultiField< 3, FieldValue< 3 >::Scalar > sources_sigma
Concentration sources - Robin type, in_flux = sources_sigma * (sources_conc - mobile_conc) ...
void next_time()
Proceed to the next time according to current estimated time step.
virtual unsigned int n_elements() const
Returns count of boundary or bulk elements.
Definition: mesh.h:361
void initialize() override
Definition: transport.cc:181
std::shared_ptr< OutputTime > output_stream_
Definition: transport.h:347
TimeMark::Type target_mark_type
TimeMark type for time marks denoting end of every time interval where transport matrix remains const...
Definition: transport.h:317
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:298
Field< 3, FieldValue< 3 >::Scalar > region_id
Definition: transport.h:139
double transport_bc_time
Time of the last update of the boundary condition terms.
Definition: transport.h:336
double * cfl_flow_
Definition: transport.h:322
Definition: mesh.h:77
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:146
Cell accessor allow iterate over DOF handler cells.
LongIdx * el_4_loc
Definition: transport.h:351
Class FEValues calculates finite element data on the actual cells such as shape function values...
BCMultiField< 3, FieldValue< 3 >::Scalar > bc_conc
Definition: transport.h:134
void chkerr(unsigned int ierr)
Replacement of new/delete operator in the spirit of xmalloc.
Definition: system.hh:142
double side_flux(const DHCellSide &cell_side)
Wrapper of following method, call side_flux with correct template parameter.
Definition: transport.cc:863
void set_balance_object(std::shared_ptr< Balance > balance) override
Definition: transport.cc:857
#define ASSERT(expr)
Allow use shorter versions of macro names if these names is not used with external library...
Definition: asserts.hh:347
const TimeStep & step(int index=-1) const
virtual ~ConvectionTransport()
Definition: transport.cc:256
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:137
double t() const
FieldCommon & units(const UnitSI &units)
Set basic units of the field.
void zero_time_step() override
Definition: transport.cc:493
Side side() const
Return Side of given cell and side_idx.
int register_class(string class_name)
Function allows simplified call of registering class to factory.
Definition: factory_impl.hh:64
void reinit(const ElementAccessor< spacedim > &cell)
Update cell-dependent data (gradients, Jacobians etc.)
Definition: fe_values.cc:541
static TimeMarks & marks()
void set(std::vector< typename Field< spacedim, Value >::FieldBasePtr > field_vec, double time, std::vector< std::string > region_set_names={"ALL"})
Basic time management class.
FieldFEScalarVec & get_p0_interpolation() override
Getter for P0 interpolation by FieldFE.
Definition: transport.cc:825
Class for declaration of inputs sequences.
Definition: type_base.hh:339
virtual ElementAccessor< 3 > element_accessor(unsigned int idx) const
Create and return ElementAccessor to element of given idx.
Definition: mesh.cc:921
const Input::Record input_rec
Record with input specification.
Definition: transport.h:345
Base class for quadrature rules on simplices in arbitrary dimensions.
Definition: quadrature.hh:48
static constexpr bool value
Definition: json.hpp:87
Symmetric Gauss-Legendre quadrature formulae on simplices.
Field< 3, FieldValue< 3 >::Scalar > subdomain
Definition: transport.h:140
const string _equation_name
Definition: transport.cc:67
FieldFEScalarVec conc_mobile_fe
Underlaying FieldFE for each substance of conc_mobile.
Definition: transport.h:143
double last_t() const
arma::vec::fixed< spacedim > centre() const
Computes the barycenter.
virtual Record & derive_from(Abstract &parent)
Method to derive new Record from an AbstractRecord parent.
Definition: type_record.cc:196
vector< VectorMPI > corr_vec
Definition: transport.h:314
void setup_components()
Discontinuous Lagrangean finite element on dim dimensional simplex.
Definition: fe_p.hh:108
Transformed quadrature points.
static constexpr Mask equation_result
Match result fields. These are never given by input or copy of input.
Definition: field_flag.hh:55
RangeConvert< DHEdgeSide, DHCellSide > edge_sides() const
Returns range of all sides looped over common Edge.
FieldCommon & input_default(const string &input_default)
TimeMark::Type equation_fixed_mark_type() const
Definitions of basic Lagrangean finite elements with polynomial shape functions.
static constexpr Mask equation_external_output
Match an output field, that can be also copy of other field.
Definition: field_flag.hh:58
Accessor to the data with type Type::Record.
Definition: accessors.hh:291
ElementAccessor< 3 > element() const
const Ret val(const string &key) const
static auto region_id(Mesh &mesh) -> IndexField
ConvectionTransport(Mesh &init_mesh, const Input::Record in_rec)
Definition: transport.cc:158
FieldSet * eq_fieldset_
Definition: equation.hh:227
void initialize(Quadrature &_quadrature, FiniteElement< DIM > &_fe, UpdateFlags _flags)
Initialize structures and calculates cell-independent data.
Definition: fe_values.cc:137
bool is_changed_dt() const
#define START_TIMER(tag)
Starts a timer with specified tag.
SubstanceList substances_
Transported substances.
Definition: transport.h:355
Mesh * mesh_
Definition: equation.hh:218
Vec get_component_vec(unsigned int sbi) override
Return PETSc vector with solution for sbi-th substance.
Definition: transport.cc:220
LongIdx * get_row_4_el() override
Return global array of order of elements within parallel vector.
Definition: transport.cc:839
virtual Value::return_type const & value(const Point &p, const ElementAccessor< spacedim > &elm) const
Definition: field.hh:452
FEValues< 3 > & fe_values(unsigned int dim)
Definition: transport.h:93
std::shared_ptr< Balance > balance_
object for calculation and writing the mass balance to file.
Definition: equation.hh:230
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
std::shared_ptr< DOFHandlerMultiDim > dh_
Definition: transport.h:362
double measure() const
Computes the measure of the element.
vector< unsigned int > subst_idx
List of indices used to call balance methods for a set of quantities.
Definition: transport.h:365
Shape function gradients.
Definition: update_flags.hh:95
Distribution * get_el_ds() const
Definition: mesh.h:171
std::shared_ptr< Balance > balance() const
Definition: equation.hh:185
FEValues< 3 > fe_values_[3]
FESideValues objects for side flux calculating.
Definition: transport.h:111
Region region() const
Definition: accessors.hh:165
Normal vectors.
void mark_input_times(const TimeGovernor &tg)
Definition: field_set.hh:310
TimeMark add(const TimeMark &mark)
Definition: time_marks.cc:81
Field< 3, FieldValue< 3 >::Scalar > porosity
Mobile porosity - usually saturated water content in the case of unsaturated flow model...
void create_transport_matrix_mpi()
Definition: transport.cc:742
Support classes for parallel programing.
void alloc_transport_structs_mpi()
Definition: transport.cc:340
int set_upper_constraint(double upper, std::string message)
Sets upper constraint for the next time step estimating.
int LongIdx
Define type that represents indices of large arrays (elements, nodes, dofs etc.)
Definition: index_types.hh:24
FieldCommon & description(const string &description)
bool is_convection_matrix_scaled
Definition: transport.h:308
void set_input_list(Input::Array input_list, const TimeGovernor &tg)
Definition: field_set.hh:282
double * cfl_source_
Definition: transport.h:322
void initialize(std::shared_ptr< OutputTime > stream, Mesh *mesh, Input::Record in_rec, const TimeGovernor &tg)
#define ASSERT_PTR(ptr)
Definition of assert macro checking non-null pointer (PTR)
Definition: asserts.hh:336
void set_components(const std::vector< string > &names)
Definition: field_set.hh:268
bool evaluate_time_constraint(double &time_constraint) override
Definition: transport.cc:517
FiniteElement< 1 > * fe1_
Definition: transport.h:103
double dt() const
Vec vcfl_flow_
Parallel vector for flow contribution to CFL condition.
Definition: transport.h:320
void set_target_time(double target_time) override
Definition: transport.cc:683
double ** tm_diag
Definition: transport.h:330
virtual void output_data() override
Write computed fields.
Definition: transport.cc:845
bool set_time(const TimeStep &time, LimitSide limit_side)
Definition: field_set.cc:164
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:829
Distributed sparse graphs, partitioning.
#define ASSERT_DBG(expr)
Vec vcfl_source_
Parallel vector for source term contribution to CFL condition.
Definition: transport.h:320
unsigned int bulk_idx() const
Returns index of the region in the bulk set.
Definition: region.hh:91
Definitions of particular quadrature rules on simplices.
#define WarningOut()
Macro defining &#39;warning&#39; record of log.
Definition: logger.hh:270
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:110
double ** cumulative_corr
Definition: transport.h:342
bool changed() const
void set_mesh(const Mesh &mesh)
Definition: field_set.hh:274
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
FETransportObjects feo_
Finite element objects.
Definition: transport.h:368
FieldCommon & flags(FieldFlag::Flags::Mask mask)
double JxW(const unsigned int point_no)
Return the product of Jacobian determinant and the quadrature weight at given quadrature point...
Definition: fe_values.hh:223
Class for representation SI units of Fields.
Definition: unit_si.hh:40
#define MPI_Barrier(comm)
Definition: mpi.h:531
double last_dt() const
void conc_sources_bdr_conditions()
Assembles concentration sources for each substance and set boundary conditions. note: the source of c...
Definition: transport.cc:389
static UnitSI & dimensionless()
Returns dimensionless unit.
Definition: unit_si.cc:55
#define DebugOut()
Macro defining &#39;debug&#39; record of log.
Definition: logger.hh:276
static bool print_message_table(ostream &stream, std::string equation_name)
Definition: field_common.cc:96
Other possible transformation of coordinates:
FiniteElement< 3 > * fe3_
Definition: transport.h:105
FiniteElement< 0 > * fe0_
Finite elements for the solution of the advection-diffusion equation.
Definition: transport.h:102
LongIdx * get_el_4_loc() const
Definition: mesh.h:177
Distribution * el_ds
Definition: transport.h:352
Implementation of range helper class.
Side accessor allows to iterate over sides of DOF handler cell.
#define FLOW123D_FORCE_LINK_IN_CHILD(x)
Definition: global_defs.h:157
#define ASSERT_EQ(a, b)
Definition of comparative assert macro (EQual)
Definition: asserts.hh:328
void make_transport_partitioning()
Definition: transport.cc:229
LongIdx * row_4_el
Definition: transport.h:350
double cfl_max_step
Time step constraint coming from CFL condition.
Definition: transport.h:318
TimeGovernor * time_
Definition: equation.hh:219
FiniteElement< 2 > * fe2_
Definition: transport.h:104
Field< 3, FieldValue< 3 >::Scalar > cross_section
Pointer to DarcyFlow field cross_section.
MultiField< 3, FieldValue< 3 >::Scalar > sources_density
Concentration sources - density of substance source, only positive part is used.
unsigned int lsize(int proc) const
get local size
arma::vec::fixed< spacedim > normal_vector(unsigned int point_no)
Returns the normal vector to a side at given quadrature point.
Definition: fe_values.hh:257
arma::vec3 centre() const
Side centre.