Arh3Reader.cc 27.1 KB
Newer Older
Siqi Ling's avatar
Siqi Ling committed
1
2
3
4
5
6
7
8
9
#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"
10
11
12
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
#include "parallel/MpiHelper.h"
#endif
Siqi Ling's avatar
Siqi Ling committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#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
    {
30
31
32
33
34
      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());
35
	
36
	TEST_EXIT(major == major_)
Siqi Ling's avatar
Siqi Ling committed
37
	  ("Cannot read Arh format: Arh3Reader major version is %i, the file major version is %i. \n",
38
39
40
	  major, major_);
	  
	TEST_EXIT(minor >= minor_)
Siqi Ling's avatar
Siqi Ling committed
41
	  ("Cannot read Arh format: Arh3Reader minor version is %i is smaller than the file minor version %i.\n", 
42
43
	  minor, minor_);
      }
Siqi Ling's avatar
Siqi Ling committed
44
45
46
47
48
49
50
51
52
      
      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, ' ');
    
53
	file.read(&typeId[0], 4);
Siqi Ling's avatar
Siqi Ling committed
54
55
	file.read(reinterpret_cast<char*>(&major_), 1);
	file.read(reinterpret_cast<char*>(&minor_), 1);
56
57
	
	firstRead(typeId, major_, minor_, id, major, minor);
Siqi Ling's avatar
Siqi Ling committed
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
231
232
233
      }
      
      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());
      
234
	Cpsformat::Value cps = Cpsformat::NONE;
Siqi Ling's avatar
Siqi Ling committed
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
	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);
252
	cps = static_cast<Cpsformat::Value>(cpsflag);
Siqi Ling's avatar
Siqi Ling committed
253
254
	
#ifdef HAVE_COMPRESSION
255
256
257
	TEST_EXIT(cps == Cpsformat::ZLIB  || 
		  cps == Cpsformat::BZIP2 ||
		  cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
258
	  ("Cannot read Arh3 file. Currently only support zlib and bzip2 compression.\n");
Siqi Ling's avatar
Siqi Ling committed
259
#else
260
	TEST_EXIT(cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
261
	  ("HAVE_COMPRESSION OFF. Cannot read compressed Arh3 file.\n");	
Siqi Ling's avatar
Siqi Ling committed
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#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
281
	int fileSize = 0, feSpacesNamesLen = 0, valueNamesLen = 0;
Siqi Ling's avatar
Siqi Ling committed
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
	
	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);
303
	  file.read(&AFEDfileName[i][0], tmpInt);
Siqi Ling's avatar
Siqi Ling committed
304
	  feSpacesNamesLen += tmpInt;
Siqi Ling's avatar
Siqi Ling committed
305
306
307
308
309
310
311
312
313
314
315
316
	  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
317
	  valueNamesLen += tmpInt;
Siqi Ling's avatar
Siqi Ling committed
318
	  tmpString.resize(tmpInt, ' ');
319
	  file.read(&tmpString[0], tmpInt); //
Siqi Ling's avatar
Siqi Ling committed
320
321
322
323
324
	  vecsName.push_back(tmpString);
	  file.read(reinterpret_cast<char*>(&tmpInt), 4);
	  sortedFeSpaces[tmpInt].push_back(i);
	  vecsFeSpaceNum.push_back(tmpInt);
	  tmpString.resize(4, ' ');
325
	  file.read(&tmpString[0], 4);
Siqi Ling's avatar
Siqi Ling committed
326
	  dataformat.push_back(tmpString);
327
328
	}
	
Siqi Ling's avatar
Siqi Ling committed
329
330
331
332
333
334
335
336
337
338
	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");
	
339
	// TODO read macro from arh
Siqi Ling's avatar
Siqi Ling committed
340
341
342
343
344
345
346
347
	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);
	  }
348
349
350
	}
	//================header is over==================//
	
Siqi Ling's avatar
Siqi Ling committed
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
	// 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 {
379
		  for(int j = 1; j < nDOF->getSize(); j++) {
Siqi Ling's avatar
Siqi Ling committed
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
		    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);
408
	      for(int j = 1; j < nDOF->getSize(); j++)
Siqi Ling's avatar
Siqi Ling committed
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
		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)
	  {
429
	    case Cpsformat::ZLIB:
Siqi Ling's avatar
Siqi Ling committed
430
431
	      in.push(boost::iostreams::zlib_decompressor());
	      break;
432
	    case Cpsformat::BZIP2:
Siqi Ling's avatar
Siqi Ling committed
433
434
	      in.push(boost::iostreams::bzip2_decompressor());
	      break;
435
	    case Cpsformat::NONE:
Siqi Ling's avatar
Siqi Ling committed
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
530
531
532
	      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)
      {
533
534
	size_t size = values.size();
	T* data = new T[size];
Siqi Ling's avatar
Siqi Ling committed
535
536
537
538
	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]);
539
	delete [] data;
Siqi Ling's avatar
Siqi Ling committed
540
541
542
543
544
545
546
547
548
      }
    
      void readFile(string filename, Mesh *mesh,
			  vector<DOFVector<double>*> vecs,
			  bool writeParallel,
			  int nProcs,
			  bool byName)
      {
	FUNCNAME("Arh3Reader::detail::readFile()");
549
550
551
552

        using boost::lexical_cast;
        using boost::filesystem::path;

Siqi Ling's avatar
Siqi Ling committed
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
	//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;
	}
583
584
585
586
587
588
589
590
591
592
593
594
595
        path file_name = filename;                    //  /path/to/filename.arh
        path extension = file_name.extension();       //  .arh 
        path file_stem = file_name.stem();            //  filename
        path file_path = file_name.parent_path();     //  /path/to/"Number of arh files doesn't match number of processors: %d vs %d\n", nProc_f, nProcs);
        if (extension.string() == ".arh") {
          // read sequential file
          read(filename, mesh, vecs, byName);
        } else if (extension.string() == ".parh") {
          // read parallel file
          std::map<int,int> partition;
          int nFiles = 0;
          int nMacros = 0;
          std::string macroFilename = "";
Siqi Ling's avatar
Siqi Ling committed
596

597
598
599
600
601
602
          std::string base_dir = readParallelFile(filename, partition, nFiles, nMacros, macroFilename);
          TEST_EXIT(nFiles > 0 && nMacros > 0 && nMacros >= nFiles)
                  ("Error while reading parh file: nFiles=%d, nMacros=%d\n", nFiles, nMacros);

          // Test whether parh file can be read to current mesh
          int nMacrosInMesh = mesh->getNumberOfMacros();
Siqi Ling's avatar
Siqi Ling committed
603
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
604
          Parallel::mpi::globalAdd(nMacrosInMesh);
Siqi Ling's avatar
Siqi Ling committed
605
#endif
606
607
608
609
          TEST_EXIT(nMacros == nMacrosInMesh)
                  ("Number of macro elements in parallel ARH files doesn't match "
                    "the number of macro elements in the mesh. %d vs %d\n",
                  nMacros, nMacrosInMesh);
Siqi Ling's avatar
Siqi Ling committed
610

611
612
613
614
615
          // TODO: read macro from macro-filename

          for (int i = 0; i < nFiles; i++) {
            std::string procFilename = file_path.string() + "/" + base_dir + "/" + file_stem.string() + "_p" + lexical_cast<string>(i) + ".arh";	      
            read(procFilename, mesh, vecs, byName);
Siqi Ling's avatar
Siqi Ling committed
616
617
	  }
	} else {
618
          ERROR_EXIT("Unknown file-extension '%s' in ARHReader", extension.string().c_str());
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
	}
	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;
639
	Cpsformat::Value cps = Cpsformat::NONE;    
Siqi Ling's avatar
Siqi Ling committed
640
641
642
643
644
645
646
647
648
649
	
	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);
650
	cps = static_cast<Cpsformat::Value>(cpsflag);
Siqi Ling's avatar
Siqi Ling committed
651
652
	
#ifdef HAVE_COMPRESSION
653
654
655
	TEST_EXIT(cps == Cpsformat::ZLIB  || 
		  cps == Cpsformat::BZIP2 ||
		  cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
656
	  ("Cannot read Arh3 file. Currently only support zlib and bzip2 compression.\n");
Siqi Ling's avatar
Siqi Ling committed
657
#else
658
	TEST_EXIT(cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
659
	  ("HAVE_COMPRESSION OFF. Cannot read compressed Arh3 file.\n");	
Siqi Ling's avatar
Siqi Ling committed
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
#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, ' ');
692
	  file.read(&tmpString[0], tmpInt); //
Siqi Ling's avatar
Siqi Ling committed
693
694
695
	  file.read(reinterpret_cast<char*>(&tmpInt), 4);
	  sortedFeSpaces[tmpInt].push_back(i);
	  tmpString.resize(4, ' ');
696
	  file.read(&tmpString[0], 4);
Siqi Ling's avatar
Siqi Ling committed
697
	  dataformat.push_back(tmpString);
698
699
700
701
702
703
	}
	
	// Read macroFile_nl
	uint32_t macroFile_nl = 0;
	file.read(reinterpret_cast<char*>(&macroFile_nl), 4);
	string tmpString("");
704
	file.read(&tmpString[0], macroFile_nl);
705
706
	
	//================header is over==================//
Siqi Ling's avatar
Siqi Ling committed
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
    
	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)
	  {
723
	    case Cpsformat::ZLIB:
Siqi Ling's avatar
Siqi Ling committed
724
725
	      in.push(boost::iostreams::zlib_decompressor());
	      break;
726
	    case Cpsformat::BZIP2:
Siqi Ling's avatar
Siqi Ling committed
727
728
	      in.push(boost::iostreams::bzip2_decompressor());
	      break;
729
	    case Cpsformat::NONE:
Siqi Ling's avatar
Siqi Ling committed
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
	      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
    
  
784
      int readNumOfMacrosFromSgArh(std::string filename, int nProc, bool newFilename)
Siqi Ling's avatar
Siqi Ling committed
785
786
787
788
789
      {
	FUNCNAME("Arh3Reader::readHeaderSize");
	using boost::lexical_cast;
	
	int sPos = filename.find(".arh");
790
	TEST_EXIT(sPos >= 0)("Failed to find file postfix: \"arh \"!\n");
Siqi Ling's avatar
Siqi Ling committed
791
792
793
	
	if (nProc >= 0) {
	  string name = filename.substr(0, sPos);
794
795
796
797
	  if (newFilename)
	    filename = name + "_p" + lexical_cast<string>(nProc) + ".arh";
	  else
	    filename = name + "-p" + lexical_cast<string>(nProc) + "-.arh";
Siqi Ling's avatar
Siqi Ling committed
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
	}
	
	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;
      }
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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
      
      void checkMeshconvParh1_0(std::string filename)
      {
	FUNCNAME("Arh3Reader::detail::checkMeshconvParh1_0()");
	
	ifstream file;
	file.open(filename.c_str(), ios::in | ios::binary);
	TEST_EXIT(file.is_open())
	  ("Cannot open file %s\n", filename.c_str());
	
	string Id(4, ' ');
	uint8_t major = 0, minor = 0;
  
	file.read(&Id[0], 4);
	file.read(reinterpret_cast<char*>(&major), 1);
	file.read(reinterpret_cast<char*>(&minor), 1);
	
	if (Id == "parh" && major == 1 && minor == 1)
	  ERROR_EXIT("Parh file 1.0 is not supported in AMDiS anymore, you can use tools/arhTools/parh_change to update it to 2.0.\n");
      }
      
      std::string readParallelFile(std::string filename)
      {
	FUNCNAME("Arh3Reader::detail::readParallelFile()");
	
	checkMeshconvParh1_0(filename);
	
	ifstream file;
	file.open(filename.c_str(), ios::in | ios::binary);
	TEST_EXIT(file.is_open())
	  ("Cannot open file %s\n", filename.c_str());
	
	string fd(16, ' ');
	file.read(&fd[0], 16);
	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));
	
	if (Id == "parh" && major == 1 && minor == 0)
	  ERROR_EXIT("Parh file 1.0 is not supported in AMDiS anymore, you can use tools/arhTools/parh_change to update it to 2.0.\n");
	  
	firstRead(Id, major, minor, "parh", PARH_MAJOR, PARH_MINOR);
	
	uint32_t baseDirLen = 0;
	string baseDir = "";
	file.read(reinterpret_cast<char*>(&baseDirLen), 4);
	baseDir.resize(baseDirLen, ' ');
	file.read(&baseDir[0], baseDirLen);
	return baseDir;
      }
Siqi Ling's avatar
Siqi Ling committed
864
        
865
      std::string readParallelFile(string filename, std::map<int,int>& partition, int& nFiles, int& nMacros, std::string& macroFilename)
Siqi Ling's avatar
Siqi Ling committed
866
      {
867
	FUNCNAME("Arh3Reader::detail::readParallelFile()");
868
869

        using boost::lexical_cast;
870
871
872
	
	checkMeshconvParh1_0(filename);
	
Siqi Ling's avatar
Siqi Ling committed
873
874
875
876
877
	ifstream file;
	file.open(filename.c_str(), ios::in | ios::binary);
	TEST_EXIT(file.is_open())
	  ("Cannot open file %s\n", filename.c_str());
	
878
	string fd(16, ' ');
879
	file.read(&fd[0], 16);
880
	string Id = fd.substr(0, 4);
881
882
	int major = lexical_cast<int>(fd.substr(5, 1));
	int minor = lexical_cast<int>(fd.substr(7, 1));
883
884
885
886
	
	if (major == 1 && minor == 0)
	  ERROR_EXIT("Parh file 1.0 is not supported in AMDiS anymore, you can use tools/arhTools/parh_change to update it to 2.0.\n");
	  
Siqi Ling's avatar
Siqi Ling committed
887
	firstRead(Id, major, minor, "parh", PARH_MAJOR, PARH_MINOR);
Siqi Ling's avatar
Siqi Ling committed
888
	
889
	uint32_t baseDirLen = 0, macroFile_nl = 0;
890
	string baseDir;
Siqi Ling's avatar
Siqi Ling committed
891
	
892
893
	file.read(reinterpret_cast<char*>(&baseDirLen), 4);
	baseDir.resize(baseDirLen, ' ');
894
	file.read(&baseDir[0], baseDirLen);
Siqi Ling's avatar
Siqi Ling committed
895
896
	file.read(reinterpret_cast<char*>(&nFiles), 4);
	file.read(reinterpret_cast<char*>(&macroFile_nl), 4);
897
	if (macroFile_nl > 0) { //TODO read macro from arh
898
	  macroFilename.resize(macroFile_nl, ' ');
899
	  file.read(&macroFilename[0], macroFile_nl);
900
901
	}
	file.read(reinterpret_cast<char*>(&nMacros), 4);
Siqi Ling's avatar
Siqi Ling committed
902
903
	
	uint32_t rank = 0;
904
	for (int i = 0; i < nMacros; i++) {
Siqi Ling's avatar
Siqi Ling committed
905
	  file.read(reinterpret_cast<char*>(&rank), 4);
906
	  partition[i] = rank;
Siqi Ling's avatar
Siqi Ling committed
907
	}
908
909
	
	return baseDir;
Siqi Ling's avatar
Siqi Ling committed
910
911
912
913
914
915
916
      }

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