ElementFileWriter.cc 13.3 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
148
149
    if (writeParaViewAnimation)
      VtkWriter::updateAnimationFile(adaptInfo, 
				     (fn + vtkExt), 
				     &paraViewAnimationFrames, 
				     (filename + pvdExt));
150
151
  }

152

153
  void ElementFileWriter::writeFile(map<int, double> &vec,
154
				    Mesh *mesh,
155
				    string filename,
156
				    string postfix,
157
158
				    int level,
				    bool writeAsVector)
Thomas Witkowski's avatar
Thomas Witkowski committed
159
  {
160
    ElementFileWriter efw("", mesh, vec);
161
162
163
164
165
166
167
168
169
170
171
172
173
    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
174
175
176
  }
  

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

181
182
183
184
185
186
187
188
189
    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));
190

191
192
    int dim = mesh->getDim();
    double val;
193

194
    // === Write header. ===
195
196
197
198
199
200
    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";
201
202


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

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

212
    while (elInfo) {
213

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


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


240
    // === Write values. ===
241

242
    // Write values header.
243
244
245
246
247
248
249
250
    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";
251
252

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

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

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

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


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

280

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

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

290
291
292
293
294
295
296
297
298
#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

299
300
301
302
303
304
305
306
307
    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));
308
309
310

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

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

322
323
324
325
326
327
328
329
330
331
332
333
334
335
    // === 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++;
	}
336
      }
337
      elInfo = stack.traverseNext(elInfo);
338
    }
339

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

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

353
354
355
    file << "        </DataArray>\n";
    file << "      </Points>\n";
    file << "      <Cells>\n";
356

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


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

381
    file << "        <DataArray type=\"Int32\" Name=\"connectivity\">\n";
382
383
384
385
386
387
    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) << " ";
388
      }
389
      file << "\n";
390
      elInfo = stack.traverseNext(elInfo);
391
    }
392
393
    file << "        </DataArray>\n";
    file << "      </Cells>\n";
394

395
396
397
398
399
400
    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";
401

402
      file.setf(ios::scientific,ios::floatfield);
403

404
405
406
407
408
409
410
411
412
413
414
415
416
417
      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;
418

419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
	  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";
436
437
438
    file << "    </Piece>\n";
    file << "  </UnstructuredGrid>\n";
    file << "</VTKFile>\n";
439
440
441
442
443
444

#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
445
  }
446
}
447
448