ElementFileWriter.cc 13.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
//
// Software License for AMDiS
//
// Copyright (c) 2010 Dresden University of Technology 
// All rights reserved.
// Authors: Simon Vey, Thomas Witkowski et al.
//
// This file is part of AMDiS
//
// See also license.opensource.txt in the distribution.


13
14
15
16
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
17
#include <boost/lexical_cast.hpp>
18

19
#include "io/VtkWriter.h"
20
21
#include "ElementFileWriter.h"
#include "BasisFunction.h"
22
#include "Initfile.h"
23
24
25
#include "Traverse.h"
#include "AdaptInfo.h"

26
27
namespace AMDiS {

28
29
30
  using namespace std;

  ElementFileWriter::ElementFileWriter(string name_, 
31
				       Mesh *mesh_,
32
				       map<int, double> &mapvec)
33
34
35
    : name(name_),
      amdisMeshDatExt(".elem.mesh"),
      vtkExt(".vtu"),
36
      pvdExt(".pvd"),
37
38
      writeAMDiSFormat(0),
      writeVtkFormat(0),
39
40
41
      writeVtkVectorFormat(0),
      writeAs3dVector(true),
      writeParaViewAnimation(0),
42
43
44
45
46
      appendIndex(0),
      indexLength(5),
      indexDecimals(3),
      tsModulo(1),
      timestepNumber(-1),
47
      mesh(mesh_),
48
49
      vec(&mapvec),
      vecs(NULL)
50
  {
Thomas Witkowski's avatar
Thomas Witkowski committed
51
    if (name != "") {
52
53
54
55
      Parameters::get(name + "->output->filename", filename);
      Parameters::get(name + "->output->AMDiS format", writeAMDiSFormat);
      Parameters::get(name + "->output->AMDiS mesh-dat ext", amdisMeshDatExt);
      Parameters::get(name + "->output->ParaView format", writeVtkFormat);
56
      Parameters::get(name + "->output->ParaView animation", writeParaViewAnimation);
57
58
59
60
      Parameters::get(name + "->output->append index", appendIndex);
      Parameters::get(name + "->output->index length", indexLength);
      Parameters::get(name + "->output->index decimals", indexDecimals);
      Parameters::get(name + "->output->write every i-th timestep", tsModulo);
Thomas Witkowski's avatar
Thomas Witkowski committed
61
    }
62
  }
63

64

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
  ElementFileWriter::ElementFileWriter(string name_,
				       Mesh *mesh_,
				       map<int, vector<double> > &mapvec)
    : name(name_),
      amdisMeshDatExt(".elem.mesh"),
      vtkExt(".vtu"),
      pvdExt(".pvd"),
      writeAMDiSFormat(0),
      writeVtkFormat(0),
      writeVtkVectorFormat(0),
      writeAs3dVector(true),
      writeParaViewAnimation(0),
      appendIndex(0),
      indexLength(5),
      indexDecimals(3),
      tsModulo(1),
      timestepNumber(-1),
      mesh(mesh_),
      vec(NULL),
      vecs(&mapvec)
  {
    if (name != "") {
      Parameters::get(name + "->output->filename", filename);
      Parameters::get(name + "->output->AMDiS format", writeAMDiSFormat);
      Parameters::get(name + "->output->AMDiS mesh-dat ext", amdisMeshDatExt);
      Parameters::get(name + "->output->ParaView format", writeVtkFormat);
      Parameters::get(name + "->output->ParaView vector format", writeVtkVectorFormat);
      Parameters::get(name + "->output->write vector as 3d vector", writeAs3dVector);
      Parameters::get(name + "->output->ParaView animation", writeParaViewAnimation);
      Parameters::get(name + "->output->append index", appendIndex);
      Parameters::get(name + "->output->index length", indexLength);
      Parameters::get(name + "->output->index decimals", indexDecimals);
      Parameters::get(name + "->output->write every i-th timestep", tsModulo);
    }
  }
  

102
  void ElementFileWriter::writeFiles(AdaptInfo *adaptInfo, bool force,
Thomas Witkowski's avatar
Thomas Witkowski committed
103
104
				     int level, Flag traverseFlag, 
				     bool (*writeElem)(ElInfo*))
105
106
  {
    FUNCNAME("ElementFileWriter::writeFiles()");
107

108
109
    timestepNumber++;
    timestepNumber %= tsModulo;
110

111
    if (timestepNumber != 0 && !force) 
112
      return;
113

114
    string fn = filename;
115

116
117
118
119
    if (appendIndex) {
      TEST_EXIT(indexLength <= 99)("index lenght > 99\n");
      TEST_EXIT(indexDecimals <= 97)("index decimals > 97\n");
      TEST_EXIT(indexDecimals < indexLength)("index length <= index decimals\n");
120
    
121
122
      char formatStr[9];
      sprintf(formatStr, "%%0%d.%df", indexLength, indexDecimals);
123

124
125
      char timeStr[20];
      sprintf(timeStr, formatStr, adaptInfo ? adaptInfo->getTime() : 0.0);
126

127
128
      fn += timeStr;
    }
129

130
131
    if (writeAMDiSFormat) {
      TEST_EXIT(mesh)("no mesh\n");
132
    
133
      writeMeshDatValues(const_cast<char*>((fn + amdisMeshDatExt).c_str()),
134
135
136
			 adaptInfo ? adaptInfo->getTime() : 0.0);
      MSG("MeshDat file written to %s\n", (fn + amdisMeshDatExt).c_str());
    }
137

138
    if (writeVtkFormat || writeVtkVectorFormat) {
139
      TEST_EXIT(mesh)("no mesh\n");
140

141
      writeVtkValues(fn, vtkExt,-1,writeVtkVectorFormat==1);
142
143
      MSG("VTK file written to %s\n", (fn + vtkExt).c_str());		     
    }
144
145
146
147

    if (writeParaViewAnimation) {
      VtkWriter::updateAnimationFile(adaptInfo, (fn + vtkExt), &paraViewAnimationFrames, (filename + pvdExt));
    }
148
149
  }

150

151
  void ElementFileWriter::writeFile(map<int, double> &vec,
152
				    Mesh *mesh,
153
				    string filename,
154
				    string postfix,
155
156
				    int level,
				    bool writeAsVector)
Thomas Witkowski's avatar
Thomas Witkowski committed
157
  {
158
    ElementFileWriter efw("", mesh, vec);
159
160
161
162
163
164
165
166
167
168
169
170
171
    efw.writeVtkValues(filename, postfix, level, writeAsVector);
  }


  void ElementFileWriter::writeFile(map<int, vector<double> > &vecs,
				    Mesh *mesh,
				    string filename,
				    string postfix,
				    int level,
				    bool writeAsVector)
  {
    ElementFileWriter efw("", mesh, vecs);
    efw.writeVtkValues(filename, postfix, level, writeAsVector);
Thomas Witkowski's avatar
Thomas Witkowski committed
172
173
174
  }
  

175
  void ElementFileWriter::writeMeshDatValues(string filename, double time)
176
177
  {
    FUNCNAME("ElementFileWriter::writeMeshDatValues()");
178

179
180
181
182
183
184
185
186
187
    boost::iostreams::filtering_ostream file;
    {
      //boost::iostreams seems not to truncate the file
      ofstream swapfile(filename.c_str(), ios::out | ios::trunc);
      TEST_EXIT(swapfile.is_open())
	("Cannot open file %s for writing!\n", name.c_str());
      swapfile.close();
    }
    file.push(boost::iostreams::file_descriptor_sink(filename, ios::trunc));
188

189
190
    int dim = mesh->getDim();
    double val;
191

192
    // === Write header. ===
193
194
195
196
197
198
    file << "mesh name: " << mesh->getName().c_str() << "\n\n";
    file << "time: " << time << "\n\n"; 
    file << "DIM: " << dim << "\n";
    file << "DIM_OF_WORLD: " << Global::getGeo(WORLD) << "\n\n";
    file << "number of vertices: " << (dim+1)*mesh->getNumberOfLeaves() << "\n";
    file << "number of elements: " << mesh->getNumberOfLeaves() << "\n\n";
199
200


201
    // === Write vertex coordinates (every vertex for every element). ===
202
    file << "vertex coordinates:\n";
203
    TraverseStack stack;
204

205
206
207
208
    ElInfo *elInfo = stack.traverseFirst(mesh,
					 -1, 
					 Mesh::CALL_LEAF_EL | 
					 Mesh::FILL_COORDS);
209

210
    while (elInfo) {
211

212
213
214
      // Write coordinates of all element vertices.
      for (int i = 0; i <= dim; ++i) {     
	for (int j = 0; j < dim; ++j) {
215
	  file << elInfo->getCoord(i)[j] << " ";
216
	}
217
	file << "\n";
218
219
220
221
      }
    
      elInfo = stack.traverseNext(elInfo);
    }
222
223


224
225
226
    // === Write elements. ===
    int numLeaves = mesh->getNumberOfLeaves();
    int vertCntr = 0;
227
228
    file << "\n";
    file << "element vertices:\n";
229
230
    for (int i = 0; i < numLeaves; ++i) {
      for (int j = 0; j <= dim; ++j) {
231
	file << vertCntr << " ";
232
	++vertCntr;
233
      }
234
      file << "\n";
235
236
237
    }


238
    // === Write values. ===
239

240
    // Write values header.
241
242
243
244
245
246
247
248
    file << "\n";
    file << "number of values: 1\n\n";
    file << "value description: " << name.c_str() << "\n";
    file << "number of interpolation points: 0" << "\n";
    file << "type: scalar" << "\n";
    file << "interpolation type: lagrange" << "\n";
    file << "interpolation degree: 1" << "\n";
    file << "end of description: " << name.c_str() << "\n\n";
249
250

    // Write values.
251
    file << "vertex values: " << name.c_str() << "\n";
252

253
    file.setf(ios::scientific,ios::floatfield);
254
255
256
257
258
259
260

    elInfo = stack.traverseFirst(mesh,
				 -1, 
				 Mesh::CALL_LEAF_EL);

    while (elInfo) {
      // Get element value.
261
      val = (*vec)[elInfo->getElement()->getIndex()];
262
263
264
    
      // Write value for each vertex of each element.
      for (int i = 0; i <= dim; ++i) {      
265
	file << val << "\n";
266
267
268
269
      }
    
      elInfo = stack.traverseNext(elInfo);
    }  // end of: mesh traverse
270
271


272
    // Write values trailor.
273
274
275
    file << "\n";
    file << "interpolation values: " << name.c_str() << "\n\n\n";
    file << "element interpolation points: " << name.c_str() << "\n";
276
  }
277

278

279
280
  void ElementFileWriter::writeVtkValues(string fname, 
					 string postfix, 
281
282
					 int level,
					 bool writeAsVector)
283
284
285
  {
    FUNCNAME("ElementFileWriter::writeVtkValues()");

286
287
    TEST_EXIT((vec!=NULL || vecs!=NULL) && (vec==NULL || vecs==NULL))("Ether vec or vecs must be given, not both and not nothing!");

288
289
290
291
292
293
294
295
296
#if HAVE_PARALLEL_DOMAIN_AMDIS
    string filename = 
      fname  + 
      "-p" + boost::lexical_cast<std::string>(MPI::COMM_WORLD.Get_rank()) + "-" +
      postfix;
#else
    string filename = fname + postfix;
#endif

297
298
299
300
301
302
303
304
305
    boost::iostreams::filtering_ostream file;
    {
      //boost::iostreams seems not to truncate the file
      ofstream swapfile(filename.c_str(), ios::out | ios::trunc);
      TEST_EXIT(swapfile.is_open())
	("Cannot open file %s for writing!\n", name.c_str());
      swapfile.close();
    }
    file.push(boost::iostreams::file_descriptor_sink(filename, ios::trunc));
306
307
308

    int dim = mesh->getDim();
    int vertices = mesh->getGeo(VERTEX);
309
310
    int nVertices = 0;
    int nElements = 0;
311
312
    Flag traverseFlag = level == -1 ? Mesh::CALL_LEAF_EL : Mesh::CALL_EL_LEVEL;

313
314
315
316
317
318
    TraverseStack stack;
    ElInfo *elInfo = stack.traverseFirst(mesh, level, traverseFlag);
    while (elInfo) {
      nElements++;
      elInfo = stack.traverseNext(elInfo);
    }
319

320
321
322
323
324
325
326
327
328
329
330
331
332
333
    // === Write vertex coordinates (every vertex for every element). ===
    elInfo = stack.traverseFirst(mesh, level, traverseFlag | Mesh::FILL_COORDS);

    std::map<DegreeOfFreedom, std::pair<int, WorldVector<double> > > dof2Idx;
    std::vector<DegreeOfFreedom> idx2Dof;
    while (elInfo) {
      // Write coordinates of all element vertices.
      for (int i = 0; i <= dim; i++) {
	DegreeOfFreedom idx = elInfo->getElement()->getDof(i, 0);
	if (dof2Idx.find(idx) == dof2Idx.end()) {
	  dof2Idx[idx] = std::make_pair(nVertices, elInfo->getCoord(i));
	  idx2Dof.push_back(idx);
	  nVertices++;
	}
334
      }
335
      elInfo = stack.traverseNext(elInfo);
336
    }
337

338
339
340
    file << "<?xml version=\"1.0\"?>\n";
    file << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n";
    file << "  <UnstructuredGrid>\n";
341
    file << "    <Piece NumberOfPoints=\"" << nVertices
342
343
344
	 << "\" NumberOfCells=\"" <<  nElements << "\">\n";
    file << "      <Points>\n";
    file << "        <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n";
345

346
347
348
    for (int i = 0; i < nVertices; i++) {
      DegreeOfFreedom dof = idx2Dof[i];
      writeCoord(file, dof2Idx[dof].second);
349
    }
350

351
352
353
    file << "        </DataArray>\n";
    file << "      </Points>\n";
    file << "      <Cells>\n";
354

355
    file << "        <DataArray type=\"Int32\" Name=\"offsets\">\n";
356
    for (int i = 0; i < nElements; i++) 
357
358
      file << " " << (i + 1) * vertices << "\n";    
    file << "        </DataArray>\n";
359
360


361
    file << "        <DataArray type=\"UInt8\" Name=\"types\">\n";
362
363
364
    for (int i = 0; i < nElements; i++) {
      switch (vertices) {
      case 2:
365
	file << " 3\n";
366
367
	break;
      case 3: 
368
	file << " 5\n";
369
370
	break;
      case 4:
371
	file << " 10\n";
372
373
374
375
376
	break;		    
      default:
	break;
      }	   
    }
377
    file << "        </DataArray>\n";
378

379
    file << "        <DataArray type=\"Int32\" Name=\"connectivity\">\n";
380
381
382
383
384
385
    elInfo = stack.traverseFirst(mesh, level, traverseFlag);
    while (elInfo) {
      // Write coordinates of all element vertices.
      for (int i = 0; i <= dim; i++) {
	DegreeOfFreedom dof = elInfo->getElement()->getDof(i, 0);
	file << (dof2Idx[dof].first) << " ";
386
      }
387
      file << "\n";
388
      elInfo = stack.traverseNext(elInfo);
389
    }
390
391
    file << "        </DataArray>\n";
    file << "      </Cells>\n";
392

393
394
395
396
397
398
    int dataLength = (vecs != NULL ? (*(vecs->begin())).second.size() : 1);
    int nComponents = (!writeAsVector || (vecs == NULL && vec != NULL) ? 1 : dataLength);
    int nDataArrays = (!writeAsVector && (vec == NULL && vecs != NULL) ? dataLength : 1);
    file << "      <CellData>\n";
    for (int i = 0; i < nDataArrays; i++) {
      file << "        <DataArray type=\"Float32\" Name=\"value"<<i<<"\" format=\"ascii\" NumberOfComponents=\""<<(writeAsVector ? std::max(3,nComponents) : nComponents)<<"\">\n";
399

400
      file.setf(ios::scientific,ios::floatfield);
401

402
403
404
405
406
407
408
409
410
411
412
413
414
415
      elInfo = stack.traverseFirst(mesh, level, traverseFlag);
      int vc = 0;
      while (elInfo) {
	// Get element value.
	int idx = elInfo->getElement()->getIndex();
	
	for (int j = 0; j < nComponents; j++) {
	  double val = (vec != NULL ? (*vec)[idx] : ((*vecs)[idx].size()==dataLength ? (*vecs)[idx][i*nComponents+j] : 0.0));

	  // Write value for each vertex of each element.
	  if (fabs(val) < 1.e-40)
	    file << "0.0";
	  else
	    file << val;
416

417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
	  if (j < nComponents-1)
	    file << " ";
	}
	if (writeAs3dVector && writeAsVector && vecs != NULL) {
	  for (int j = nComponents; j < 3; j++)
	    file << " 0.0";
	}
	file << "\n";

	vc++;
	elInfo = stack.traverseNext(elInfo);
      }

      file << "        </DataArray>\n";
    }

    file << "      </CellData>\n";
434
435
436
    file << "    </Piece>\n";
    file << "  </UnstructuredGrid>\n";
    file << "</VTKFile>\n";
437
438
439
440
441
442

#if HAVE_PARALLEL_DOMAIN_AMDIS
    if (MPI::COMM_WORLD.Get_rank() == 0)
      VtkWriter::writeParallelFile(fname + ".pvtu", MPI::COMM_WORLD.Get_size(),
				   fname, ".vtu", 1);
#endif
443
  }
444
}
445
446