Flow123d  last_with_con_2.0.0-4-g42e6930
msh_gmshreader.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 msh_gmshreader.cc
15  * @ingroup mesh
16  * @brief
17  * @author dalibor
18  */
19 
20 #include <istream>
21 #include <string>
22 #include <limits>
23 
24 #include "msh_gmshreader.h"
25 
26 #include "system/system.hh"
27 #include "system/sys_profiler.hh"
28 #include "system/tokenizer.hh"
29 #include "boost/lexical_cast.hpp"
30 
31 #include "mesh/mesh.h"
32 #include "mesh/nodes.hh"
33 
34 
35 using namespace std;
36 
37 
39 : tok_(file_name)
40 {
42  tok_.set_comment_pattern( "#");
44 }
45 
46 
47 
49 : tok_(in)
50 {
52  tok_.set_comment_pattern( "#");
54 }
55 
56 
57 
58 GmshMeshReader::~GmshMeshReader() // Tokenizer close the file automatically
59 {}
60 
61 
62 
64  START_TIMER("GMSHReader - read mesh");
65 
66  OLD_ASSERT( mesh , "Argument mesh is NULL.\n");
67  read_nodes(mesh);
68  read_elements(mesh);
69 }
70 
71 
72 
74  using namespace boost;
75  MessageOut() << "- Reading nodes...";
76 
77  if (! tok_.skip_to("$Nodes")) THROW(ExcMissingSection() << EI_Section("$Nodes") << EI_GMSHFile(tok_.f_name()) );
78  try {
79  tok_.next_line(false);
80  unsigned int n_nodes = lexical_cast<unsigned int> (*tok_);;
81  INPUT_CHECK( n_nodes > 0, "Zero number of nodes, %s.\n", tok_.position_msg().c_str() );
82  ++tok_; // end of line
83 
84  mesh->node_vector.reserve(n_nodes);
85  for (unsigned int i = 0; i < n_nodes; ++i) {
86  tok_.next_line();
87 
88  unsigned int id = lexical_cast<unsigned int> (*tok_); ++tok_;
89  NodeFullIter node = mesh->node_vector.add_item(id);
90 
91  node->point()(0)=lexical_cast<double> (*tok_); ++tok_;
92  node->point()(1)=lexical_cast<double> (*tok_); ++tok_;
93  node->point()(2)=lexical_cast<double> (*tok_); ++tok_;
94  ++tok_; // skip mesh size parameter
95  }
96 
97  } catch (bad_lexical_cast &) {
98  THROW(ExcWrongFormat() << EI_Type("number") << EI_TokenizerMsg(tok_.position_msg()) << EI_GMSHFile(tok_.f_name()) );
99  }
100  MessageOut().fmt("... {} nodes read. \n", mesh->node_vector.size());
101 }
102 
103 
104 
106  using namespace boost;
107  MessageOut() << "- Reading elements...";
108 
109  if (! tok_.skip_to("$Elements")) THROW(ExcMissingSection() << EI_Section("$Elements") << EI_GMSHFile(tok_.f_name()) );
110  try {
111  tok_.next_line(false);
112  unsigned int n_elements = lexical_cast<unsigned int> (*tok_);
113  INPUT_CHECK( n_elements > 0, "Zero number of elements, %s.\n", tok_.position_msg().c_str());
114  ++tok_; // end of line
115 
116  mesh->element.reserve(n_elements);
117 
118  for (unsigned int i = 0; i < n_elements; ++i) {
119  tok_.next_line();
120 
121  unsigned int id = lexical_cast<unsigned int>(*tok_); ++tok_;
122 
123 
124  //get element type: supported:
125  // 1 Line (2 nodes)
126  // 2 Triangle (3 nodes)
127  // 4 Tetrahedron (4 nodes)
128  // 15 Point (1 node)
129  unsigned int type = lexical_cast<unsigned int>(*tok_); ++tok_;
130  unsigned int dim;
131  switch (type) {
132  case 1:
133  dim = 1;
134  break;
135  case 2:
136  dim = 2;
137  break;
138  case 4:
139  dim = 3;
140  break;
141  case 15:
142  dim = 0;
143  break;
144  default:
145  dim = 0;
146  THROW(ExcUnsupportedType() << EI_ElementId(id) << EI_ElementType(type) << EI_GMSHFile(tok_.f_name()) );
147  break;
148  }
149 
150  //get number of tags (at least 2)
151  unsigned int n_tags = lexical_cast<unsigned int>(*tok_);
152  INPUT_CHECK(n_tags >= 2, "At least two element tags have to be defined for element with id=%d, %s.\n",
153  id, tok_.position_msg().c_str());
154  ++tok_;
155 
156  //get tags 1 and 2
157  unsigned int region_id = lexical_cast<unsigned int>(*tok_); ++tok_;
158  lexical_cast<unsigned int>(*tok_); ++tok_; // GMSH region number, we do not store this
159  //get remaining tags
160  unsigned int partition_id=0;
161  if (n_tags > 2) { partition_id = lexical_cast<unsigned int>(*tok_); ++tok_; } // save partition number from the new GMSH format
162  for (unsigned int ti = 3; ti < n_tags; ti++) ++tok_; //skip remaining tags
163 
164  // allocate element arrays TODO: should be in mesh class
165  Element *ele=nullptr;
166  RegionIdx region_idx = mesh->region_db_.get_region( region_id, dim );
167  if ( !region_idx.is_valid() ) {
168  region_idx = mesh->region_db_.add_region( region_id, mesh->region_db_.create_label_from_id(region_id),
169  dim, "$Element" );
170  }
171  mesh->region_db_.mark_used_region(region_idx.idx());
172 
173  if (region_idx.is_boundary()) {
174  ele = mesh->bc_elements.add_item(id);
175  } else {
176  if(dim == 0 )
177  WarningOut().fmt("Bulk elements of zero size(dim=0) are not supported. Mesh file: {}, Element ID: {}.\n", tok_.f_name() ,id);
178  else
179  ele = mesh->element.add_item(id);
180  }
181  ele->init(dim, mesh, region_idx);
182  ele->pid=partition_id;
183 
184  unsigned int ni;
185  FOR_ELEMENT_NODES(ele, ni) {
186  unsigned int node_id = lexical_cast<unsigned int>(*tok_);
187  NodeIter node = mesh->node_vector.find_id( node_id );
188  INPUT_CHECK( node!=mesh->node_vector.end() ,
189  "Unknown node id %d in specification of element with id=%d, %s.\n",
190  node_id, id, tok_.position_msg().c_str());
191  ele->node[ni] = node;
192  ++tok_;
193  }
194  }
195 
196  } catch (bad_lexical_cast &) {
197  THROW(ExcWrongFormat() << EI_Type("number") << EI_TokenizerMsg(tok_.position_msg()) << EI_GMSHFile(tok_.f_name()) );
198  }
199 
200  mesh->n_all_input_elements_=mesh->element.size() + mesh->bc_elements.size();
201  MessageOut().fmt("... {} bulk elements, {} boundary elements. \n", mesh->element.size(), mesh->bc_elements.size());
202 }
203 
204 
205 
207  OLD_ASSERT( mesh , "Argument mesh is NULL.\n");
208  using namespace boost;
209 
210  if (! tok_.skip_to("$PhysicalNames", "$Nodes") ) return;
211  try {
212  tok_.next_line(false);
213  unsigned int n_physicals = lexical_cast<unsigned int> (*tok_);
214  ++tok_; // end of line
215 
216  for (unsigned int i = 0; i < n_physicals; ++i) {
217  tok_.next_line();
218  // format of one line:
219  // dim physical-id physical-name
220 
221  unsigned int dim = lexical_cast<unsigned int>(*tok_); ++tok_;
222  unsigned int id = lexical_cast<unsigned int>(*tok_); ++tok_;
223  string name = *tok_; ++tok_;
224 
225  mesh->region_db_.add_region(id, name, dim, "$PhysicalNames");
226  }
227 
228  } catch (bad_lexical_cast &) {
229  THROW(ExcWrongFormat() << EI_Type("number") << EI_TokenizerMsg(tok_.position_msg()) << EI_GMSHFile(tok_.f_name()) );
230  }
231 }
232 
233 
234 // Is assumed to be called just after tok.skip_to("..")
235 // reads the header from the tokenizer @p tok and return it as the second parameter
237  using namespace boost;
238  try {
239  // string tags
240  tok_.next_line(false);
241  unsigned int n_str = lexical_cast<unsigned int>(*tok_); ++tok_;
242  head.field_name="";
243  head.interpolation_scheme = "";
244  if (n_str > 0) {
245  tok_.next_line(); n_str--;
246  head.field_name= *tok_; ++tok_; // unquoted by tokenizer if needed
247  }
248  if (n_str > 0) {
249  tok_.next_line(); n_str--;
250  head.interpolation_scheme = *tok_; ++tok_;
251  }
252  for(;n_str>0;n_str--) tok_.next_line(false); // skip possible remaining tags
253 
254  //real tags
255  tok_.next_line();
256  unsigned int n_real = lexical_cast<unsigned int>(*tok_); ++tok_;
257  head.time=0.0;
258  if (n_real>0) {
259  tok_.next_line(); n_real--;
260  head.time=lexical_cast<double>(*tok_); ++tok_;
261  }
262  for(;n_real>0;n_real--) tok_.next_line(false);
263 
264  // int tags
265  tok_.next_line();
266  unsigned int n_int = lexical_cast<unsigned int>(*tok_); ++tok_;
267  head.time_index=0;
268  head.n_components=1;
269  head.n_entities=0;
270  head.partition_index=0;
271  if (n_int>0) {
272  tok_.next_line(); n_int--;
273  head.time_index=lexical_cast<unsigned int>(*tok_); ++tok_;
274  }
275  if (n_int>0) {
276  tok_.next_line(); n_int--;
277  head.n_components=lexical_cast<unsigned int>(*tok_); ++tok_;
278  }
279  if (n_int>0) {
280  tok_.next_line(); n_int--;
281  head.n_entities=lexical_cast<unsigned int>(*tok_); ++tok_;
282  }
283  for(;n_int>0;n_int--) tok_.next_line(false);
284  head.position = tok_.get_position();
285  } catch (bad_lexical_cast &) {
286  THROW(ExcWrongFormat() << EI_Type("$ElementData header") << EI_TokenizerMsg(tok_.position_msg()) << EI_GMSHFile(tok_.f_name()) );
287  }
288 }
289 
290 
291 
292 template<typename T>
294  std::vector<int> const & el_ids, unsigned int component_idx)
295 {
296  using namespace boost;
297 
298  GMSH_DataHeader actual_header = find_header(search_header.time, search_header.field_name);
299  if ( !current_cache_->is_actual(actual_header.time, search_header.field_name) ) {
300 
301  unsigned int id, idx, i_row;
302  unsigned int n_read = 0;
303  unsigned int size_of_cache; // count of vectors stored in cache
304  vector<int>::const_iterator id_iter = el_ids.begin();
305 
306  // check that the header is valid, try to correct
307  if (actual_header.n_entities != search_header.n_entities) {
308  WarningOut().fmt("In file '{}', '$ElementData' section for field '{}', time: {}.\nWrong number of entities: {}, using {} instead.\n",
309  tok_.f_name(), search_header.field_name, actual_header.time, actual_header.n_entities, search_header.n_entities);
310  // actual_header.n_entities=search_header.n_entities;
311  }
312 
313  if (search_header.n_components == 1) {
314  // read for MultiField to 'n_comp' vectors
315  // or for Field if ElementData contains only one value
316  size_of_cache = actual_header.n_components;
317  }
318  else {
319  // read for Field if more values is stored to one vector
320  size_of_cache = 1;
321  if (actual_header.n_components != search_header.n_components) {
322  WarningOut().fmt("In file '{}', '$ElementData' section for field '{}', time: {}.\nWrong number of components: {}, using {} instead.\n",
323  tok_.f_name(), search_header.field_name, actual_header.time, actual_header.n_components, search_header.n_components);
324  actual_header.n_components=search_header.n_components;
325  }
326  }
327 
328  // create vector of shared_ptr for cache
329  typename ElementDataCache<T>::CacheData data_cache(size_of_cache);
330  for (unsigned int i=0; i<size_of_cache; ++i) {
331  typename ElementDataCache<T>::ComponentDataPtr row_vec = std::make_shared<std::vector<T>>();
332  row_vec->resize(search_header.n_components*search_header.n_entities);
333  data_cache[i] = row_vec;
334  }
335 
336  // read @p data buffer as we have correct header with already passed time
337  // we assume that @p data buffer is big enough
338  tok_.set_position(actual_header.position);
339 
340  // read data
341  for (i_row = 0; i_row < actual_header.n_entities; ++i_row)
342  try {
343  tok_.next_line();
344  id = lexical_cast<unsigned int>(*tok_); ++tok_;
345  //skip_element = false;
346  while (id_iter != el_ids.end() && *id_iter < (int)id) {
347  ++id_iter; // skip initialization of some rows in data if ID is missing
348  }
349  if (id_iter == el_ids.end()) {
350  WarningOut().fmt("In file '{}', '$ElementData' section for field '{}', time: {}.\nData ID {} not found or is not in order. Skipping rest of data.\n",
351  tok_.f_name(), search_header.field_name, actual_header.time, id);
352  break;
353  }
354  // save data from the line if ID was found
355  if (*id_iter == (int)id) {
356  for (unsigned int i_vec=0; i_vec<size_of_cache; ++i_vec) {
357  idx = (id_iter - el_ids.begin()) * search_header.n_components;
358  std::vector<T> &vec = *( data_cache[i_vec].get() );
359  for (unsigned int i_col=0; i_col < search_header.n_components; ++i_col, ++idx) {
360  vec[idx] = lexical_cast<T>(*tok_);
361  ++tok_;
362  }
363  }
364  n_read++;
365  }
366  // skip the line if ID on the line < actual ID in the map el_ids
367  } catch (bad_lexical_cast &) {
368  THROW(ExcWrongFormat() << EI_Type("$ElementData line") << EI_TokenizerMsg(tok_.position_msg())
369  << EI_GMSHFile(tok_.f_name()) );
370  }
371  // possibly skip remaining lines after break
372  while (i_row < actual_header.n_entities) tok_.next_line(false), ++i_row;
373 
374  LogOut().fmt("time: {}; {} entities of field {} read.\n",
375  actual_header.time, n_read, actual_header.field_name);
376 
377  search_header.actual = true; // use input header to indicate modification of @p data buffer
378 
379  // set new cache
380  delete current_cache_;
381  current_cache_ = new ElementDataCache<T>(actual_header.time, actual_header.field_name, data_cache);
382  }
383 
384  if (component_idx == std::numeric_limits<unsigned int>::max()) component_idx = 0;
385  return static_cast< ElementDataCache<T> *>(current_cache_)->get_component_data(component_idx);
386 }
387 
388 
389 
391 {
392  header_table_.clear();
393  GMSH_DataHeader header;
394  while ( !tok_.eof() ) {
395  if ( tok_.skip_to("$ElementData") ) {
396  read_data_header(header);
397  HeaderTable::iterator it = header_table_.find(header.field_name);
398 
399  if (it == header_table_.end()) { // field doesn't exists, insert new vector to map
401  vec.push_back(header);
402  header_table_[header.field_name]=vec;
403  } else if ( header.time <= it->second.back().time ) { // time is in wrong order. can't be add
404  WarningOut().fmt("Wrong time order: field '{}', time '{}', file '{}'. Skipping this '$ElementData' section.\n",
405  header.field_name, header.time, tok_.f_name() );
406  } else { // add new time step
407  it->second.push_back(header);
408  }
409  }
410  }
411 
412  tok_.set_position( Tokenizer::Position() );
413 }
414 
415 
416 
417 GMSH_DataHeader & GmshMeshReader::find_header(double time, std::string field_name)
418 {
419  HeaderTable::iterator table_it = header_table_.find(field_name);
420 
421  if (table_it == header_table_.end()) {
422  // no data found
423  THROW( ExcFieldNameNotFound() << EI_FieldName(field_name) << EI_GMSHFile(tok_.f_name()));
424  }
425 
426  auto comp = [](double t, const GMSH_DataHeader &a) {
427  return t * (1.0 + 2.0*numeric_limits<double>::epsilon()) < a.time;
428  };
429 
430  std::vector<GMSH_DataHeader>::iterator headers_it = std::upper_bound(table_it->second.begin(),
431  table_it->second.end(),
432  time,
433  comp);
434 
435  if (headers_it == table_it->second.begin()) {
436  THROW( ExcFieldNameNotFound() << EI_FieldName(field_name)
437  << EI_GMSHFile(tok_.f_name()) << EI_Time(time));
438  }
439 
440  --headers_it;
441  return *headers_it;
442 }
443 
444 
445 // explicit instantiation of template methods
446 #define READER_GET_ELEMENT_DATA(TYPE) \
447 template typename ElementDataCache<TYPE>::ComponentDataPtr GmshMeshReader::get_element_data<TYPE>(GMSH_DataHeader &search_header, \
448  std::vector<int> const & el_ids, unsigned int component_idx)
449 
451 READER_GET_ELEMENT_DATA(unsigned int);
void read_elements(Mesh *)
std::string field_name
#define READER_GET_ELEMENT_DATA(TYPE)
#define FOR_ELEMENT_NODES(i, j)
Definition: elements.h:188
std::shared_ptr< std::vector< T > > ComponentDataPtr
Tokenizer::Position position
Position of data in mesh file.
bool is_boundary() const
Returns true if it is a Boundary region and false if it is a Bulk region.
Definition: region.hh:73
Definition: nodes.hh:32
Nodes of a mesh.
int pid
Definition: elements.h:76
#define MessageOut()
Macro defining &#39;message&#39; record of log.
Definition: logger.hh:231
Definition: mesh.h:95
#define INPUT_CHECK(i,...)
Debugging macros.
Definition: global_defs.h:51
void reserve(unsigned int size)
Reallocates the container space.
Definition: sys_vector.hh:469
string create_label_from_id(unsigned int id) const
Definition: region.cc:337
Node ** node
Definition: elements.h:79
FullIter add_item(int id)
Definition: sys_vector.hh:359
GmshMeshReader(const FilePath &file_name)
FullIter find_id(const int id)
Definition: sys_vector.hh:434
void read_data_header(GMSH_DataHeader &head)
ElementDataCacheBase * current_cache_
Cache with last read element data.
GMSH_DataHeader & find_header(double time, std::string field_name)
#define LogOut()
Macro defining &#39;log&#39; record of log.
Definition: logger.hh:237
Region get_region(unsigned int id, unsigned int dim)
Definition: region.cc:150
ElementDataCache< T >::ComponentDataPtr get_element_data(GMSH_DataHeader &search_header, std::vector< int > const &el_ids, unsigned int component_idx)
unsigned int size() const
Returns size of the container. This is independent of the allocated space.
Definition: sys_vector.hh:391
#define OLD_ASSERT(...)
Definition: global_defs.h:131
unsigned int n_entities
Number of rows.
void make_header_table()
#define START_TIMER(tag)
Starts a timer with specified tag.
ElementVector bc_elements
Definition: mesh.h:229
unsigned int n_components
Number of values on one row.
void read_mesh(Mesh *mesh)
void init(unsigned int dim, Mesh *mesh_in, RegionIdx reg)
Definition: elements.cc:60
Dedicated class for storing path to input and output files.
Definition: file_path.hh:48
void mark_used_region(unsigned int idx)
Definition: region.cc:235
const double epsilon
Definition: mathfce.h:23
Region add_region(unsigned int id, const std::string &label, unsigned int dim, const std::string &address="implicit")
Definition: region.cc:85
HeaderTable header_table_
Table with data of ElementData headers.
unsigned int n_all_input_elements_
Number of elements read from input.
Definition: mesh.h:357
void read_physical_names(Mesh *mesh)
RegionDB region_db_
Definition: mesh.h:366
void read_nodes(Mesh *)
#define WarningOut()
Macro defining &#39;warning&#39; record of log.
Definition: logger.hh:234
std::string interpolation_scheme
Currently ont used.
bool is_actual(double time, std::string quantity_name)
Check if cache stored actual data.
bool is_valid() const
Returns false if the region has undefined/invalid value.
Definition: region.hh:77
unsigned int time_index
Currently ont used.
FullIter end()
Returns FullFullIterer of the fictions past the end element.
Definition: sys_vector.hh:387
unsigned int partition_index
?? Currently ont used
#define THROW(whole_exception_expr)
Wrapper for throw. Saves the throwing point.
Definition: exceptions.hh:45
Tokenizer tok_
Tokenizer used for reading ASCII GMSH file format.
NodeVector node_vector
Vector of nodes of the mesh.
Definition: mesh.h:219
ElementVector element
Vector of elements of the mesh.
Definition: mesh.h:221
unsigned int idx() const
Returns a global index of the region.
Definition: region.hh:81