Flow123d  release_3.0.0-899-g9314a17
field_common.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_common.hh
15  * @brief
16  */
17 
18 #ifndef FIELD_COMMON_HH_
19 #define FIELD_COMMON_HH_
20 
21 #include <algorithm> // for sort, unique
22 #include <boost/exception/detail/error_info_impl.hpp> // for error_info
23 #include <boost/exception/info.hpp> // for operator<<
24 #include <limits> // for numeric_limits
25 #include <memory> // for shared_ptr
26 #include <ostream> // for operator<<
27 #include <string> // for string, basic_...
28 #include <utility> // for make_pair, pair
29 #include <vector> // for vector, allocator
30 #include "fields/field_algo_base.hh" // for FieldResult
31 #include "fields/field_flag.hh" // for FieldFlag, Fie...
32 #include "fields/field_values.hh" // for FieldEnum
33 #include "tools/unit_si.hh" // for UnitSI
34 #include "input/accessors.hh" // for Record, Array ...
35 #include "input/input_exception.hh" // for ExcInputMessage
36 #include "input/type_base.hh" // for Array, Type
37 #include "input/type_generic.hh" // for Instance
38 #include "input/type_record.hh" // for Record
39 #include "input/type_selection.hh" // for Selection
40 #include "io/output_time.hh" // for OutputTime
41 #include "mesh/region.hh" // for Region (ptr only)
42 #include "system/asserts.hh" // for Assert, ASSERT
43 #include "system/exc_common.hh" // for EI_Message
44 #include "system/exceptions.hh" // for operator<<
45 #include "system/flag_array.hh" // for FlagArray<>::Mask
46 #include "tools/time_governor.hh" // for TimeGovernor (...
47 
48 class Mesh;
49 class Observe;
50 
51 
52 using namespace std;
53 
54 namespace IT=Input::Type;
55 
56 /**
57  * Left and right time limit, used in the @p set_time() method.
58  * Assigned values allow to index an array.
59  */
60 enum class LimitSide {
61  left=0,
62  right=1
63 };
64 
65 
66 
67 /**
68  * @brief Common abstract parent of all Field<...> classes.
69  *
70  * We need common ancestor in order to keep a list of all fields in one EqData object and allow
71  * collective operations like @p set_time or @p init_from_input.
72  */
73 class FieldCommon {
74 
75 public:
76  TYPEDEF_ERR_INFO(EI_Time, double);
77  TYPEDEF_ERR_INFO(EI_Field, std::string);
78  DECLARE_INPUT_EXCEPTION(ExcNonascendingTime,
79  << "Non-ascending time: " << EI_Time::val << " for field " << EI_Field::qval << ".\n");
80  DECLARE_INPUT_EXCEPTION(ExcMissingDomain,
81  << "Missing domain specification (region or r_id) in the field descriptor:");
82  DECLARE_EXCEPTION(ExcFieldMeshDifference,
83  << "Two copies of the field " << EI_Field::qval << "call set_mesh with different arguments.\n");
84 
85 
86 
87  /// Store data of one initialization message.
88  struct MessageData {
89  /// Constructor
90  MessageData(std::string default_value, std::string field_name, std::string region_list)
91  : default_value_(default_value), field_name_(field_name), region_list_(region_list) {};
92 
93  std::string default_value_; ///< Default value of the field.
94  std::string field_name_; ///< Parameter name_ of the field.
95  std::string region_list_; ///< List of regions separated by comma.
96  };
97 
98  /**
99  * Set name of the field. In fact there are two attributes set by this method.
100  *
101  * The first is name used to identify the field as part of a FieldSet or MultiField objects.
102  * This name is permanent and can be set only by this method. Can be accessed by @p name() method.
103  * This name is also used at output.
104  *
105  * The second is @p input_name_ that determines appropriate key name in the input field descriptor.
106  * This name is also set by this method, but is stored in the internal shared space which
107  * is overwritten during call of copy_from method or assignment operator. Can be accessed by @p input_name() mathod.
108  *
109  */
110  FieldCommon &name(const string & name)
111  { name_=shared_->input_name_ = name;
112  return *this;
113  }
114  /**
115  * Set description of the field, used for description of corresponding key in documentation.
116  */
117  FieldCommon & description(const string & description)
118  { shared_->input_description_ = description; return *this;}
119  /**
120  * Set default value for the field's key from which the default constant valued field will be constructed.
121  *
122  * During the first call of the @p set_time method, we check that the field is defined on all regions.
123  * On regions where it is not set yet, we use given @p dflt string to get particular instance of
124  * FieldBase<> (see @p check_initialized_region_fields_).
125  * The default string is interpreted in the same way as if it appears in the input file
126  * as the value of the field. In particular it can be whole record with @p TYPE of the field etc.
127  * Most common choice is however mere constant.
128  */
129  FieldCommon & input_default(const string &input_default)
130  { shared_->input_default_ = input_default; return *this;}
131  /**
132  * @brief Set basic units of the field.
133  *
134  * Currently, we use it only during output and we represents units just by a string.
135  *
136  * TODO:
137  * Particular class for representing and conversion of various units would be more appropriate.
138  * This can allow specification of the units on the inptu, automatic conversion and the same on the output.
139  * Possibly this allow using Boost::Units library, however, it seems to introduce lot of boilerplate code.
140  * But can increase correctness of the calculations.
141  */
142  FieldCommon & units(const UnitSI & units)
143  { shared_->units_ = units; return *this;}
144 
145  /**
146  * Set limits of value of the field.
147  */
148  FieldCommon & set_limits(double min, double max = std::numeric_limits<double>::max())
149  {
150  ASSERT(min < max)(min)(max).error("Invalid field limits!");
151  shared_->limits_ = std::make_pair(min, max);
152  return *this;
153  }
154 
155  /**
156  * For the fields returning "Enum", we have to pass the Input::Type::Selection object to
157  * the field implementations.
158  *
159  * We must save raw pointer since selection may not be yet initialized (during static initialization phase).
160  */
162  {
163  shared_->input_element_selection_=element_selection;
164  return *this;
165  }
166 
167  /**
168  * Output discrete space used in the output() method. Can be different for different field copies.
169  * one can choose between:
170  * data constant on elements, linear data given in nodes, and discontinuous linear data.
171  *
172  * If not set explicitly by this method, the default value is OutputTime::ELEM_DATA
173  */
175  { if (rt!=OutputTime::UNDEFINED) type_of_output_data_ = rt; return *this; }
176 
177  /**
178  * Set given mask to the field flags, ignoring default setting.
179  * Default setting is declare_input & equation_input & allow_output.
180  */
181  FieldCommon & flags(FieldFlag::Flags::Mask mask)
182  { flags_ = FieldFlag::Flags(mask); return *this; }
183 
184  /**
185  * Add given mask to the field flags.
186  */
187  FieldCommon & flags_add(FieldFlag::Flags::Mask mask)
188  { flags().add(mask); return *this; }
189 
190  /**
191  * Set vector of component names.
192  * Set number of components for run-time sized vectors. This is used latter when we construct
193  * objects derived from FieldBase<...>.
194  *
195  * n_comp_ is constant zero for fixed values, this zero is set by Field<...> constructors
196  */
197  void set_components(const std::vector<string> &names) {
198  // Test of unique values in names vector for MultiField
199  if (multifield_) {
200  std::vector<string> cpy = names;
201  std::sort( cpy.begin(), cpy.end() );
202  cpy.erase( std::unique( cpy.begin(), cpy.end() ), cpy.end() );
203  if (names.size() != cpy.size()) {
204  THROW( Input::ExcInputMessage() << EI_Message("The field " + this->input_name()
205  + " has set non-unique names of components.") );
206  }
207  }
208 
209  shared_->comp_names_ = names;
210  shared_->n_comp_ = (shared_->n_comp_ ? names.size() : 0);
211  }
212 
213 
214  /**
215  * Set internal mesh pointer.
216  */
217  virtual void set_mesh(const Mesh &mesh) {};
218  /**
219  * Set the data list from which field will read its input. It is list of "field descriptors".
220  * When reading from the input list we consider only field descriptors containing key of
221  * named by the field name. These field descriptors has to have times forming ascending sequence.
222  *
223  * The list is used by set_time method to set field on individual regions to actual FieldBase descendants.
224  */
225  virtual void set_input_list(const Input::Array &list, const TimeGovernor &tg) =0;
226 
227  /**
228  * Getters.
229  */
230  const std::string &input_name() const
231  { return shared_->input_name_;}
232 
233  const std::string &name() const
234  { return name_;}
235 
236  const std::string description() const
237  {return shared_->input_description_;}
238 
239  const std::string &input_default() const
240  { return shared_->input_default_;}
241 
242  const UnitSI &units() const
243  {
244  ASSERT(shared_->units_.is_def())(name()).error("Getting undefined unit.\n");
245  return shared_->units_;
246  }
247 
248  std::pair<double, double> limits() const
249  {
250  return shared_->limits_;
251  }
252 
254  { return type_of_output_data_; }
255 
256  bool is_bc() const
257  { return shared_->bc_;}
258 
259  unsigned int n_comp() const
260  { return shared_->n_comp_;}
261 
262  const Mesh * mesh() const
263  { return shared_->mesh_;}
264 
266  { return flags_; }
267 
269  { return flags_; }
270 
271  /**
272  * Returns time set by last call of set_time method.
273  * Can be different for different field copies.
274  */
275  double time() const
276  { return last_time_; }
277 
278  /**
279  * Returns true if the field change algorithm for the current time set through the @p set_time method.
280  * This happen for all times in the field descriptors on the input of this particular field.
281  */
282  bool is_jump_time() {
283  return is_jump_time_;
284  }
285 
286  /**
287  * Returns number of field descriptors containing the field.
288  */
289  unsigned int input_list_size() const {
290  return shared_->input_list_.size();
291  }
292 
293  /**
294  * If the field on given region @p reg exists and is of type FieldConstant<...> the method method returns true
295  * otherwise it returns false.
296  * Then one can call ElementAccessor<spacedim>(mesh(), reg ) to construct an ElementAccessor @p elm
297  * pointing to "virtual" element on which Field::value returns constant value.
298  * Unlike the Field<>::field_result method, this one provides no value, so it have common header (arguments, return type) and
299  * could be part of FieldCommon and FieldSet which is useful in some applications.
300  *
301  * TODO:Current implementation use virtual functions and can be prohibitively slow if called for every element. If this
302  * becomes necessary it is possible to incorporate such test into set_time method and in this method just return precomputed result.
303  */
304  virtual bool is_constant(Region reg) =0;
305 
306 
307  /**
308  * @brief Indicates special field states.
309  *
310  * Extension of the previous method. Return possible values from the enum @p FieldResult, see description there.
311  * The initial state is @p field_none, if the field is correctly set on all regions of the @p region_set given as parameter
312  * we return state @p field_other or even more particular result.
313  *
314  * Special field values spatially constant. Could allow optimization of tensor multiplication and
315  * tensor or vector addition. field_result_ should be set in constructor and in set_time method of particular Field implementation.
316  * We return value @p result_none, if the field is not initialized on the region of the given element accessor @p elm.
317  * Other possible results are: result_zeros, result_eye, result_ones, result_constant, result_other
318  * see @p FieldResult for explanation.
319  *
320  * Multifield return most particular value that holds for all its subfields.
321  *
322  *
323  */
324  virtual FieldResult field_result( RegionSet region_set) const =0;
325 
326  /**
327  * Return specification of the field value type in form of the string:
328  * [ <element type>, NRows, NCols]
329  *
330  * Result is valid JSON (and/or flow style YAML).
331  * For multifields not implemented.
332  */
333  virtual std::string get_value_attribute() const =0;
334 
335  /**
336  * Returns true if set_time_result_ is not @p TimeStatus::constant.
337  * Returns the same value as last set_time method.
338  */
339  bool changed() const
340  {
341  ASSERT( set_time_result_ != TimeStatus::unknown ).error("Invalid time status.");
342  return ( (set_time_result_ == TimeStatus::changed) );
343  }
344 
345  /**
346  * Common part of the field descriptor. To get finished record
347  * one has to add keys for individual fields. This is done automatically
348  * using FieldSet::get_input_type().
349  */
350  static IT::Record field_descriptor_record(const string& record_name);
351 
352  /**
353  * Create description of field descriptor record.
354  */
355  static const std::string field_descriptor_record_description(const string& record_name);
356 
357  /**
358  * Returns input type for particular field instance, this is reference to a static member input_type of the corresponding @p FieldBase
359  * class (i.e. with the same template parameters). This is used in FieldSet::make_field_descriptor_type.
360  */
361  virtual IT::Instance get_input_type() =0;
362 
363  /**
364  * Returns input type for MultiField instance.
365  * TODO: temporary solution, see @p multifield_
366  */
367  virtual IT::Array get_multifield_input_type() =0;
368 
369  /**
370  * Pass through the input array @p input_list_, collect all times where the field could change and
371  * put appropriate time marks into global TimeMarks object.
372  * Introduced time marks have both given @p mark_type and @p type_input() type.
373  *
374  * Further development:
375  * - we have to distinguish "jump" times and "smooth" times
376  */
377  void mark_input_times(const TimeGovernor &tg);
378 
379  /**
380  * Abstract method to update field to the new time level.
381  * Implemented by in class template Field<...>.
382  *
383  * Return true if the value of the field was changed on some region.
384  * The returned value is also stored in @p changed_during_set_time data member.
385  *
386  * Default values helps when creating steady field. Note that default TimeGovernor constructor
387  * set time to 0.0.
388  *
389  * Different field copies can be set to different times.
390  *
391  * TODO: update following:
392  * Set side of limit when calling @p set_time
393  * with jump time, i.e. time where the field change implementation on some region.
394  * Wee assume that implementations prescribe only smooth fields.
395  * This method invalidate result of
396  * @p changed() so it should be called just before @p set_time.
397  * Can be different for different field copies.
398  */
399  virtual bool set_time(const TimeStep &time, LimitSide limit_side) =0;
400 
401  /**
402  * Check that @p other is instance of the same Field<..> class and
403  * perform assignment. Polymorphic copy.
404  *
405  * The copy is performed only if *this have set flag 'input_copy'.
406  * If *this have set also the flag 'decare_input' the copy is performed only if the
407  * input_list is empty.
408  */
409  virtual void copy_from(const FieldCommon & other) =0;
410 
411  /**
412  * Output the field.
413  * The parameter @p output_fields is checked for value named by the field name. If the key exists,
414  * then the output of the field is performed. If the key do not appear in the input, no output is done.
415  */
416  virtual void field_output(std::shared_ptr<OutputTime> stream) =0;
417 
418  /**
419  * Perform the observe output of the field.
420  * The Observe object passed by the parameter is called with the particular Field<> as the parameter
421  * to evaluate the field in observation points and store the values in the OutputData arrays.
422  */
423  virtual void observe_output(std::shared_ptr<Observe> observe) =0;
424 
425 
426  /**
427  * Sets @p component_index_
428  */
429  void set_component_index(unsigned int idx)
430  {
431  this->component_index_ = idx;
432  }
433 
434  /**
435  * Return @p multifield_ flag.
436  * TODO: temporary solution
437  */
438  inline bool is_multifield() const
439  {
440  return this->multifield_;
441  }
442 
443  /**
444  * Print stored messages to table.
445  *
446  * Return true if messages_data_ vector is nonempty and clear its.
447  */
448  static bool print_message_table(ostream& stream, std::string equation_name);
449 
450  /**
451  * Virtual destructor.
452  */
453  virtual ~FieldCommon();
454 
455 
456 protected:
457  /**
458  * Private default constructor. Should be used only through
459  * Field<...>
460  */
461  FieldCommon();
462 
463  /**
464  * Private copy constructor. Should be used only through
465  * Field<...>
466  */
467  FieldCommon(const FieldCommon & other);
468 
469  /**
470  * Invalidate last time in order to force set_time method
471  * update region_fields_.
472  */
474  {
475  last_time_ = -numeric_limits<double>::infinity();
476  }
477 
478  /**
479  * Setters for essential field properties.
480  */
481  /**
482  * Data shared among copies of the same field.
483  *
484  * This allow field copies in different equations with different time setting, but
485  * sharing common input field descriptor array and common history.
486  */
487  struct SharedData {
488  /**
489  * Empty constructor.
490  */
492  : list_idx_(0), limits_(std::make_pair(-std::numeric_limits<double>::max(), std::numeric_limits<double>::max())) {};
493 
494  /**
495  * True for boundary fields.
496  */
497  bool bc_;
498  /**
499  * Number of components for fields that return variable size vectors. Zero in other cases.
500  */
501  unsigned int n_comp_;
502  /**
503  * Names of field components.
504  */
506  /**
507  * Name of the particular field. Used to name the key in the Field list Record.
508  */
509  std::string input_name_;
510  /**
511  * Description of corresponding key in the Field list Record.
512  */
513  std::string input_description_;
514  /**
515  * Units of the field values. Currently just a string description.
516  */
518  /**
519  * For Enum valued fields this is the input type selection that should be used
520  * to read possible values of the field (e.g. for FieldConstant the key 'value' has this selection input type).
521  *
522  * Is empty selection for for non-enum values fields.
523  */
525  /**
526  * Possible default value of the field.
527  */
529  /**
530  * Pointer to the mesh on which the field lives.
531  */
532  const Mesh *mesh_;
533 
534  /**
535  * Vector of input field descriptors from which the field is set.
536  */
538 
539  /**
540  * Index to current position of input field descriptor.
541  */
542  unsigned int list_idx_;
543 
544  /**
545  * True after check_initialized_region_fields_ is called. That happen at first call of the set_time method.
546  */
548 
549  /**
550  * For which values of an enum valued field we do not
551  * check the field. User is responsible, that the value will not be called
552  * on such regions.
553  */
555 
556  /**
557  * Allow set minimal and maximal limit value of Field.
558  */
559  std::pair<double, double> limits_;
560 
561 
562  };
563 
564  /**
565  * Name that identifies the field in the field_set. By default this is same as
566  * shared_->input_name_.
567  */
568  std::string name_;
569 
570  /**
571  * Data shared among copies of the same input field.
572  */
573  std::shared_ptr<SharedData> shared_;
574 
575  /**
576  * Result of last set time method
577  */
578  enum class TimeStatus {
579  changed, //< Field changed during last set time call.
580  constant, //< Field doesn't change.
581  unknown //< Before first call of set_time.
582  };
583 
584  // TODO: Merge time information: set_time_result_, last_time_, last_limit_side_, is_jump_time into
585  // a single structure with single getter.
586  /**
587  * Status of @p history.
588  */
590 
591  /**
592  * Last set time. Can be different for different field copies.
593  * Store also time limit, since the field may be discontinuous.
594  */
595  double last_time_ = -numeric_limits<double>::infinity();
596  LimitSide last_limit_side_ = LimitSide::left;
597 
598  /**
599  * Set to true by the @p set_time method the field algorithm change on any region.
600  * Accessible through the @p is_jump_time method.
601  */
603 
604  /**
605  * Output data type used in the output() method. Can be different for different field copies.
606  */
608 
609  /**
610  * Specify if the field is part of a MultiField and which component it is
611  */
612  unsigned int component_index_;
613 
614  /**
615  * Flag determining if object is Multifield or Field.
616  * TODO: temporary solution, goal is to make these two classes to behave similarly
617  */
619 
620  /**
621  * Maximum number of FieldBase objects we store per one region.
622  */
623  static const unsigned int history_length_limit_=3;
624 
625  /// Field flags. Default setting is "an equation input field, that can read from user input, and can be written to output"
627 
628  /// Vector of data of initialization messages.
630 
631  /**
632  * Stream output operator
633  */
634  friend std::ostream &operator<<(std::ostream &stream, const FieldCommon &field) {
635 
636  vector<string> limit_side_str = {"left", "right"};
637 
638  stream
639  << "field name:" << field.name()
640  << " n. comp.:" << field.n_comp()
641  << " last time:" << field.last_time_
642  << " last limit side:" << limit_side_str[(unsigned int) field.last_limit_side_];
643  return stream;
644  }
645 };
646 
647 
648 
649 
650 
651 
652 
653 #endif /* FIELD_COMMON_HH_ */
virtual void set_mesh(const Mesh &mesh)
std::string input_description_
Common abstract parent of all Field<...> classes.
Definition: field_common.hh:73
std::pair< double, double > limits_
bool is_jump_time_
Accessor to input data conforming to declared Array.
Definition: accessors.hh:567
FieldCommon & input_selection(Input::Type::Selection element_selection)
static constexpr Mask allow_output
The field can output. Is part of generated output selection. (default on)
Definition: field_flag.hh:37
FieldFlag::Flags get_flags() const
FieldCommon & flags_add(FieldFlag::Flags::Mask mask)
OutputTime::DiscreteSpace get_output_type() const
std::string name_
#define DECLARE_EXCEPTION(ExcName, Format)
Macro for simple definition of exceptions.
Definition: exceptions.hh:158
unsigned int component_index_
std::pair< double, double > limits() const
Store data of one initialization message.
Definition: field_common.hh:88
Definitions of ASSERTS.
vector< Input::Record > input_list_
Definition: mesh.h:80
Helper class that stores data of generic types.
Definition: type_generic.hh:89
double last_time_
const std::string & input_default() const
#define ASSERT(expr)
Allow use shorter versions of macro names if these names is not used with external library...
Definition: asserts.hh:346
Basic time management functionality for unsteady (and steady) solvers (class Equation).
FieldCommon & units(const UnitSI &units)
Set basic units of the field.
const std::string description() const
Basic time management class.
Class for declaration of inputs sequences.
Definition: type_base.hh:346
std::string default_value_
Default value of the field.
Definition: field_common.hh:91
std::shared_ptr< SharedData > shared_
double time() const
friend std::ostream & operator<<(std::ostream &stream, const FieldCommon &field)
std::string field_name_
Parameter name_ of the field.
Definition: field_common.hh:94
const std::string & name() const
FieldFlag::Flags & flags()
FieldCommon & input_default(const string &input_default)
const UnitSI & units() const
MessageData(std::string default_value, std::string field_name, std::string region_list)
Constructor.
Definition: field_common.hh:90
unsigned int input_list_size() const
bool is_multifield() const
LimitSide last_limit_side_
#define TYPEDEF_ERR_INFO(EI_Type, Type)
Macro to simplify declaration of error_info types.
Definition: exceptions.hh:194
std::vector< FieldEnum > no_check_values_
FieldResult
bool is_jump_time()
#define DECLARE_INPUT_EXCEPTION(ExcName, Format)
Macro for simple definition of input exceptions.
FieldCommon & description(const string &description)
static std::vector< MessageData > messages_data_
Vector of data of initialization messages.
void set_component_index(unsigned int idx)
IT::Selection input_element_selection_
const Mesh * mesh() const
FieldCommon & name(const string &name)
unsigned int n_comp() const
bool changed() const
void set_components(const std::vector< string > &names)
Record type proxy class.
Definition: type_record.hh:182
void set_history_changed()
FieldCommon & set_limits(double min, double max=std::numeric_limits< double >::max())
FlagArray< FieldFlag > Flags
Definition: field_flag.hh:26
FieldCommon & flags(FieldFlag::Flags::Mask mask)
const std::string & input_name() const
static constexpr Mask equation_input
The field is data parameter of the owning equation. (default on)
Definition: field_flag.hh:33
Class for representation SI units of Fields.
Definition: unit_si.hh:40
bool is_bc() const
#define THROW(whole_exception_expr)
Wrapper for throw. Saves the throwing point.
Definition: exceptions.hh:53
Representation of one time step..
TimeStatus set_time_result_
std::string region_list_
List of regions separated by comma.
Definition: field_common.hh:95
Template for classes storing finite set of named values.
LimitSide
Definition: field_common.hh:60
FieldCommon & output_type(OutputTime::DiscreteSpace rt)
static constexpr Mask declare_input
The field can be set from input. The key in input field descriptor is declared. (default on) ...
Definition: field_flag.hh:35
std::vector< std::string > comp_names_