Flow123d  PE_user_fields-12e8aadde
darcy_flow_mh.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 darcy_flow_mh.cc
15  * @ingroup flow
16  * @brief Setup and solve linear system of mixed-hybrid discretization of the linear
17  * porous media flow with possible preferential flow in fractures and chanels.
18  */
19 
20 //#include <limits>
21 #include <vector>
22 //#include <iostream>
23 //#include <iterator>
24 //#include <algorithm>
25 #include <armadillo>
26 
27 #include "petscmat.h"
28 #include "petscviewer.h"
29 #include "petscerror.h"
30 #include "mpi.h"
31 
32 #include "system/system.hh"
33 #include "system/sys_profiler.hh"
34 #include "system/index_types.hh"
35 #include "input/factory.hh"
36 
37 #include "mesh/mesh.h"
38 #include "mesh/bc_mesh.hh"
39 #include "mesh/partitioning.hh"
40 #include "mesh/accessors.hh"
41 #include "mesh/range_wrapper.hh"
42 #include "la/distribution.hh"
43 #include "la/linsys.hh"
44 #include "la/linsys_PETSC.hh"
45 #include "la/linsys_BDDC.hh"
46 #include "la/schur.hh"
47 //#include "la/sparse_graph.hh"
49 #include "la/vector_mpi.hh"
50 
51 #include "flow/assembly_mh_old.hh"
52 #include "flow/darcy_flow_mh.hh"
54 #include "flow/assembly_models.hh"
55 
56 #include "tools/time_governor.hh"
58 #include "fields/field.hh"
59 #include "fields/field_values.hh"
61 #include "fields/field_fe.hh"
62 #include "fields/field_model.hh"
63 #include "fields/field_constant.hh"
64 
65 #include "coupling/balance.hh"
66 
69 
70 #include "fem/fe_p.hh"
71 
72 
73 FLOW123D_FORCE_LINK_IN_CHILD(darcy_flow_mh)
74 
75 
76 
77 
78 
79 namespace it = Input::Type;
80 
81 const std::string DarcyMH::equation_name_ = "Flow_Darcy_MH";
82 
84  return it::Selection("MH_MortarMethod")
85  .add_value(NoMortar, "None", "No Mortar method is applied.")
86  .add_value(MortarP0, "P0", "Mortar space: P0 on elements of lower dimension.")
87  .add_value(MortarP1, "P1", "Mortar space: P1 on intersections, using non-conforming pressures.")
88  .close();
89 }
90 
91 
93  return it::Selection("Flow_Darcy_BC_Type")
94  .add_value(none, "none",
95  "Homogeneous Neumann boundary condition\n(zero normal flux over the boundary).")
96  .add_value(dirichlet, "dirichlet",
97  "Dirichlet boundary condition. "
98  "Specify the pressure head through the ``bc_pressure`` field "
99  "or the piezometric head through the ``bc_piezo_head`` field.")
100  .add_value(total_flux, "total_flux", "Flux boundary condition (combines Neumann and Robin type). "
101  "Water inflow equal to (($ \\delta_d(q_d^N + \\sigma_d (h_d^R - h_d) )$)). "
102  "Specify the water inflow by the ``bc_flux`` field, the transition coefficient by ``bc_robin_sigma`` "
103  "and the reference pressure head or piezometric head through ``bc_pressure`` or ``bc_piezo_head`` respectively.")
104  .add_value(seepage, "seepage",
105  "Seepage face boundary condition. Pressure and inflow bounded from above. Boundary with potential seepage flow "
106  "is described by the pair of inequalities: "
107  "(($h_d \\le h_d^D$)) and (($ -\\boldsymbol q_d\\cdot\\boldsymbol n \\le \\delta q_d^N$)), where the equality holds in at least one of them. "
108  "Caution: setting (($q_d^N$)) strictly negative "
109  "may lead to an ill posed problem since a positive outflow is enforced. "
110  "Parameters (($h_d^D$)) and (($q_d^N$)) are given by the fields ``bc_switch_pressure`` (or ``bc_switch_piezo_head``) and ``bc_flux`` respectively."
111  )
112  .add_value(river, "river",
113  "River boundary condition. For the water level above the bedrock, (($H_d > H_d^S$)), the Robin boundary condition is used with the inflow given by: "
114  "(( $ \\delta_d(q_d^N + \\sigma_d(H_d^D - H_d) )$)). For the water level under the bedrock, constant infiltration is used: "
115  "(( $ \\delta_d(q_d^N + \\sigma_d(H_d^D - H_d^S) )$)). Parameters: ``bc_pressure``, ``bc_switch_pressure``, "
116  " ``bc_sigma``, ``bc_flux``."
117  )
118  .close();
119 }
120 
122 
123  const it::Record &field_descriptor =
125  .copy_keys( DarcyMH::EqFields().make_field_descriptor_type(equation_name_ + "_Data_aux") )
126  .declare_key("bc_piezo_head", FieldAlgorithmBase< 3, FieldValue<3>::Scalar >::get_input_type_instance(),
127  "Boundary piezometric head for BC types: dirichlet, robin, and river." )
128  .declare_key("bc_switch_piezo_head", FieldAlgorithmBase< 3, FieldValue<3>::Scalar >::get_input_type_instance(),
129  "Boundary switch piezometric head for BC types: seepage, river." )
130  .declare_key("init_piezo_head", FieldAlgorithmBase< 3, FieldValue<3>::Scalar >::get_input_type_instance(),
131  "Initial condition for the pressure given as the piezometric head." )
132  .close();
133  return field_descriptor;
134 }
135 
137  it::Record ns_rec = Input::Type::Record("NonlinearSolver", "Non-linear solver settings.")
138  .declare_key("linear_solver", LinSys::get_input_type(), it::Default("{}"),
139  "Linear solver for MH problem.")
140  .declare_key("tolerance", it::Double(0.0), it::Default("1E-6"),
141  "Residual tolerance.")
142  .declare_key("min_it", it::Integer(0), it::Default("1"),
143  "Minimum number of iterations (linear solutions) to use.\nThis is usefull if the convergence criteria "
144  "does not characterize your goal well enough so it converges prematurely, possibly even without a single linear solution."
145  "If greater then 'max_it' the value is set to 'max_it'.")
146  .declare_key("max_it", it::Integer(0), it::Default("100"),
147  "Maximum number of iterations (linear solutions) of the non-linear solver.")
148  .declare_key("converge_on_stagnation", it::Bool(), it::Default("false"),
149  "If a stagnation of the nonlinear solver is detected the solver stops. "
150  "A divergence is reported by default, forcing the end of the simulation. By setting this flag to 'true', the solver "
151  "ends with convergence success on stagnation, but it reports warning about it.")
152  .close();
153 
155 
156  return it::Record(equation_name_, "Mixed-Hybrid solver for saturated Darcy flow.")
159  .declare_key("gravity", it::Array(it::Double(), 3,3), it::Default("[ 0, 0, -1]"),
160  "Vector of the gravity force. Dimensionless.")
161  .declare_key("user_fields", it::Array(DarcyMH::EqFields().get_user_field(equation_name_)),
163  "Input fields of the equation defined by user.")
165  "Input data for Darcy flow model.")
166  .declare_key("nonlinear_solver", ns_rec, it::Default("{}"),
167  "Non-linear solver for MH problem.")
168  .declare_key("output_stream", OutputTime::get_input_type(), it::Default("{}"),
169  "Output stream settings.\n Specify file format, precision etc.")
170 
172  IT::Default("{ \"fields\": [ \"pressure_p0\", \"velocity_p0\" ] }"),
173  "Specification of output fields and output times.")
175  "Output settings specific to Darcy flow model.\n"
176  "Includes raw output and some experimental functionality.")
177  .declare_key("balance", Balance::get_input_type(), it::Default("{}"),
178  "Settings for computing mass balance.")
179  .declare_key("n_schurs", it::Integer(0,2), it::Default("2"),
180  "Number of Schur complements to perform when solving MH system.")
181  .declare_key("mortar_method", get_mh_mortar_selection(), it::Default("\"None\""),
182  "Method for coupling Darcy flow between dimensions on incompatible meshes. [Experimental]" )
183  .close();
184 }
185 
186 
187 const int DarcyMH::registrar =
188  Input::register_class< DarcyMH, Mesh &, const Input::Record >(equation_name_) +
190 
191 
192 
194 {
195  *this += field_ele_pressure.name("pressure_p0")
196  .units(UnitSI().m())
198  .description("Pressure solution - P0 interpolation.");
199 
200  *this += field_edge_pressure.name("pressure_edge")
201  .units(UnitSI().m())
202  .flags(FieldFlag::input_copy)
203  .description("Pressure solution - Crouzeix-Raviart interpolation.");
204 
205  *this += field_ele_piezo_head.name("piezo_head_p0")
206  .units(UnitSI().m())
208  .description("Piezo head solution - P0 interpolation.");
209 
210  *this += field_ele_velocity.name("velocity_p0")
211  .units(UnitSI().m().s(-1))
213  .description("Velocity solution - P0 interpolation.");
214 
215  *this += flux.name("flux")
216  .units(UnitSI().m().s(-1))
218  .description("Darcy flow flux.");
219 
220  *this += anisotropy.name("anisotropy")
221  .description("Anisotropy of the conductivity tensor.")
222  .input_default("1.0")
223  .units( UnitSI::dimensionless() );
224 
225  *this += cross_section.name("cross_section")
226  .description("Complement dimension parameter (cross section for 1D, thickness for 2D).")
227  .input_default("1.0")
228  .units( UnitSI().m(3).md() );
229 
230  *this += conductivity.name("conductivity")
231  .description("Isotropic conductivity scalar.")
232  .input_default("1.0")
233  .units( UnitSI().m().s(-1) )
234  .set_limits(0.0);
235 
236  *this += sigma.name("sigma")
237  .description("Transition coefficient between dimensions.")
238  .input_default("1.0")
239  .units( UnitSI::dimensionless() );
240 
241  *this += water_source_density.name("water_source_density")
242  .description("Water source density.")
243  .input_default("0.0")
244  .units( UnitSI().s(-1) );
245 
246  *this += bc_type.name("bc_type")
247  .description("Boundary condition type.")
248  .input_selection( get_bc_type_selection() )
249  .input_default("\"none\"")
250  .units( UnitSI::dimensionless() );
251 
252  *this += bc_pressure
253  .disable_where(bc_type, {none, seepage} )
254  .name("bc_pressure")
255  .description("Prescribed pressure value on the boundary. Used for all values of ``bc_type`` except ``none`` and ``seepage``. "
256  "See documentation of ``bc_type`` for exact meaning of ``bc_pressure`` in individual boundary condition types.")
257  .input_default("0.0")
258  .units( UnitSI().m() );
259 
260  *this += bc_flux
261  .disable_where(bc_type, {none, dirichlet} )
262  .name("bc_flux")
263  .description("Incoming water boundary flux. Used for bc_types : ``total_flux``, ``seepage``, ``river``.")
264  .input_default("0.0")
265  .units( UnitSI().m().s(-1) );
266 
267  *this += bc_robin_sigma
268  .disable_where(bc_type, {none, dirichlet, seepage} )
269  .name("bc_robin_sigma")
270  .description("Conductivity coefficient in the ``total_flux`` or the ``river`` boundary condition type.")
271  .input_default("0.0")
272  .units( UnitSI().s(-1) );
273 
274  *this += bc_switch_pressure
275  .disable_where(bc_type, {none, dirichlet, total_flux} )
276  .name("bc_switch_pressure")
277  .description("Critical switch pressure for ``seepage`` and ``river`` boundary conditions.")
278  .input_default("0.0")
279  .units( UnitSI().m() );
280 
281 
282  //these are for unsteady
283  *this += init_pressure.name("init_pressure")
284  .description("Initial condition for pressure in time dependent problems.")
285  .input_default("0.0")
286  .units( UnitSI().m() );
287 
288  *this += storativity.name("storativity")
289  .description("Storativity (in time dependent problems).")
290  .input_default("0.0")
291  .units( UnitSI().m(-1) );
292 
293  *this += extra_storativity.name("extra_storativity")
294  .description("Storativity added from upstream equation.")
295  .units( UnitSI().m(-1) )
296  .input_default("0.0")
297  .flags( input_copy );
298 
299  *this += extra_source.name("extra_water_source_density")
300  .description("Water source density added from upstream equation.")
301  .input_default("0.0")
302  .units( UnitSI().s(-1) )
303  .flags( input_copy );
304 
305  *this += gravity_field.name("gravity")
306  .description("Gravity vector.")
307  .input_default("0.0")
308  .units( UnitSI::dimensionless() );
309 
310  *this += bc_gravity.name("bc_gravity")
311  .description("Boundary gravity vector.")
312  .input_default("0.0")
313  .units( UnitSI::dimensionless() );
314 
315  *this += init_piezo_head.name("init_piezo_head")
316  .units(UnitSI().m())
317  .input_default("0.0")
318  .description("Init piezo head.");
319 
320  *this += bc_piezo_head.name("bc_piezo_head")
321  .units(UnitSI().m())
322  .input_default("0.0")
323  .description("Boundary piezo head.");
324 
325  *this += bc_switch_piezo_head.name("bc_switch_piezo_head")
326  .units(UnitSI().m())
327  .input_default("0.0")
328  .description("Boundary switch piezo head.");
329 
330  //time_term_fields = this->subset({"storativity"});
331  //main_matrix_fields = this->subset({"anisotropy", "conductivity", "cross_section", "sigma", "bc_type", "bc_robin_sigma"});
332  //rhs_fields = this->subset({"water_source_density", "bc_pressure", "bc_flux"});
333 }
334 
336 {
337  mortar_method_=NoMortar;
338 }
339 
340 
341 
342 
343 //=============================================================================
344 // CREATE AND FILL GLOBAL MH MATRIX OF THE WATER MODEL
345 // - do it in parallel:
346 // - initial distribution of elements, edges
347 //
348 /*! @brief CREATE AND FILL GLOBAL MH MATRIX OF THE WATER MODEL
349  *
350  * Parameters {Solver,NSchurs} number of performed Schur
351  * complements (0,1,2) for water flow MH-system
352  *
353  */
354 //=============================================================================
355 DarcyMH::DarcyMH(Mesh &mesh_in, const Input::Record in_rec, TimeGovernor *tm)
356 : DarcyFlowInterface(mesh_in, in_rec),
357  output_object(nullptr),
358  data_changed_(false),
359  schur0(nullptr),
360  steady_diagonal(nullptr),
361  steady_rhs(nullptr),
362  new_diagonal(nullptr),
363  previous_solution(nullptr)
364 {
365 
366  START_TIMER("Darcy constructor");
367  {
368  auto time_rec = in_rec.val<Input::Record>("time");
369  if (tm == nullptr)
370  {
371  time_ = new TimeGovernor(time_rec);
372  }
373  else
374  {
375  TimeGovernor tm_from_rec(time_rec);
376  if (!tm_from_rec.is_default()) // is_default() == false when time record is present in input file
377  {
378  MessageOut() << "Duplicate key 'time', time in flow equation is already initialized from parent class!";
379  ASSERT_PERMANENT(false);
380  }
381  time_ = tm;
382  }
383  }
384 
385  eq_fields_ = make_shared<EqFields>();
386  eq_data_ = make_shared<EqData>();
387  this->eq_fieldset_ = eq_fields_.get();
388 
389  eq_data_->is_linear=true;
390 
391  size = mesh_->n_elements() + mesh_->n_sides() + mesh_->n_edges();
392  n_schur_compls = in_rec.val<int>("n_schurs");
393  eq_data_->mortar_method_= in_rec.val<MortarMethod>("mortar_method");
394  if (eq_data_->mortar_method_ != NoMortar) {
396  }
397 
398 
399 
400  //side_ds->view( std::cout );
401  //el_ds->view( std::cout );
402  //edge_ds->view( std::cout );
403  //rows_ds->view( std::cout );
404 
405 }
406 
408 {
409  // DebugOut() << "t = " << time_->t() << " step_end " << time_->step().end() << "\n";
411  {
412  // In steady case, the solution is computed with the data present at time t,
413  // and the steady state solution is valid until another change in data,
414  // which should correspond to time (t+dt).
415  // "The data change appears immediatly."
416  double next_t = time_->t() + time_->estimate_dt();
417  // DebugOut() << "STEADY next_t = " << next_t << "\n";
418  return next_t * (1 - 2*std::numeric_limits<double>::epsilon());
419  }
420  else
421  {
422  // In unsteady case, the solution is computed with the data present at time t,
423  // and the solution is valid at the time t+dt.
424  // "The data change does not appear immediatly, it is integrated over time interval dt."
425  // DebugOut() << "UNSTEADY\n";
426  return time_->t();
427  }
428 }
429 
431 //connecting data fields with mesh
432 {
433 
434  START_TIMER("data init");
435  eq_data_->mesh = mesh_;
436  eq_fields_->set_mesh(*mesh_);
437 
438  auto gravity_array = input_record_.val<Input::Array>("gravity");
439  std::vector<double> gvec;
440  gravity_array.copy_to(gvec);
441  gvec.push_back(0.0); // zero pressure shift
442  eq_data_->gravity_ = arma::vec(gvec);
443  eq_data_->gravity_vec_ = eq_data_->gravity_.subvec(0,2);
444 
445  FieldValue<3>::VectorFixed gvalue(eq_data_->gravity_vec_);
446  auto field_algo=std::make_shared<FieldConstant<3, FieldValue<3>::VectorFixed>>();
447  field_algo->set_value(gvalue);
448  eq_fields_->gravity_field.set(field_algo, 0.0);
449  eq_fields_->bc_gravity.set(field_algo, 0.0);
450 
451  eq_fields_->bc_pressure.add_factory(
452  std::make_shared<AddPotentialFactory<3, FieldValue<3>::Scalar> >
453  (eq_fields_->bc_gravity, eq_fields_->X(), eq_fields_->bc_piezo_head) );
454  eq_fields_->bc_switch_pressure.add_factory(
455  std::make_shared<AddPotentialFactory<3, FieldValue<3>::Scalar> >
456  (eq_fields_->bc_gravity, eq_fields_->X(), eq_fields_->bc_switch_piezo_head) );
457  eq_fields_->init_pressure.add_factory(
458  std::make_shared<AddPotentialFactory<3, FieldValue<3>::Scalar> >
459  (eq_fields_->gravity_field, eq_fields_->X(), eq_fields_->init_piezo_head) );
460 
461 
462  eq_fields_->set_input_list( this->input_record_.val<Input::Array>("input_fields"), *time_ );
463  // read optional user fields
464  Input::Array user_fields_arr;
465  if (input_record_.opt_val("user_fields", user_fields_arr)) {
466  eq_fields_->set_user_fields_map(user_fields_arr);
467  }
468 
469  // Check that the time step was set for the transient simulation.
470  if (! zero_time_term(true) && time_->is_default() ) {
471  //THROW(ExcAssertMsg());
472  //THROW(ExcMissingTimeGovernor() << input_record_.ei_address());
473  MessageOut() << "Missing the key 'time', obligatory for the transient problems." << endl;
474  ASSERT_PERMANENT(false);
475  }
476 
477  eq_fields_->mark_input_times(*time_);
478 }
479 
480 
481 
483 
484  { // init DOF handler for pressure fields
485 // std::shared_ptr< FiniteElement<0> > fe0_rt = std::make_shared<FE_RT0_disc<0>>();
486  std::shared_ptr< FiniteElement<1> > fe1_rt = std::make_shared<FE_RT0_disc<1>>();
487  std::shared_ptr< FiniteElement<2> > fe2_rt = std::make_shared<FE_RT0_disc<2>>();
488  std::shared_ptr< FiniteElement<3> > fe3_rt = std::make_shared<FE_RT0_disc<3>>();
489  std::shared_ptr< FiniteElement<0> > fe0_disc = std::make_shared<FE_P_disc<0>>(0);
490  std::shared_ptr< FiniteElement<1> > fe1_disc = std::make_shared<FE_P_disc<1>>(0);
491  std::shared_ptr< FiniteElement<2> > fe2_disc = std::make_shared<FE_P_disc<2>>(0);
492  std::shared_ptr< FiniteElement<3> > fe3_disc = std::make_shared<FE_P_disc<3>>(0);
493  std::shared_ptr< FiniteElement<0> > fe0_cr = std::make_shared<FE_CR<0>>();
494  std::shared_ptr< FiniteElement<1> > fe1_cr = std::make_shared<FE_CR<1>>();
495  std::shared_ptr< FiniteElement<2> > fe2_cr = std::make_shared<FE_CR<2>>();
496  std::shared_ptr< FiniteElement<3> > fe3_cr = std::make_shared<FE_CR<3>>();
497 // static FiniteElement<0> fe0_sys = FE_P_disc<0>(0); //TODO fix and use solution with FESystem<0>( {fe0_rt, fe0_disc, fe0_cr} )
498  FESystem<0> fe0_sys( {fe0_disc, fe0_disc, fe0_cr} );
499  FESystem<1> fe1_sys( {fe1_rt, fe1_disc, fe1_cr} );
500  FESystem<2> fe2_sys( {fe2_rt, fe2_disc, fe2_cr} );
501  FESystem<3> fe3_sys( {fe3_rt, fe3_disc, fe3_cr} );
502  MixedPtr<FESystem> fe_sys( std::make_shared<FESystem<0>>(fe0_sys), std::make_shared<FESystem<1>>(fe1_sys),
503  std::make_shared<FESystem<2>>(fe2_sys), std::make_shared<FESystem<3>>(fe3_sys) );
504  std::shared_ptr<DiscreteSpace> ds = std::make_shared<EqualOrderDiscreteSpace>( mesh_, fe_sys);
505  eq_data_->dh_ = std::make_shared<DOFHandlerMultiDim>(*mesh_);
506  eq_data_->dh_->distribute_dofs(ds);
507  }
508 
509  init_eq_data();
510  this->eq_data_->multidim_assembler = AssemblyFlowBase::create< AssemblyMH >(eq_fields_, eq_data_);
512 
513  eq_fields_->add_coords_field();
514 
515  { // construct pressure, velocity and piezo head fields
516  uint rt_component = 0;
517  eq_data_->full_solution = eq_data_->dh_->create_vector();
518  auto ele_flux_ptr = create_field_fe<3, FieldValue<3>::VectorFixed>(eq_data_->dh_, &eq_data_->full_solution, rt_component);
519  eq_fields_->flux.set(ele_flux_ptr, 0.0);
520 
521  eq_fields_->field_ele_velocity.set(Model<3, FieldValue<3>::VectorFixed>::create(fn_mh_velocity(), eq_fields_->flux, eq_fields_->cross_section), 0.0);
522 
523  uint p_ele_component = 1;
524  auto ele_pressure_ptr = create_field_fe<3, FieldValue<3>::Scalar>(eq_data_->dh_, &eq_data_->full_solution, p_ele_component);
525  eq_fields_->field_ele_pressure.set(ele_pressure_ptr, 0.0);
526 
527  uint p_edge_component = 2;
528  auto edge_pressure_ptr = create_field_fe<3, FieldValue<3>::Scalar>(eq_data_->dh_, &eq_data_->full_solution, p_edge_component);
529  eq_fields_->field_edge_pressure.set(edge_pressure_ptr, 0.0);
530 
531  eq_fields_->field_ele_piezo_head.set(
532  Model<3, FieldValue<3>::Scalar>::create(fn_mh_piezohead(), eq_fields_->gravity_field, eq_fields_->X(), eq_fields_->field_ele_pressure),
533  0.0
534  );
535  }
536 
537  { // init DOF handlers represents edge DOFs
538  uint p_edge_component = 2;
539  eq_data_->dh_cr_ = std::make_shared<SubDOFHandlerMultiDim>(eq_data_->dh_,p_edge_component);
540  }
541 
542  { // init DOF handlers represents side DOFs
543  MixedPtr<FE_CR_disc> fe_cr_disc;
544  std::shared_ptr<DiscreteSpace> ds_cr_disc = std::make_shared<EqualOrderDiscreteSpace>( mesh_, fe_cr_disc);
545  eq_data_->dh_cr_disc_ = std::make_shared<DOFHandlerMultiDim>(*mesh_);
546  eq_data_->dh_cr_disc_->distribute_dofs(ds_cr_disc);
547  }
548 
549  // Initialize bc_switch_dirichlet to size of global boundary.
550  eq_data_->bc_switch_dirichlet.resize(mesh_->n_elements()+mesh_->bc_mesh()->n_elements(), 1);
551 
552 
555  .val<Input::Record>("nonlinear_solver")
556  .val<Input::AbstractRecord>("linear_solver");
557 
558  // auxiliary set_time call since allocation assembly evaluates fields as well
561 
562 
563 
564  // allocate time term vectors
565  VecDuplicate(schur0->get_solution(), &previous_solution);
566  VecCreateMPI(PETSC_COMM_WORLD, eq_data_->dh_->distr()->lsize(),PETSC_DETERMINE,&(steady_diagonal));
567  VecDuplicate(steady_diagonal,& new_diagonal);
568  VecZeroEntries(new_diagonal);
569  VecDuplicate(steady_diagonal, &steady_rhs);
570 
571 
572  // initialization of balance object
573  balance_ = std::make_shared<Balance>("water", mesh_);
574  balance_->init_from_input(input_record_.val<Input::Record>("balance"), time());
575  eq_data_->water_balance_idx = balance_->add_quantity("water_volume");
576  balance_->allocate(eq_data_->dh_->distr()->lsize(), 1);
577  balance_->units(UnitSI().m(3));
578 
579 
580  eq_data_->balance = balance_;
581  eq_data_->lin_sys = schur0;
582 
583 
585 }
586 
588 {}
589 
591 {
592 
593  /* TODO:
594  * - Allow solution reconstruction (pressure and velocity) from initial condition on user request.
595  * - Steady solution as an intitial condition may be forced by setting inti_time =-1, and set data for the steady solver in that time.
596  * Solver should be able to switch from and to steady case depending on the zero time term.
597  */
598 
600 
601  // zero_time_term means steady case
602  bool zero_time_term_from_right = zero_time_term();
603 
604 
605  if (zero_time_term_from_right) {
606  MessageOut() << "Flow zero time step - steady case\n";
607  // steady case
608  VecZeroEntries(schur0->get_solution());
609  //read_initial_condition(); // Possible solution guess for steady case.
610  use_steady_assembly_ = true;
611  solve_nonlinear(); // with right limit data
612  // eq_data_->full_solution.local_to_ghost_begin();
613  // eq_data_->full_solution.local_to_ghost_end();
614  } else {
615  MessageOut() << "Flow zero time step - unsteady case\n";
616  VecZeroEntries(schur0->get_solution());
617  VecZeroEntries(previous_solution);
618 
620  reconstruct_solution_from_schur(eq_data_->multidim_assembler);
621 
622  assembly_linear_system(); // in particular due to balance
623 // print_matlab_matrix("matrix_zero");
624  }
625  //solution_output(T,right_limit); // data for time T in any case
626 
627  eq_data_->full_solution.local_to_ghost_begin();
628  eq_data_->full_solution.local_to_ghost_end();
629  output_data();
630 }
631 
632 //=============================================================================
633 // COMPOSE and SOLVE WATER MH System possibly through Schur complements
634 //=============================================================================
636 {
637  START_TIMER("Solving MH system");
638 
639  time_->next_time();
640 
641  time_->view("DARCY"); //time governor information output
642 
643  solve_time_step();
644 
645  eq_data_->full_solution.local_to_ghost_begin();
646  eq_data_->full_solution.local_to_ghost_end();
647 }
648 
649 
650 void DarcyMH::solve_time_step(bool output)
651 {
653 
654  bool zero_time_term_from_left=zero_time_term();
655 
656  bool jump_time = eq_fields_->storativity.is_jump_time();
657  if (! zero_time_term_from_left) {
658  MessageOut() << "Flow time step - unsteady case\n";
659  // time term not treated as zero
660  // Unsteady solution up to the T.
661 
662  // this flag is necesssary for switching BC to avoid setting zero neumann on the whole boundary in the steady case
663  use_steady_assembly_ = false;
664 
666  solve_nonlinear(); // with left limit data
667  if (jump_time) {
668  WarningOut() << "Output of solution discontinuous in time not supported yet.\n";
669  //solution_output(T, left_limit); // output use time T- delta*dt
670  //output_data();
671  }
672  }
673 
674  if (time_->is_end()) {
675  // output for unsteady case, end_time should not be the jump time
676  // but rether check that
677  if (! zero_time_term_from_left && ! jump_time && output) output_data();
678  return;
679  }
680 
682  bool zero_time_term_from_right=zero_time_term();
683  if (zero_time_term_from_right) {
684  MessageOut() << "Flow time step - steady case\n";
685  // this flag is necesssary for switching BC to avoid setting zero neumann on the whole boundary in the steady case
686  use_steady_assembly_ = true;
687  solve_nonlinear(); // with right limit data
688 
689  } else if (! zero_time_term_from_left && jump_time) {
690  WarningOut() << "Discontinuous time term not supported yet.\n";
691  //solution_transfer(); // internally call set_time(T, left) and set_time(T,right) again
692  //solve_nonlinear(); // with right limit data
693  }
694 
695  //solution_output(T,right_limit); // data for time T in any case
696  if (output) output_data();
697 }
698 
699 
700 bool DarcyMH::zero_time_term(bool time_global) {
701  if (time_global) {
702  return (eq_fields_->storativity.input_list_size() == 0);
703  } else {
704  return eq_fields_->storativity.field_result(mesh_->region_db().get_region_set("BULK")) == result_zeros;
705  }
706 }
707 
708 
710 {
711 
713  double residual_norm = schur0->compute_residual();
715  MessageOut().fmt("[nonlinear solver] norm of initial residual: {}\n", residual_norm);
716 
717  // Reduce is_linear flag.
718  int is_linear_common;
719  MPI_Allreduce(&(eq_data_->is_linear), &is_linear_common,1, MPI_INT ,MPI_MIN,PETSC_COMM_WORLD);
720 
721  Input::Record nl_solver_rec = input_record_.val<Input::Record>("nonlinear_solver");
722  this->tolerance_ = nl_solver_rec.val<double>("tolerance");
723  this->max_n_it_ = nl_solver_rec.val<unsigned int>("max_it");
724  this->min_n_it_ = nl_solver_rec.val<unsigned int>("min_it");
725  if (this->min_n_it_ > this->max_n_it_) this->min_n_it_ = this->max_n_it_;
726 
727  if (! is_linear_common) {
728  // set tolerances of the linear solver unless they are set by user.
729  schur0->set_tolerances(0.1*this->tolerance_, 0.01*this->tolerance_, 100);
730  }
731  vector<double> convergence_history;
732 
733  Vec save_solution;
734  VecDuplicate(schur0->get_solution(), &save_solution);
735  while (nonlinear_iteration_ < this->min_n_it_ ||
736  (residual_norm > this->tolerance_ && nonlinear_iteration_ < this->max_n_it_ )) {
737  ASSERT_EQ( convergence_history.size(), nonlinear_iteration_ );
738  convergence_history.push_back(residual_norm);
739 
740  // stagnation test
741  if (convergence_history.size() >= 5 &&
742  convergence_history[ convergence_history.size() - 1]/convergence_history[ convergence_history.size() - 2] > 0.9 &&
743  convergence_history[ convergence_history.size() - 1]/convergence_history[ convergence_history.size() - 5] > 0.8) {
744  // stagnation
745  if (input_record_.val<Input::Record>("nonlinear_solver").val<bool>("converge_on_stagnation")) {
746  WarningOut().fmt("Accept solution on stagnation. Its: {} Residual: {}\n", nonlinear_iteration_, residual_norm);
747  break;
748  } else {
749  THROW(ExcSolverDiverge() << EI_Reason("Stagnation."));
750  }
751  }
752 
753  if (! is_linear_common)
754  VecCopy( schur0->get_solution(), save_solution);
757 
758  // hack to make BDDC work with empty compute_residual
759  if (is_linear_common){
760  // we want to print this info in linear (and steady) case
761  residual_norm = schur0->compute_residual();
762  MessageOut().fmt("[nonlinear solver] lin. it: {}, reason: {}, residual: {}\n",
763  si.n_iterations, si.converged_reason, residual_norm);
764  break;
765  }
766  data_changed_=true; // force reassembly for non-linear case
767 
768  double alpha = 1; // how much of new solution
769  VecAXPBY(schur0->get_solution(), (1-alpha), alpha, save_solution);
770 
771  //LogOut().fmt("Linear solver ended with reason: {} \n", si.converged_reason );
772  //ASSERT_PERMANENT_GE( si.converged_reason, 0).error("Linear solver failed to converge. \n");
774 
775  residual_norm = schur0->compute_residual();
776  MessageOut().fmt("[nonlinear solver] it: {} lin. it: {}, reason: {}, residual: {}\n",
777  nonlinear_iteration_, si.n_iterations, si.converged_reason, residual_norm);
778  }
779  chkerr(VecDestroy(&save_solution));
780  this -> postprocess();
781 
782  // adapt timestep
783  if (! this->zero_time_term()) {
784  double mult = 1.0;
785  if (nonlinear_iteration_ < 3) mult = 1.6;
786  if (nonlinear_iteration_ > 7) mult = 0.7;
787  time_->set_upper_constraint(time_->dt() * mult, "Darcy adaptivity.");
788  // int result = time_->set_upper_constraint(time_->dt() * mult, "Darcy adaptivity.");
789  //DebugOut().fmt("time adaptivity, res: {} it: {} m: {} dt: {} edt: {}\n", result, nonlinear_iteration_, mult, time_->dt(), time_->estimate_dt());
790  }
791 }
792 
794 {
796 }
797 
799 {
800  START_TIMER("postprocess");
801 
802  //fix velocity when mortar method is used
803  if(eq_data_->mortar_method_ != MortarMethod::NoMortar){
804  auto multidim_assembler = AssemblyFlowBase::create< AssemblyMH >(eq_fields_, eq_data_);
805  for ( DHCellAccessor dh_cell : eq_data_->dh_->own_range() ) {
806  unsigned int dim = dh_cell.dim();
807  multidim_assembler[dim-1]->fix_velocity(dh_cell);
808  }
809  }
810  //ElementAccessor<3> ele;
811 
812  // modify side fluxes in parallel
813  // for every local edge take time term on digonal and add it to the corresponding flux
814  /*
815  for (unsigned int i_loc = 0; i_loc < el_ds->lsize(); i_loc++) {
816  ele = mesh_->element_accessor(el_4_loc[i_loc]);
817  for (unsigned int i=0; i<ele->n_sides(); i++) {
818  side_rows[i] = side_row_4_id[ mh_dh.side_dof( ele_ac.side(i) ) ];
819  values[i] = -1.0 * ele_ac.measure() *
820  data.cross_section.value(ele_ac.centre(), ele_ac.element_accessor()) *
821  data.water_source_density.value(ele_ac.centre(), ele_ac.element_accessor()) /
822  ele_ac.n_sides();
823  }
824  VecSetValues(schur0->get_solution(), ele_ac.n_sides(), side_rows, values, ADD_VALUES);
825  }
826  VecAssemblyBegin(schur0->get_solution());
827  VecAssemblyEnd(schur0->get_solution());
828  */
829 }
830 
831 
833  START_TIMER("Darcy output data");
834 
835  //print_matlab_matrix("matrix_" + std::to_string(time_->step().index()));
836 
837  //time_->view("DARCY"); //time governor information output
838  this->output_object->output();
839 
840 
841  START_TIMER("Darcy balance output");
842  balance_->calculate_cumulative(eq_data_->water_balance_idx, schur0->get_solution());
843  balance_->calculate_instant(eq_data_->water_balance_idx, schur0->get_solution());
844  balance_->output();
845 }
846 
847 
849 {
850  return schur0->get_solution_precision();
851 }
852 
853 
854 // ===========================================================================================
855 //
856 // MATRIX ASSEMBLY - we use abstract assembly routine, where LS Mat/Vec SetValues
857 // are in fact pointers to allocating or filling functions - this is governed by Linsystem roitunes
858 //
859 // =======================================================================================
861 {
862  START_TIMER("DarcyFlowMHy::assembly_mh_matrix");
863 
864  // set auxiliary flag for switchting Dirichlet like BC
865  eq_data_->force_no_neumann_bc = use_steady_assembly_ && (nonlinear_iteration_ == 0);
866  eq_data_->n_schur_compls = n_schur_compls;
867 
868 
869  balance_->start_flux_assembly(eq_data_->water_balance_idx);
870 
871  // TODO: try to move this into balance, or have it in the generic assembler class, that should perform the cell loop
872  // including various pre- and post-actions
873  for ( DHCellAccessor dh_cell : eq_data_->dh_->own_range() ) {
874  unsigned int dim = dh_cell.dim();
875  assembler[dim-1]->assemble(dh_cell);
876  }
877 
878 
879  balance_->finish_flux_assembly(eq_data_->water_balance_idx);
880 
881 }
882 
883 
885 {
886  START_TIMER("DarcyFlowMH::allocate_mh_matrix");
887 
888  // set auxiliary flag for switchting Dirichlet like BC
889  eq_data_->n_schur_compls = n_schur_compls;
890  LinSys *ls = schur0;
891 
892  // to make space for second schur complement, max. 10 neighbour edges of one el.
893  double zeros[100000];
894  for(int i=0; i<100000; i++) zeros[i] = 0.0;
895 
896  std::vector<LongIdx> tmp_rows;
897  tmp_rows.reserve(200);
898 
899  std::vector<LongIdx> dofs, dofs_ngh;
900  dofs.reserve(eq_data_->dh_->max_elem_dofs());
901  dofs_ngh.reserve(eq_data_->dh_->max_elem_dofs());
902 
903  for ( DHCellAccessor dh_cell : eq_data_->dh_->own_range() ) {
904  ElementAccessor<3> ele = dh_cell.elm();
905 
906  const uint ndofs = dh_cell.n_dofs();
907  dofs.resize(ndofs);
908  dh_cell.get_dof_indices(dofs);
909 
910  // whole local MH matrix
911  ls->mat_set_values(ndofs, dofs.data(), ndofs, dofs.data(), zeros);
912 
913  tmp_rows.clear();
914 
915  // compatible neighborings rows
916  unsigned int n_neighs = ele->n_neighs_vb();
917  for ( DHCellSide neighb_side : dh_cell.neighb_sides() ) {
918  // every compatible connection adds a 2x2 matrix involving
919  // current element pressure and a connected edge pressure
920 
921  // read neighbor dofs (dh dofhandler)
922  // neighbor cell owning neighb_side
923  DHCellAccessor dh_neighb_cell = neighb_side.cell();
924 
925  const uint ndofs_ngh = dh_neighb_cell.n_dofs();
926  dofs_ngh.resize(ndofs_ngh);
927  dh_neighb_cell.get_dof_indices(dofs_ngh);
928 
929  // local index of pedge dof on neighboring cell
930  // (dim+1) is number of edges of higher dim element
931  // TODO: replace with DHCell getter when available for FESystem component
932  const unsigned int t = dh_neighb_cell.n_dofs() - (dh_neighb_cell.dim()+1) + neighb_side.side().side_idx();
933  tmp_rows.push_back(dofs_ngh[t]);
934  }
935 
936  const uint nsides = ele->n_sides();
937  LongIdx * edge_rows = dofs.data() + nsides; // pointer to start of ele
938  // allocate always also for schur 2
939  ls->mat_set_values(nsides+1, edge_rows, n_neighs, tmp_rows.data(), zeros); // (edges, ele) x (neigh edges)
940  ls->mat_set_values(n_neighs, tmp_rows.data(), nsides+1, edge_rows, zeros); // (neigh edges) x (edges, ele)
941  ls->mat_set_values(n_neighs, tmp_rows.data(), n_neighs, tmp_rows.data(), zeros); // (neigh edges) x (neigh edges)
942 
943  tmp_rows.clear();
944 
945  if (eq_data_->mortar_method_ != NoMortar) {
946  auto &isec_list = mesh_->mixed_intersections().element_intersections_[ele.idx()];
947  for(auto &isec : isec_list ) {
948  IntersectionLocalBase *local = isec.second;
949  DHCellAccessor dh_cell_slave = eq_data_->dh_->cell_accessor_from_element(local->bulk_ele_idx());
950 
951  const uint ndofs_slave = dh_cell_slave.n_dofs();
952  dofs_ngh.resize(ndofs_slave);
953  dh_cell_slave.get_dof_indices(dofs_ngh);
954 
955  //DebugOut().fmt("Alloc: {} {}", ele.idx(), local->bulk_ele_idx());
956  for(unsigned int i_side=0; i_side < dh_cell_slave.elm()->n_sides(); i_side++) {
957  // TODO: replace with DHCell getter when available for FESystem component
958  tmp_rows.push_back( dofs_ngh[(ndofs_slave+1)/2+i_side] );
959  //DebugOut() << "aedge" << print_var(tmp_rows[tmp_rows.size()-1]);
960  }
961  }
962  }
963  /*
964  for(unsigned int i_side=0; i_side < ele->n_sides(); i_side++) {
965  DebugOut() << "aedge:" << print_var(edge_rows[i_side]);
966  }*/
967 
968  edge_rows = dofs.data() + nsides +1; // pointer to start of edges
969  ls->mat_set_values(nsides, edge_rows, tmp_rows.size(), tmp_rows.data(), zeros); // master edges x neigh edges
970  ls->mat_set_values(tmp_rows.size(), tmp_rows.data(), nsides, edge_rows, zeros); // neigh edges x master edges
971  ls->mat_set_values(tmp_rows.size(), tmp_rows.data(), tmp_rows.size(), tmp_rows.data(), zeros); // neigh edges x neigh edges
972 
973  }
974 /*
975  // alloc edge diagonal entries
976  if(rank == 0)
977  for( vector<Edge>::iterator edg = mesh_->edges.begin(); edg != mesh_->edges.end(); ++edg) {
978  int edg_idx = mh_dh.row_4_edge[edg->side(0)->edge_idx()];
979 
980 // for( vector<Edge>::iterator edg2 = mesh_->edges.begin(); edg2 != mesh_->edges.end(); ++edg2){
981 // int edg_idx2 = mh_dh.row_4_edge[edg2->side(0)->edge_idx()];
982 // if(edg_idx == edg_idx2){
983 // DBGCOUT(<< "P[ " << rank << " ] " << "edg alloc: " << edg_idx << " " << edg_idx2 << "\n");
984  ls->mat_set_value(edg_idx, edg_idx, 0.0);
985 // }
986 // }
987  }
988  */
989  /*
990  if (mortar_method_ == MortarP0) {
991  P0_CouplingAssembler(*this).assembly(*ls);
992  } else if (mortar_method_ == MortarP1) {
993  P1_CouplingAssembler(*this).assembly(*ls);
994  }*/
995 }
996 
998 {
999  START_TIMER("assembly source term");
1000  balance_->start_source_assembly(eq_data_->water_balance_idx);
1001 
1002  std::vector<LongIdx> global_dofs(eq_data_->dh_->max_elem_dofs());
1003 
1004  for ( DHCellAccessor dh_cell : eq_data_->dh_->own_range() ) {
1005  ElementAccessor<3> ele = dh_cell.elm();
1006 
1007  const uint ndofs = dh_cell.n_dofs();
1008  global_dofs.resize(ndofs);
1009  dh_cell.get_dof_indices(global_dofs);
1010 
1011  double cs = eq_fields_->cross_section.value(ele.centre(), ele);
1012 
1013  // set sources
1014  double source = ele.measure() * cs *
1015  (eq_fields_->water_source_density.value(ele.centre(), ele)
1016  +eq_fields_->extra_source.value(ele.centre(), ele));
1017  // TODO: replace with DHCell getter when available for FESystem component
1018  schur0->rhs_set_value(global_dofs[ndofs/2], -1.0 * source );
1019 
1020  balance_->add_source_values(eq_data_->water_balance_idx, ele.region().bulk_idx(),
1021  {dh_cell.get_loc_dof_indices()[ndofs/2]}, {0}, {source});
1022  }
1023 
1024  balance_->finish_source_assembly(eq_data_->water_balance_idx);
1025 }
1026 
1027 
1028 
1029 
1030 /*******************************************************************************
1031  * COMPOSE WATER MH MATRIX WITHOUT SCHUR COMPLEMENT
1032  ******************************************************************************/
1033 
1035 
1036  START_TIMER("preallocation");
1037 
1038  if (schur0 == NULL) { // create Linear System for MH matrix
1039 
1040  if (in_rec.type() == LinSys_BDDC::get_input_type()) {
1041 #ifdef FLOW123D_HAVE_BDDCML
1042  WarningOut() << "For BDDC no Schur complements are used.";
1043  n_schur_compls = 0;
1044  LinSys_BDDC *ls = new LinSys_BDDC(&(*eq_data_->dh_->distr()),
1045  true); // swap signs of matrix and rhs to make the matrix SPD
1046  ls->set_from_input(in_rec);
1047  ls->set_solution( eq_data_->full_solution.petsc_vec() );
1048  // possible initialization particular to BDDC
1049  START_TIMER("BDDC set mesh data");
1051  schur0=ls;
1052  END_TIMER("BDDC set mesh data");
1053 #else
1054  //Exception
1055  THROW( ExcBddcmlNotSupported() );
1056 #endif // FLOW123D_HAVE_BDDCML
1057  }
1058  else if (in_rec.type() == LinSys_PETSC::get_input_type()) {
1059  // use PETSC for serial case even when user wants BDDC
1060  if (n_schur_compls > 2) {
1061  WarningOut() << "Invalid number of Schur Complements. Using 2.";
1062  n_schur_compls = 2;
1063  }
1064 
1065  LinSys_PETSC *schur1, *schur2;
1066 
1067  if (n_schur_compls == 0) {
1068  LinSys_PETSC *ls = new LinSys_PETSC( &(*eq_data_->dh_->distr()) );
1069 
1070  // temporary solution; we have to set precision also for sequantial case of BDDC
1071  // final solution should be probably call of direct solver for oneproc case
1072  if (in_rec.type() != LinSys_BDDC::get_input_type()) ls->set_from_input(in_rec);
1073  else {
1074  ls->LinSys::set_from_input(in_rec); // get only common options
1075  }
1076 
1077  ls->set_solution( eq_data_->full_solution.petsc_vec() );
1078  schur0=ls;
1079  } else {
1080  IS is;
1081  auto side_dofs_vec = get_component_indices_vec(0);
1082 
1083  ISCreateGeneral(PETSC_COMM_SELF, side_dofs_vec.size(), &(side_dofs_vec[0]), PETSC_COPY_VALUES, &is);
1084  //ISView(is, PETSC_VIEWER_STDOUT_SELF);
1085  //ASSERT_PERMANENT(err == 0).error("Error in ISCreateStride.");
1086 
1087  SchurComplement *ls = new SchurComplement(&(*eq_data_->dh_->distr()), is);
1088 
1089  // make schur1
1091  if (n_schur_compls==1) {
1092  schur1 = new LinSys_PETSC(ds);
1093  schur1->set_positive_definite();
1094  } else {
1095  IS is;
1096  auto elem_dofs_vec = get_component_indices_vec(1);
1097 
1098  const PetscInt *b_indices;
1099  ISGetIndices(ls->IsB, &b_indices);
1100  uint b_size = ls->loc_size_B;
1101  for(uint i_b=0, i_bb=0; i_b < b_size && i_bb < elem_dofs_vec.size(); i_b++) {
1102  if (b_indices[i_b] == elem_dofs_vec[i_bb])
1103  elem_dofs_vec[i_bb++] = i_b + ds->begin();
1104  }
1105  ISRestoreIndices(ls->IsB, &b_indices);
1106 
1107 
1108  ISCreateGeneral(PETSC_COMM_SELF, elem_dofs_vec.size(), &(elem_dofs_vec[0]), PETSC_COPY_VALUES, &is);
1109  //ISView(is, PETSC_VIEWER_STDOUT_SELF);
1110  //ASSERT_PERMANENT(err == 0).error("Error in ISCreateStride.");
1111  SchurComplement *ls1 = new SchurComplement(ds, is); // is is deallocated by SchurComplement
1112  ls1->set_negative_definite();
1113 
1114  // make schur2
1115  schur2 = new LinSys_PETSC( ls1->make_complement_distribution() );
1116  schur2->set_positive_definite();
1117  ls1->set_complement( schur2 );
1118  schur1 = ls1;
1119  }
1120  ls->set_complement( schur1 );
1121  ls->set_from_input(in_rec);
1122  ls->set_solution( eq_data_->full_solution.petsc_vec() );
1123  schur0=ls;
1124  }
1125 
1126  START_TIMER("PETSC PREALLOCATION");
1127  schur0->set_symmetric();
1129 
1131 
1132  VecZeroEntries(schur0->get_solution());
1133  END_TIMER("PETSC PREALLOCATION");
1134  }
1135  else {
1136  THROW( ExcUnknownSolver() );
1137  }
1138 
1139  END_TIMER("preallocation");
1140  }
1141 
1142 }
1143 
1144 
1145 
1146 
1148  START_TIMER("DarcyFlowMH_Steady::assembly_linear_system");
1149 
1150  eq_data_->is_linear=true;
1151  bool is_steady = zero_time_term();
1152  //DebugOut() << "Assembly linear system\n";
1153  if (data_changed_) {
1154  data_changed_ = false;
1155  //DebugOut() << "Data changed\n";
1156  // currently we have no optimization for cases when just time term data or RHS data are changed
1157  START_TIMER("full assembly");
1158  if (typeid(*schur0) != typeid(LinSys_BDDC)) {
1159  schur0->start_add_assembly(); // finish allocation and create matrix
1160  }
1161 
1164 
1166 
1167 
1168  assembly_mh_matrix( eq_data_->multidim_assembler ); // fill matrix
1169 
1171 // print_matlab_matrix("matrix");
1173  //MatView( *const_cast<Mat*>(schur0->get_matrix()), PETSC_VIEWER_STDOUT_WORLD );
1174  //VecView( *const_cast<Vec*>(schur0->get_rhs()), PETSC_VIEWER_STDOUT_WORLD);
1175 
1176  if (! is_steady) {
1177  START_TIMER("fix time term");
1178  //DebugOut() << "setup time term\n";
1179  // assembly time term and rhs
1180  setup_time_term();
1181  modify_system();
1182  }
1183  else
1184  {
1185  balance_->start_mass_assembly(eq_data_->water_balance_idx);
1186  balance_->finish_mass_assembly(eq_data_->water_balance_idx);
1187  }
1188  END_TIMER("full assembly");
1189  } else {
1190  START_TIMER("modify system");
1191  if (! is_steady) {
1192  modify_system();
1193  } else {
1194  //Should be replaced with exception if error will be switched on.
1195  //ASSERT_PERMANENT(false).error("Planned computation time for steady solver, but data are not changed.\n");
1196  }
1197  END_TIMER("modiffy system");
1198  }
1199 
1200 }
1201 
1202 
1203 void DarcyMH::print_matlab_matrix(std::string matlab_file)
1204 {
1205  std::string output_file;
1206 
1207  if ( typeid(*schur0) == typeid(LinSys_BDDC) ){
1208 // WarningOut() << "Can output matrix only on a single processor.";
1209 // output_file = FilePath(matlab_file + "_bddc.m", FilePath::output_file);
1210 // ofstream os( output_file );
1211 // auto bddc = static_cast<LinSys_BDDC*>(schur0);
1212 // bddc->print_matrix(os);
1213  }
1214  else {//if ( typeid(*schur0) == typeid(LinSys_PETSC) ){
1215  output_file = FilePath(matlab_file + ".m", FilePath::output_file);
1216  PetscViewer viewer;
1217  PetscViewerASCIIOpen(PETSC_COMM_WORLD, output_file.c_str(), &viewer);
1218  PetscViewerSetFormat(viewer, PETSC_VIEWER_ASCII_MATLAB);
1219  MatView( *const_cast<Mat*>(schur0->get_matrix()), viewer);
1220  VecView( *const_cast<Vec*>(schur0->get_rhs()), viewer);
1221  VecView( *const_cast<Vec*>(schur0->get_rhs()), viewer);
1222  VecView( *const_cast<Vec*>(&(schur0->get_solution())), viewer);
1223  }
1224 // else{
1225 // WarningOut() << "No matrix output available for the current solver.";
1226 // return;
1227 // }
1228 
1229  // compute h_min for different dimensions
1230  double d_max = std::numeric_limits<double>::max();
1231  double h1 = d_max, h2 = d_max, h3 = d_max;
1232  double he2 = d_max, he3 = d_max;
1233  for (auto ele : mesh_->elements_range()) {
1234  switch(ele->dim()){
1235  case 1: h1 = std::min(h1,ele.measure()); break;
1236  case 2: h2 = std::min(h2,ele.measure()); break;
1237  case 3: h3 = std::min(h3,ele.measure()); break;
1238  }
1239 
1240  for (unsigned int j=0; j<ele->n_sides(); j++) {
1241  switch(ele->dim()){
1242  case 2: he2 = std::min(he2, ele.side(j)->measure()); break;
1243  case 3: he3 = std::min(he3, ele.side(j)->measure()); break;
1244  }
1245  }
1246  }
1247  if(h1 == d_max) h1 = 0;
1248  if(h2 == d_max) h2 = 0;
1249  if(h3 == d_max) h3 = 0;
1250  if(he2 == d_max) he2 = 0;
1251  if(he3 == d_max) he3 = 0;
1252 
1253  FILE * file;
1254  file = fopen(output_file.c_str(),"a");
1255  fprintf(file, "nA = %d;\n", eq_data_->dh_cr_disc_->distr()->size());
1256  fprintf(file, "nB = %d;\n", eq_data_->dh_->mesh()->get_el_ds()->size());
1257  fprintf(file, "nBF = %d;\n", eq_data_->dh_cr_->distr()->size());
1258  fprintf(file, "h1 = %e;\nh2 = %e;\nh3 = %e;\n", h1, h2, h3);
1259  fprintf(file, "he2 = %e;\nhe3 = %e;\n", he2, he3);
1260  fclose(file);
1261 }
1262 
1263 
1264 //template <int dim>
1265 //std::vector<arma::vec3> dof_points(DHCellAccessor cell, const Mapping<dim, 3> &mapping) {
1266 //
1267 //
1268 // vector<arma::vec::fixed<dim+1>> bary_dof_points = cell->fe()->dof_points();
1269 //
1270 // std::vector<arma::vec3> points(20);
1271 // points.resize(0);
1272 //
1273 //}
1274 //
1275 
1277  START_TIMER("DarcyFlowMH_Steady::set_mesh_data_for_bddc");
1278  // prepare mesh for BDDCML
1279  // initialize arrays
1280  // auxiliary map for creating coordinates of local dofs and global-to-local numbering
1281  std::map<int, arma::vec3> localDofMap;
1282  // connectivity for the subdomain, i.e. global dof numbers on element, stored element-by-element
1283  // Indices of Nodes on Elements
1284  std::vector<int> inet;
1285  // number of degrees of freedom on elements - determines elementwise chunks of INET array
1286  // Number of Nodes on Elements
1287  std::vector<int> nnet;
1288  // Indices of Subdomain Elements in Global Numbering - for local elements, their global indices
1289  std::vector<int> isegn;
1290 
1291  // This array is currently not used in BDDCML, it was used as an interface scaling alternative to scaling
1292  // by diagonal. It corresponds to the rho-scaling.
1293  std::vector<double> element_permeability;
1294 
1295  // maximal and minimal dimension of elements
1296  uint elDimMax = 1;
1297  uint elDimMin = 3;
1298  std::vector<LongIdx> cell_dofs_global(10);
1299 
1300 
1301 
1302  for ( DHCellAccessor dh_cell : eq_data_->dh_->own_range() ) {
1303  // for each element, create local numbering of dofs as fluxes (sides), pressure (element centre), Lagrange multipliers (edges), compatible connections
1304 
1305  dh_cell.get_dof_indices(cell_dofs_global);
1306 
1307  inet.insert(inet.end(), cell_dofs_global.begin(), cell_dofs_global.end());
1308  uint n_inet = cell_dofs_global.size();
1309 
1310 
1311  uint dim = dh_cell.elm().dim();
1312  elDimMax = std::max( elDimMax, dim );
1313  elDimMin = std::min( elDimMin, dim );
1314 
1315  // TODO: this is consistent with previous implementation, but may be wrong as it use global element numbering
1316  // used in sequential mesh, do global numbering of distributed elements.
1317  isegn.push_back( dh_cell.elm_idx());
1318 
1319  // TODO: use FiniteElement::dof_points
1320  for (unsigned int si=0; si<dh_cell.elm()->n_sides(); si++) {
1321  arma::vec3 coord = dh_cell.elm().side(si)->centre();
1322  // TODO: replace with DHCell getter when available for FESystem component
1323  // flux dof points
1324  localDofMap.insert( std::make_pair( cell_dofs_global[si], coord ) );
1325  // pressure trace dof points
1326  localDofMap.insert( std::make_pair( cell_dofs_global[si+dim+2], coord ) );
1327  }
1328  // pressure dof points
1329  arma::vec3 elm_centre = dh_cell.elm().centre();
1330  localDofMap.insert( std::make_pair( cell_dofs_global[dim+1], elm_centre ) );
1331 
1332  // insert dofs related to compatible connections
1333  //const Element *ele = dh_cell.elm().element();
1334  for(DHCellSide side : dh_cell.neighb_sides()) {
1335  uint neigh_dim = side.cell().elm().dim();
1336  side.cell().get_dof_indices(cell_dofs_global);
1337  int edge_row = cell_dofs_global[neigh_dim+2+side.side_idx()];
1338  localDofMap.insert( std::make_pair( edge_row, side.centre() ) );
1339  inet.push_back( edge_row );
1340  n_inet++;
1341  }
1342  nnet.push_back(n_inet);
1343 
1344 
1345  // version for rho scaling
1346  // trace computation
1347  double conduct = eq_fields_->conductivity.value( elm_centre , dh_cell.elm() );
1348  auto aniso = eq_fields_->anisotropy.value( elm_centre , dh_cell.elm() );
1349 
1350  // compute mean on the diagonal
1351  double coef = 0.;
1352  for ( int i = 0; i < 3; i++) {
1353  coef = coef + aniso.at(i,i);
1354  }
1355  // Maybe divide by cs
1356  coef = conduct*coef / 3;
1357 
1358  ASSERT_GT( coef, 0. ).error("Zero coefficient of hydrodynamic resistance. \n");
1359  element_permeability.push_back( 1. / coef );
1360  }
1361 // uint i_inet = 0;
1362 // for(int n_dofs : nnet) {
1363 // DebugOut() << "nnet: " << n_dofs;
1364 // for(int j=0; j < n_dofs; j++, i_inet++) {
1365 // DebugOut() << "inet: " << inet[i_inet];
1366 // }
1367 // }
1368 
1369  auto distr = eq_data_->dh_->distr();
1370 // for(auto pair : localDofMap) {
1371 // DebugOut().every_proc() << "r: " << distr->myp() << " gi: " << pair.first << "xyz: " << pair.second[0];
1372 //
1373 // }
1374 
1375 
1376  //convert set of dofs to vectors
1377  // number of nodes (= dofs) on the subdomain
1378  int numNodeSub = localDofMap.size();
1379  //ASSERT_PERMANENT_EQ( (unsigned int)numNodeSub, eq:data_->dh_->lsize() );
1380  // Indices of Subdomain Nodes in Global Numbering - for local nodes, their global indices
1381  std::vector<int> isngn( numNodeSub );
1382  // pseudo-coordinates of local nodes (i.e. dofs)
1383  // they need not be exact, they are used just for some geometrical considerations in BDDCML,
1384  // such as selection of corners maximizing area of a triangle, bounding boxes fro subdomains to
1385  // find candidate neighbours etc.
1386  std::vector<double> xyz( numNodeSub * 3 ) ;
1387  int ind = 0;
1388  std::map<int,arma::vec3>::iterator itB = localDofMap.begin();
1389  for ( ; itB != localDofMap.end(); ++itB ) {
1390  isngn[ind] = itB -> first;
1391 
1392  arma::vec3 coord = itB -> second;
1393  for ( int j = 0; j < 3; j++ ) {
1394  xyz[ j*numNodeSub + ind ] = coord[j];
1395  }
1396 
1397  ind++;
1398  }
1399  localDofMap.clear();
1400 
1401  // Number of Nodal Degrees of Freedom
1402  // nndf is trivially one - dofs coincide with nodes
1403  std::vector<int> nndf( numNodeSub, 1 );
1404 
1405  // prepare auxiliary map for renumbering nodes
1406  typedef std::map<int,int> Global2LocalMap_; //! type for storage of global to local map
1407  Global2LocalMap_ global2LocalNodeMap;
1408  for ( unsigned ind = 0; ind < isngn.size(); ++ind ) {
1409  global2LocalNodeMap.insert( std::make_pair( static_cast<unsigned>( isngn[ind] ), ind ) );
1410  }
1411 
1412  // renumber nodes in the inet array to locals
1413  int indInet = 0;
1414  for ( unsigned int iEle = 0; iEle < isegn.size(); iEle++ ) {
1415  int nne = nnet[ iEle ];
1416  for ( int ien = 0; ien < nne; ien++ ) {
1417 
1418  int indGlob = inet[indInet];
1419  // map it to local node
1420  Global2LocalMap_::iterator pos = global2LocalNodeMap.find( indGlob );
1421  ASSERT( pos != global2LocalNodeMap.end() )(indGlob).error("Cannot remap node global index to local indices.\n");
1422  int indLoc = static_cast<int> ( pos -> second );
1423 
1424  // store the node
1425  inet[ indInet++ ] = indLoc;
1426  }
1427  }
1428 
1429  int numNodes = size;
1430  int numDofsInt = size;
1431  int spaceDim = 3; // TODO: what is the proper value here?
1432  int meshDim = elDimMax;
1433 
1434  /**
1435  * We need:
1436  * - local to global element map (possibly mesh->el_4_loc
1437  * - inet, nnet - local dof numbers per element, local numbering of only those dofs that are on owned elements
1438  * 1. collect DH local dof indices on elements, manage map from DH local indices to BDDC local dof indices
1439  * 2. map collected DH indices to BDDC indices using the map
1440  * - local BDDC dofs to global dofs, use DH to BDDC map with DH local to global map
1441  * - XYZ - permuted, collect in main loop into array of size of all DH local dofs, compress and rearrange latter
1442  * - element_permeability - in main loop
1443  */
1444  bddc_ls -> load_mesh( LinSys_BDDC::BDDCMatrixType::SPD_VIA_SYMMETRICGENERAL, spaceDim, numNodes, numDofsInt, inet, nnet, nndf, isegn, isngn, isngn, xyz, element_permeability, meshDim );
1445 }
1446 
1447 
1448 
1449 
1450 //=============================================================================
1451 // DESTROY WATER MH SYSTEM STRUCTURE
1452 //=============================================================================
1454  if (previous_solution != nullptr) chkerr(VecDestroy(&previous_solution));
1455  if (steady_diagonal != nullptr) chkerr(VecDestroy(&steady_diagonal));
1456  if (new_diagonal != nullptr) chkerr(VecDestroy(&new_diagonal));
1457  if (steady_rhs != nullptr) chkerr(VecDestroy(&steady_rhs));
1458 
1459 
1460  if (schur0 != NULL) {
1461  delete schur0;
1462  }
1463 
1464  if (output_object) delete output_object;
1465 
1466  if(time_ != nullptr)
1467  delete time_;
1468 
1469 }
1470 
1471 
1472 /*
1473 void mat_count_off_proc_values(Mat m, Vec v) {
1474  int n, first, last;
1475  const PetscInt *cols;
1476  Distribution distr(v);
1477 
1478  int n_off = 0;
1479  int n_on = 0;
1480  int n_off_rows = 0;
1481  MatGetOwnershipRange(m, &first, &last);
1482  for (int row = first; row < last; row++) {
1483  MatGetRow(m, row, &n, &cols, PETSC_NULL);
1484  bool exists_off = false;
1485  for (int i = 0; i < n; i++)
1486  if (distr.get_proc(cols[i]) != distr.myp())
1487  n_off++, exists_off = true;
1488  else
1489  n_on++;
1490  if (exists_off)
1491  n_off_rows++;
1492  MatRestoreRow(m, row, &n, &cols, PETSC_NULL);
1493  }
1494 }
1495 */
1496 
1497 
1498 
1499 
1500 
1501 
1502 
1503 
1504 
1505 
1506 
1507 
1509 {
1510  DebugOut().fmt("Setup with dt: {}\n", time_->dt());
1511  for ( DHCellAccessor dh_cell : eq_data_->dh_->own_range() ) {
1512  ElementAccessor<3> ele = dh_cell.elm();
1513 
1514  double init_value = eq_fields_->init_pressure.value(ele.centre(),ele);
1515 
1516  LocDofVec loc_dofs = dh_cell.get_loc_dof_indices();
1517  for (unsigned int i=0; i<ele->n_sides(); i++) {
1518  uint n_sides_of_edge = ele.side(i)->edge().n_sides();
1519  uint edge_dof = ele->n_sides()+1+i;
1520  // set initial condition
1521  eq_data_->full_solution.add(loc_dofs[edge_dof], init_value/n_sides_of_edge);
1522  }
1523  }
1524 
1525  eq_data_->full_solution.ghost_to_local_begin();
1526  eq_data_->full_solution.ghost_to_local_end();
1527  eq_data_->full_solution.local_to_ghost_begin();
1528  eq_data_->full_solution.local_to_ghost_end();
1529 }
1530 
1531 
1533 {
1534  START_TIMER("DarcyFlowMH::reconstruct_solution_from_schur");
1535 
1536  for ( DHCellAccessor dh_cell : eq_data_->dh_->own_range() ) {
1537  unsigned int dim = dh_cell.dim();
1538  assembler[dim-1]->assemble_reconstruct(dh_cell);
1539  }
1540 
1541  eq_data_->full_solution.local_to_ghost_begin();
1542  eq_data_->full_solution.local_to_ghost_end();
1543 }
1544 
1545 
1547  // save diagonal of steady matrix
1548  MatGetDiagonal(*( schur0->get_matrix() ), steady_diagonal);
1549  // save RHS
1550  VecCopy(*( schur0->get_rhs()), steady_rhs);
1551 
1552 
1553  PetscScalar *local_diagonal;
1554  VecGetArray(new_diagonal,& local_diagonal);
1555 
1556  DebugOut().fmt("Setup with dt: {}\n", time_->dt());
1557 
1558  balance_->start_mass_assembly(eq_data_->water_balance_idx);
1559 
1560  std::vector<LongIdx> dofs;
1561  dofs.reserve(eq_data_->dh_->max_elem_dofs());
1562 
1563  for ( DHCellAccessor dh_cell : eq_data_->dh_->own_range() ) {
1564  ElementAccessor<3> ele = dh_cell.elm();
1565  dofs.resize(dh_cell.n_dofs());
1566  dh_cell.get_dof_indices(dofs);
1567 
1568  // TODO: replace with DHCell getter when available for FESystem component
1569  const uint p_ele_dof = dh_cell.n_dofs() / 2;
1570  // set new diagonal
1571  double diagonal_coeff = eq_fields_->cross_section.value(ele.centre(), ele)
1572  * ( eq_fields_->storativity.value(ele.centre(), ele)
1573  +eq_fields_->extra_storativity.value(ele.centre(), ele))
1574  * ele.measure();
1575  local_diagonal[dh_cell.get_loc_dof_indices()[p_ele_dof]]= - diagonal_coeff / time_->dt();
1576 
1577  balance_->add_mass_values(eq_data_->water_balance_idx, dh_cell,
1578  {dh_cell.get_loc_dof_indices()[p_ele_dof]},
1579  {diagonal_coeff}, 0.0);
1580  }
1581  VecRestoreArray(new_diagonal,& local_diagonal);
1582  MatDiagonalSet(*( schur0->get_matrix() ), new_diagonal, ADD_VALUES);
1583 
1584  schur0->set_matrix_changed();
1585 
1586  balance_->finish_mass_assembly(eq_data_->water_balance_idx);
1587 }
1588 
1590  START_TIMER("modify system");
1591  if (time_->is_changed_dt() && time_->step().index()>0) {
1592  double scale_factor=time_->step(-2).length()/time_->step().length();
1593  if (scale_factor != 1.0) {
1594  // if time step has changed and setup_time_term not called
1595  MatDiagonalSet(*( schur0->get_matrix() ),steady_diagonal, INSERT_VALUES);
1596 
1597  VecScale(new_diagonal, time_->last_dt()/time_->dt());
1598  MatDiagonalSet(*( schur0->get_matrix() ),new_diagonal, ADD_VALUES);
1600  }
1601  }
1602 
1603  // modify RHS - add previous solution
1604  VecPointwiseMult(*( schur0->get_rhs()), new_diagonal, previous_solution);
1605 // VecPointwiseMult(*( schur0->get_rhs()), new_diagonal, schur0->get_solution());
1606  VecAXPY(*( schur0->get_rhs()), 1.0, steady_rhs);
1608 
1609  //VecSwap(previous_solution, schur0->get_solution());
1610 }
1611 
1612 
1613 /// Helper method fills range (min and max) of given component
1614 void dofs_range(unsigned int n_dofs, unsigned int &min, unsigned int &max, unsigned int component) {
1615  if (component==0) {
1616  min = 0;
1617  max = n_dofs/2;
1618  } else if (component==1) {
1619  min = n_dofs/2;
1620  max = (n_dofs+1)/2;
1621  } else {
1622  min = (n_dofs+1)/2;
1623  max = n_dofs;
1624  }
1625 }
1626 
1627 
1629  ASSERT_LT(component, 3).error("Invalid component!");
1630  unsigned int i, n_dofs, min, max;
1631  std::vector<int> dof_vec;
1632  std::vector<LongIdx> dof_indices(eq_data_->dh_->max_elem_dofs());
1633  for ( DHCellAccessor dh_cell : eq_data_->dh_->own_range() ) {
1634  n_dofs = dh_cell.get_dof_indices(dof_indices);
1635  dofs_range(n_dofs, min, max, component);
1636  for (i=min; i<max; ++i) dof_vec.push_back(dof_indices[i]);
1637  }
1638  return dof_vec;
1639 }
1640 
1641 
1642 //-----------------------------------------------------------------------------
1643 // vim: set cindent:
LimitSide::right
@ right
Element::n_neighs_vb
unsigned int n_neighs_vb() const
Return number of neighbours.
Definition: elements.h:65
LocDofVec
arma::Col< IntIdx > LocDofVec
Definition: index_types.hh:28
DarcyMH::balance_
std::shared_ptr< Balance > balance_
Definition: darcy_flow_mh.hh:365
Side::edge
Edge edge() const
Returns pointer to the edge connected to the side.
Definition: accessors_impl.hh:227
EquationBase::mesh_
Mesh * mesh_
Definition: equation.hh:219
linsys_BDDC.hh
Solver based on Multilevel BDDC - using corresponding class of OpenFTL package.
Input::Type::Bool
Class for declaration of the input of type Bool.
Definition: type_base.hh:452
result_zeros
@ result_zeros
Definition: field_algo_base.hh:74
LinSys::get_solution
const Vec & get_solution()
Definition: linsys.hh:281
MPI_MIN
#define MPI_MIN
Definition: mpi.h:198
DarcyMH::previous_solution
Vec previous_solution
Definition: darcy_flow_mh.hh:389
DarcyMH::solution_precision
virtual double solution_precision() const
Definition: darcy_flow_mh.cc:848
DarcyMH::init_eq_data
void init_eq_data()
Definition: darcy_flow_mh.cc:430
ASSERT_GT
#define ASSERT_GT(a, b)
Definition of comparative assert macro (Greater Than) only for debug mode.
Definition: asserts.hh:317
LinSys::SolveInfo::n_iterations
int n_iterations
Definition: linsys.hh:109
Armor::vec
ArmaVec< double, N > vec
Definition: armor.hh:885
DarcyMH::solve_nonlinear
void solve_nonlinear()
Solve method common to zero_time_step and update solution.
Definition: darcy_flow_mh.cc:709
DarcyFlowMHOutput::output
void output()
Calculate values for output.
Definition: darcy_flow_mh_output.cc:245
TimeGovernor::dt
double dt() const
Definition: time_governor.hh:565
DarcyMH::use_steady_assembly_
bool use_steady_assembly_
Definition: darcy_flow_mh.hh:374
UnitSI::dimensionless
static UnitSI & dimensionless()
Returns dimensionless unit.
Definition: unit_si.cc:55
SchurComplement::set_complement
void set_complement(LinSys_PETSC *ls)
Set complement LinSys object.
Definition: schur.cc:287
factory.hh
field_constant.hh
LinSys
Definition: la_linsys_new.hh:169
vector_mpi.hh
time_governor.hh
Basic time management class.
field_add_potential.hh
DarcyMH::size
int size
Definition: darcy_flow_mh.hh:369
DarcyMH::steady_rhs
Vec steady_rhs
Definition: darcy_flow_mh.hh:387
field_algo_base.hh
DarcyMH::solve_time_step
void solve_time_step(bool output=true)
Solve the problem without moving to next time and without output.
Definition: darcy_flow_mh.cc:650
MeshBase::region_db
const RegionDB & region_db() const
Definition: mesh.h:175
DarcyMH::update_solution
void update_solution() override
Definition: darcy_flow_mh.cc:635
DarcyMH::EqFields::EqFields
EqFields()
Creation of all fields.
Definition: darcy_flow_mh.cc:193
DarcyMH::EqFields::river
@ river
Definition: darcy_flow_mh.hh:154
LinSys::SolveInfo
Definition: linsys.hh:104
ASSERT
#define ASSERT(expr)
Definition: asserts.hh:351
DarcyMH::type_field_descriptor
static const Input::Type::Record & type_field_descriptor()
Definition: darcy_flow_mh.cc:121
LinSys::set_symmetric
void set_symmetric(bool flag=true)
Definition: linsys.hh:560
DarcyMH::postprocess
virtual void postprocess()
postprocess velocity field (add sources)
Definition: darcy_flow_mh.cc:798
Mesh::n_sides
unsigned int n_sides() const
Definition: mesh.cc:308
DarcyFlowInterface::MortarP1
@ MortarP1
Definition: darcy_flow_interface.hh:33
EquationBase::time_
TimeGovernor * time_
Definition: equation.hh:220
DarcyMH::setup_time_term
virtual void setup_time_term()
Definition: darcy_flow_mh.cc:1546
distribution.hh
Support classes for parallel programing.
LinSys_BDDC::get_input_type
static const Input::Type::Record & get_input_type()
Definition: linsys_BDDC.cc:39
bc_mesh.hh
Edge::n_sides
unsigned int n_sides() const
Returns number of sides aligned with the edge.
Definition: accessors.hh:329
Input::Type::Integer
Class for declaration of the integral input data.
Definition: type_base.hh:483
Input::Record::val
const Ret val(const string &key) const
Definition: accessors_impl.hh:31
DHCellAccessor::get_dof_indices
unsigned int get_dof_indices(std::vector< LongIdx > &indices) const
Fill vector of the global indices of dofs associated to the cell.
Definition: dh_cell_accessor.hh:80
TimeGovernor::set_upper_constraint
int set_upper_constraint(double upper, std::string message)
Sets upper constraint for the next time step estimating.
Definition: time_governor.cc:555
EquationBase::time
TimeGovernor & time()
Definition: equation.hh:148
Input::Type::Selection::close
const Selection & close() const
Close the Selection, no more values can be added.
Definition: type_selection.cc:65
fmt::fprintf
FMT_FUNC int fprintf(std::ostream &os, CStringRef format, ArgList args)
Definition: ostream.cc:56
FilePath
Dedicated class for storing path to input and output files.
Definition: file_path.hh:54
linsys.hh
Wrappers for linear systems based on MPIAIJ and MATIS format.
Input::Type::Double
Class for declaration of the input data that are floating point numbers.
Definition: type_base.hh:534
LinSys::rhs_zero_entries
virtual PetscErrorCode rhs_zero_entries()
Definition: linsys.hh:272
chkerr
void chkerr(unsigned int ierr)
Replacement of new/delete operator in the spirit of xmalloc.
Definition: system.hh:142
DarcyMH::create_linear_system
void create_linear_system(Input::AbstractRecord rec)
Definition: darcy_flow_mh.cc:1034
FLOW123D_FORCE_LINK_IN_CHILD
#define FLOW123D_FORCE_LINK_IN_CHILD(x)
Definition: global_defs.h:104
LinSys_PETSC
Definition: linsys_PETSC.hh:43
MeshBase::n_edges
unsigned int n_edges() const
Definition: mesh.h:114
LinSys::mat_zero_entries
virtual PetscErrorCode mat_zero_entries()
Definition: linsys.hh:263
THROW
#define THROW(whole_exception_expr)
Wrapper for throw. Saves the throwing point.
Definition: exceptions.hh:53
LinSys::SolveInfo::converged_reason
int converged_reason
Definition: linsys.hh:108
std::vector< double >
ElementAccessor< 3 >
DarcyMH::output_data
virtual void output_data() override
Write computed fields.
Definition: darcy_flow_mh.cc:832
DarcyMH::~DarcyMH
virtual ~DarcyMH() override
Definition: darcy_flow_mh.cc:1453
system.hh
arma::vec3
Definition: doxy_dummy_defs.hh:17
LinSys::set_rhs_changed
void set_rhs_changed()
Definition: linsys.hh:217
fn_mh_velocity
Definition: assembly_models.hh:29
SchurComplement::make_complement_distribution
Distribution * make_complement_distribution()
get distribution of complement object if complement is defined
Definition: schur.cc:294
assembly_models.hh
Functors of FieldModels used in Darcy flow module.
DHCellAccessor::dim
unsigned int dim() const
Return dimension of element appropriate to cell.
Definition: dh_cell_accessor.hh:101
DarcyMH::get_mh_mortar_selection
static const Input::Type::Selection & get_mh_mortar_selection()
Selection for enum MortarMethod.
Definition: darcy_flow_mh.cc:83
LinSys::solve
virtual SolveInfo solve()=0
field_fe.hh
uint
unsigned int uint
Definition: mh_dofhandler.hh:101
Input::AbstractRecord::type
Input::Type::Record type() const
Definition: accessors.cc:273
linsys_PETSC.hh
Solver based on the original PETSc solver using MPIAIJ matrix and succesive Schur complement construc...
DarcyMH::max_n_it_
unsigned int max_n_it_
Definition: darcy_flow_mh.hh:380
dofs_range
void dofs_range(unsigned int n_dofs, unsigned int &min, unsigned int &max, unsigned int component)
Helper method fills range (min and max) of given component.
Definition: darcy_flow_mh.cc:1614
LinSys::set_negative_definite
void set_negative_definite(bool flag=true)
Definition: linsys.hh:587
MeshBase::elements_range
Range< ElementAccessor< 3 > > elements_range() const
Returns range of mesh elements.
Definition: mesh.cc:1168
index_types.hh
LinSys::set_positive_definite
void set_positive_definite(bool flag=true)
Definition: linsys.hh:575
ASSERT_LT
#define ASSERT_LT(a, b)
Definition of comparative assert macro (Less Than) only for debug mode.
Definition: asserts.hh:301
DarcyMH::allocate_mh_matrix
void allocate_mh_matrix()
Definition: darcy_flow_mh.cc:884
LinSys::set_matrix_changed
void set_matrix_changed()
Definition: linsys.hh:211
fe_p.hh
Definitions of basic Lagrangean finite elements with polynomial shape functions.
DarcyMH::prepare_new_time_step
void prepare_new_time_step()
Definition: darcy_flow_mh.cc:793
DarcyMH::assembly_mh_matrix
void assembly_mh_matrix(MultidimAssembly &assembler)
Definition: darcy_flow_mh.cc:860
LinSys::start_allocation
virtual void start_allocation()
Definition: linsys.hh:332
DarcyMH::solved_time
virtual double solved_time() override
Definition: darcy_flow_mh.cc:407
DarcyFlowMHOutput::get_input_type
static const Input::Type::Instance & get_input_type(FieldSet &eq_data, const std::string &equation_name)
Definition: darcy_flow_mh_output.cc:62
Input::Type::Record::size
unsigned int size() const
Returns number of keys in the Record.
Definition: type_record.hh:602
SchurComplement
Definition: schur.hh:64
TimeGovernor::is_end
bool is_end() const
Returns true if the actual time is greater than or equal to the end time.
Definition: time_governor.hh:595
SchurComplement::set_from_input
void set_from_input(const Input::Record in_rec) override
Definition: schur.cc:138
Input::Type::Default
Class Input::Type::Default specifies default value of keys of a Input::Type::Record.
Definition: type_record.hh:61
DHCellSide
Side accessor allows to iterate over sides of DOF handler cell.
Definition: dh_cell_accessor.hh:176
Input::Type::Record::derive_from
virtual Record & derive_from(Abstract &parent)
Method to derive new Record from an AbstractRecord parent.
Definition: type_record.cc:196
DarcyMH::eq_data_
std::shared_ptr< EqData > eq_data_
Definition: darcy_flow_mh.hh:392
Distribution
Definition: distribution.hh:50
DarcyMH::output_object
DarcyFlowMHOutput * output_object
Definition: darcy_flow_mh.hh:367
Mesh::bc_mesh
BCMesh * bc_mesh() const override
Implement MeshBase::bc_mesh(), getter of boundary mesh.
Definition: mesh.h:563
AddPotentialFactory
Definition: field_add_potential.hh:49
LimitSide::left
@ left
LinSys::compute_residual
virtual double compute_residual()=0
DarcyFlowInterface::NoMortar
@ NoMortar
Definition: darcy_flow_interface.hh:31
accessors.hh
LinSys::set_tolerances
virtual void set_tolerances(double r_tol, double a_tol, unsigned int max_it)=0
Input::Record
Accessor to the data with type Type::Record.
Definition: accessors.hh:291
LinSys::rhs_set_value
void rhs_set_value(int row, double val)
Definition: linsys.hh:380
FieldFlag::equation_result
static constexpr Mask equation_result
Match result fields. These are never given by input or copy of input.
Definition: field_flag.hh:55
sys_profiler.hh
DarcyMH::EqFields::get_bc_type_selection
static const Input::Type::Selection & get_bc_type_selection()
Return a Selection corresponding to enum BC_Type.
Definition: darcy_flow_mh.cc:92
darcy_flow_mh_output.hh
Output class for darcy_flow_mh model.
ASSERT_PERMANENT
#define ASSERT_PERMANENT(expr)
Allow use shorter versions of macro names if these names is not used with external library.
Definition: asserts.hh:348
field_model.hh
DarcyMH::assembly_source_term
virtual void assembly_source_term()
Source term is implemented differently in LMH version.
Definition: darcy_flow_mh.cc:997
DarcyMH::DarcyFlowMHOutput
friend class DarcyFlowMHOutput
Definition: darcy_flow_mh.hh:394
LinSys::get_matrix
virtual const Mat * get_matrix()
Definition: linsys.hh:186
mpi.h
mixed_mesh_intersections.hh
schur.hh
Assembly explicit Schur complement for the given linear system. Provides method for resolution of the...
DarcyMH::modify_system
void modify_system()
Definition: darcy_flow_mh.cc:1589
DarcyMH::EqFields
Definition: darcy_flow_mh.hh:143
DarcyMH::min_n_it_
unsigned int min_n_it_
Definition: darcy_flow_mh.hh:379
TimeGovernor
Basic time management functionality for unsteady (and steady) solvers (class Equation).
Definition: time_governor.hh:317
TimeGovernor::step
const TimeStep & step(int index=-1) const
Definition: time_governor.cc:756
DarcyMH::zero_time_term
virtual bool zero_time_term(bool time_global=false)
Definition: darcy_flow_mh.cc:700
DarcyMH::steady_diagonal
Vec steady_diagonal
Definition: darcy_flow_mh.hh:386
DHCellAccessor::elm
const ElementAccessor< 3 > elm() const
Return ElementAccessor to element of loc_ele_idx_.
Definition: dh_cell_accessor.hh:71
field_values.hh
Input::AbstractRecord
Accessor to the polymorphic input data of a type given by an AbstracRecord object.
Definition: accessors.hh:458
Input::Type::Default::obligatory
static Default obligatory()
The factory function to make an empty default value which is obligatory.
Definition: type_record.hh:110
SchurComplement::IsB
IS IsB
Definition: schur.hh:138
UnitSI
Class for representation SI units of Fields.
Definition: unit_si.hh:40
LinSys_BDDC
Definition: linsys_BDDC.hh:39
fn_mh_piezohead
Definition: assembly_models.hh:37
ASSERT_EQ
#define ASSERT_EQ(a, b)
Definition of comparative assert macro (EQual) only for debug mode.
Definition: asserts.hh:333
DarcyMH::print_matlab_matrix
void print_matlab_matrix(string matlab_file)
Print darcy flow matrix in matlab format into a file.
Definition: darcy_flow_mh.cc:1203
EquationBase::input_record_
Input::Record input_record_
Definition: equation.hh:221
RegionDB::get_region_set
RegionSet get_region_set(const std::string &set_name) const
Definition: region.cc:328
FieldCommon::field_descriptor_record_description
static const std::string field_descriptor_record_description(const string &record_name)
Definition: field_common.cc:73
DarcyMH::eq_fields_
std::shared_ptr< EqFields > eq_fields_
Definition: darcy_flow_mh.hh:391
Input::Record::opt_val
bool opt_val(const string &key, Ret &value) const
Definition: accessors_impl.hh:107
Input::Type::Record::declare_key
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
MPI_INT
#define MPI_INT
Definition: mpi.h:160
DarcyFlowMHOutput::get_input_type_specific
static const Input::Type::Instance & get_input_type_specific()
Definition: darcy_flow_mh_output.cc:69
DarcyMH::schur0
LinSys * schur0
Definition: darcy_flow_mh.hh:384
mesh.h
DHCellAccessor::n_dofs
unsigned int n_dofs() const
Return number of dofs on given cell.
Definition: dh_cell_accessor.hh:420
Input::Type::Selection
Template for classes storing finite set of named values.
Definition: type_selection.hh:65
std::map
Definition: doxy_dummy_defs.hh:11
DarcyMH::reconstruct_solution_from_schur
void reconstruct_solution_from_schur(MultidimAssembly &assembler)
Definition: darcy_flow_mh.cc:1532
DarcyFlowInterface::MortarMethod
MortarMethod
Type of experimental Mortar-like method for non-compatible 1d-2d interaction.
Definition: darcy_flow_interface.hh:30
DarcyFlowInterface::get_input_type
static Input::Type::Abstract & get_input_type()
Definition: darcy_flow_interface.hh:23
LinSys::start_add_assembly
virtual void start_add_assembly()
Definition: linsys.hh:340
DarcyMH::EqFields::none
@ none
Definition: darcy_flow_mh.hh:150
TimeGovernor::estimate_dt
double estimate_dt() const
Estimate choice of next time step according to actual setting of constraints.
Definition: time_governor.cc:631
DarcyMH::n_schur_compls
int n_schur_compls
Definition: darcy_flow_mh.hh:370
TimeGovernor::view
void view(const char *name="") const
Definition: time_governor.cc:772
FieldFlag::input_copy
static constexpr Mask input_copy
Definition: field_flag.hh:44
Input::Type::Record::close
Record & close() const
Close the Record for further declarations of keys.
Definition: type_record.cc:304
LinSys_BDDC::set_from_input
void set_from_input(const Input::Record in_rec) override
Definition: linsys_BDDC.cc:279
SchurComplement::loc_size_B
int loc_size_B
Definition: schur.hh:137
Input::Type
Definition: balance.hh:41
MixedMeshIntersections::element_intersections_
std::vector< std::vector< ILpair > > element_intersections_
Definition: mixed_mesh_intersections.hh:83
partitioning.hh
Input::Type::Record
Record type proxy class.
Definition: type_record.hh:182
DarcyMH::new_diagonal
Vec new_diagonal
Definition: darcy_flow_mh.hh:388
DarcyMH::get_component_indices_vec
std::vector< int > get_component_indices_vec(unsigned int component) const
Get vector of all DOF indices of given component (0..side, 1..element, 2..edge)
Definition: darcy_flow_mh.cc:1628
LongIdx
int LongIdx
Define type that represents indices of large arrays (elements, nodes, dofs etc.)
Definition: index_types.hh:24
LinSys_PETSC::set_from_input
void set_from_input(const Input::Record in_rec) override
Definition: linsys_PETSC.cc:470
Mesh
Definition: mesh.h:359
DarcyMH::EqFields::total_flux
@ total_flux
Definition: darcy_flow_mh.hh:152
OutputTime::get_input_type
static const Input::Type::Record & get_input_type()
The specification of output stream.
Definition: output_time.cc:38
Element::n_sides
unsigned int n_sides() const
Definition: elements.h:131
DarcyMH::nonlinear_iteration_
unsigned int nonlinear_iteration_
Definition: darcy_flow_mh.hh:381
Input::Type::Record::copy_keys
Record & copy_keys(const Record &other)
Copy keys from other record.
Definition: type_record.cc:216
FieldAlgorithmBase
Definition: field_algo_base.hh:112
Input::Type::Array
Class for declaration of inputs sequences.
Definition: type_base.hh:339
DarcyMH::tolerance_
double tolerance_
Definition: darcy_flow_mh.hh:378
DarcyMH::set_mesh_data_for_bddc
void set_mesh_data_for_bddc(LinSys_BDDC *bddc_ls)
Definition: darcy_flow_mh.cc:1276
DarcyMH::get_input_type
static const Input::Type::Record & get_input_type()
Definition: darcy_flow_mh.cc:136
Model
Definition: field_model.hh:338
DHCellAccessor
Cell accessor allow iterate over DOF handler cells.
Definition: dh_cell_accessor.hh:43
LinSys::finish_assembly
virtual void finish_assembly()=0
LinSys::get_rhs
virtual const Vec * get_rhs()
Definition: linsys.hh:202
MPI_Allreduce
#define MPI_Allreduce(sendbuf, recvbuf, count, datatype, op, comm)
Definition: mpi.h:612
Input::Array
Accessor to input data conforming to declared Array.
Definition: accessors.hh:566
DarcyMH::assembly_linear_system
virtual void assembly_linear_system()
Definition: darcy_flow_mh.cc:1147
DarcyMH::DarcyMH
DarcyMH(Mesh &mesh, const Input::Record in_rec, TimeGovernor *tm=nullptr)
CREATE AND FILL GLOBAL MH MATRIX OF THE WATER MODEL.
Definition: darcy_flow_mh.cc:355
WarningOut
#define WarningOut()
Macro defining 'warning' record of log.
Definition: logger.hh:278
ElementAccessor::region
Region region() const
Definition: accessors.hh:198
DarcyMH::equation_name_
static const std::string equation_name_
Definition: darcy_flow_mh.hh:402
EquationBase::record_template
static Input::Type::Record & record_template()
Template Record with common keys for derived equations.
Definition: equation.cc:35
LinSys::get_solution_precision
virtual double get_solution_precision()=0
MixedPtr
Definition: mixed.hh:247
SchurComplement
SchurComplement SchurComplement
Definition: linsys.hh:91
TimeGovernor::is_default
bool is_default()
Definition: time_governor.hh:388
darcy_flow_mh.hh
mixed-hybrid model of linear Darcy flow, possibly unsteady.
LinSys::set_solution
void set_solution(Vec sol_vec)
Definition: linsys.hh:289
DarcyMH::initialize_specific
virtual void initialize_specific()
Definition: darcy_flow_mh.cc:587
DarcyMH::EqFields::seepage
@ seepage
Definition: darcy_flow_mh.hh:153
std::vector::data
T data
Definition: doxy_dummy_defs.hh:7
LinSys::get_input_type
static Input::Type::Abstract & get_input_type()
Definition: linsys.cc:29
ElementAccessor::idx
unsigned int idx() const
We need this method after replacing Region by RegionIdx, and movinf RegionDB instance into particular...
Definition: accessors.hh:215
FilePath::output_file
@ output_file
Definition: file_path.hh:69
EquationBase::eq_fieldset_
FieldSet * eq_fieldset_
Definition: equation.hh:228
TimeGovernor::is_changed_dt
bool is_changed_dt() const
Definition: time_governor.hh:529
DarcyFlowInterface::MortarP0
@ MortarP0
Definition: darcy_flow_interface.hh:32
balance.hh
local_to_global_map.hh
DarcyMH::data_changed_
bool data_changed_
Definition: darcy_flow_mh.hh:375
MeshBase::n_elements
unsigned int n_elements() const
Definition: mesh.h:111
TimeStep::index
unsigned int index() const
Definition: time_governor.hh:159
IntersectionLocalBase::bulk_ele_idx
unsigned int bulk_ele_idx() const
Returns index of bulk element.
Definition: intersection_local.hh:77
DarcyMH::EqFields::dirichlet
@ dirichlet
Definition: darcy_flow_mh.hh:151
Mesh::mixed_intersections
MixedMeshIntersections & mixed_intersections()
Definition: mesh.cc:849
DebugOut
#define DebugOut()
Macro defining 'debug' record of log.
Definition: logger.hh:284
Input::Type::Selection::add_value
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.
Definition: type_selection.cc:50
ElementAccessor::side
SideIter side(const unsigned int loc_index)
Definition: accessors_impl.hh:131
TimeGovernor::next_time
void next_time()
Proceed to the next time according to current estimated time step.
Definition: time_governor.cc:670
TimeStep::length
double length() const
Definition: time_governor.hh:160
Input::Type::Default::optional
static Default optional()
The factory function to make an empty default value which is optional.
Definition: type_record.hh:124
DarcyMH::read_initial_condition
virtual void read_initial_condition()
Definition: darcy_flow_mh.cc:1508
RegionIdx::bulk_idx
unsigned int bulk_idx() const
Returns index of the region in the bulk set.
Definition: region.hh:90
START_TIMER
#define START_TIMER(tag)
Starts a timer with specified tag.
Definition: sys_profiler.hh:115
FESystem
Compound finite element on dim dimensional simplex.
Definition: fe_system.hh:101
DarcyMH::registrar
static const int registrar
Registrar of class to factory.
Definition: darcy_flow_mh.hh:400
DarcyMH::initialize
void initialize() override
Definition: darcy_flow_mh.cc:482
LinSys_PETSC::get_input_type
static const Input::Type::Record & get_input_type()
Definition: linsys_PETSC.cc:32
DarcyMH::zero_time_step
void zero_time_step() override
Definition: darcy_flow_mh.cc:590
field.hh
DarcyFlowInterface
Definition: darcy_flow_interface.hh:15
Balance::get_input_type
static const Input::Type::Record & get_input_type()
Main balance input record type.
Definition: balance.cc:53
IntersectionResult::none
@ none
assembly_mh_old.hh
ElementAccessor::measure
double measure() const
Computes the measure of the element.
Definition: accessors_impl.hh:59
END_TIMER
#define END_TIMER(tag)
Ends a timer with specified tag.
Definition: sys_profiler.hh:149
DarcyMH::eq_fields
EqFields & eq_fields()
Definition: darcy_flow_mh.hh:268
TimeGovernor::last_dt
double last_dt() const
Definition: time_governor.hh:548
FieldValue
Definition: field_values.hh:645
range_wrapper.hh
Implementation of range helper class.
ElementAccessor::centre
arma::vec::fixed< spacedim > centre() const
Computes the barycenter.
Definition: accessors_impl.hh:81
IntersectionLocalBase
Common base for intersection object.
Definition: intersection_local.hh:48
Distribution::begin
unsigned int begin(int proc) const
get starting local index
Definition: distribution.hh:109
DarcyMH::EqData::EqData
EqData()
Constructor.
Definition: darcy_flow_mh.cc:335
MessageOut
#define MessageOut()
Macro defining 'message' record of log.
Definition: logger.hh:275
LinSys::mat_set_values
virtual void mat_set_values(int nrow, int *rows, int ncol, int *cols, double *vals)=0
intersection_local.hh
Classes with algorithms for computation of intersections of meshes.
TimeGovernor::t
double t() const
Definition: time_governor.hh:542