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