Arh3Reader.cc 29.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
      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());
32
	
33
	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
	// TODO read macro from arh
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
	  using boost::filesystem::path;
579
580
581
	  
	  path file_name = filename;
	  path file_onlyname = file_name.filename();
582
583
	  path file_path = file_name.remove_filename();
	  
Siqi Ling's avatar
Siqi Ling committed
584
	  int sPos = filename.find(".arh");
585
	  string filenameWithoutExt = filename.substr(0, sPos);
586
587
	  string parh = filenameWithoutExt + ".parh";
	  
588
589
	  sPos = file_onlyname.string().find(".arh");
	  string onlynameWithoutExt = file_onlyname.string().substr(0, sPos);
590
	  
591
592
593
594
	  
	  int nProcs_ = 0, nMacros_ = 0, nMacros = 0;
	  vector<int> partition;
	  
595
596
597
	  bool parhExists = boost::filesystem::exists(parh);
	  bool newFilename = parhExists;
	  string basedir =  parhExists ? readParallelFile(parh, partition, nProcs_, nMacros_) : ".";
Siqi Ling's avatar
Siqi Ling committed
598

599
600
	  filenameWithoutExt = file_path.string() + '/' + basedir + '/' + onlynameWithoutExt;
	  
Siqi Ling's avatar
Siqi Ling committed
601
602
	  if (nProcs == -1) {
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
603
604
605
606
607
608
609
	    string procFilename = filenameWithoutExt + "_p" + lexical_cast<string>(MPI::COMM_WORLD.Get_rank()) + ".arh";
	    
	    if (!boost::filesystem::exists(procFilename))
	      procFilename = filenameWithoutExt + "-p" + lexical_cast<string>(MPI::COMM_WORLD.Get_rank()) + "-.arh";
	    
	    TEST_EXIT(boost::filesystem::exists(procFilename))("Arh data file not found in: %s\n", procFilename.c_str());
	    
Siqi Ling's avatar
Siqi Ling committed
610
611
612
613
614
	    read(procFilename, mesh, vecs, byName);
#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 {
615
616
	      
	    int nProc_f = 0;
617
	    if (!parhExists) {
618
619
620
621
622
623
624
625
626
627
628
629
	      for (; nProc_f < nProcs + 1; nProc_f++) {
		string fn = filenameWithoutExt + "-p" + boost::lexical_cast<string>(nProc_f) + "-.arh";
		if(!boost::filesystem::exists(fn)) break;
	      }
	      if (nProc_f != nProcs) {
		newFilename = true;
		for (nProc_f = 0; nProc_f < nProcs + 1; nProc_f++) {
		  string fn = filenameWithoutExt + "_p" + boost::lexical_cast<string>(nProc_f) + ".arh";
		  if(!boost::filesystem::exists(fn)) break;
		}
	      }
	    } else {
Praetorius, Simon's avatar
Praetorius, Simon committed
630
	      for (nProc_f = 0; nProc_f < nProcs + 1; nProc_f++) {
631
		string fn = filenameWithoutExt + "_p" + boost::lexical_cast<string>(nProc_f) + ".arh";
Siqi Ling's avatar
Siqi Ling committed
632
633
		if(!boost::filesystem::exists(fn)) break;
	      }
634
635
636
637
638
639
640
	      if (nProc_f != nProcs) {
		newFilename = false;
		for (nProc_f = 0; nProc_f < nProcs + 1; nProc_f++) {
		  string fn = filenameWithoutExt + "-p" + boost::lexical_cast<string>(nProc_f) + "-.arh";
		  if(!boost::filesystem::exists(fn)) break;
		}
	      }
Siqi Ling's avatar
Siqi Ling committed
641
	    }
642
643
644
645
	    
	    TEST_EXIT(nProc_f == nProcs)
	      ("Number of arh files doesn't match number of processors: %d vs %d\n", nProc_f, nProcs);
	      
Praetorius, Simon's avatar
Praetorius, Simon committed
646
	    if (parhExists) {
647
648
	      TEST_EXIT(nProc_f == nProcs_)
		("Number of arh files doesn't match the label in parh file: %d vs %d", nProc_f, nProcs_);
Praetorius, Simon's avatar
Praetorius, Simon committed
649
            }
Siqi Ling's avatar
Siqi Ling committed
650
	      
651
	    if (!parhExists) {
Siqi Ling's avatar
Siqi Ling committed
652
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS	      
653
	      if (MPI::COMM_WORLD.Get_rank() == 0)
Siqi Ling's avatar
Siqi Ling committed
654
655
#endif
	        for(int i = 0; i < nProcs; i++)
656
		  nMacros_ += readNumOfMacrosFromSgArh(filename, i, newFilename);
Siqi Ling's avatar
Siqi Ling committed
657
658
659
660
661
	    }
	      
	    nMacros = mesh->getNumberOfMacros();
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
	    Parallel::mpi::globalAdd(nMacros);
662
	    if(MPI::COMM_WORLD.Get_rank() == 0)
Siqi Ling's avatar
Siqi Ling committed
663
#endif	      
664
	    {
Siqi Ling's avatar
Siqi Ling committed
665
666
667
	      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_); 
668
	    }
Siqi Ling's avatar
Siqi Ling committed
669

670
	    if (!parhExists) {
671
672
673
674
675
676
677
678
679
680
681
	      if (newFilename) {
		for (int i = 0; i < nProcs; i++) {
		  string procFilename = filenameWithoutExt + "_p" + lexical_cast<string>(i) + ".arh";
		  read(procFilename, mesh, vecs, byName);
		}
	      } else
	      {
		for (int i = 0; i < nProcs; i++) {
		  string procFilename = filenameWithoutExt + "-p" + lexical_cast<string>(i) + "-.arh";
		  read(procFilename, mesh, vecs, byName);
		}
Siqi Ling's avatar
Siqi Ling committed
682
683
684
685
686
687
688
689
	      }
	    } 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();
690
691
692
693
694
695
696
697
698
699
	      if (newFilename) {
		for (;it2 != needFiles.end(); it2++) {
		  string procFilename = filenameWithoutExt + "_p" + lexical_cast<string>(*it2) + ".arh";
		  read(procFilename, mesh, vecs, byName);
		}
	      } else {
		for (;it2 != needFiles.end(); it2++) {
		  string procFilename = filenameWithoutExt + "-p" + lexical_cast<string>(*it2) + "-.arh";
		  read(procFilename, mesh, vecs, byName);
		}
Siqi Ling's avatar
Siqi Ling committed
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
	      }
	    }
	  }
	} 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;
725
	Cpsformat::Value cps = Cpsformat::NONE;    
Siqi Ling's avatar
Siqi Ling committed
726
727
728
729
730
731
732
733
734
735
	
	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);
736
	cps = static_cast<Cpsformat::Value>(cpsflag);
Siqi Ling's avatar
Siqi Ling committed
737
738
	
#ifdef HAVE_COMPRESSION
739
740
741
	TEST_EXIT(cps == Cpsformat::ZLIB  || 
		  cps == Cpsformat::BZIP2 ||
		  cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
742
	  ("Cannot read Arh3 file. Currently only support zlib and bzip2 compression.\n");
Siqi Ling's avatar
Siqi Ling committed
743
#else
744
	TEST_EXIT(cps == Cpsformat::NONE)
Siqi Ling's avatar
Siqi Ling committed
745
	  ("HAVE_COMPRESSION OFF. Cannot read compressed Arh3 file.\n");	
Siqi Ling's avatar
Siqi Ling committed
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
#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, ' ');
778
	  file.read(&tmpString[0], tmpInt); //
Siqi Ling's avatar
Siqi Ling committed
779
780
781
	  file.read(reinterpret_cast<char*>(&tmpInt), 4);
	  sortedFeSpaces[tmpInt].push_back(i);
	  tmpString.resize(4, ' ');
782
	  file.read(&tmpString[0], 4);
Siqi Ling's avatar
Siqi Ling committed
783
	  dataformat.push_back(tmpString);
784
785
786
787
788
789
	}
	
	// Read macroFile_nl
	uint32_t macroFile_nl = 0;
	file.read(reinterpret_cast<char*>(&macroFile_nl), 4);
	string tmpString("");
790
	file.read(&tmpString[0], macroFile_nl);
791
792
	
	//================header is over==================//
Siqi Ling's avatar
Siqi Ling committed
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
    
	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)
	  {
809
	    case Cpsformat::ZLIB:
Siqi Ling's avatar
Siqi Ling committed
810
811
	      in.push(boost::iostreams::zlib_decompressor());
	      break;
812
	    case Cpsformat::BZIP2:
Siqi Ling's avatar
Siqi Ling committed
813
814
	      in.push(boost::iostreams::bzip2_decompressor());
	      break;
815
	    case Cpsformat::NONE:
Siqi Ling's avatar
Siqi Ling committed
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
864
865
866
867
868
869
	      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
    
  
870
      int readNumOfMacrosFromSgArh(std::string filename, int nProc, bool newFilename)
Siqi Ling's avatar
Siqi Ling committed
871
872
873
874
875
      {
	FUNCNAME("Arh3Reader::readHeaderSize");
	using boost::lexical_cast;
	
	int sPos = filename.find(".arh");
876
	TEST_EXIT(sPos >= 0)("Failed to find file postfix: \"arh \"!\n");
Siqi Ling's avatar
Siqi Ling committed
877
878
879
	
	if (nProc >= 0) {
	  string name = filename.substr(0, sPos);
880
881
882
883
	  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
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
	}
	
	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;
      }
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
      
      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
950
        
951
      std::string readParallelFile(string filename, vector<int>& partition, int& nFiles, int& nMacros)
Siqi Ling's avatar
Siqi Ling committed
952
      {
953
954
955
956
	FUNCNAME("Arh3Reader::detail::readParallelFile()");
	
	checkMeshconvParh1_0(filename);
	
Siqi Ling's avatar
Siqi Ling committed
957
958
959
960
961
	ifstream file;
	file.open(filename.c_str(), ios::in | ios::binary);
	TEST_EXIT(file.is_open())
	  ("Cannot open file %s\n", filename.c_str());
	
962
	string fd(16, ' ');
963
	file.read(&fd[0], 16);
964
965
966
	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));
967
968
969
970
	
	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
971
	firstRead(Id, major, minor, "parh", PARH_MAJOR, PARH_MINOR);
Siqi Ling's avatar
Siqi Ling committed
972
	
973
974
	uint32_t baseDirLen = 0, macroFile_nl = 0;
	string baseDir, macroFilename;
Siqi Ling's avatar
Siqi Ling committed
975
	
976
977
	file.read(reinterpret_cast<char*>(&baseDirLen), 4);
	baseDir.resize(baseDirLen, ' ');
978
	file.read(&baseDir[0], baseDirLen);
Siqi Ling's avatar
Siqi Ling committed
979
980
	file.read(reinterpret_cast<char*>(&nFiles), 4);
	file.read(reinterpret_cast<char*>(&macroFile_nl), 4);
981
	if (macroFile_nl > 0) { //TODO read macro from arh
982
	  macroFilename.resize(macroFile_nl, ' ');
983
	  file.read(&macroFilename[0], macroFile_nl);
984
985
	}
	file.read(reinterpret_cast<char*>(&nMacros), 4);
Siqi Ling's avatar
Siqi Ling committed
986
987
	
	uint32_t rank = 0;
988
	for (int i = 0; i < nMacros; i++) {
Siqi Ling's avatar
Siqi Ling committed
989
990
991
	  file.read(reinterpret_cast<char*>(&rank), 4);
	  partition.push_back(rank);
	}
992
993
	
	return baseDir;
Siqi Ling's avatar
Siqi Ling committed
994
995
996
997
998
999
1000
      }

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