Flow123d  release_3.0.0-1113-g35b167a
field_elementwise.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 field_elementwise.cc
15  * @brief
16  */
17 
18 
19 #include <boost/type_traits/is_floating_point.hpp>
21 #include "fields/field_instances.hh" // for instantiation macros
22 #include "tools/unit_si.hh"
23 #include "system/file_path.hh"
24 #include "system/exceptions.hh"
25 #include "input/input_type.hh"
26 #include "io/msh_gmshreader.h"
27 #include "io/reader_cache.hh"
28 
29 /// Implementation.
30 
31 namespace IT = Input::Type;
32 
33 FLOW123D_FORCE_LINK_IN_CHILD(field_elementwise)
34 
35 
36 template <int spacedim, class Value>
37 const Input::Type::Record & FieldElementwise<spacedim, Value>::get_input_type()
38 {
39  return IT::Record("FieldElementwise", FieldAlgorithmBase<spacedim,Value>::template_name()+" Field piecewise constant on mesh elements.")
43  "Input file with ASCII GMSH file format.")
45  "The values of the Field are read from the ```$ElementData``` section with field name given by this key.")
46  //.declare_key("unit", FieldAlgorithmBase<spacedim, Value>::get_input_type_unit_si(), IT::Default::optional(),
47  // "Definition of unit.")
48  .declare_key("default_value", IT::Double(), IT::Default::optional(),
49  "Allow set default value of elements that have not listed values in mesh data file.")
50  .declare_key("time_unit", IT::String(), IT::Default::read_time("Common unit of TimeGovernor."),
51  "Definition of unit of all times defined in mesh data file.")
52  .declare_key("read_time_shift", TimeGovernor::get_input_time_type(), IT::Default("0.0"),
53  "Allow set time shift of field data read from the mesh data file. For time 't', field descriptor with time 'T', "
54  "time shift 'S' and if 't > T', we read time frame 't + S'.")
55  .close();
56 }
57 
58 
59 template <int spacedim, class Value>
61  Input::register_class< FieldElementwise<spacedim, Value>, unsigned int >("FieldElementwise") +
63 
64 
65 
66 template <int spacedim, class Value>
68 : FieldAlgorithmBase<spacedim, Value>(n_comp),
69  internal_raw_data(true), mesh_(NULL), unit_si_( UnitSI::dimensionless() )
70 
71 {
72  n_components_ = this->value_.n_rows() * this->value_.n_cols();
73  this->is_constant_in_space_ = false;
74 }
75 
76 
77 
78 template <int spacedim, class Value>
80  unsigned int n_components)
81 : FieldAlgorithmBase<spacedim, Value>(n_components),
82 internal_raw_data(false), mesh_(NULL), unit_si_( UnitSI::dimensionless() )
83 {
84  n_components_ = this->value_.n_rows() * this->value_.n_cols();
85  data_ = data;
86  //this->scale_and_check_limits();
87 }
88 
89 
90 
91 
92 template <int spacedim, class Value>
94  this->init_unit_conversion_coefficient(rec, init_data);
95  this->in_rec_ = rec;
96  this->unit_si_ = init_data.unit_si_;
97  this->limits_ = init_data.limits_;
98 
99  DebugOut() << "Reader file: " << string(reader_file_);
100  ASSERT(internal_raw_data).error("Trying to initialize internal FieldElementwise from input.");
101  ASSERT(reader_file_ == FilePath()).error("Multiple call of init_from_input.");
102  reader_file_ = FilePath( rec.val<FilePath>("mesh_data_file") );
103 
104  field_name_ = rec.val<std::string>("field_name");
105  if (!in_rec_.opt_val("default_value", default_value_) ) {
106  default_value_ = numeric_limits<double>::signaling_NaN();
107  }
108 }
109 
110 
111 
112 /*template <int spacedim, class Value>
113 void FieldElementwise<spacedim, Value>::set_data_row(unsigned int boundary_idx, typename Value::return_type &value) {
114  Value ref(value);
115  OLD_ASSERT( this->value_.n_cols() == ref.n_cols(), "Size of variable vectors do not match.\n" );
116  OLD_ASSERT( mesh_, "Null mesh pointer of elementwise field: %s, did you call set_mesh()?\n", field_name_.c_str());
117  OLD_ASSERT( boundary_domain_ , "Method set_data_row can be used only for boundary fields.");
118  unsigned int vec_pos = boundary_idx * n_components_;
119  std::vector<typename Value::element_type> &vec = *( data_.get() );
120  for(unsigned int row=0; row < ref.n_rows(); row++)
121  for(unsigned int col=0; col < ref.n_cols(); col++, vec_pos++)
122  vec[vec_pos] = ref(row,col);
123 
124 }*/
125 
126 
127 template <int spacedim, class Value>
129  OLD_ASSERT(mesh_, "Null mesh pointer of elementwise field: %s, did you call set_mesh()?\n", field_name_.c_str());
130  if ( reader_file_ == FilePath() ) return false;
131 
132  //walkaround for the steady time governor - there is no data to be read in time==infinity
133  //TODO: is it possible to check this before calling set_time?
134  //if (time.end() == numeric_limits< double >::infinity()) return false;
135 
136  double time_unit_coef = time.read_coef(in_rec_.find<string>("time_unit"));
137  double time_shift = time.read_time( in_rec_.find<Input::Tuple>("read_time_shift") );
138  double read_time = (time.end()+time_shift) / time_unit_coef;
139  BaseMeshReader::HeaderQuery header_query(field_name_, read_time, OutputTime::DiscreteSpace::ELEM_DATA);
140  ReaderCache::get_reader(reader_file_)->find_header(header_query);
141  data_ = ReaderCache::get_reader(reader_file_)-> template get_element_data<typename Value::element_type>(
143  CheckResult checked_data = ReaderCache::get_reader(reader_file_)->scale_and_check_limits(field_name_,
145 
146  if (checked_data == CheckResult::not_a_number) {
147  THROW( ExcUndefElementValue() << EI_Field(field_name_) );
148  } else if (checked_data == CheckResult::out_of_limits) {
149  WarningOut().fmt("Values of some elements of FieldElementwise '{}' at address '{}' is out of limits: <{}, {}>\n"
150  "Unit of the Field: [{}]\n",
152  }
153 
154  return true;
155 }
156 
157 
158 
159 template <int spacedim, class Value>
160 void FieldElementwise<spacedim, Value>::set_mesh(const Mesh *mesh, bool boundary_domain) {
161  // set mesh only once or to same value
162  OLD_ASSERT(mesh_ == nullptr || mesh_ == mesh, "Trying to change mesh of the FieldElementwise.");
163  boundary_domain_ = boundary_domain;
164 
165  mesh_=mesh;
167 
168  // allocate
169  if (!data_) {
170  data_ = std::make_shared<std::vector<typename Value::element_type>>();
171  data_->resize(n_entities_ * n_components_);
172  }
173 
174  if ( reader_file_ == FilePath() ) return;
175  ReaderCache::get_reader(reader_file_)->check_compatible_mesh( const_cast<Mesh &>(*mesh) );
176 }
177 
178 
179 
180 /**
181  * Returns one value in one given point. ResultType can be used to avoid some costly calculation if the result is trivial.
182  */
183 template <int spacedim, class Value>
184 typename Value::return_type const & FieldElementwise<spacedim, Value>::value(const Point &p, const ElementAccessor<spacedim> &elm)
185 {
186  OLD_ASSERT( elm.is_elemental(), "FieldElementwise works only for 'elemental' ElementAccessors.\n");
187  OLD_ASSERT( elm.is_boundary() == boundary_domain_, "Trying to get value of FieldElementwise '%s' for wrong ElementAccessor type (boundary/bulk).\n", field_name_.c_str() );
188 
189  unsigned int idx = n_components_ * elm.idx();
191 
192  return Value::from_raw(this->r_value_, (typename Value::element_type *)(&vec[idx]));
193 }
194 
195 
196 
197 /**
198  * Returns std::vector of scalar values in several points at once.
199  */
200 template <int spacedim, class Value>
203 {
204  OLD_ASSERT( elm.is_elemental(), "FieldElementwise works only for 'elemental' ElementAccessors.\n");
205  OLD_ASSERT( elm.is_boundary() == boundary_domain_, "Trying to get value of FieldElementwise '%s' for wrong ElementAccessor type (boundary/bulk).\n", field_name_.c_str() );
206  OLD_ASSERT_EQUAL( point_list.size(), value_list.size() );
208  unsigned int idx = n_components_ * elm.idx();
210 
211  typename Value::return_type const &ref = Value::from_raw(this->r_value_, (typename Value::element_type *)(&vec[idx]));
212  for(unsigned int i=0; i< value_list.size(); i++) {
213  OLD_ASSERT( Value(value_list[i]).n_rows()==this->value_.n_rows(),
214  "value_list[%d] has wrong number of rows: %d; should match number of components: %d\n",
215  i, Value(value_list[i]).n_rows(),this->value_.n_rows());
216 
217  value_list[i] = ref;
218  }
219  } else {
220  xprintf(UsrErr, "FieldElementwise is not implemented for discrete return types.\n");
221  }
222 }
223 
224 
225 
226 template <int spacedim, class Value>
228 
229 
230 // Instantiations of FieldElementwise
void init_unit_conversion_coefficient(const Input::Record &rec, const struct FieldAlgoBaseInitData &init_data)
Init value of unit_conversion_coefficient_ from input.
std::shared_ptr< std::vector< typename Value::element_type > > data_
Raw buffer of n_entities rows each containing Value::size() doubles.
double read_coef(Input::Iterator< std::string > unit_it) const
std::string format_text() const
Definition: unit_si.cc:127
std::pair< double, double > limits_
Some value(s) is set to NaN.
Value::return_type const & value(const Point &p, const ElementAccessor< spacedim > &elm) override
unsigned int component_idx_
Specify if the field is part of a MultiField and which component it is.
Class Input::Type::Default specifies default value of keys of a Input::Type::Record.
Definition: type_record.hh:61
bool is_boundary() const
We need this method after replacing Region by RegionIdx, and movinf RegionDB instance into particular...
Definition: accessors.hh:106
Abstract linear system class.
Definition: balance.hh:35
static Default obligatory()
The factory function to make an empty default value which is obligatory.
Definition: type_record.hh:110
#define INSTANCE_ALL(field)
Definition: mesh.h:76
Iterator< Ret > find(const string &key) const
Helper struct stores data for initizalize descentants of FieldAlgorithmBase.
#define ASSERT(expr)
Allow use shorter versions of macro names if these names is not used with external library...
Definition: asserts.hh:346
Some value(s) is out of limits.
Value::return_type r_value_
virtual void init_from_input(const Input::Record &rec, const struct FieldAlgoBaseInitData &init_data) override
Record & close() const
Close the Record for further declarations of keys.
Definition: type_record.cc:303
static constexpr bool value
Definition: json.hpp:87
double unit_conversion_coefficient_
Coeficient of conversion of user-defined unit.
virtual Record & derive_from(Abstract &parent)
Method to derive new Record from an AbstractRecord parent.
Definition: type_record.cc:195
static Default optional()
The factory function to make an empty default value which is optional.
Definition: type_record.hh:124
#define OLD_ASSERT(...)
Definition: global_defs.h:131
bool opt_val(const string &key, Ret &value) const
bool is_elemental() const
Definition: accessors.hh:79
Class for declaration of the input data that are floating point numbers.
Definition: type_base.hh:541
static const Input::Type::Tuple & get_input_time_type(double lower_bound=-std::numeric_limits< double >::max(), double upper_bound=std::numeric_limits< double >::max())
bool set_time(const TimeStep &time) override
double default_value_
Default value of element if not set in mesh data file.
static FileName input()
The factory function for declaring type FileName for input files.
Definition: type_base.cc:526
Accessor to the data with type Type::Record.
Definition: accessors.hh:292
const Ret val(const string &key) const
#define xprintf(...)
Definition: system.hh:92
FieldElementwise(unsigned int n_comp=0)
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:501
double end() const
Space< spacedim >::Point Point
CheckResult
Return type of method that checked data stored in ElementDataCache (NaN values, limits) ...
double read_time(Input::Iterator< Input::Tuple > time_it, double default_time=std::numeric_limits< double >::quiet_NaN()) const
Record & copy_keys(const Record &other)
Copy keys from other record.
Definition: type_record.cc:215
Dedicated class for storing path to input and output files.
Definition: file_path.hh:54
Definition: system.hh:64
unsigned int n_components_
Size of Value.
static Default read_time(const std::string &description)
The factory function to make an default value that will be specified at the time when a key will be r...
Definition: type_record.hh:97
const UnitSI & unit_si_
void set_mesh(const Mesh *mesh, bool boundary_domain) override
bool is_constant_in_space_
Flag detects that field is only dependent on time.
virtual unsigned int n_elements(bool boundary=false) const
Returns count of boundary or bulk elements.
Definition: mesh.h:346
Value value_
Last value, prevents passing large values (vectors) by value.
unsigned int n_entities_
Number of rows in data_ buffer.
#define WarningOut()
Macro defining &#39;warning&#39; record of log.
Definition: logger.hh:246
void value_list(const std::vector< Point > &point_list, const ElementAccessor< spacedim > &elm, std::vector< typename Value::return_type > &value_list) override
#define OLD_ASSERT_EQUAL(a, b)
Definition: global_defs.h:133
std::pair< double, double > limits_
Record type proxy class.
Definition: type_record.hh:182
Input::Record in_rec_
Accessor to Input::Record.
Accessor to the data with type Type::Tuple.
Definition: accessors.hh:412
Class for representation SI units of Fields.
Definition: unit_si.hh:40
static std::shared_ptr< BaseMeshReader > get_reader(const FilePath &file_path)
Definition: reader_cache.cc:36
#define DebugOut()
Macro defining &#39;debug&#39; record of log.
Definition: logger.hh:252
unsigned int idx() const
Return local idx of element in boundary / bulk part of element vector.
Definition: accessors.hh:111
Class for declaration of the input data that are in string format.
Definition: type_base.hh:589
#define THROW(whole_exception_expr)
Wrapper for throw. Saves the throwing point.
Definition: exceptions.hh:53
Representation of one time step..
#define FLOW123D_FORCE_LINK_IN_CHILD(x)
Definition: global_defs.h:180
string address_string() const
Definition: accessors.cc:184