Flow123d  release_2.1.0-84-g6a13a75
output_vtk.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 output_vtk.cc
15  * @brief The functions for outputs to VTK files.
16  */
17 
18 #include "output_vtk.hh"
19 #include "output_data_base.hh"
20 #include "output_mesh_data.hh"
21 #include "output_mesh.hh"
22 
23 #include <limits.h>
24 #include "input/factory.hh"
26 #include "system/file_path.hh"
27 
28 #include "config.h"
29 #include <zlib.h>
30 
32 
33 
34 using namespace Input::Type;
35 
36 const Record & OutputVTK::get_input_type() {
37  return Record("vtk", "Parameters of vtk output format.")
38  // It is derived from abstract class
40  .declare_key("variant", OutputVTK::get_input_type_variant(), Default("\"ascii\""),
41  "Variant of output stream file format.")
42  // The parallel or serial variant
43  //.declare_key("parallel", Bool(), Default("false"),
44  // "Parallel or serial version of file format.")
45  .close();
46 }
47 
48 
50  return Selection("VTK variant (ascii or binary)")
52  "ASCII variant of VTK file format")
54  "Uncompressed appended binary XML VTK format without usage of base64 encoding of appended data.")
55 #ifdef FLOW123D_HAVE_ZLIB
57  "Appended binary XML VTK format without usage of base64 encoding of appended data. Compressed with ZLib.")
58 #endif // FLOW123D_HAVE_ZLIB
59  .close();
60 }
61 
62 
63 const int OutputVTK::registrar = Input::register_class< OutputVTK >("vtk") +
65 
66 
67 
69 {
70  this->enable_refinement_ = true;
71 }
72 
73 
74 
76 {
77  this->write_tail();
78 }
79 
80 
81 
82 void OutputVTK::init_from_input(const std::string &equation_name, Mesh &mesh, const Input::Record &in_rec)
83 {
84  OutputTime::init_from_input(equation_name, mesh, in_rec);
85 
86  if(this->rank == 0) {
87  auto format_rec = (Input::Record)(input_record_.val<Input::AbstractRecord>("format"));
88  variant_type_ = format_rec.val<VTKVariant>("variant");
89 
90  this->fix_main_file_extension(".pvd");
91  try {
92  this->_base_filename.open_stream( this->_base_file );
93  } INPUT_CATCH(FilePath::ExcFileOpen, FilePath::EI_Address_String, input_record_)
94 
95  LogOut() << "Writing flow output file: " << this->_base_filename << " ... ";
96 
97  this->make_subdirectory();
98  this->write_head();
99  }
100 
101 }
102 
103 
104 
106 {
107  ASSERT_PTR(output_mesh_).error();
108 
109  /* It's possible now to do output to the file only in the first process */
110  if(this->rank != 0) {
111  /* TODO: do something, when support for Parallel VTK is added */
112  return 0;
113  }
114 
115  ASSERT(this->_base_file.is_open())(this->_base_filename).error();
116 
117  ostringstream ss;
118  ss << main_output_basename_ << "-"
119  << std::setw(6) << std::setfill('0') << this->current_step
120  << ".vtu";
121 
122 
123  std::string frame_file_name = ss.str();
124  FilePath frame_file_path({main_output_dir_, main_output_basename_, frame_file_name}, FilePath::output_file);
125 
126  /* Set up data file */
127  try {
128  frame_file_path.open_stream(_data_file);
129  } INPUT_CATCH(FilePath::ExcFileOpen, FilePath::EI_Address_String, input_record_)
130 
131 
132  LogOut() << __func__ << ": Writing output file " << this->_base_filename << " ... ";
133 
134  /* Set floating point precision to max */
135  this->_base_file.precision(std::numeric_limits<double>::digits10);
136 
137  /* Strip out relative path and add "base/" string */
138  std::string relative_frame_file = main_output_basename_ + "/" + frame_file_name;
139  this->_base_file << scientific << "<DataSet timestep=\"" << (isfinite(this->time)?this->time:0)
140  << "\" group=\"\" part=\"0\" file=\"" << relative_frame_file <<"\"/>" << endl;
141 
142  LogOut() << "O.K.";
143 
144  LogOut() << __func__ << ": Writing output (frame " << this->current_step << ") file " << relative_frame_file << " ... ";
145 
146  this->write_vtk_vtu();
147 
148  /* Close stream for file of current frame */
149  _data_file.close();
150  //delete data_file;
151  //this->_data_file = NULL;
152 
153  LogOut() << "O.K.";
154 
155  return 1;
156 }
157 
158 
159 
160 
162 {
163  ASSERT_EQ(this->_base_filename.extension(), ".pvd").error();
166 
167  vector<string> sub_path = { main_output_dir_, main_output_basename_, "__tmp__" };
168  FilePath fp(sub_path, FilePath::output_file);
169  fp.create_output_dir();
170 }
171 
172 
173 
174 
176 {
177  ofstream &file = this->_data_file;
178 
179  file << "<?xml version=\"1.0\"?>" << endl;
180  // TODO: test endianess of platform (this would be important, when raw
181  // data will be saved to the VTK file)
182  file << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\"";
183  if ( this->variant_type_ != VTKVariant::VARIANT_ASCII ) {
184  file << " header_type=\"UInt64\"";
185  }
186  if ( this->variant_type_ == VTKVariant::VARIANT_BINARY_ZLIB ) {
187  file << " compressor=\"vtkZLibDataCompressor\"";
188  }
189  file << ">" << endl;
190  file << "<UnstructuredGrid>" << endl;
191 }
192 
193 
194 
196 {
197  auto offsets = output_mesh_->offsets_->data_;
198  unsigned int n_elements = offsets.size();
199 
200  data.resize(n_elements);
201  int n_nodes;
202 
203  n_nodes = offsets[0];
204  switch(n_nodes) {
205  case 2:
206  data[0] = (unsigned int)VTK_LINE;
207  break;
208  case 3:
209  data[0] = (unsigned int)VTK_TRIANGLE;
210  break;
211  case 4:
212  data[0] = (unsigned int)VTK_TETRA;
213  break;
214  }
215 
216  for(unsigned int i=1; i < n_elements; i++)
217  {
218  n_nodes = offsets[i]-offsets[i-1];
219  switch(n_nodes) {
220  case 2:
221  data[i] = (unsigned int)VTK_LINE;
222  break;
223  case 3:
224  data[i] = (unsigned int)VTK_TRIANGLE;
225  break;
226  case 4:
227  data[i] = (unsigned int)VTK_TETRA;
228  break;
229  }
230  }
231 }
232 
233 
234 
236 {
237  // names of types in DataArray section
238  static const std::vector<std::string> types = {
239  "Int8", "UInt8", "Int16", "UInt16", "Int32", "UInt32", "Float32", "Float64" };
240  // formats of DataArray section
241  static const std::vector<std::string> formats = { "ascii", "appended", "appended" };
242 
243  ofstream &file = this->_data_file;
244 
245  file << "<DataArray type=\"" << types[output_data->vtk_type_] << "\" ";
246  // possibly write name
247  if( ! output_data->output_field_name.empty())
248  file << "Name=\"" << output_data->output_field_name <<"\" ";
249  // write number of components
250  if (output_data->n_elem_ > 1)
251  {
252  file
253  << "NumberOfComponents=\"" << output_data->n_elem_ << "\" ";
254  }
255  file << "format=\"" << formats[this->variant_type_] << "\"";
256 
257  if ( this->variant_type_ == VTKVariant::VARIANT_ASCII ) {
258  // ascii output
259  file << ">" << endl;
260  file << std::fixed << std::setprecision(10); // Set precision to max
261  output_data->print_ascii_all(file);
262  file << "\n</DataArray>" << endl;
263  } else {
264  // binary output is stored to appended_data_ stream
265  double range_min, range_max;
266  output_data->get_min_max_range(range_min, range_max);
267  file << " offset=\"" << appended_data_.tellp() << "\" ";
268  file << "RangeMin=\"" << range_min << "\" RangeMax=\"" << range_max << "\"/>" << endl;
269  if ( this->variant_type_ == VTKVariant::VARIANT_BINARY_UNCOMPRESSED ) {
270  output_data->print_binary_all( appended_data_ );
271  } else { // ZLib compression
272  stringstream uncompressed_data, compressed_data;
273  output_data->print_binary_all( uncompressed_data, false );
274  this->compress_data(uncompressed_data, compressed_data);
275  appended_data_ << compressed_data.str();
276  }
277  }
278 
279 }
280 
281 
282 void OutputVTK::compress_data(stringstream &uncompressed_stream, stringstream &compressed_stream) {
283  // size of block of compressed data.
284  static const size_t BUF_SIZE = 32 * 1024;
285 
286  string uncompressed_string = uncompressed_stream.str(); // full uncompressed string
287  uLong uncompressed_size = uncompressed_string.size(); // size of uncompressed string
288  stringstream compressed_data; // helper stream stores blocks of compress data
289 
290  uLong count_of_blocks = (uncompressed_size + BUF_SIZE - 1) / BUF_SIZE;
291  uLong last_block_size = (uncompressed_size % BUF_SIZE);
292  compressed_stream.write(reinterpret_cast<const char*>(&count_of_blocks), sizeof(unsigned long long int));
293  compressed_stream.write(reinterpret_cast<const char*>(&BUF_SIZE), sizeof(unsigned long long int));
294  compressed_stream.write(reinterpret_cast<const char*>(&last_block_size), sizeof(unsigned long long int));
295 
296  for (uLong i=0; i<count_of_blocks; ++i) {
297  // get block of data for compression
298  std::string data_block = uncompressed_string.substr(i*BUF_SIZE, BUF_SIZE);
299  uLong data_block_size = data_block.size();
300 
301  std::vector<uint8_t> buffer;
302  uint8_t temp_buffer[BUF_SIZE];
303 
304  // set zlib object
305  z_stream strm;
306  strm.zalloc = 0;
307  strm.zfree = 0;
308  strm.next_in = reinterpret_cast<uint8_t *>(&data_block[0]);
309  strm.avail_in = data_block_size;
310  strm.next_out = temp_buffer;
311  strm.avail_out = BUF_SIZE;
312 
313  // compression of data
314  deflateInit(&strm, Z_BEST_COMPRESSION);
315  while (strm.avail_in != 0) {
316  int res = deflate(&strm, Z_NO_FLUSH);
317  ASSERT_EQ(res, Z_OK).error();
318  if (strm.avail_out == 0) {
319  buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUF_SIZE);
320  strm.next_out = temp_buffer;
321  strm.avail_out = BUF_SIZE;
322  }
323  }
324  int deflate_res = Z_OK;
325  while (deflate_res == Z_OK) {
326  if (strm.avail_out == 0) {
327  buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUF_SIZE);
328  strm.next_out = temp_buffer;
329  strm.avail_out = BUF_SIZE;
330  }
331  deflate_res = deflate(&strm, Z_FINISH);
332  }
333  ASSERT_EQ(deflate_res, Z_STREAM_END).error();
334  buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUF_SIZE - strm.avail_out);
335  deflateEnd(&strm);
336 
337  // store compress data and its size to streams
338  std::string str(buffer.begin(), buffer.end());
339  uLong compressed_data_size = str.size();
340  compressed_stream.write(reinterpret_cast<const char*>(&compressed_data_size), sizeof(unsigned long long int));
341  compressed_data << str;
342  }
343  // push compress data to returned stream
344  compressed_stream << compressed_data.str();
345 }
346 
347 
349 {
350  for(OutputDataPtr data : output_data_vec)
351  write_vtk_data(data);
352 }
353 
354 
355 
356 
358  OutputDataFieldVec &output_data_vec)
359 {
360  if (output_data_vec.empty()) return;
361 
362  file << "Scalars=\"";
363  for(OutputDataPtr data : output_data_vec )
364  if (data->n_elem_ == OutputDataBase::N_SCALAR) file << data->output_field_name << ",";
365  file << "\" ";
366 
367  file << "Vectors=\"";
368  for(OutputDataPtr data : output_data_vec )
369  if (data->n_elem_ == OutputDataBase::N_VECTOR) file << data->output_field_name << ",";
370  file << "\" ";
371 
372  file << "Tensors=\"";
373  for(OutputDataPtr data : output_data_vec )
374  if (data->n_elem_ == OutputDataBase::N_TENSOR) file << data->output_field_name << ",";
375  file << "\"";
376 }
377 
378 
380 {
381  ofstream &file = this->_data_file;
382 
383  // merge node and corner data
384  OutputDataFieldVec node_corner_data(output_data_vec_[NODE_DATA]);
385  node_corner_data.insert(node_corner_data.end(),
387 
388  if( ! node_corner_data.empty() ) {
389  /* Write <PointData begin */
390  file << "<PointData ";
391  write_vtk_data_names(file, node_corner_data);
392  file << ">" << endl;
393 
394  /* Write data on nodes */
395  this->write_vtk_field_data(output_data_vec_[NODE_DATA]);
396 
397  /* Write data in corners of elements */
399 
400  /* Write PointData end */
401  file << "</PointData>" << endl;
402  }
403 }
404 
405 
407 {
408  ofstream &file = this->_data_file;
409 
410  auto &data_map = this->output_data_vec_[ELEM_DATA];
411  if (data_map.empty()) return;
412 
413  /* Write CellData begin */
414  file << "<CellData ";
415  write_vtk_data_names(file, data_map);
416  file << ">" << endl;
417 
418  /* Write own data */
419  this->write_vtk_field_data(data_map);
420 
421  /* Write PointData end */
422  file << "</CellData>" << endl;
423 }
424 
425 
427 {
428  ofstream &file = this->_data_file;
429 
430  file << "</UnstructuredGrid>" << endl;
431  if ( this->variant_type_ != VTKVariant::VARIANT_ASCII ) {
432  // appended data of binary compressed output
433  file << "<AppendedData encoding=\"raw\">" << endl;
434  // appended data starts with '_' character
435  file << "_" << appended_data_.str() << endl;
436  file << "</AppendedData>" << endl;
437  }
438  file << "</VTKFile>" << endl;
439 }
440 
441 
443 {
444  ofstream &file = this->_data_file;
445 
446  /* Write header */
447  this->write_vtk_vtu_head();
448 
449  /* When there is no discontinuous data, then write classical vtu */
450  if ( this->output_data_vec_[CORNER_DATA].empty() )
451  {
452  /* Write Piece begin */
453  file << "<Piece NumberOfPoints=\"" << output_mesh_->n_nodes()
454  << "\" NumberOfCells=\"" << output_mesh_->n_elements() <<"\">" << endl;
455 
456  /* Write VTK Geometry */
457  file << "<Points>" << endl;
458  write_vtk_data(output_mesh_->nodes_);
459  file << "</Points>" << endl;
460 
461 
462  /* Write VTK Topology */
463  file << "<Cells>" << endl;
464  write_vtk_data(output_mesh_->connectivity_);
465  write_vtk_data(output_mesh_->offsets_);
466  auto types = std::make_shared<MeshData<unsigned int>>("types");
467  fill_element_types_vector(types->data_);
468  write_vtk_data( types );
469  file << "</Cells>" << endl;
470 
471  /* Write VTK scalar and vector data on nodes to the file */
472  this->write_vtk_node_data();
473 
474  /* Write VTK data on elements */
475  this->write_vtk_element_data();
476 
477  /* Write Piece end */
478  file << "</Piece>" << endl;
479 
480  } else {
481  /* Write Piece begin */
482  file << "<Piece NumberOfPoints=\"" << output_mesh_discont_->n_nodes()
483  << "\" NumberOfCells=\"" << output_mesh_->n_elements() <<"\">" << endl;
484 
485  /* Write VTK Geometry */
486  file << "<Points>" << endl;
488  file << "</Points>" << endl;
489 
490  /* Write VTK Topology */
491  file << "<Cells>" << endl;
492  write_vtk_data(output_mesh_discont_->connectivity_);
494  auto types = std::make_shared<MeshData<unsigned int>>("types");
495  fill_element_types_vector(types->data_);
496  write_vtk_data( types );
497  file << "</Cells>" << endl;
498 
499  /* Write VTK scalar and vector data on nodes to the file */
500  this->write_vtk_node_data();
501 
502  /* Write VTK data on elements */
503  this->write_vtk_element_data();
504 
505  /* Write Piece end */
506  file << "</Piece>" << endl;
507  }
508 
509  /* Write tail */
510  this->write_vtk_vtu_tail();
511 }
512 
513 
514 
516 {
517  /* It's possible now to do output to the file only in the first process */
518  if(this->rank != 0) {
519  /* TODO: do something, when support for Parallel VTK is added */
520  return 0;
521  }
522 
523  LogOut() << __func__ << ": Writing output file (head) " << this->_base_filename << " ... ";
524 
525  this->_base_file << "<?xml version=\"1.0\"?>" << endl;
526  this->_base_file << "<VTKFile type=\"Collection\" version=\"0.1\" byte_order=\"LittleEndian\">" << endl;
527  this->_base_file << "<Collection>" << endl;
528 
529  LogOut() << "O.K.";
530 
531  return 1;
532 }
533 
534 
536 {
537  /* It's possible now to do output to the file only in the first process */
538  if(this->rank != 0) {
539  /* TODO: do something, when support for Parallel VTK is added */
540  return 0;
541  }
542 
543  LogOut() << __func__ << ": Writing output file (tail) " << this->_base_filename << " ... ";
544 
545  this->_base_file << "</Collection>" << endl;
546  this->_base_file << "</VTKFile>" << endl;
547 
548  LogOut() << "O.K.";
549 
550  return 1;
551 }
552 
553 
554 
555 
556 
557 
Classes for auxiliary output mesh.
string stem() const
Definition: file_path.cc:193
double time
Definition: output_time.hh:208
std::shared_ptr< OutputMesh > output_mesh_
Output mesh.
Definition: output_time.hh:248
virtual void init_from_input(const std::string &equation_name, Mesh &mesh, const Input::Record &in_rec)
Constructor of OutputTime object. It opens base file for writing.
Definition: output_time.cc:76
Input::Record input_record_
Definition: output_time.hh:224
std::shared_ptr< OutputMeshDiscontinuous > output_mesh_discont_
Discontinuous (non-conforming) mesh. Used for CORNER_DATA.
Definition: output_time.hh:250
void fix_main_file_extension(std::string extension)
Definition: output_time.cc:157
unsigned int size() const
Returns number of keys in the Record.
Definition: type_record.hh:593
void make_subdirectory()
Definition: output_vtk.cc:161
static const Input::Type::Record & get_input_type()
The definition of input record for vtk file format.
Definition: output_vtk.cc:36
void create_output_dir()
Definition: file_path.cc:176
void write_vtk_field_data(OutputDataFieldVec &output_data_map)
Definition: output_vtk.cc:348
void write_vtk_vtu(void)
This function write all scalar and vector data on nodes and elements to the VTK file (...
Definition: output_vtk.cc:442
Class Input::Type::Default specifies default value of keys of a Input::Type::Record.
Definition: type_record.hh:56
FilePath _base_filename
Definition: output_time.hh:234
void write_vtk_data(OutputDataPtr output_data)
Definition: output_vtk.cc:235
static const int registrar
Registrar of class to factory.
Definition: output_vtk.hh:122
#define INPUT_CATCH(ExceptionType, AddressEITag, input_accessor)
Definition: accessors.hh:57
static Input::Type::Abstract & get_input_format_type()
The specification of output file format.
Definition: output_time.cc:58
void fill_element_types_vector(std::vector< unsigned int > &data)
Fills the given vector with VTK element types indicators.
Definition: output_vtk.cc:195
Definition: mesh.h:95
string main_output_basename_
Basename of main output file (without extension)
Definition: output_vtk.hh:202
#define ASSERT(expr)
Allow use shorter versions of macro names if these names is not used with external library...
Definition: asserts.hh:347
int write_head(void)
This function writes header of VTK (.pvd) file format.
Definition: output_vtk.cc:515
string main_output_dir_
Main output file directory.
Definition: output_vtk.hh:205
void write_vtk_element_data(void)
Write data on elements to the VTK file (.vtu)
Definition: output_vtk.cc:406
#define LogOut()
Macro defining &#39;log&#39; record of log.
Definition: logger.hh:237
Record & close() const
Close the Record for further declarations of keys.
Definition: type_record.cc:301
VTKVariant
The declaration enumeration used for variant of file VTK format.
Definition: output_vtk.hh:85
virtual Record & derive_from(Abstract &parent)
Method to derive new Record from an AbstractRecord parent.
Definition: type_record.cc:193
void open_stream(Stream &stream) const
Definition: file_path.cc:211
int write_data(void)
This function write data to VTK (.pvd) file format for curent time.
Definition: output_vtk.cc:105
ofstream _data_file
Definition: output_vtk.hh:189
int current_step
Definition: output_time.hh:203
ostringstream appended_data_
Definition: output_vtk.hh:194
Accessor to the data with type Type::Record.
Definition: accessors.hh:286
const Ret val(const string &key) const
void write_vtk_vtu_tail(void)
Write tail of VTK file (.vtu)
Definition: output_vtk.cc:426
This class is used for output data to VTK file format.
Definition: output_vtk.hh:34
Selection & add_value(const int value, const std::string &key, const std::string &description="", TypeBase::attribute_map attributes=TypeBase::attribute_map())
Adds one new value with name given by key to the Selection.
string parent_path() const
Definition: file_path.cc:183
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:488
int write_tail(void)
This function writes tail of VTK (.pvd) file format.
Definition: output_vtk.cc:535
ofstream _base_file
Definition: output_time.hh:229
~OutputVTK()
The destructor of this class. It writes tail of the file too.
Definition: output_vtk.cc:75
string extension() const
Definition: file_path.cc:198
Accessor to the polymorphic input data of a type given by an AbstracRecord object.
Definition: accessors.hh:453
Dedicated class for storing path to input and output files.
Definition: file_path.hh:48
OutputVTK()
The constructor of this class. The head of file is written, when constructor is called.
Definition: output_vtk.cc:68
#define ASSERT_PTR(ptr)
Definition of assert macro checking non-null pointer (PTR)
Definition: asserts.hh:336
const Selection & close() const
Close the Selection, no more values can be added.
VTKVariant variant_type_
Output format (ascii, binary or binary compressed)
Definition: output_vtk.hh:208
void write_vtk_node_data(void)
Write data on nodes to the VTK file (.vtu)
Definition: output_vtk.cc:379
OutputDataFieldVec output_data_vec_[N_DISCRETE_SPACES]
Definition: output_time.hh:198
void compress_data(stringstream &uncompressed_stream, stringstream &compressed_stream)
Definition: output_vtk.cc:282
std::shared_ptr< OutputDataBase > OutputDataPtr
Definition: output_time.hh:191
Record type proxy class.
Definition: type_record.hh:177
bool enable_refinement_
Auxliary flag for refinement enabling, due to gmsh format.
Definition: output_time.hh:255
void write_vtk_vtu_head(void)
Write header of VTK file (.vtu)
Definition: output_vtk.cc:175
void init_from_input(const std::string &equation_name, Mesh &mesh, const Input::Record &in_rec) override
Override OutputTime::init_from_input.
Definition: output_vtk.cc:82
Template for classes storing finite set of named values.
#define FLOW123D_FORCE_LINK_IN_CHILD(x)
Definition: global_defs.h:180
#define ASSERT_EQ(a, b)
Definition of comparative assert macro (EQual)
Definition: asserts.hh:328
static const Input::Type::Selection & get_input_type_variant()
The definition of input record for selection of variant of file format.
Definition: output_vtk.cc:49
void write_vtk_data_names(ofstream &file, OutputDataFieldVec &output_data_map)
Write names of data sets in output_data vector that have value type equal to type. Output is done into stream file.
Definition: output_vtk.cc:357