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