Mesh Oriented datABase  (version 5.6.0)
An array-based unstructured mesh library
ReadGmsh.cpp
Go to the documentation of this file.
1 /**
2  * MOAB, a Mesh-Oriented datABase, is a software component for creating,
3  * storing and accessing finite element mesh data.
4  *
5  * Copyright 2004 Sandia Corporation. Under the terms of Contract
6  * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government
7  * retains certain rights in this software.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  */
15 
16 /**
17  * \class ReadGmsh
18  * \brief Gmsh (http://www.geuz.org/gmsh) file reader
19  *
20  * See: http://geuz.org/gmsh/doc/texinfo/gmsh.html#MSH-ASCII-file-format
21  *
22  * \author Jason Kraftcheck
23  */
24 
25 #include "ReadGmsh.hpp"
26 #include "FileTokenizer.hpp" // for file tokenizer
27 #include "Internals.hpp"
28 #include "moab/Interface.hpp"
29 #include "moab/ReadUtilIface.hpp"
30 #include "moab/Range.hpp"
31 #include "MBTagConventions.hpp"
32 #include "MBParallelConventions.h"
33 #include "moab/CN.hpp"
34 #include "GmshUtil.hpp"
35 
36 #include <cerrno>
37 #include <cstring>
38 #include <map>
39 #include <set>
40 
41 namespace moab
42 {
43 
45 {
46  return new ReadGmsh( iface );
47 }
48 
49 ReadGmsh::ReadGmsh( Interface* impl ) : mdbImpl( impl ), globalId( 0 )
50 {
52 }
53 
55 {
56  if( readMeshIface )
57  {
59  readMeshIface = 0;
60  }
61 }
62 
63 ErrorCode ReadGmsh::read_tag_values( const char* /* file_name */,
64  const char* /* tag_name */,
65  const FileOptions& /* opts */,
66  std::vector< int >& /* tag_values_out */,
67  const SubsetList* /* subset_list */ )
68 {
69  return MB_NOT_IMPLEMENTED;
70 }
71 
72 ErrorCode ReadGmsh::load_file( const char* filename,
73  const EntityHandle*,
74  const FileOptions&,
75  const ReaderIface::SubsetList* subset_list,
76  const Tag* file_id_tag )
77 {
78  int num_material_sets = 0;
79  const int* material_set_list = 0;
80 
81  if( subset_list )
82  {
83  if( subset_list->tag_list_length > 1 && !strcmp( subset_list->tag_list[0].tag_name, MATERIAL_SET_TAG_NAME ) )
84  {
85  MB_SET_ERR( MB_UNSUPPORTED_OPERATION, "GMsh supports subset read only by material ID" );
86  }
87  material_set_list = subset_list->tag_list[0].tag_values;
88  num_material_sets = subset_list->tag_list[0].num_tag_values;
89  }
90 
91  geomSets.clear();
93 
94  // Create set for more convenient check for material set ids
95  std::set< int > blocks;
96  for( const int* mat_set_end = material_set_list + num_material_sets; material_set_list != mat_set_end;
97  ++material_set_list )
98  blocks.insert( *material_set_list );
99 
100  // Map of ID->handle for nodes
101  std::map< long, EntityHandle > node_id_map;
102  int data_size = 8;
103 
104  // Open file and hand off pointer to tokenizer
105  FILE* file_ptr = fopen( filename, "r" );
106  if( !file_ptr )
107  {
108  MB_SET_ERR( MB_FILE_DOES_NOT_EXIST, filename << ": " << strerror( errno ) );
109  }
110  FileTokenizer tokens( file_ptr, readMeshIface );
111 
112  // Determine file format version
113  const char* const start_tokens[] = { "$NOD", "$MeshFormat", 0 };
114  int format_version = tokens.match_token( start_tokens );
115  if( !format_version ) return MB_FILE_DOES_NOT_EXIST;
116 
117  // If version 2.0, read additional header info
118  if( 2 == format_version )
119  {
120  double version;
121  if( !tokens.get_doubles( 1, &version ) ) return MB_FILE_WRITE_ERROR;
122 
123  if( version != 2.0 && version != 2.1 && version != 2.2 )
124  {
125  MB_SET_ERR( MB_FILE_DOES_NOT_EXIST, filename << ": unknown format version: " << version );
126  }
127 
128  int file_format;
129  if( !tokens.get_integers( 1, &file_format ) || !tokens.get_integers( 1, &data_size ) ||
130  !tokens.match_token( "$EndMeshFormat" ) )
131  return MB_FILE_WRITE_ERROR;
132  // If physical entities in the gmsh file -> discard this
133  const char* const phys_tokens[] = { "$Nodes", "$PhysicalNames", 0 };
134  int hasPhys = tokens.match_token( phys_tokens );
135 
136  if( hasPhys == 2 )
137  {
138  long num_phys;
139  if( !tokens.get_long_ints( 1, &num_phys ) ) return MB_FILE_WRITE_ERROR;
140  for( long loop_phys = 0; loop_phys < num_phys; loop_phys++ )
141  {
142  long physDim;
143  long physGroupNum;
144  // char const * physName;
145  if( !tokens.get_long_ints( 1, &physDim ) ) return MB_FILE_WRITE_ERROR;
146  if( !tokens.get_long_ints( 1, &physGroupNum ) ) return MB_FILE_WRITE_ERROR;
147  const char* ptc = tokens.get_string();
148  if( !ptc ) return MB_FILE_WRITE_ERROR;
149  // try to get to the end of the line, without reporting errors
150  // really, we need to skip this
151  while( !tokens.get_newline( false ) )
152  ptc = tokens.get_string();
153  }
154  if( !tokens.match_token( "$EndPhysicalNames" ) || !tokens.match_token( "$Nodes" ) )
155  return MB_FILE_WRITE_ERROR;
156  }
157  }
158 
159  // Read number of nodes
160  long num_nodes;
161  if( !tokens.get_long_ints( 1, &num_nodes ) ) return MB_FILE_WRITE_ERROR;
162 
163  // Allocate nodes
164  std::vector< double* > coord_arrays;
165  EntityHandle handle = 0;
166  ErrorCode result = readMeshIface->get_node_coords( 3, num_nodes, MB_START_ID, handle, coord_arrays );
167  if( MB_SUCCESS != result ) return result;
168 
169  // Read nodes
170  double *x = coord_arrays[0], *y = coord_arrays[1], *z = coord_arrays[2];
171  for( long i = 0; i < num_nodes; ++i, ++handle )
172  {
173  long id;
174  if( !tokens.get_long_ints( 1, &id ) || !tokens.get_doubles( 1, x++ ) || !tokens.get_doubles( 1, y++ ) ||
175  !tokens.get_doubles( 1, z++ ) )
176  return MB_FILE_WRITE_ERROR;
177 
178  if( !node_id_map.insert( std::pair< long, EntityHandle >( id, handle ) ).second )
179  {
180  MB_SET_ERR( MB_FILE_WRITE_ERROR, "Duplicate node ID at line " << tokens.line_number() );
181  }
182  }
183 
184  // Create reverse map from handle to id
185  std::vector< int > ids( num_nodes );
186  std::vector< int >::iterator id_iter = ids.begin();
187  std::vector< EntityHandle > handles( num_nodes );
188  std::vector< EntityHandle >::iterator h_iter = handles.begin();
189  for( std::map< long, EntityHandle >::iterator i = node_id_map.begin(); i != node_id_map.end();
190  ++i, ++id_iter, ++h_iter )
191  {
192  *id_iter = i->first;
193  *h_iter = i->second;
194  }
195  // Store IDs in tags
196  result = mdbImpl->tag_set_data( globalId, &handles[0], num_nodes, &ids[0] );
197  if( MB_SUCCESS != result ) return result;
198  if( file_id_tag )
199  {
200  result = mdbImpl->tag_set_data( *file_id_tag, &handles[0], num_nodes, &ids[0] );
201  if( MB_SUCCESS != result ) return result;
202  }
203  ids.clear();
204  handles.clear();
205 
206  // Get tokens signifying end of node data and start of elements
207  if( !tokens.match_token( format_version == 1 ? "$ENDNOD" : "$EndNodes" ) ||
208  !tokens.match_token( format_version == 1 ? "$ELM" : "$Elements" ) )
209  return MB_FILE_WRITE_ERROR;
210 
211  // Get element count
212  long num_elem;
213  if( !tokens.get_long_ints( 1, &num_elem ) ) return MB_FILE_WRITE_ERROR;
214 
215  // Lists of data accumulated for elements
216  std::vector< EntityHandle > connectivity;
217  std::vector< int > mat_set_list, geom_set_list, part_set_list, id_list;
218  // Temporary, per-element data
219  std::vector< int > int_data( 5 ), tag_data( 2 );
220  std::vector< long > tmp_conn;
221  int curr_elem_type = -1;
222  for( long i = 0; i < num_elem; ++i )
223  {
224  // Read element description
225  // File format 1.0
226  if( 1 == format_version )
227  {
228  if( !tokens.get_integers( 5, &int_data[0] ) ) return MB_FILE_WRITE_ERROR;
229  tag_data[0] = int_data[2];
230  tag_data[1] = int_data[3];
231  if( (unsigned)tag_data[1] < GmshUtil::numGmshElemType &&
232  GmshUtil::gmshElemTypes[tag_data[1]].num_nodes != (unsigned)int_data[4] )
233  {
235  "Invalid node count for element type at line " << tokens.line_number() );
236  }
237  }
238  // File format 2.0
239  else
240  {
241  if( !tokens.get_integers( 3, &int_data[0] ) ) return MB_FILE_WRITE_ERROR;
242  tag_data.resize( int_data[2] );
243  if( !tokens.get_integers( tag_data.size(), &tag_data[0] ) ) return MB_FILE_WRITE_ERROR;
244  }
245 
246  // If a list of material sets was specified in the
247  // argument list, skip any elements for which the
248  // material set is not specified or is not in the
249  // passed list.
250  if( !blocks.empty() && ( tag_data.empty() || blocks.find( tag_data[0] ) != blocks.end() ) ) continue;
251 
252  // If the next element is not the same type as the last one,
253  // create a sequence for the block of elements we've read
254  // to this point (all of the same type), and clear accumulated
255  // data.
256  if( int_data[1] != curr_elem_type )
257  {
258  if( !id_list.empty() )
259  { // First iteration
260  result = create_elements( GmshUtil::gmshElemTypes[curr_elem_type], id_list, mat_set_list, geom_set_list,
261  part_set_list, connectivity, file_id_tag );
262  if( MB_SUCCESS != result ) return result;
263  }
264 
265  id_list.clear();
266  mat_set_list.clear();
267  geom_set_list.clear();
268  part_set_list.clear();
269  connectivity.clear();
270  curr_elem_type = int_data[1];
271  if( (unsigned)curr_elem_type >= GmshUtil::numGmshElemType ||
272  GmshUtil::gmshElemTypes[curr_elem_type].mb_type == MBMAXTYPE )
273  {
275  "Unsupported element type " << curr_elem_type << " at line " << tokens.line_number() );
276  }
277  tmp_conn.resize( GmshUtil::gmshElemTypes[curr_elem_type].num_nodes );
278  }
279 
280  // Store data from element description
281  id_list.push_back( int_data[0] );
282  if( tag_data.size() > 3 ) part_set_list.push_back( tag_data[3] ); // it must be new format for gmsh, >= 2.5
283  // it could have negative partition ids, for ghost elements
284  else if( tag_data.size() > 2 )
285  part_set_list.push_back( tag_data[2] ); // old format, partition id saved in 3rd tag field
286  else
287  part_set_list.push_back( 0 );
288  geom_set_list.push_back( tag_data.size() > 1 ? tag_data[1] : 0 );
289  mat_set_list.push_back( tag_data.size() > 0 ? tag_data[0] : 0 );
290 
291  // Get element connectivity
292  if( !tokens.get_long_ints( tmp_conn.size(), &tmp_conn[0] ) ) return MB_FILE_WRITE_ERROR;
293 
294  // Convert connectivity from IDs to handles
295  for( unsigned j = 0; j < tmp_conn.size(); ++j )
296  {
297  std::map< long, EntityHandle >::iterator k = node_id_map.find( tmp_conn[j] );
298  if( k == node_id_map.end() )
299  {
300  MB_SET_ERR( MB_FILE_WRITE_ERROR, "Invalid node ID at line " << tokens.line_number() );
301  }
302  connectivity.push_back( k->second );
303  }
304  } // for (num_nodes)
305 
306  // Create entity sequence for last element(s).
307  if( !id_list.empty() )
308  {
309  result = create_elements( GmshUtil::gmshElemTypes[curr_elem_type], id_list, mat_set_list, geom_set_list,
310  part_set_list, connectivity, file_id_tag );
311  if( MB_SUCCESS != result ) return result;
312  }
313 
314  // Construct parent-child relations for geometric sets.
315  // Note: At the time this comment was written, the following
316  // function was not implemented.
317  result = create_geometric_topology();
318  geomSets.clear();
319  return result;
320 }
321 
322 //! Create an element sequence
324  const std::vector< int >& elem_ids,
325  const std::vector< int >& matl_ids,
326  const std::vector< int >& geom_ids,
327  const std::vector< int >& prtn_ids,
328  const std::vector< EntityHandle >& connectivity,
329  const Tag* file_id_tag )
330 {
331  ErrorCode result;
332 
333  // Make sure input is consistent
334  const unsigned long num_elem = elem_ids.size();
335  const int node_per_elem = type.num_nodes;
336  if( matl_ids.size() != num_elem || geom_ids.size() != num_elem || prtn_ids.size() != num_elem ||
337  connectivity.size() != num_elem * node_per_elem )
338  return MB_FAILURE;
339 
340  // Create the element sequence
341  // for points, simply gather the connectivities and create the materials
342  if( type.mb_type == MBVERTEX )
343  {
344  Range elements;
345  elements.insert< std::vector< EntityHandle > >( connectivity.begin(), connectivity.end() );
346  result = create_sets( type.mb_type, elements, matl_ids, 0 );
347  if( MB_SUCCESS != result ) return result;
348 
349  return MB_SUCCESS;
350  }
351  EntityHandle handle = 0;
352  EntityHandle* conn_array;
353  result =
354  readMeshIface->get_element_connect( num_elem, node_per_elem, type.mb_type, MB_START_ID, handle, conn_array );
355  if( MB_SUCCESS != result ) return result;
356 
357  // Copy passed element connectivity into entity sequence data.
358  if( type.node_order )
359  {
360  for( unsigned long i = 0; i < num_elem; ++i )
361  for( int j = 0; j < node_per_elem; ++j )
362  conn_array[i * node_per_elem + type.node_order[j]] = connectivity[i * node_per_elem + j];
363  }
364  else
365  {
366  memcpy( conn_array, &connectivity[0], connectivity.size() * sizeof( EntityHandle ) );
367  }
368 
369  // Notify MOAB of the new elements
370  result = readMeshIface->update_adjacencies( handle, num_elem, node_per_elem, conn_array );
371  if( MB_SUCCESS != result ) return result;
372 
373  // Store element IDs
374  Range elements( handle, handle + num_elem - 1 );
375  result = mdbImpl->tag_set_data( globalId, elements, &elem_ids[0] );
376  if( MB_SUCCESS != result ) return result;
377  if( file_id_tag )
378  {
379  result = mdbImpl->tag_set_data( *file_id_tag, elements, &elem_ids[0] );
380  if( MB_SUCCESS != result ) return result;
381  }
382 
383  // Add elements to material sets
384  result = create_sets( type.mb_type, elements, matl_ids, 0 );
385  if( MB_SUCCESS != result ) return result;
386  // Add elements to geometric sets
387  result = create_sets( type.mb_type, elements, geom_ids, 1 );
388  if( MB_SUCCESS != result ) return result;
389  // Add elements to parallel partitions
390  result = create_sets( type.mb_type, elements, prtn_ids, 2 );
391  if( MB_SUCCESS != result ) return result;
392 
393  return MB_SUCCESS;
394 }
395 
396 //! Add elements to sets as dictated by grouping ID in file.
398  const Range& elements,
399  const std::vector< int >& set_ids,
400  int set_type )
401 {
402  ErrorCode result;
403 
404  // Get a unique list of set IDs
405  std::set< int > ids;
406  for( std::vector< int >::const_iterator i = set_ids.begin(); i != set_ids.end(); ++i )
407  ids.insert( *i );
408 
409  // No Sets?
410  if( ids.empty() || ( ids.size() == 1 && *ids.begin() == 0 ) ) return MB_SUCCESS; // no sets (all ids are zero)
411 
412  // Get/create tag handles
413  int num_tags;
414  Tag tag_handles[2];
415  int tag_val;
416  const void* tag_values[2] = { &tag_val, NULL };
417 
418  switch( set_type )
419  {
420  default:
421  return MB_FAILURE;
422  case 0:
423  case 2: {
424  const char* name = set_type ? PARALLEL_PARTITION_TAG_NAME : MATERIAL_SET_TAG_NAME;
425  result = mdbImpl->tag_get_handle( name, 1, MB_TYPE_INTEGER, tag_handles[0], MB_TAG_SPARSE | MB_TAG_CREAT );
426  if( MB_SUCCESS != result ) return result;
427  num_tags = 1;
428  break;
429  }
430  case 1: {
431  result = mdbImpl->tag_get_handle( GEOM_DIMENSION_TAG_NAME, 1, MB_TYPE_INTEGER, tag_handles[1],
433  if( MB_SUCCESS != result ) return result;
434  tag_values[1] = NULL;
435  tag_handles[0] = globalId;
436  num_tags = 2;
437  break;
438  }
439  } // switch
440 
441  // For each unique set ID...
442  for( std::set< int >::iterator i = ids.begin(); i != ids.end(); ++i )
443  {
444  // Skip "null" set ID
445  if( *i == 0 ) continue;
446 
447  // Get all entities with the current set ID
448  Range entities, sets;
449  std::vector< int >::const_iterator j = set_ids.begin();
450  for( Range::iterator k = elements.begin(); k != elements.end(); ++j, ++k )
451  if( *i == *j ) entities.insert( *k );
452 
453  // Get set by ID
454  // Cppcheck warning (false positive): variable tag_val is assigned a value that is never
455  // used
456  tag_val = *i;
457  result = mdbImpl->get_entities_by_type_and_tag( 0, MBENTITYSET, tag_handles, tag_values, num_tags, sets );
458  if( MB_SUCCESS != result && MB_ENTITY_NOT_FOUND != result ) return result;
459 
460  // Don't use existing geometry sets (from some other file)
461  if( 1 == set_type ) // Geometry
462  sets = intersect( sets, geomSets );
463 
464  // Get set handle
465  EntityHandle set;
466  // If no sets with ID, create one
467  if( sets.empty() )
468  {
469  result = mdbImpl->create_meshset( MESHSET_SET, set );
470  if( MB_SUCCESS != result ) return result;
471 
472  result = mdbImpl->tag_set_data( tag_handles[0], &set, 1, &*i );
473  if( MB_SUCCESS != result ) return result;
474 
475  if( 1 == set_type )
476  { // Geometry
477  int dim = CN::Dimension( type );
478  result = mdbImpl->tag_set_data( tag_handles[1], &set, 1, &dim );
479  if( MB_SUCCESS != result ) return result;
480  geomSets.insert( set );
481  }
482  }
483  else
484  {
485  set = *sets.begin();
486  if( 1 == set_type )
487  { // Geometry
488  int dim = CN::Dimension( type );
489  // Get dimension of set
490  int dim2;
491  result = mdbImpl->tag_get_data( tag_handles[1], &set, 1, &dim2 );
492  if( MB_SUCCESS != result ) return result;
493  // If we're putting geometry of a higher dimension into the
494  // set, increase the dimension of the set.
495  if( dim > dim2 )
496  {
497  result = mdbImpl->tag_set_data( tag_handles[1], &set, 1, &dim );
498  if( MB_SUCCESS != result ) return result;
499  }
500  }
501  }
502 
503  // Put the mesh entities into the set
504  result = mdbImpl->add_entities( set, entities );
505  if( MB_SUCCESS != result ) return result;
506  } // for (ids)
507 
508  return MB_SUCCESS;
509 }
510 
511 //! NOT IMPLEMENTED
512 //! Reconstruct parent-child relations for geometry sets from
513 //! mesh connectivity.
515 {
516  if( geomSets.empty() ) return MB_SUCCESS;
517 
518  // Not implemented yet
519  geomSets.clear();
520  return MB_SUCCESS;
521 }
522 
523 } // namespace moab