Arh3Reader.cc 26.1 KB
Newer Older
Siqi Ling's avatar
Siqi Ling committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "Arh3Reader.h"
#include "Mesh.h"
#include "MeshStructure.h"
#include "Traverse.h"
#include "DOFVector.h"
#include "SystemVector.h"
#include "Debug.h"
#include "../Arh3Reader.h"
#include "Arh3Writer.h"

#include <boost/filesystem.hpp>
#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 Arh3Reader
  {
    namespace detail
    {
27
28
29
30
31
32
33
      void firstRead(std::string id_, uint8_t major_, uint8_t minor_, //version in file
		     std::string id, uint8_t major, uint8_t minor)   //class version
      {
	TEST_EXIT(id == id_)
	  ("Cannot read Arh format: this file is not \"%s\" format.\n", id.c_str());
	  
	TEST_EXIT(major == major_)
Siqi Ling's avatar
Siqi Ling committed
34
	  ("Cannot read Arh format: Arh3Reader major version is %i, the file major version is %i. \n",
35
36
37
	  major, major_);
	  
	TEST_EXIT(minor >= minor_)
Siqi Ling's avatar
Siqi Ling committed
38
	  ("Cannot read Arh format: Arh3Reader minor version is %i is smaller than the file minor version %i.\n", 
39
40
	  minor, minor_);
      }
Siqi Ling's avatar
Siqi Ling committed
41
42
43
44
45
46
47
48
49
      
      void firstRead(ifstream& file, string id, uint8_t major, uint8_t minor)
      {
	FUNCNAME("Arh3Reader::detail::firstRead");
	
	uint8_t major_ = 0;
	uint8_t minor_ = 0;
	string typeId(4, ' ');
    
50
	file.read(&typeId[0], 4);
Siqi Ling's avatar
Siqi Ling committed
51
52
	file.read(reinterpret_cast<char*>(&major_), 1);
	file.read(reinterpret_cast<char*>(&minor_), 1);
53
54
	
	firstRead(typeId, major_, minor_, id, major, minor);
Siqi Ling's avatar
Siqi Ling committed
55
56
57
58
59
60
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
      }
      
      void setDofValues(int macroElIndex, Mesh *mesh,
			     vector<vector<double> >& values, 
                             vector<DOFVector<double>*>& vecs,
                             vector<vector<int> >& feSpaces)
      {
	if(vecs.size() == 0)
	  return;

	std::set<int> unique;
	std::pair<std::set<int>::iterator,bool> ret;
	std::vector<std::set<int> > visited;
	std::vector<int> dofIndex;
	int globalDof = 0; 

	for(size_t i = 0; i < feSpaces.size(); i++)
	{
	  visited.push_back(unique);
	  dofIndex.push_back(0);
	}

	TraverseStack stack;
	ElInfo *elInfo = stack.traverseFirstOneMacro(mesh, macroElIndex, -1, 
						    Mesh::CALL_EVERY_EL_PREORDER);
	while (elInfo) {
	  Element *el = elInfo->getElement();
	  if (el->isLeaf())
	  {
	    int valuePos = 0;
	    for(size_t i = 0; i < feSpaces.size(); i++)
	    {
	      int num = -1;
	      for(size_t j = 0; j < feSpaces[i].size(); j++)
	      {
		if((vecs.size() > (unsigned)feSpaces[i][j]) && vecs[feSpaces[i][j]])
		{
		  num = feSpaces[i][j];
		  break;
		}
	      }
	      if(num == -1)
	      {
		valuePos += feSpaces[i].size();
		continue;
	      }
	      DOFAdmin* admin = vecs[num]->getFeSpace()->getAdmin(); 
	      TEST_EXIT(admin)("the DOFAdmin of DOFVector is null, this should not happen.");

	      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(size_t j = 0 ; j < feSpaces[i].size(); j++)
		      {
			if((vecs.size() > (unsigned)feSpaces[i][j]) && vecs[feSpaces[i][j]])
			{
			  (*vecs[feSpaces[i][j]])[globalDof] = values[valuePos + j][dofIndex[i]];
			}
		      }
		      dofIndex[i]++;
		    }
		  }
	      }
	      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(size_t j = 0 ; j < feSpaces[i].size(); j++)
		      {
			if((vecs.size() > (unsigned)feSpaces[i][j]) && vecs[feSpaces[i][j]])
			  (*vecs[feSpaces[i][j]])[globalDof] = values[valuePos + j][dofIndex[i]];
		      }
		      dofIndex[i]++;
		    }
		  }
		}
	      }
	      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(size_t j = 0 ; j < feSpaces[i].size(); j++)
		      {
			if((vecs.size() > (unsigned)feSpaces[i][j]) && vecs[feSpaces[i][j]])
			  (*vecs[feSpaces[i][j]])[globalDof] = values[valuePos + j][dofIndex[i]];
		      }
		      dofIndex[i]++;
		    }
		  }
		}
	      }
	      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(size_t j = 0 ; j < feSpaces[i].size(); j++)
		    {
		      if((vecs.size() > (unsigned)feSpaces[i][j]) && vecs[feSpaces[i][j]])
			(*vecs[feSpaces[i][j]])[globalDof] = values[valuePos + j][dofIndex[i]];
		    }
		    dofIndex[i]++;    
		  }
		}
	      }
	      valuePos += feSpaces[i].size();
	    }
	  }                                                                                         
	  elInfo = stack.traverseNext(elInfo);
	} 
      }
      
      void read(string filename,
                         Mesh *mesh,
                         vector<DOFVector<double>*> vecs,
                         bool byName)
       {
	FUNCNAME("Arh3Reader::detail::read()");
	
	using namespace ::AMDiS::io::Arh3Writer;

	// Get set of all macro elements in mesh.
	std::set<int> macroInMesh;
	for (std::deque<MacroElement*>::iterator it = mesh->getMacroElements().begin();
	    it != mesh->getMacroElements().end(); ++it)
	  macroInMesh.insert((*it)->getIndex());

	RefinementManager *refManager = NULL;
	switch (mesh->getDim()) {
	case 1:
	  refManager = new RefinementManager1d();
	  break;
	case 2:
	  refManager = new RefinementManager2d();
	  break;
	case 3:
	  refManager = new RefinementManager3d();
	  break;
	default:
	  ERROR_EXIT("Should not happen!\n");
	}
	ifstream file;
	file.open(filename.c_str(), ios::in | ios::binary);
	TEST_EXIT(file.is_open())
	  ("Cannot open file %s\n", filename.c_str());
      
231
	Cpsformat::Value cps = Cpsformat::NONE;
Siqi Ling's avatar
Siqi Ling committed
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
	uint32_t headerLen = 0;
	uint32_t nMacroElements = 0;
	uint32_t nValueVectors = 0;
	uint32_t nFeSpaces = 0;
	uint32_t dim = 0, dow = 0;
	int cpsflag = 0;

	// Read fixed header
	firstRead(file, "sarh", MAJOR, MINOR);
      
	file.read(reinterpret_cast<char*>(&headerLen), 4);
	file.read(reinterpret_cast<char*>(&dow), 4);
	file.read(reinterpret_cast<char*>(&dim), 4);
	file.read(reinterpret_cast<char*>(&nFeSpaces), 4);
	file.read(reinterpret_cast<char*>(&nValueVectors), 4);
	file.read(reinterpret_cast<char*>(&nMacroElements), 4);
	file.read(reinterpret_cast<char*>(&cpsflag), 4);
249
	cps = static_cast<Cpsformat::Value>(cpsflag);
Siqi Ling's avatar
Siqi Ling committed
250
251
	
#ifdef HAVE_COMPRESSION
252
253
254
	TEST_EXIT(cps == Cpsformat::ZLIB  || 
		  cps == Cpsformat::BZIP2 ||
		  cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
255
	  ("Cannot read Arh3 file. Currently only support zlib and bzip2 compression.\n");
Siqi Ling's avatar
Siqi Ling committed
256
#else
257
	TEST_EXIT(cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
258
	  ("HAVE_COMPRESSION OFF. Cannot read compressed Arh3 file.\n");	
Siqi Ling's avatar
Siqi Ling committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#endif
	  
	TEST_EXIT(dow == (unsigned)mesh->getGeo(WORLD))
	  ("Dow is not match!\n");
	TEST_EXIT(dim == (unsigned)mesh->getDim())
	  ("Dim is not match!\n");
	TEST_EXIT(nValueVectors >= vecs.size())
	  ("File %s has %d vector(s), which is less than the number of DOFVectors %i in vecs!\n",
	   filename.c_str(), nValueVectors, vecs.size());

	vector<string> vecsName;
	
	vector<int> filesNameLen;
	vector<string> filesName;
	
	vector<int> vecsFeSpaceNum;
	vector<string> dataformat;
	vector<int> macroElIndex(nMacroElements);
	vector<pair<int,int> > macroElSize(nMacroElements); // pos, uncompressed size
Siqi Ling's avatar
Siqi Ling committed
278
	int fileSize = 0, feSpacesNamesLen = 0, valueNamesLen = 0;
Siqi Ling's avatar
Siqi Ling committed
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
	
	vector<vector<int> > feSpaceDOFs;
	vector<string> AFEDfileName(nFeSpaces);
	vector<int> perDOFs(4, 0);
	vector<vector<int> > sortedFeSpaces(nFeSpaces);
	
	// Read macro table
	for(size_t i = 0; i < nMacroElements; i++)
	{
	  file.read(reinterpret_cast<char*>(&macroElIndex[i]), 4);
	  file.read(reinterpret_cast<char*>(&macroElSize[i].first), 4);
	  file.read(reinterpret_cast<char*>(&macroElSize[i].second), 4);
	}
	file.seekg(4, ios_base::cur);
	file.read(reinterpret_cast<char*>(&fileSize), 4);
	file.seekg(4, ios_base::cur);
	// Read feSpace table
	for(size_t i = 0; i < nFeSpaces; i++)
	{
	  uint32_t tmpInt = 0;
	  file.read(reinterpret_cast<char*>(&tmpInt), 4);
300
	  file.read(&AFEDfileName[i][0], tmpInt);
Siqi Ling's avatar
Siqi Ling committed
301
	  feSpacesNamesLen += tmpInt;
Siqi Ling's avatar
Siqi Ling committed
302
303
304
305
306
307
308
309
310
311
312
313
	  for(int j = 0; j < 4; j++)
	  {
	    file.read(reinterpret_cast<char*>(&perDOFs[j]), 4);
	  }
	  feSpaceDOFs.push_back(perDOFs);
	}
	// Read value table
	for(size_t i = 0; i < nValueVectors; i++)
	{
	  string tmpString("");
	  uint32_t tmpInt = 0;
	  file.read(reinterpret_cast<char*>(&tmpInt), 4);
Siqi Ling's avatar
Siqi Ling committed
314
	  valueNamesLen += tmpInt;
Siqi Ling's avatar
Siqi Ling committed
315
	  tmpString.resize(tmpInt, ' ');
316
	  file.read(&tmpString[0], tmpInt); //
Siqi Ling's avatar
Siqi Ling committed
317
318
319
320
321
	  vecsName.push_back(tmpString);
	  file.read(reinterpret_cast<char*>(&tmpInt), 4);
	  sortedFeSpaces[tmpInt].push_back(i);
	  vecsFeSpaceNum.push_back(tmpInt);
	  tmpString.resize(4, ' ');
322
	  file.read(&tmpString[0], 4);
Siqi Ling's avatar
Siqi Ling committed
323
	  dataformat.push_back(tmpString);
324
325
	}
	
Siqi Ling's avatar
Siqi Ling committed
326
327
328
329
330
331
332
333
334
335
	int headerLen_= 34 + 
			nMacroElements * 12 + 12 +
			feSpacesNamesLen +
			nFeSpaces * 20 +
			valueNamesLen +
			nValueVectors * 12;
			
	TEST_EXIT_DBG(headerLen_ <= headerLen) 
	  ("Header length (without macro file name) is already larger than the header specified in the file.\n");
	
336
	// Read macroFile_nl //TODO
Siqi Ling's avatar
Siqi Ling committed
337
338
339
340
341
342
343
344
	if (headerLen_ < headerLen) {
	  uint32_t macroFile_nl = 0;
	  file.read(reinterpret_cast<char*>(&macroFile_nl), 4);
	  if (macroFile_nl > 0) {
	    string tmpString("");
	    tmpString.resize(macroFile_nl, ' ');
	    file.read(&tmpString[0], macroFile_nl);
	  }
345
346
347
	}
	//================header is over==================//
	
Siqi Ling's avatar
Siqi Ling committed
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
	// Adjust and check vecs
	if(byName)
	{
	  if(!vecs.empty())
	  {
	    vector<DOFVector<double>*> tmpVecs = vecs;
	    vecs.clear();
	    vecs.resize(nValueVectors, NULL);
	    
	    for(size_t k = 0; k < tmpVecs.size(); k++)
	    {
	      if(!tmpVecs[k])
		break;
	      
	      size_t i;
	      TEST_EXIT(tmpVecs[k]->getFeSpace()->getAdmin())
		("Vecs number %i has no DOFAdmin. Should not happen.\n", k);
	      DimVec<int>* nDOF = tmpVecs[k]->getFeSpace()->getBasisFcts()->getNumberOfDofs();
	      
	      for(i = 0; i < nValueVectors; i++) {
		
		if(tmpVecs[k]->getName() != vecsName[i])  
		  continue;
		
		bool matchdof = true;
		if ((*nDOF)[0] != feSpaceDOFs[vecsFeSpaceNum[i]][3])
		  matchdof = false;
		else {
376
		  for(int j = 1; j < nDOF->getSize(); j++) {
Siqi Ling's avatar
Siqi Ling committed
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
		    if((*nDOF)[j] != feSpaceDOFs[vecsFeSpaceNum[i]][j-1]){
		      matchdof = false;
		      break;
		    }
		  }
		}
		if(matchdof) {
		  vecs[i] = tmpVecs[k];
		  break;
		}
	      }
	      TEST_EXIT(i < nValueVectors)
		("NO DOFVector with the same name and feSpace is found in the file.\n");
	    }
	  }
	}
	else
	{
	  for(size_t i = 0; i < vecs.size(); i++) {
	    if(vecs[i]) {
	      
	      TEST_EXIT(vecs[i]->getFeSpace()->getAdmin())
	      ("Vecs number %i has no DOFAdmin. Should not happen.\n", i);
    
	      DimVec<int>* nDOF = vecs[i]->getFeSpace()->getBasisFcts()->getNumberOfDofs();
	      
	      TEST_EXIT((*nDOF)[0] == feSpaceDOFs[vecsFeSpaceNum[i]][3])
		  ("The fespace of vec number %i is not equal to the correspond fespace.\n", i+1);
405
	      for(int j = 1; j < nDOF->getSize(); j++)
Siqi Ling's avatar
Siqi Ling committed
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
		TEST_EXIT((*nDOF)[j] == feSpaceDOFs[vecsFeSpaceNum[i]][j-1])
		  ("The fespace of vec number %i is not equal to the correspond fespace.\n", i+1);
	    }
	  }
	}
	// Read data: meshstructure and dof values
	for (size_t i = 0; i < nMacroElements; i++) {
	  stringstream dataStream(ios::out | ios::in | ios::binary);
	  int size = (i == nMacroElements - 1) ?  fileSize - macroElSize[i].first
	    : (macroElSize[i+1].first - macroElSize[i].first);
	    
	  char* buffer = new char[size];
	  file.read(buffer, size);
	  dataStream.write(buffer, size);
	  delete[] buffer;
#ifdef HAVE_COMPRESSION
	  stringstream tmp(ios::out | ios::in);
	  boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
	  switch(cps)
	  {
426
	    case Cpsformat::ZLIB:
Siqi Ling's avatar
Siqi Ling committed
427
428
	      in.push(boost::iostreams::zlib_decompressor());
	      break;
429
	    case Cpsformat::BZIP2:
Siqi Ling's avatar
Siqi Ling committed
430
431
	      in.push(boost::iostreams::bzip2_decompressor());
	      break;
432
	    case Cpsformat::NONE:
Siqi Ling's avatar
Siqi Ling committed
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
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
	      break;
	    default:
	      MSG("NOT correct compression flag.\n");
	  }
	  in.push(dataStream);
	  boost::iostreams::copy(in, tmp);
	  dataStream.str(tmp.str());
#endif  
          uint32_t nStructureCodes = 0;
	  uint32_t codeSize = 0;

	  dataStream.read(reinterpret_cast<char*>(&nStructureCodes), 4);
	  dataStream.read(reinterpret_cast<char*>(&codeSize), 4);
	  
	  vector<uint64_t> structureCode(nStructureCodes);
	  dataStream.read(reinterpret_cast<char*>(&(structureCode[0])), 8 * nStructureCodes);

	  MeshStructure elementStructure;
	  elementStructure.init(structureCode, codeSize);
	  if (macroInMesh.count(macroElIndex[i]))
	    elementStructure.fitMeshToStructure(mesh, refManager, false, macroElIndex[i]);

	  if (nValueVectors > 0) {
	    vector<vector<double> > values(nValueVectors);
	    int valuePos = 0;
	    for(unsigned int j = 0; j < nFeSpaces; j++)
	    {
	      uint32_t nValuesPerVector = 0;
	      dataStream.read(reinterpret_cast<char*>(&nValuesPerVector), 4);
	      
	      for(size_t k = 0; k < sortedFeSpaces[j].size(); k++)
	      {
		values[valuePos + k].resize(nValuesPerVector); 
		readValues(dataStream, dataformat[valuePos + k], values[valuePos + k]);
	      } 
	      valuePos += sortedFeSpaces[j].size();
	    }
	    if(!vecs.empty())
	    {
	      if(macroInMesh.count(macroElIndex[i]))
	      {
		setDofValues(macroElIndex[i], mesh, values, vecs, sortedFeSpaces);
	      }
	    }
	  }
	}
	delete refManager;
      }
      
      void readValues(stringstream& file, 
		      string dataformat, 
		      vector<double>& values)
      {
	using namespace ::AMDiS::io::Arh3Writer;
	
	std::map<string,Valformat>::const_iterator it = dataformatMap.find(dataformat);
	TEST_EXIT(it != dataformatMap.end())("Wrong data format.\n");
	
	switch(it->second) {
	  case SI08:
	    readValues<int8_t>(file, values);
	    break;
	  case SI16:
	    readValues<int16_t>(file, values);
	    break;
	  case SI32:
	    readValues<int32_t>(file, values);
	    break;	    
	  case SI64:
	    readValues<int64_t>(file, values);
	    break;	
	  case UI08:
	    readValues<uint8_t>(file, values);
	    break;	  
	  case UI16:
	    readValues<uint16_t>(file, values);
	    break;
	  case UI32:
	    readValues<uint32_t>(file, values);
	    break;	  
	  case UI64:
	    readValues<uint64_t>(file, values);
	    break;
	  case SF32:
	    readValues<float>(file, values);
	    break;	
	  case SF64:
	    readValues<double>(file, values);
	    break;
	  default:
	    ERROR_EXIT("Wrong data format.\n");
	}
      }
      
      template<typename T>
      void readValues(stringstream& file, vector<double>& values)
      {
530
531
	size_t size = values.size();
	T* data = new T[size];
Siqi Ling's avatar
Siqi Ling committed
532
533
534
535
	file.read(reinterpret_cast<char*>(&data[0]), sizeof(T) * size);
	
	for (size_t i = 0; i < size; i++)
	  values[i] = static_cast<double>(data[i]);
536
	delete [] data;
Siqi Ling's avatar
Siqi Ling committed
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
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
      }
    
      void readFile(string filename, Mesh *mesh,
			  vector<DOFVector<double>*> vecs,
			  bool writeParallel,
			  int nProcs,
			  bool byName)
      {
	FUNCNAME("Arh3Reader::detail::readFile()");
	//The last element in vecs must NOT be NULL
	std::set<string> nameSet;
	pair<std::set<string>::iterator,bool> ret;
	  
	while(!vecs.empty())
	{
	  if(vecs.back() == NULL)
	    vecs.pop_back();
	  else
	    break;
	}
	// This is the precondition
	for(size_t i = 0; i < vecs.size(); i++)
	{
	  if(vecs[i])
	  {
	    if(!mesh)
	      mesh = vecs[i]->getFeSpace()->getMesh();
	    else
	      TEST_EXIT(mesh == vecs[i]->getFeSpace()->getMesh())
		("The mesh of the DOFVectors should be the same for Reader because in one file there is only one mesh.\n");
	    ret = nameSet.insert(vecs[i]->getName());
	    TEST_EXIT(ret.second)("DOFVectors in vecs cannot have idential name. Please check.\n");
	  }
	}
	if(!mesh)
	{
	  WARNING("You haven't specified the target, no mesh or DOFVectors is given.\n");
	  return;
	}
	if (writeParallel) {
	  using boost::lexical_cast;
578
579
580
581
	  using namespace boost::filesystem;
	  
	  path file_name = filename;
	  path file_onlyname = file_name.filename();
Siqi Ling's avatar
Siqi Ling committed
582
	  int sPos = filename.find(".arh");
583
584
585
586
	  string filenameWithoutExt = filename.substr(0, sPos);
	  sPos = file_onlyname.string().find(".arh");
	  string onlynameWithoutExt = file_onlyname.string().substr(0, sPos);
	  string parh = filenameWithoutExt + ".parh";
Siqi Ling's avatar
Siqi Ling committed
587
	  string basedir = "./";
588
589
590
591
592
593
594
595
	  path file_path = file_name.remove_filename();
	  
	  int nProcs_ = 0, nMacros_ = 0, nMacros = 0;
	  vector<int> partition;
	  bool parhExists = exists(parh);
	  
	  if (parhExists)
	    basedir = readParallelFile(parh, partition, nProcs_, nMacros_);
Siqi Ling's avatar
Siqi Ling committed
596

Siqi Ling's avatar
Siqi Ling committed
597
	  filenameWithoutExt = file_path.string() + '/' + basedir + onlynameWithoutExt;
598
	    
Siqi Ling's avatar
Siqi Ling committed
599
600
	  if (nProcs == -1) {
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
601
	    string procFilename = filenameWithoutExt + "-p" + lexical_cast<string>(MPI::COMM_WORLD.Get_rank()) + "-.arh";
Siqi Ling's avatar
Siqi Ling committed
602
603
604
605
606
607
	    read(procFilename, mesh, vecs, byName);
	    MSG("ARH file read from: %s\n", procFilename.c_str());
#else
	    ERROR_EXIT("Reading parallel ARH files in sequential computations requires to specify the number of nodes on which the ARH file was created!\n");
#endif
	  } else {
608
	    if (!parhExists) {
Siqi Ling's avatar
Siqi Ling committed
609
	      for (; nProcs_ < nProcs + 1; nProcs_++) {
610
		string fn = filenameWithoutExt + "-p" + boost::lexical_cast<string>(nProcs_) + "-.arh";
Siqi Ling's avatar
Siqi Ling committed
611
612
613
614
615
616
		if(!boost::filesystem::exists(fn)) break;
	      }
	    }
	    TEST_EXIT(nProcs_ == nProcs)
	      ("Number of arh files doesn't match number of processors: %d vs %d\n", nProcs_, nProcs);
	      
617
	    if (!parhExists) {
Siqi Ling's avatar
Siqi Ling committed
618
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS	      
619
	      if (MPI::COMM_WORLD.Get_rank() == 0)
Siqi Ling's avatar
Siqi Ling committed
620
621
622
623
624
625
626
627
#endif
	        for(int i = 0; i < nProcs; i++)
		  nMacros_ += readNumOfMacrosFromSgArh(filename, i);
	    }
	      
	    nMacros = mesh->getNumberOfMacros();
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
	    Parallel::mpi::globalAdd(nMacros);
628
	    if(MPI::COMM_WORLD.Get_rank() == 0)
Siqi Ling's avatar
Siqi Ling committed
629
#endif	      
630
	    {
Siqi Ling's avatar
Siqi Ling committed
631
632
633
	      TEST_EXIT(nMacros == nMacros_)
		  ("Number of macro elements in parallel ARH files doesn't match to the current runtime. %d vs %d\n",
		  nMacros, nMacros_); 
634
	    }
Siqi Ling's avatar
Siqi Ling committed
635

636
	    if (!parhExists) {
Siqi Ling's avatar
Siqi Ling committed
637
	      for (int i = 0; i < nProcs; i++) {
638
		string procFilename = filenameWithoutExt + "-p" + lexical_cast<string>(i) + "-.arh";
Siqi Ling's avatar
Siqi Ling committed
639
640
641
642
643
644
645
646
647
648
		read(procFilename, mesh, vecs, byName);
	      }
	    } else {
	      std::set<int> needFiles;
	      deque<MacroElement*>::iterator it = mesh->firstMacroElement();
	      for (;it != mesh->endOfMacroElements(); it++)
		needFiles.insert(partition[(*it)->getIndex()]);
	      
	      std::set<int>::iterator it2 = needFiles.begin();
	      for (;it2 != needFiles.end(); it2++) {
649
		string procFilename = filenameWithoutExt + "-p" + lexical_cast<string>(*it2) + "-.arh";
Siqi Ling's avatar
Siqi Ling committed
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
		read(procFilename, mesh, vecs, byName);
	      }
	    }
	  }
	} else {
	  read(filename, mesh, vecs, byName);
	}
	MSG("ARH file read from: %s\n", filename.c_str());
      }
      
      void readMetaFromSgArh(std::string filename, int nProc, 
			   std::vector< std::set<std::pair<int, int> > >& data)
      {
	using namespace ::AMDiS::io::Arh3Writer;
	
	ifstream file;
	file.open(filename.c_str(), ios::in | ios::binary);
	TEST_EXIT(file.is_open())
	  ("Cannot open file %s\n", filename.c_str());
	  
	uint32_t dow = 0, dim = 0;
	uint32_t headerLen = 0;
	uint32_t nMacroElements = 0;
	uint32_t nValueVectors = 0;
	uint32_t nFeSpaces = 0;
	int cpsflag = 0, fileSize = 0;
676
	Cpsformat::Value cps = Cpsformat::NONE;    
Siqi Ling's avatar
Siqi Ling committed
677
678
679
680
681
682
683
684
685
686
	
	firstRead(file, "sarh", MAJOR, MINOR);

	file.read(reinterpret_cast<char*>(&headerLen), 4);
	file.read(reinterpret_cast<char*>(&dow), 4);
	file.read(reinterpret_cast<char*>(&dim), 4);
	file.read(reinterpret_cast<char*>(&nFeSpaces), 4);
	file.read(reinterpret_cast<char*>(&nValueVectors), 4);
	file.read(reinterpret_cast<char*>(&nMacroElements), 4);
	file.read(reinterpret_cast<char*>(&cpsflag), 4);
687
	cps = static_cast<Cpsformat::Value>(cpsflag);
Siqi Ling's avatar
Siqi Ling committed
688
689
	
#ifdef HAVE_COMPRESSION
690
691
692
	TEST_EXIT(cps == Cpsformat::ZLIB  || 
		  cps == Cpsformat::BZIP2 ||
		  cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
693
	  ("Cannot read Arh3 file. Currently only support zlib and bzip2 compression.\n");
Siqi Ling's avatar
Siqi Ling committed
694
#else
695
	TEST_EXIT(cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
696
	  ("HAVE_COMPRESSION OFF. Cannot read compressed Arh3 file.\n");	
Siqi Ling's avatar
Siqi Ling committed
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
#endif
      
	vector<int> macroElIndex(nMacroElements);
	vector<pair<int, int> > macroElSize(nMacroElements);
	vector<vector<int> > sortedFeSpaces(nFeSpaces);
	vector<string> dataformat;
	  
	// Read macro table
	for(uint32_t i = 0; i < nMacroElements; i++) {
	  file.read(reinterpret_cast<char*>(&macroElIndex[i]), 4);
	  file.read(reinterpret_cast<char*>(&macroElSize[i].first), 4);
	  file.read(reinterpret_cast<char*>(&macroElSize[i].second), 4);
	}
	file.seekg(4, ios_base::cur);
	file.read(reinterpret_cast<char*>(&fileSize), 4);
	file.seekg(4, ios_base::cur);
	
	// Read feSpace table
	for(size_t i = 0; i < nFeSpaces; i++)
	{
	  uint32_t tmpInt = 0;
	  file.read(reinterpret_cast<char*>(&tmpInt), 4);
	  file.seekg(tmpInt, ios_base::cur);
	  file.seekg(16, ios_base::cur);
	}
	
	// Read value table
	for(uint32_t i = 0; i < nValueVectors; i++) {
	  string tmpString("");
	  uint32_t tmpInt = 0;
	  file.read(reinterpret_cast<char*>(&tmpInt), 4);
	  tmpString.resize(tmpInt, ' ');
729
	  file.read(&tmpString[0], tmpInt); //
Siqi Ling's avatar
Siqi Ling committed
730
731
732
	  file.read(reinterpret_cast<char*>(&tmpInt), 4);
	  sortedFeSpaces[tmpInt].push_back(i);
	  tmpString.resize(4, ' ');
733
	  file.read(&tmpString[0], 4);
Siqi Ling's avatar
Siqi Ling committed
734
	  dataformat.push_back(tmpString);
735
736
737
738
739
740
	}
	
	// Read macroFile_nl
	uint32_t macroFile_nl = 0;
	file.read(reinterpret_cast<char*>(&macroFile_nl), 4);
	string tmpString("");
741
	file.read(&tmpString[0], macroFile_nl);
742
743
	
	//================header is over==================//
Siqi Ling's avatar
Siqi Ling committed
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
    
	for (uint32_t i = 0; i < nMacroElements; i++) {
	  stringstream dataStream(ios::out | ios::in | ios::binary);
	  int size = (i == nMacroElements - 1) ?  fileSize - macroElSize[i].first
	    : (macroElSize[i+1].first - macroElSize[i].first);
	    
	  char* buffer = new char[size];
	  file.read(buffer, size);
	  dataStream.write(buffer, size);
	  delete[] buffer;
	  
#ifdef HAVE_COMPRESSION      
	  stringstream tmp(ios::out | ios::in);
	  boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
	  switch(cps)
	  {
760
	    case Cpsformat::ZLIB:
Siqi Ling's avatar
Siqi Ling committed
761
762
	      in.push(boost::iostreams::zlib_decompressor());
	      break;
763
	    case Cpsformat::BZIP2:
Siqi Ling's avatar
Siqi Ling committed
764
765
	      in.push(boost::iostreams::bzip2_decompressor());
	      break;
766
	    case Cpsformat::NONE:
Siqi Ling's avatar
Siqi Ling committed
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
	      break;
	    default:
	      MSG("NOT correct compression flag.\n");
	  }
	  in.push(dataStream);
	  boost::iostreams::copy(in, tmp);
	  dataStream.str(tmp.str());
#endif	    
	  uint32_t nStructureCodes = 0;
	  uint32_t codeSize = 0;

	  dataStream.read(reinterpret_cast<char*>(&nStructureCodes), 4);
	  dataStream.read(reinterpret_cast<char*>(&codeSize), 4);

	  data[nProc].insert(make_pair(macroElIndex[i], codeSize));
	  
	  // We only need codeSize for each macro element data block, so skip all of the unnecessary.
          dataStream.seekg(8 * nStructureCodes, ios_base::cur); 

	  if (nValueVectors > 0) {
	    
	    int valuePos = 0;
	    for(uint32_t j = 0; j < nFeSpaces; j++) {
	      uint32_t nValuesPerVector = 0;
	      dataStream.read(reinterpret_cast<char*>(&nValuesPerVector), 4);
	      
	      for(size_t k = 0; k < sortedFeSpaces[j].size(); k++) {
		
		std::map<string,Valformat>::const_iterator it = dataformatMap.find(dataformat[valuePos + k]);
		TEST_EXIT(it != dataformatMap.end())("Wrong data format.\n");
		
		int unitsize = 0;
		switch(it->second) {
		  case SI08: 
		  case UI08: unitsize = 1;break;
		  case SI16:
		  case UI16: unitsize = 2;break;
		  case SI32:
		  case UI32:
		  case SF32: unitsize = 4;break;
		  case SI64:
		  case UI64:
		  case SF64: unitsize = 8;break;
		  default:ERROR_EXIT("Wrong data format.\n");
		}
		dataStream.seekg(unitsize * nValuesPerVector, ios_base::cur);
	      }
	      valuePos += sortedFeSpaces[j].size();
	    }
	  }
	}
      } // end readMetaFromSgArh
    
  
      int readNumOfMacrosFromSgArh(std::string filename, int nProc)
      {
	FUNCNAME("Arh3Reader::readHeaderSize");
	using boost::lexical_cast;
	
	int sPos = filename.find(".arh");
	TEST_EXIT(sPos >= 0)("Failed to find file postfix!\n");
	
	if (nProc >= 0) {
	  string name = filename.substr(0, sPos);
	  filename = name + "-p" + lexical_cast<string>(nProc) + "-.arh";
	}
	
	ifstream file;
	  
	file.open(filename.c_str(), ios::in | ios::binary);
	TEST_EXIT(file.is_open())
	  ("Cannot open file %s\n", filename.c_str());
	  
	int nMacroElements = 0;
	firstRead(file, "sarh", MAJOR, MINOR);
	file.seekg(20, ios_base::cur); 
	file.read(reinterpret_cast<char*>(&nMacroElements), 4);
	file.close();
	
	return nMacroElements;
      }
        
849
      std::string readParallelFile(string filename, vector<int>& partition, int& nFiles, int& nMacros)
Siqi Ling's avatar
Siqi Ling committed
850
851
852
853
854
855
      {
	ifstream file;
	file.open(filename.c_str(), ios::in | ios::binary);
	TEST_EXIT(file.is_open())
	  ("Cannot open file %s\n", filename.c_str());
	
856
	string fd(16, ' ');
857
	file.read(&fd[0], 16);
858
859
860
	string Id = fd.substr(0, 4);
	int major = boost::lexical_cast<int>(fd.substr(5, 1));
	int minor = boost::lexical_cast<int>(fd.substr(7, 1));
Siqi Ling's avatar
Siqi Ling committed
861
	firstRead(Id, major, minor, "parh", PARH_MAJOR, PARH_MINOR);
Siqi Ling's avatar
Siqi Ling committed
862
	
863
864
	uint32_t baseDirLen = 0, macroFile_nl = 0;
	string baseDir, macroFilename;
Siqi Ling's avatar
Siqi Ling committed
865
	
866
867
	file.read(reinterpret_cast<char*>(&baseDirLen), 4);
	baseDir.resize(baseDirLen, ' ');
868
	file.read(&baseDir[0], baseDirLen);
Siqi Ling's avatar
Siqi Ling committed
869
870
	file.read(reinterpret_cast<char*>(&nFiles), 4);
	file.read(reinterpret_cast<char*>(&macroFile_nl), 4);
871
	if (macroFile_nl > 0) { //TODO
872
	  macroFilename.resize(macroFile_nl, ' ');
873
	  file.read(&macroFilename[0], macroFile_nl);
874
875
	}
	file.read(reinterpret_cast<char*>(&nMacros), 4);
Siqi Ling's avatar
Siqi Ling committed
876
877
	
	uint32_t rank = 0;
878
	for (int i = 0; i < nMacros; i++) {
Siqi Ling's avatar
Siqi Ling committed
879
880
881
	  file.read(reinterpret_cast<char*>(&rank), 4);
	  partition.push_back(rank);
	}
882
883
	
	return baseDir;
Siqi Ling's avatar
Siqi Ling committed
884
885
886
887
888
889
890
      }

    } // end namespace detail
  } // end namespace Arh3Reader
} } // end namespace io, AMDiS