Flow123d  JS_before_hm-1575-ga41e096
field.hh
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 field.hh
15  * @brief
16  */
17 
18 #ifndef FIELD_HH_
19 #define FIELD_HH_
20 
21 #include <stdio.h> // for sprintf
22 #include <string.h> // for memcpy
23 #include <algorithm> // for find, min
24 #include <boost/circular_buffer.hpp>
25 #include <memory> // for dynamic_pointe...
26 #include <new> // for operator new[]
27 #include <ostream> // for basic_ostream:...
28 #include <string> // for basic_string
29 #include <utility> // for pair
30 #include <vector> // for vector
31 #include <armadillo>
32 #include "fields/field_algo_base.hh" // for FieldAlgorithm...
33 #include "fields/field_common.hh" // for FieldCommon::T...
34 #include "fields/field_values.hh" // for FieldValue<>::...
35 #include "fields/field_value_cache.hh" // for FieldValueCache
36 #include "input/accessors.hh" // for ExcTypeMismatch
37 #include "input/accessors_impl.hh" // for Record::opt_val
38 #include "input/factory_impl.hh" // for Factory::create
39 #include "input/input_exception.hh" // for FieldCommon::E...
40 #include "input/storage.hh" // for ExcStorageType...
41 #include "input/type_base.hh" // for Array
42 #include "input/type_generic.hh" // for Instance
43 #include "input/type_record.hh" // for Record::ExcRec...
44 #include "io/output_time.hh" // for OutputTime
45 #include "mesh/elements.h" // for Element::dim
46 #include "mesh/region.hh" // for RegionDB::ExcU...
47 #include "system/asserts.hh" // for Assert, ASSERT
48 #include "system/exc_common.hh" // for ExcAssertMsg
49 #include "system/exceptions.hh" // for ExcAssertMsg::...
50 #include "system/global_defs.h" // for OLD_ASSERT, msg
51 #include "tools/time_governor.hh" // for TimeStep
52 
53 class Mesh;
54 class Observe;
55 class EvalPoints;
56 class BulkPoint;
57 class EdgePoint;
58 class CouplingPoint;
59 class BoundaryPoint;
60 class FieldSet;
61 template <int spacedim> class ElementAccessor;
62 template <int spacedim, class Value> class FieldFE;
63 namespace detail
64 {
65  template< typename CALLABLE, typename TUPLE, int INDEX >
67 }
68 
69 using namespace std;
70 namespace IT=Input::Type;
71 
72 /**
73  * @brief Class template representing a field with values dependent on: point, element, and region.
74  *
75  * By "field" we mean a mapping of a a pair (Point, Time) to a @p Value, where
76  * Point is from @p spacedim dimensional ambient space, Time is real number (set by @p set_time method),
77  * and @p Value type representing range of the field, which can be: real scalar, integer scalar (a discrete value),
78  * real vector of fixed (compile time) size, real vector of runtime size, or a matrix of fixed dimensions.
79  * Extensions to vectors or matrices of integers, or to variable tensors are possible. For vector and matrix values
80  * we use classes provided by Armadillo library for linear algebra.
81  * The @p Value template parameter should FieldValue<> template, usual choices are:
82  * FieldValue<spacedim>::Scalar, FieldValue<spacedim>::Integer, FieldValue<spacedim>::Enum,
83  * FieldValue<spacedim>::VectorFixed, FieldValue<spacedim>::TensorFixed.
84  *
85  * This class assign particular fields (instances of descendants of FiledBase) to the regions. It keeps a table of pointers to fields for every possible bulk
86  * region index (very same functionality, but for boundary regions is provided by @p BCField class). This class has interface very similar to FiledBase, however
87  * key methods @p value, and @p value_list are not virtual in this class by contrast these methods are inlined to minimize overhead for
88  * simplest fields like FieldConstant.
89  *
90  * TODO: currently it works only for spacedim==3 since we have only mesh in 3D ambient space.
91  *
92  */
93 template<int spacedim, class Value>
94 class Field : public FieldCommon {
95 public:
96 
98  typedef std::shared_ptr< FieldBaseType > FieldBasePtr;
100  typedef Value ValueType;
101 
102  static const unsigned int space_dim = spacedim;
103 
104 
105  /**
106  * Factory class that creates an instance of FieldBase for field
107  * with name @p field_name based on data in field descriptor @p rec.
108  *
109  * Default implementation in method @p create_field just reads key given by
110  * @p field_name and creates instance using @p FieldBase<...>::function_factory.
111  * Function should return empty SharedField (that is shared_ptr to FieldBase).
112  *
113  * Implementation of these descendants is necessary:
114  * 1) for backward compatibility with old BCD input files
115  * 2) for setting pressure values are piezometric head values
116  */
117  /**
118  * Note for future:
119  * We pass through parameter @p field information about field that holds the factory which are necessary
120  * for interpreting user input and create particular field instance. It would be clearer to pass these information
121  * when the factory is assigned to a field. Moreover some information may not be set to field at all but directly passed
122  * to the factory.
123  */
124  class FactoryBase {
125  public:
126  /**
127  * Default method that creates an instance of FieldBase for field.
128  *
129  * Reads key given by @p field_name and creates the field instance using
130  * @p FieldBase<...>::function_factory.
131  */
132  virtual FieldBasePtr create_field(Input::Record rec, const FieldCommon &field);
133 
134  /**
135  * Check if Input::Record accessor contains data of field given by input_name.
136  *
137  * Returns true when ever the method create_field returns non-null pointer, otherwise returns false.
138  */
139  virtual bool is_active_field_descriptor(const Input::Record &in_rec, const std::string &input_name);
140  };
141 
142  /**
143  * Default constructor.
144  *
145  */
146  Field();
147 
148  Field(const string &name, bool bc = false);
149 
150  /**
151  * Constructor that must be used for create of MultiField components.
152  *
153  * Set parameters @p component_index_, @p shared_->input_name_ and @p name_.
154  * Parameter name_ of Field is consisted of component name and MultiField name.
155  */
156  Field(unsigned int component_index, string input_name, string name = "", bool bc = false);
157 
158  /**
159  * Copy constructor. Keeps shared history, declaration data, mesh.
160  */
161  Field(const Field &other);
162 
163  /**
164  * Assignment operator. Same properties as copy constructor, but class member name_ is not copied.
165  *
166  * Question: do we really need this, isn't copy constructor enough?
167  * Answer: It is necessary in (usual) case when Field instance is created as the class member
168  * but is filled later by assignment possibly from other class.
169  * TODO: operator can be merged with copy constructor, but we must provide to set correct value
170  * of name in method copy_from
171  */
172  Field &operator=(const Field &other);
173 
174 
175  /// Return appropriate value to BulkPoint in FieldValueCache
176  typename Value::return_type operator() (BulkPoint &p);
177 
178 
179  /// Return appropriate value to EdgePoint in FieldValueCache
180  typename Value::return_type operator() (EdgePoint &p);
181 
182 
183  /// Return appropriate value to CouplingPoint in FieldValueCache
184  typename Value::return_type operator() (CouplingPoint &p);
185 
186 
187  /// Return appropriate value to BoundaryPoint in FieldValueCache
188  typename Value::return_type operator() (BoundaryPoint &p);
189 
190 
191  /**
192  * Returns reference to input type of particular field instance, this is static member @p input_type of the corresponding FieldBase class
193  * (i.e. with same template parameters). However, for fields returning "Enum" we have to create whole unique Input::Type hierarchy using following method
194  * @p meka_input_tree.
195  * every instance since every such field use different Selection for initialization, even if all returns just unsigned int.
196  */
197  IT::Instance get_input_type() override;
198 
199  IT::Array get_multifield_input_type() override;
200 
201 
202  /**
203  * By this method you can allow that the field need not to be set on regions (and times) where the given @p control_field is
204  * FieldConstant and has value in given @p value_list. We check this in the set_time method. Through this mechanism we
205  * can switch of e.g. boundary data fields according to the type of the boundary condition.
206  */
207  auto disable_where(
208  const Field<spacedim, typename FieldValue<spacedim>::Enum > &control_field,
209  const vector<FieldEnum> &value_list) -> Field &;
210 
211 
212 
213  /**
214  * Set mesh pointer and resize region arrays.
215  *
216  * Implements abstract method.
217  */
218  void set_mesh(const Mesh &mesh) override;
219 
220 
221  /**
222  * Direct read access to the table of Field pointers on regions.
223  */
224  //std::shared_ptr< FieldBaseType > operator[] (Region reg);
225 
226  /**
227  * Implementation of @p FieldCommonBase::is_constant().
228  * See also Field<>::field_result which provide better information about special field values.
229  */
230  bool is_constant(Region reg) override;
231 
232  /**
233  * Assigns given @p field to all regions in region set given by @p region_set_names.
234  * Field is added to the history with given time and possibly used in the next call of the set_time method.
235  * Caller is responsible for correct construction of given field.
236  *
237  * Use this method only if necessary.
238  */
239  void set(FieldBasePtr field, double time, std::vector<std::string> region_set_names = {"ALL"});
240 
241  /**
242  * Same as before but the field is first created using FieldBase::function_factory(), from
243  * given abstract record accessor @p a_rec.
244  */
245  void set(const Input::AbstractRecord &a_rec, double time, std::vector<std::string> region_set_names = {"ALL"});
246 
247  /**
248  * Check that whole field list is set, possibly use default values for unset regions
249  * and call set_time for every field in the field list.
250  *
251  * Returns true if the field has been changed.
252  */
253  bool set_time(const TimeStep &time, LimitSide limit_side) override;
254 
255  /**
256  * Check that other has same type and assign from it.
257  */
258  void copy_from(const FieldCommon & other) override;
259 
260  /**
261  * Implementation of FieldCommonBase::output().
262  */
263  void field_output(std::shared_ptr<OutputTime> stream) override;
264 
265  /**
266  * Implementation of FieldCommonBase::observe_output().
267  */
268  void observe_output(std::shared_ptr<Observe> observe) override;
269 
270  /**
271  * Returns true, if field is currently set to a time in which it is discontinuous.
272  */
273  //bool is_jump_time();
274 
275 
276  /**
277  * @brief Indicates special field states.
278  *
279  * Return possible values from the enum @p FieldResult, see description there.
280  * The initial state is @p field_none, if the field is correctly set on all regions of the @p region_set given as parameter
281  * we return state @p field_other
282  * - Special field values spatially constant. Could allow optimization of tensor multiplication and
283  * tensor or vector addition. field_result_ should be set in constructor and in set_time method of particular Field implementation.
284  * We return value @p result_none, if the field is not initialized on the region of the given element accessor @p elm.
285  * Other possible results are: result_zeros, result_eye, result_ones, result_constant, result_other
286  * see @p FieldResult for explanation.
287  */
288  FieldResult field_result( RegionSet region_set) const override;
289 
290  /**
291  * Return value of input type attribute 'field_value_shape' that is appended to the
292  * input type of this field in FieldSet::make_field_descriptor_type and also to the output field selection
293  * created in EquationOutput::make_output_type.
294  * This attribute is used by GeoMop to have semantics of the input and output field data.
295  *
296  * Attribute value is a valid JSON (and/or flow style YAML) with keys:
297  * 'subfields' - value True for multifields, False or not presented for single value fields
298  * 'shape' - [ NRows, Ncols] ... given by FieldValue
299  * 'type' - <element type> (Double or Integer) ... given by FieldValue
300  * 'limit' - bounds of the field values.
301  *
302  */
303  std::string get_value_attribute() const override;
304 
305  /**
306  * Returns one value in one given point @p on an element given by ElementAccessor @p elm.
307  * It returns reference to he actual value in order to avoid temporaries for vector and tensor values.
308  */
309  virtual typename Value::return_type const &value(const Point &p, const ElementAccessor<spacedim> &elm) const;
310 
311  /**
312  * Returns std::vector of scalar values in several points at once. The base class implements
313  * trivial implementation using the @p value(,,) method. This is not optimal as it involves lot of virtual calls,
314  * but this overhead can be negligible for more complex fields as Python of Formula.
315  */
316  virtual void value_list(const Armor::array &point_list, const ElementAccessor<spacedim> &elm,
317  std::vector<typename Value::return_type> &value_list) const;
318 
319  /**
320  * Add a new factory for creating Field algorithms on individual regions.
321  * The last factory is tried first, the last one is always the default implementation
322  * Field<...>::FactoryBase.
323  *
324  * The Field<...> object keeps a list of such factories. When the instance of a new field algorithm
325  * has to be created from the input field descriptor, we pass through the list of factories backward
326  * and let factories to create the field algorithm instance from the actual input field descriptor.
327  * The first instance (non-null pointer) is used.
328  */
329  void add_factory(std::shared_ptr<FactoryBase> factory);
330 
331  void set_input_list(const Input::Array &list, const TimeGovernor &tg) override;
332 
333  /**
334  * Interpolate given field into output discrete @p space_type and store the values
335  * into storage of output time @p stream for postponed output.
336  */
337  void compute_field_data(OutputTime::DiscreteSpace space_type, std::shared_ptr<OutputTime> stream);
338 
339  /// Implements FieldCommon::cache_allocate
340  void cache_reallocate(const ElementCacheMap &cache_map, unsigned int region_idx) const override;
341 
342  /// Implements FieldCommon::cache_update
343  void cache_update(ElementCacheMap &cache_map, unsigned int region_patch_idx) const override;
344 
345  /// Implements FieldCommon::value_cache
346  FieldValueCache<double> * value_cache() override;
347 
348  /// Implements FieldCommon::value_cache
349  const FieldValueCache<double> * value_cache() const override;
350 
351  /**
352  * Implementation of FieldCommon::set_dependency().
353  */
354  std::vector<const FieldCommon *> set_dependency(FieldSet &field_set, unsigned int i_reg) const override;
355 
356 protected:
357 
358  /// Return item of @p value_cache_ given by i_cache_point.
359  typename Value::return_type operator[] (unsigned int i_cache_point) const;
360 
361  /**
362  * Read input into @p regions_history_ possibly pop some old values from the
363  * history queue to keep its size less then @p history_length_limit_.
364  */
365  void update_history(const TimeStep &time);
366 
367  /// Fills acutally the data cache with field values, used in @p compute_field_data
368  void fill_data_cache(OutputTime::DiscreteSpace space_type,
369  std::shared_ptr<OutputTime> stream,
370  std::shared_ptr<ElementDataCache<typename Value::element_type>> data_cache);
371 
372  /**
373  * Check that whole field list (@p region_fields_) is set, possibly use default values for unset regions.
374  */
375  void check_initialized_region_fields_();
376 
377  /**
378  * Check that the field is in fact FieldFE set on all bulk regions, return shared pointer to that FieldFE or NULL
379  * if the Field is not FieldFE.
380  */
381  std::shared_ptr< FieldFE<spacedim, Value> > get_field_fe();
382 
383  /**************** Shared data **************/
384 
385  /// Pair: time, pointer to FieldBase instance
386  typedef pair<double, FieldBasePtr> HistoryPoint;
387  /// Nearest history of one region.
388  typedef boost::circular_buffer<HistoryPoint> RegionHistory;
389 
390  struct SharedData {
391 
392  /**
393  * History for every region. Shared among copies.
394  */
396  };
397 
398  /**************** Data per copy **************/
399 
400  std::shared_ptr<SharedData> data_;
401 
402  /**
403  * If this pointer is set, turn off check of initialization in the
404  * @p set_time method on the regions where the method @p get_constant_enum_value
405  * of the control field returns value from @p no_check_values_. This
406  * field is private copy, its set_time method is called from the
407  * set_Time method of actual object.
408  */
410  std::shared_ptr<ControlField> no_check_control_field_;
411 
412  /**
413  * Table with pointers to fields on individual regions.
414  */
416 
418 
419  /**
420  * Field value data cache
421  *
422  * Data is ordered like three dimensional table. The highest level is determinated by subsets,
423  * those data ranges are holds in subset_starts. Data block size of each subset is determined
424  * by number of eval_points (of subset) and maximal number of stored elements.
425  * The table is allocated to hold all subsets, but only those marked in used_subsets are updated.
426  * Order of subsets is same as in eval_points.
427  */
429 
430 
431 
432  template<int dim, class Val>
433  friend class MultiField;
434 
435  template< typename CALLABLE, typename TUPLE, int INDEX >
437 
438 };
439 
440 
441 
442 
443 
444 
445 
446 /****************************************************************************************
447  * Inlined methods of Field< ... >
448  */
449 
450 template<int spacedim, class Value>
451 inline typename Value::return_type const & Field<spacedim,Value>::value(const Point &p, const ElementAccessor<spacedim> &elm) const
452 {
453 
454  ASSERT(this->set_time_result_ != TimeStatus::unknown)(this->name()).error("Unknown time status.\n");
455  OLD_ASSERT(elm.region_idx().idx() < region_fields_.size(), "Region idx %u out of range %lu, field: %s\n",
456  elm.region_idx().idx(), (unsigned long int) region_fields_.size(), name().c_str());
457  OLD_ASSERT( region_fields_[elm.region_idx().idx()] ,
458  "Null field ptr on region id: %d, idx: %d, field: %s\n", elm.region().id(), elm.region_idx().idx(), name().c_str());
459  return region_fields_[elm.region_idx().idx()]->value(p,elm);
460 }
461 
462 
463 
464 template<int spacedim, class Value>
467 {
468  ASSERT(this->set_time_result_ != TimeStatus::unknown)(this->name()).error("Unknown time status.\n");
469  OLD_ASSERT(elm.region_idx().idx() < region_fields_.size(), "Region idx %u out of range %lu, field: %s\n",
470  elm.region_idx().idx(), (unsigned long int) region_fields_.size(), name().c_str());
471  OLD_ASSERT( region_fields_[elm.region_idx().idx()] ,
472  "Null field ptr on region id: %d, field: %s\n", elm.region().id(), name().c_str());
473  ASSERT_DBG(point_list.n_rows() == spacedim && point_list.n_cols() == 1).error("Invalid point size.\n");
474 
475  region_fields_[elm.region_idx().idx()]->value_list(point_list,elm, value_list);
476 }
477 
478 
479 
480 
481 
482 
483 #endif /* FIELD_HH_ */
Common abstract parent of all Field<...> classes.
Definition: field_common.hh:74
Container for various descendants of FieldCommonBase.
Definition: field_set.hh:159
pair< double, FieldBasePtr > HistoryPoint
Pair: time, pointer to FieldBase instance.
Definition: field.hh:386
Accessor to input data conforming to declared Array.
Definition: accessors.hh:566
Point accessor allow iterate over bulk quadrature points defined in local element coordinates...
Definition: eval_subset.hh:96
Point accessor allow iterate over quadrature points of given side defined in local element coordinate...
Definition: eval_subset.hh:154
Class template representing a field with values dependent on: point, element, and region...
Definition: field.hh:94
Definitions of ASSERTS.
Directing class of FieldValueCache.
Definition: mesh.h:77
Helper class that stores data of generic types.
Definition: type_generic.hh:89
uint n_cols() const
Definition: armor.hh:720
#define ASSERT(expr)
Allow use shorter versions of macro names if these names is not used with external library...
Definition: asserts.hh:347
Basic time management functionality for unsteady (and steady) solvers (class Equation).
Point accessor allow iterate over quadrature points of given side defined in local element coordinate...
Definition: eval_subset.hh:184
Basic time management class.
Class for declaration of inputs sequences.
Definition: type_base.hh:339
std::shared_ptr< SharedData > data_
Definition: field.hh:400
static constexpr bool value
Definition: json.hpp:87
#define OLD_ASSERT(...)
Definition: global_defs.h:131
Global macros to enhance readability and debugging, general constants.
Definition: field.hh:63
Accessor to the data with type Type::Record.
Definition: accessors.hh:291
FieldAlgorithmBase< spacedim, Value >::Point Point
Definition: field.hh:99
std::shared_ptr< ControlField > no_check_control_field_
Definition: field.hh:410
virtual Value::return_type const & value(const Point &p, const ElementAccessor< spacedim > &elm) const
Definition: field.hh:451
uint n_rows() const
Definition: armor.hh:715
Space< spacedim >::Point Point
virtual void value_list(const Armor::array &point_list, const ElementAccessor< spacedim > &elm, std::vector< typename Value::return_type > &value_list) const
Definition: field.hh:465
base case for building up arguments for the function call
Definition: field.hh:66
std::vector< FieldBasePtr > region_fields_
Definition: field.hh:415
Value ValueType
Definition: field.hh:100
Accessor to the polymorphic input data of a type given by an AbstracRecord object.
Definition: accessors.hh:458
Region region() const
Definition: accessors.hh:165
FieldResult
std::shared_ptr< FieldBaseType > FieldBasePtr
Definition: field.hh:98
FieldAlgorithmBase< spacedim, Value > FieldBaseType
Definition: field.hh:97
std::vector< std::shared_ptr< FactoryBase > > factories_
Definition: field.hh:417
Point accessor allow iterate over quadrature points of given side defined in local element coordinate...
Definition: eval_subset.hh:213
Class holds local coordinations of evaluating points (bulk and sides) specified by element dimension...
Definition: eval_points.hh:43
boost::circular_buffer< HistoryPoint > RegionHistory
Nearest history of one region.
Definition: field.hh:388
RegionIdx region_idx() const
Definition: accessors.hh:168
#define ASSERT_DBG(expr)
Field< spacedim, typename FieldValue< spacedim >::Enum > ControlField
Definition: field.hh:409
Class for representation of a vector of fields of the same physical quantity.
Definition: multi_field.hh:87
Representation of one time step..
LimitSide
Definition: field_common.hh:61
unsigned int id() const
Returns id of the region (using RegionDB)
Definition: region.cc:37
Definition: field.hh:62
FieldValueCache< typename Value::element_type > value_cache_
Definition: field.hh:428
unsigned int idx() const
Returns a global index of the region.
Definition: region.hh:82
std::vector< RegionHistory > region_history_
Definition: field.hh:395