Arh3Reader.cc 25.7 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
34
35
36
37
38
39
40
      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_)
	  ("Cannot read Arh format: Arh2Reader major version is %i, the file major version is %i. \n",
	  major, major_);
	  
	TEST_EXIT(minor >= minor_)
	  ("Cannot read Arh format: ArhReader minor version is %i is smaller than the file minor version %i.\n", 
	  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
256
	  ("Cannot read Arh2 file. Currently only support zlib and bzip2 compression.\n");
#else
257
	TEST_EXIT(cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
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
295
296
297
298
299
300
	  ("HAVE_COMPRESSION OFF. Cannot read compressed Arh2 file.\n");	
#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<int> vecsNameLen;
	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
	int fileSize = 0;
	
	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);
301
	  file.read(&AFEDfileName[i][0], tmpInt);
Siqi Ling's avatar
Siqi Ling committed
302
303
304
305
306
307
308
309
310
311
312
313
314
315
	  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);
	  vecsNameLen.push_back(tmpInt);
	  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
	}
	
326
	// Read macroFile_nl //TODO
327
328
329
330
331
	uint32_t macroFile_nl = 0;
	file.read(reinterpret_cast<char*>(&macroFile_nl), 4);
	if (macroFile_nl > 0) {
	  string tmpString("");
	  tmpString.resize(macroFile_nl, ' ');
332
	  file.read(&tmpString[0], macroFile_nl);
333
334
335
336
	}
	
	//================header is over==================//
	
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
	// 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 {
365
		  for(int j = 1; j < nDOF->getSize(); j++) {
Siqi Ling's avatar
Siqi Ling committed
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
		    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);
394
	      for(int j = 1; j < nDOF->getSize(); j++)
Siqi Ling's avatar
Siqi Ling committed
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
		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)
	  {
415
	    case Cpsformat::ZLIB:
Siqi Ling's avatar
Siqi Ling committed
416
417
	      in.push(boost::iostreams::zlib_decompressor());
	      break;
418
	    case Cpsformat::BZIP2:
Siqi Ling's avatar
Siqi Ling committed
419
420
	      in.push(boost::iostreams::bzip2_decompressor());
	      break;
421
	    case Cpsformat::NONE:
Siqi Ling's avatar
Siqi Ling committed
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
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
	      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)
      {
519
520
	size_t size = values.size();
	T* data = new T[size];
Siqi Ling's avatar
Siqi Ling committed
521
522
523
524
	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]);
525
	delete [] data;
Siqi Ling's avatar
Siqi Ling committed
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
      }
    
      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;
567
568
569
570
	  using namespace boost::filesystem;
	  
	  path file_name = filename;
	  path file_onlyname = file_name.filename();
Siqi Ling's avatar
Siqi Ling committed
571
	  int sPos = filename.find(".arh");
572
573
574
575
	  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
576
	  string basedir = "./";
577
578
579
580
581
582
583
584
	  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
585

Siqi Ling's avatar
Siqi Ling committed
586
	  filenameWithoutExt = file_path.string() + '/' + basedir + onlynameWithoutExt;
587
	    
Siqi Ling's avatar
Siqi Ling committed
588
589
	  if (nProcs == -1) {
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
590
	    string procFilename = filenameWithoutExt + "-p" + lexical_cast<string>(MPI::COMM_WORLD.Get_rank()) + "-.arh";
Siqi Ling's avatar
Siqi Ling committed
591
592
593
594
595
596
	    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 {
597
	    if (!parhExists) {
Siqi Ling's avatar
Siqi Ling committed
598
	      for (; nProcs_ < nProcs + 1; nProcs_++) {
599
		string fn = filenameWithoutExt + "-p" + boost::lexical_cast<string>(nProcs_) + "-.arh";
Siqi Ling's avatar
Siqi Ling committed
600
601
602
603
604
605
		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);
	      
606
	    if (!parhExists) {
Siqi Ling's avatar
Siqi Ling committed
607
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS	      
608
	      if (MPI::COMM_WORLD.Get_rank() == 0)
Siqi Ling's avatar
Siqi Ling committed
609
610
611
612
613
614
615
616
#endif
	        for(int i = 0; i < nProcs; i++)
		  nMacros_ += readNumOfMacrosFromSgArh(filename, i);
	    }
	      
	    nMacros = mesh->getNumberOfMacros();
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
	    Parallel::mpi::globalAdd(nMacros);
617
	    if(MPI::COMM_WORLD.Get_rank() == 0)
Siqi Ling's avatar
Siqi Ling committed
618
#endif	      
619
	    {
Siqi Ling's avatar
Siqi Ling committed
620
621
622
	      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_); 
623
	    }
Siqi Ling's avatar
Siqi Ling committed
624

625
	    if (!parhExists) {
Siqi Ling's avatar
Siqi Ling committed
626
	      for (int i = 0; i < nProcs; i++) {
627
		string procFilename = filenameWithoutExt + "-p" + lexical_cast<string>(i) + "-.arh";
Siqi Ling's avatar
Siqi Ling committed
628
629
630
631
632
633
634
635
636
637
		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++) {
638
		string procFilename = filenameWithoutExt + "-p" + lexical_cast<string>(*it2) + "-.arh";
Siqi Ling's avatar
Siqi Ling committed
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
		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;
665
	Cpsformat::Value cps = Cpsformat::NONE;    
Siqi Ling's avatar
Siqi Ling committed
666
667
668
669
670
671
672
673
674
675
	
	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);
676
	cps = static_cast<Cpsformat::Value>(cpsflag);
Siqi Ling's avatar
Siqi Ling committed
677
678
	
#ifdef HAVE_COMPRESSION
679
680
681
	TEST_EXIT(cps == Cpsformat::ZLIB  || 
		  cps == Cpsformat::BZIP2 ||
		  cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
682
683
	  ("Cannot read Arh2 file. Currently only support zlib and bzip2 compression.\n");
#else
684
	TEST_EXIT(cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
	  ("HAVE_COMPRESSION OFF. Cannot read compressed Arh2 file.\n");	
#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, ' ');
718
	  file.read(&tmpString[0], tmpInt); //
Siqi Ling's avatar
Siqi Ling committed
719
720
721
	  file.read(reinterpret_cast<char*>(&tmpInt), 4);
	  sortedFeSpaces[tmpInt].push_back(i);
	  tmpString.resize(4, ' ');
722
	  file.read(&tmpString[0], 4);
Siqi Ling's avatar
Siqi Ling committed
723
	  dataformat.push_back(tmpString);
724
725
726
727
728
729
	}
	
	// Read macroFile_nl
	uint32_t macroFile_nl = 0;
	file.read(reinterpret_cast<char*>(&macroFile_nl), 4);
	string tmpString("");
730
	file.read(&tmpString[0], macroFile_nl);
731
732
	
	//================header is over==================//
Siqi Ling's avatar
Siqi Ling committed
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
    
	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)
	  {
749
	    case Cpsformat::ZLIB:
Siqi Ling's avatar
Siqi Ling committed
750
751
	      in.push(boost::iostreams::zlib_decompressor());
	      break;
752
	    case Cpsformat::BZIP2:
Siqi Ling's avatar
Siqi Ling committed
753
754
	      in.push(boost::iostreams::bzip2_decompressor());
	      break;
755
	    case Cpsformat::NONE:
Siqi Ling's avatar
Siqi Ling committed
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
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
	      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;
      }
        
838
      std::string readParallelFile(string filename, vector<int>& partition, int& nFiles, int& nMacros)
Siqi Ling's avatar
Siqi Ling committed
839
840
841
842
843
844
      {
	ifstream file;
	file.open(filename.c_str(), ios::in | ios::binary);
	TEST_EXIT(file.is_open())
	  ("Cannot open file %s\n", filename.c_str());
	
845
	string fd(16, ' ');
846
	file.read(&fd[0], 16);
847
848
849
	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
850
	firstRead(Id, major, minor, "parh", PARH_MAJOR, PARH_MINOR);
Siqi Ling's avatar
Siqi Ling committed
851
	
852
853
	uint32_t baseDirLen = 0, macroFile_nl = 0;
	string baseDir, macroFilename;
Siqi Ling's avatar
Siqi Ling committed
854
	
855
856
	file.read(reinterpret_cast<char*>(&baseDirLen), 4);
	baseDir.resize(baseDirLen, ' ');
857
	file.read(&baseDir[0], baseDirLen);
Siqi Ling's avatar
Siqi Ling committed
858
859
	file.read(reinterpret_cast<char*>(&nFiles), 4);
	file.read(reinterpret_cast<char*>(&macroFile_nl), 4);
860
	if (macroFile_nl > 0) { //TODO
861
	  macroFilename.resize(macroFile_nl, ' ');
862
	  file.read(&macroFilename[0], macroFile_nl);
863
864
	}
	file.read(reinterpret_cast<char*>(&nMacros), 4);
Siqi Ling's avatar
Siqi Ling committed
865
866
	
	uint32_t rank = 0;
867
	for (int i = 0; i < nMacros; i++) {
Siqi Ling's avatar
Siqi Ling committed
868
869
870
	  file.read(reinterpret_cast<char*>(&rank), 4);
	  partition.push_back(rank);
	}
871
872
	
	return baseDir;
Siqi Ling's avatar
Siqi Ling committed
873
874
875
876
877
878
879
      }

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