Arh3Writer.cc 22.7 KB
Newer Older
Siqi Ling's avatar
Siqi Ling committed
1
2
3
#include <fstream>
#include <stdint.h>
#include <iostream>
4
#include <streambuf>
Siqi Ling's avatar
Siqi Ling committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

#include "Arh3Writer.h"
#include "Mesh.h"
#include "MeshStructure.h"
#include "Traverse.h"
#include "DOFVector.h"
#include "../Arh3Reader.h"

#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#ifdef HAVE_COMPRESSION
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#endif

namespace AMDiS { namespace io {
  
  using namespace std;

  namespace Arh3Writer
  {
    namespace detail
    {
      void write(string filename, 
  			DOFVector<double>* vec0, 
  			DOFVector<double>* vec1,
  			DOFVector<double>* vec2,
			bool writeParallel,
			Cpsformat cps,
			string dataformat,
35
			bool writeMacro)
Siqi Ling's avatar
Siqi Ling committed
36
37
38
39
40
41
42
43
44
      {
        vector<DOFVector<double>*> vecs(0);
        if (vec0 != NULL)
          vecs.push_back(vec0);
        if (vec1 != NULL)
          vecs.push_back(vec1);
        if (vec2 != NULL)
          vecs.push_back(vec2);

45
        write(filename, NULL, vecs, writeParallel, cps, dataformat, writeMacro);
Siqi Ling's avatar
Siqi Ling committed
46
47
48
      }
  
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS  
49
      void writeParallelFile(string filename, Mesh* mesh, bool createSubDir, bool writeMacro)
Siqi Ling's avatar
Siqi Ling committed
50
51
52
53
      {
	ofstream file;
        file.open(filename.c_str(), ios::out | ios::binary | ios::trunc);
	
54
55
56
57
	string typeId = "parh", macroFilename = "", perFilename = "";
	string baseDir = createSubDir ?  "./data/" : "";
	string macroData = "", periodicData = "";
	uint32_t baseDirLen = baseDir.length();
Siqi Ling's avatar
Siqi Ling committed
58
	Parameters::get(mesh->getName() + "->macro file name", macroFilename);
59
60
61
	Parameters::get(mesh->getName() + "->periodic file", perFilename);
	
	int major = 1, minor = 0;
Siqi Ling's avatar
Siqi Ling committed
62
	uint32_t nFiles = MPI::COMM_WORLD.Get_size();
63
	uint32_t macroFile_nl = 0;
Siqi Ling's avatar
Siqi Ling committed
64
65
	map<int, int> partitionMap = 
	  Parallel::MeshDistributor::globalMeshDistributor->getPartitionMap();
66
67
68
69
70
71
72
73
74
75
76
77
78
	uint32_t nMacros = partitionMap.size();
	
	typeId += '_' + boost::lexical_cast<string>(major) + '.' + boost::lexical_cast<string>(minor);
	if (typeId.length() <= 16) {	// 16 is the Id size
	  string rest(16 - typeId.length(), ' ');
	  typeId.append(rest);
	}
	else
	  ERROR_EXIT("Should not happen.\n");
	
	file.write(typeId.c_str(), 16);
	file.write(reinterpret_cast<char*>(&baseDirLen), 4);
	file.write(baseDir.c_str(), baseDirLen);
Siqi Ling's avatar
Siqi Ling committed
79
	file.write(reinterpret_cast<char*>(&nFiles), 4);
80
81
82
83
84
85
86
87
88
89
	
	if (writeMacro && macroFilename.length()) {
	  macroFile_nl = 13;
	  readFileToString(macroFilename, macroData);
	  
	  if (perFilename.length()) {
	    macroFile_nl = 27;
	    readFileToString(perFilename, periodicData);
	  }
	}
Siqi Ling's avatar
Siqi Ling committed
90
	file.write(reinterpret_cast<char*>(&macroFile_nl), 4);
91
	file.write(reinterpret_cast<char*>(&nMacros), 4);
Siqi Ling's avatar
Siqi Ling committed
92
93
94
95
96
97
98
	
	map<int, int>::const_iterator it = partitionMap.begin();
	uint32_t rank = 0;
	for (;it != partitionMap.end(); it++) {
	  rank = it->second;
	  file.write(reinterpret_cast<char*>(&rank), 4);
	}
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
	
	// write macro and periodic file
	if (writeMacro && macroFilename.length()) {
	  file.seekp(0, ios_base::end);
	  long macroPos = file.tellp(), perPos = 0;
	  file.write(macroData.c_str(), macroData.length());
	  
	  if (perFilename.length()) {
	    perPos = file.tellp();
	    file.write(periodicData.c_str(), periodicData.length());
	  }
	  
	  // update macroFile_nl
	  int offset = 16 +		//typeId
		       4 +		//baseDirLen
		       baseDirLen +	//baseDir
		       4 +		//nFiles
		       4;		//macroFile_nl
	  file.seekp(offset);
	  file << "this:" << macroPos;
	  if (perFilename.length())
	    file << ";this:" << perPos;
	}
Siqi Ling's avatar
Siqi Ling committed
122
123
124
125
126
127
128
129
130
      }
#endif

      void write(string filename, 
		 Mesh* mesh, 
		 vector<DOFVector<double>*> vecs,
		 bool writeParallel,
		 Cpsformat cps,
		 string dataformat,
131
		 bool writeMacro)
Siqi Ling's avatar
Siqi Ling committed
132
133
134
135
136
137
      {
	FUNCNAME("Arh3Writer::detail::write()");
	
	map<string,Valformat>::const_iterator it = dataformatMap.find(dataformat);
	TEST_EXIT(it != dataformatMap.end())("Wrong data format.\n");
	
138
139
140
141
142
	std::set<Mesh*> meshset;
	std::set<string> nameset;
	if (mesh)
	  meshset.insert(mesh);
	for (size_t i = 0; i < vecs.size(); i++) {
Siqi Ling's avatar
Siqi Ling committed
143
	  TEST_EXIT(vecs[i] != NULL)("Vecs[%i] is NULL. Please check.\n", i);
144
145
146
	  meshset.insert(vecs[i]->getFeSpace()->getMesh());
	  nameset.insert(vecs[i]->getName());
	}
Siqi Ling's avatar
Siqi Ling committed
147
	  
148
149
150
	if (meshset.size() == 0) {
	  WARNING("There is nothing to be writen.\n");
	  return;
Siqi Ling's avatar
Siqi Ling committed
151
	}
152
153
154
155
156
157
	
	TEST_EXIT(nameset.size() == vecs.size())
	  ("DOFVectors in vecs cannot have idential name. Please check.\n");
	
	bool multiMesh = meshset.size() > 1;
	
Siqi Ling's avatar
Siqi Ling committed
158
	//if mesh exists, the meshes in vecs should be the same.
159
160
	if (mesh) {
	  for (size_t i = 0; i < vecs.size(); i++)
Siqi Ling's avatar
Siqi Ling committed
161
	    TEST_EXIT(mesh == vecs[i]->getFeSpace()->getMesh())
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
	      ("The mesh of DOFVector %i in vecs is not equal to the second parameter.\n", i);
	  writeAux(filename, mesh, vecs, writeParallel, cps, dataformat, writeMacro); 
	} else {
	  if (!multiMesh)
	    writeAux(filename, vecs[0]->getFeSpace()->getMesh(), vecs, writeParallel, cps, dataformat, writeMacro); 
	  else {
	    vector<bool> visited(vecs.size(), false);
	    vector<DOFVector<double>*> splitedVecs(0);
	    Mesh* tmpMesh = NULL;
	  
	    for(size_t i = 0; i < vecs.size(); i++) {
	      if(!visited[i]) {
		splitedVecs.clear();
		splitedVecs.push_back(vecs[i]);
		visited[i] = true;
		tmpMesh = vecs[i]->getFeSpace()->getMesh();
		for(size_t j = i + 1; j < vecs.size(); j++)
		  if(vecs[j]->getFeSpace()->getMesh() == tmpMesh)
		  {
		    splitedVecs.push_back(vecs[j]);
		    visited[j] = true;
		  }
Siqi Ling's avatar
Siqi Ling committed
184
185
	      }
	      string newfilename = filename;
186
187
188
189
190
191
192
193
194
195
196
197
198
	      if(filename.length() > 4 && filename.substr(filename.length()- 4, filename.length()) == ".arh")
		newfilename = filename.substr(0, filename.length() - 4) +
		  "." + tmpMesh->getName() + filename.substr(filename.length()-4 , filename.length());
	      else
		newfilename = filename + "." + tmpMesh->getName() + ".arh";
		
	      writeAux(newfilename, 
		       splitedVecs[0]->getFeSpace()->getMesh(), 
		       splitedVecs, 
		       writeParallel, 
		       cps, 
		       dataformat,
		       writeMacro); 
Siqi Ling's avatar
Siqi Ling committed
199
200
201
202
203
204
205
206
207
208
209
210
211
	    }
	  }
        }        
      }
  
      int writeHeader(ofstream& file,
                               Mesh *mesh,
                               vector<DOFVector<double>*> vecs,
                               map<const FiniteElemSpace*, vector<int> >& feSpaces,
			       Cpsformat cps,
			       string dataformat)
      {
        FUNCNAME("Arh3Writer::detail::writeHeader()");
212
// 	int nbits = boost::lexical_cast<int>(dataformat.substr(2, 2));
Siqi Ling's avatar
Siqi Ling committed
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
        TEST_EXIT(file.is_open())("the file is not open. should not happen.\n");
	
	map<const FiniteElemSpace*, string> AFEDfileName;
	
        uint32_t valueNamesLen = 0, fileNamesLen = 0;
        for (size_t i = 0; i < vecs.size(); i++)
          valueNamesLen += vecs[i]->getName().length();
	
	map<const FiniteElemSpace*, vector<int> >::iterator feSpaceIt;
	for (feSpaceIt = feSpaces.begin(); feSpaceIt != feSpaces.end(); feSpaceIt++)
	  AFEDfileName.insert(make_pair(feSpaceIt->first, string()));
    
        uint32_t nValueVectors = vecs.size();
        uint32_t nFeSpaces = feSpaces.size();
	uint32_t nMacroElements = mesh->getNumberOfMacros();
	
	uint32_t nMacro = 0;
	TraverseStack st;
	ElInfo *el = st.traverseFirst(mesh, 0, Mesh::CALL_EL_LEVEL);
	while (el) {
	  nMacro++;
	  el = st.traverseNext(el);
	}
	
        uint32_t dow = mesh->getGeo(WORLD);
        uint32_t dim = mesh->getDim();
        uint32_t headerLen = 34 +                         //fixed part of header 
			     nMacroElements * 12 + 12 +   //macroElemnts table
			     fileNamesLen +		  //feSpaces table
			     nFeSpaces * 20 + 	          //feSpaces table
			     valueNamesLen + 	          //value vector table
244
245
			     nValueVectors * 12 +         //also value vector table
			     4;				  //macroFile_nl
Siqi Ling's avatar
Siqi Ling committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
        string typeId = "sarh";
#ifndef HAVE_COMPRESSION
	cps = NONE;
#endif
        uint8_t *major = const_cast<uint8_t*>(&(AMDiS::io::Arh3Reader::MAJOR)); 
        uint8_t *minor = const_cast<uint8_t*>(&(AMDiS::io::Arh3Reader::MINOR));
	int cpsflag = static_cast<int>(cps);
	uint32_t minus1 = -1;
        
	//fixed header
        file.write(typeId.c_str(), 4);
        file.write(reinterpret_cast<char*>(major), 1);
        file.write(reinterpret_cast<char*>(minor), 1);
        file.write(reinterpret_cast<char*>(&headerLen), 4);
        file.write(reinterpret_cast<char*>(&dow), 4);
        file.write(reinterpret_cast<char*>(&dim), 4);
        file.write(reinterpret_cast<char*>(&nFeSpaces), 4);
        file.write(reinterpret_cast<char*>(&nValueVectors), 4);
        file.write(reinterpret_cast<char*>(&nMacroElements), 4);
	file.write(reinterpret_cast<char*>(&cpsflag), 4);
	//macro table
	deque<MacroElement*>::const_iterator macroIter = mesh->firstMacroElement();
	
	while(macroIter != mesh->endOfMacroElements())
	{
	  uint32_t macroIndex = (*macroIter)->getIndex();
	  file.write(reinterpret_cast<char*>(&macroIndex), 4);
	  file.write(reinterpret_cast<char*>(&minus1), 4);
	  file.write(reinterpret_cast<char*>(&minus1), 4);
	  macroIter++;
	}
	file.write(reinterpret_cast<char*>(&minus1), 4);
	file.write(reinterpret_cast<char*>(&minus1), 4);
	file.write(reinterpret_cast<char*>(&minus1), 4);
	
	vector<int> feSpaceNumOfVecs(vecs.size());
	uint32_t posDOFs = 0, nameStrLen = 0;
	string nameStr("");
	size_t i = 0;
	
	//feSpace table
	for(feSpaceIt = feSpaces.begin(); feSpaceIt != feSpaces.end(); feSpaceIt++, i++)
	{
	  nameStr = AFEDfileName[feSpaceIt->first];
	  nameStrLen = nameStr.length();
	  file.write(reinterpret_cast<char*>(&nameStrLen), 4);
	  file.write(nameStr.c_str(), nameStrLen);
	  DimVec<int>* nDOF = feSpaceIt->first->getBasisFcts()->getNumberOfDofs();
	  //
295
	  for(int j = 1; j < nDOF->getSize(); j++) {
Siqi Ling's avatar
Siqi Ling committed
296
297
298
            posDOFs = (*nDOF)[j];
            file.write(reinterpret_cast<char*>(&posDOFs), 4);
          }
299
          for(int j = nDOF->getSize(); j < 4 ; j++) {
Siqi Ling's avatar
Siqi Ling committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
            posDOFs = 0;
            file.write(reinterpret_cast<char*>(&posDOFs), 4);
          }
          posDOFs = (*nDOF)[0];
	  file.write(reinterpret_cast<char*>(&posDOFs), 4);
	  //
          for(size_t j = 0; j < feSpaceIt->second.size(); j++)
	    feSpaceNumOfVecs[feSpaceIt->second[j]] = i;
	}
	
	//vector table
        for(i = 0; i < vecs.size(); i++)
        {
          nameStr = vecs[i]->getName();
          nameStrLen = nameStr.length();
          file.write(reinterpret_cast<char*>(&nameStrLen), 4);
          file.write(nameStr.c_str(), nameStrLen);
	  file.write(reinterpret_cast<char*>(&feSpaceNumOfVecs[i]), 4);
	  file.write(dataformat.c_str(), 4);
        }
320
321
322
        
        uint32_t macroFile_nl = 0;
        file.write(reinterpret_cast<char*>(&macroFile_nl), 4);
Siqi Ling's avatar
Siqi Ling committed
323
324
325
326
327
328
329
        return headerLen;
      }
 
      void writeAux(string filename, Mesh *mesh,
                        vector<DOFVector<double>*> vecs,
                        bool writeParallel,
			Cpsformat cps,
330
331
			string dataformat,
			bool writeMacro)
Siqi Ling's avatar
Siqi Ling committed
332
333
334
      {
        FUNCNAME("Arh3Writer::detail::writeAux()");
	
335
336
	TEST_EXIT(mesh)("empty mesh.\n");
	
Siqi Ling's avatar
Siqi Ling committed
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
        //initialization
        ofstream file;
        file.open(filename.c_str(), ios::out | ios::binary | ios::trunc);

        map<const FiniteElemSpace*, vector<int> > sortedFeSpaces;
	map<const FiniteElemSpace*, vector<int> >::iterator feSpaceIt;
        vector<pair<int, int> > macroSize; // (uncompressed size, compressed size)
        
        DegreeOfFreedom globalDof;  
        size_t i = 0, j = 0;
    
        for(i = 0; i < vecs.size(); i++)
	{
          sortedFeSpaces[vecs[i]->getFeSpace()].push_back(i);
	}
	vector<std::set<DegreeOfFreedom> > visited(sortedFeSpaces.size());
	pair<std::set<DegreeOfFreedom>::iterator,bool> ret;
        //file header information 
        int headerLen = writeHeader(file, mesh, vecs, sortedFeSpaces, cps, dataformat);
    
        //macro elements information
        MeshStructure elementStructure;
        vector<vector<double> > values(vecs.size());
        int32_t macroElIndex = -1;
    
        TraverseStack stack;
        ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_EVERY_EL_PREORDER);
        while (elInfo) {
          if (elInfo->getLevel() == 0) {
            if (macroElIndex != -1) {
              elementStructure.commit();
	      macroSize.push_back(writeMacroElement(file, elementStructure, values, sortedFeSpaces, cps, dataformat));
            }
	    elementStructure.clear();
 	
	    macroElIndex = elInfo->getElement()->getIndex();
	    
	    for (j = 0; j < vecs.size(); j++)
	      values[j].clear();
	    
            for (j = 0; j < sortedFeSpaces.size(); j++)
              visited[j].clear();
          }
          elementStructure.insertElement(elInfo->getElement()->isLeaf());
      
          if (elInfo->getElement()->isLeaf()) 
          {
            int valuePos = 0;
            for(feSpaceIt = sortedFeSpaces.begin(), i = 0; feSpaceIt != sortedFeSpaces.end(); feSpaceIt++, i++)
            {
              DOFAdmin* admin = feSpaceIt->first->getAdmin();
              TEST_EXIT(admin)("the DOFAdmin of DOFVector is null, this should not happen.\n");       
  
              int n0, nd, nd0;

              if ((nd = admin->getNumberOfDofs(VERTEX)))  {                                                      
                int vertices = mesh->getGeo(VERTEX);
                nd0 = admin->getNumberOfPreDofs(VERTEX);                                                         
                n0 = mesh->getNode(VERTEX); //                                                          
                for (int n = 0; n < vertices; n++)
                  for(int d = 0; d < nd; d++)
                  {
                    globalDof = elInfo->getElement()->getDof(n0 + n, nd0 + d);
                    ret = visited[i].insert(globalDof);
                    if(ret.second)
                    {
                      for(j = 0 ; j < feSpaceIt->second.size(); j++)
                      {
                        values[valuePos + j].push_back((*vecs[feSpaceIt->second[j]])[globalDof]);
                      }
                    }
                  }
              }
              if (mesh->getDim() > 1) {
                if ((nd = admin->getNumberOfDofs(EDGE)))  {                                                      
                  int edges = mesh->getGeo(EDGE); 
                  nd0 = admin->getNumberOfPreDofs(EDGE);                                                         
                  n0 = mesh->getNode(EDGE);                                                          
                  for (int n = 0; n < edges; n++)
                  for(int d = 0; d < nd; d++)
                  {
                    globalDof = elInfo->getElement()->getDof(n0 + n, nd0 + d);
                    ret = visited[i].insert(globalDof);
                    if(ret.second)
                    {
                      for(j = 0 ; j < feSpaceIt->second.size(); j++)
                      {
                        values[valuePos + j].push_back((*vecs[feSpaceIt->second[j]])[globalDof]);
                      }
                    }
                  }
                }
              }
              if (mesh->getDim() == 3) {
                if ((nd = admin->getNumberOfDofs(FACE)))  {                                                      
                  int faces = mesh->getGeo(FACE);
                  nd0 = admin->getNumberOfPreDofs(FACE);                                                         
                  n0 = mesh->getNode(FACE);                                                          
                  for (int n = 0; n < faces; n++)
                  for(int d = 0; d < nd; d++)
                  {
                    globalDof = elInfo->getElement()->getDof(n0 + n, nd0 + d);
                    ret = visited[i].insert(globalDof);
                    if(ret.second)
                    {
                      for(j = 0 ; j < feSpaceIt->second.size(); j++)
                      {
                        values[valuePos + j].push_back((*vecs[feSpaceIt->second[j]])[globalDof]);
                      }
                    }
                  }
                }
              }                                   
              if ((nd = admin->getNumberOfDofs(CENTER)))  {                                                      
                nd0 = admin->getNumberOfPreDofs(CENTER);                                                         
                n0 = mesh->getNode(CENTER);      
                for(int d = 0; d < nd; d++)
                {
                  globalDof = elInfo->getElement()->getDof(n0, nd0 + d);
                  ret = visited[i].insert(globalDof);
                    if(ret.second)
                    {
                      for(j = 0 ; j < feSpaceIt->second.size(); j++)
                      {
                        values[valuePos + j].push_back((*vecs[feSpaceIt->second[j]])[globalDof]);
                      }
                    }
                }
              }
              valuePos += feSpaceIt->second.size();
            }//feSpace loop
          }//isLeaf

          elInfo = stack.traverseNext(elInfo);
        }
        // And write the last macro element to file.
        TEST_EXIT_DBG(macroElIndex != -1)("Should not happen!\n");
        elementStructure.commit();
	macroSize.push_back(writeMacroElement(file, elementStructure, values, sortedFeSpaces, cps, dataformat));
	TEST_EXIT(macroSize.size() == (unsigned)mesh->getNumberOfMacros())("Should not happen.\n");
	//reset the macro positions in file
	setMacrosPos(file, headerLen, macroSize);
479
480
	if (writeMacro)
	  setMacroFile(file, headerLen, mesh);
Siqi Ling's avatar
Siqi Ling committed
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
        file.close();
        MSG("ARH file written to: %s\n", filename.c_str());
      }
      
      void setMacrosPos(ofstream& file, int headerLen,
	                    vector<pair<int, int> >& macroSize)
      {
	file.seekp(34);
	long pos = 0;
	int startPos = headerLen;
	for(size_t i = 0; i < macroSize.size(); i++)
	{
	  pos = file.tellp();
	  file.seekp(pos + 4);
	  file.write(reinterpret_cast<char*>(&startPos), 4);
	  file.write(reinterpret_cast<char*>(&macroSize[i].first), 4);
	  startPos += macroSize[i].second;
	}
	pos = file.tellp();
	file.seekp(pos + 4);
	file.write(reinterpret_cast<char*>(&startPos), 4);
      }
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
      
      void setMacroFile(std::ofstream& file, int headerLen, Mesh* mesh)
      {
	string macroFilename = "", perFilename = "";
	string macroData = "", periodicData = "";
	
	Parameters::get(mesh->getName() + "->macro file name", macroFilename);
	Parameters::get(mesh->getName() + "->periodic file", perFilename);
	
	if (!macroFilename.length()) {
	  WARNING("macro file not found.\n");
	  return;
	}
	
	// write macro file to the end
	readFileToString(macroFilename, macroData);
	file.seekp(0, ios_base::end);
	long macroPos = file.tellp(), perPos = 0;
	file.write(macroData.c_str(), macroData.length());
	
	// write periodic file to the end
	if (perFilename.length()) {
	  readFileToString(perFilename, periodicData);
	  perPos = file.tellp();
	  file.write(periodicData.c_str(), periodicData.length());
	}
	
	// update macroFile_nl
	uint32_t macroFile_nl = perFilename.length() ? 27 : 13;
	file.seekp(headerLen - 4);
	file.write(reinterpret_cast<char*>(&macroFile_nl), 4);
	file << "this:" << macroPos;
	if (perFilename.length())
	  file << ";this:" << perPos;
	
	// update headerLen
	headerLen += macroFile_nl;
	file.seekp(6);
	file.write(reinterpret_cast<char*>(&headerLen), 4);
      }
      
      void readFileToString(std::string filename, std::string& data)
      {
	ifstream file(filename.c_str());
	file.seekg(0, std::ios::end);
	data.reserve(file.tellg());
	file.seekg(0, std::ios::beg);
	data.assign((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
      }
Siqi Ling's avatar
Siqi Ling committed
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
  
      pair<int, int> writeMacroElement(ofstream &file, 
				    MeshStructure &code,
				    vector<vector<double> >& values,
                                    map<const FiniteElemSpace*, vector<int> >& feSpaces,
				    Cpsformat cps,
				    string dataformat)
      {
	stringstream dataStream(ios::out | ios::in | ios::binary);
    
        uint32_t nStructureCodes = code.getCode().size();
        dataStream.write(reinterpret_cast<char*>(&nStructureCodes), 4);
    
        uint32_t codeSize = code.getNumElements();
        dataStream.write(reinterpret_cast<char*>(&codeSize), 4);

        dataStream.write(reinterpret_cast<char*>(&(const_cast<vector<uint64_t>&>(code.getCode())[0])), 
	       8 * nStructureCodes);
	
        if (values.size() > 0) {
	  int moreSize = 0, valuePos = 0;
          map<const FiniteElemSpace*, vector<int> >::iterator it; 
          for(it = feSpaces.begin(); it != feSpaces.end(); it++)
          {
            uint32_t nValuesPerVector = values[valuePos].size();
            dataStream.write(reinterpret_cast<char*>(&nValuesPerVector), 4);
	    moreSize += 4;
	    
            for (size_t i = 0; i < it->second.size(); i++)
	      moreSize += writeValues(dataStream, dataformat, values[valuePos + i]);
	    
            valuePos += it->second.size();
          }
        }
	stringstream tmp(ios::out | ios::in | ios::binary);
        boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
#ifdef HAVE_COMPRESSION
	switch(cps)
	{
	  case ZLIB: 
	    in.push(boost::iostreams::zlib_compressor());
	    break;
	  case BZIP2:
	    in.push(boost::iostreams::bzip2_compressor());
	    break;
	  case NONE:
	    break;
	  default:
	    MSG("NOT correct compression flag.\n");
	}
#endif
	in.push(dataStream);
	boost::iostreams::copy(in, tmp);
	file << tmp.rdbuf();
        return make_pair(dataStream.str().length(), tmp.str().length());
      }
      
      template<typename T>
      int writeValues(stringstream& file, vector<double>& values)
      {
612
613
	size_t size = values.size();
	T* data = new T[size];
Siqi Ling's avatar
Siqi Ling committed
614
615
616
617
	for (size_t i = 0; i < size; i++)
	  data[i] = static_cast<T>(values[i]);
	
	file.write(reinterpret_cast<char*>(&data[0]), sizeof(T) * size);
618
	delete [] data;
Siqi Ling's avatar
Siqi Ling committed
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
	return sizeof(T) * size;
      }
      
      int writeValues(stringstream& file,
		       string dataformat, 
		       vector<double>& values)
      {
	FUNCNAME("Arh3Writer::detail::writeValues()");
	int newsize = 0;
	std::map<string,Valformat>::const_iterator it = dataformatMap.find(dataformat);
	
	TEST_EXIT(it != dataformatMap.end())("Wrong data format.\n");
	
	switch(it->second) {
	  case SI08:
	    newsize = writeValues<int8_t>(file, values);
	    break;
	  case SI16:
	    newsize = writeValues<int16_t>(file, values);
	    break;
	  case SI32:
	    newsize = writeValues<int32_t>(file, values);
	    break;	    
	  case SI64:
	    newsize = writeValues<int64_t>(file, values);
	    break;	
	  case UI08:
	    newsize = writeValues<uint8_t>(file, values);
	    break;	  
	  case UI16:
	    newsize = writeValues<uint16_t>(file, values);
	    break;
	  case UI32:
	    newsize = writeValues<uint32_t>(file, values);
	    break;	  
	  case UI64:
	    newsize = writeValues<uint64_t>(file, values);
	    break;
	  case SF32:
	    newsize = writeValues<float>(file, values);
	    break;	
	  case SF64:
	    newsize = writeValues<double>(file, values);
	    break;
	  default:
	    ERROR_EXIT("Wrong data format.\n");
	}
	return newsize;
      }
    }//end namespace detail
  } // end namespace Arh3Writer
} } // end namespace io, AMDiS