MacroReader.cc 62.5 KB
Newer Older
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
27
28
29
30
31
#include "MacroReader.h"
#include "MacroWriter.h"
#include "MacroElement.h"
#include "Boundary.h"
#include "FiniteElemSpace.h"
#include "Mesh.h"
#include <string>
#include "FixVec.h"
#include "FixVecConvert.h"
#include "PeriodicMap.h"
#include "ElInfo.h"
#include "Parameters.h"
#include "DOFIterator.h"
#include "SurfaceRegion_ED.h"
#include "ElementRegion_ED.h"
#include "LeafData.h"
#include "VertexVector.h"
#include <map>
#include <iostream>
#include <fstream>

namespace AMDiS {

  MacroInfo* MacroReader::readMacro(const char *filename, 
				    Mesh* mesh,
				    const char *periodicFile,
				    int check)
  {
    FUNCNAME("Mesh::readMacro()");

    TEST_EXIT(filename)("no file specified; filename NULL pointer\n");
32
33
   
    MacroInfo *macroInfo = NEW MacroInfo();
34
35
    macroInfo->readAMDiSMacro(filename, mesh);

36
37
38
39
    ::std::deque<MacroElement*>::iterator mel = macroInfo->mel.begin();
    int **melVertex = macroInfo->mel_vertex;
    WorldVector<double> *coords = macroInfo->coords;
    DegreeOfFreedom **dof = macroInfo->dof;
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

    // === read periodic data =================================
    if (periodicFile&&(strcmp(periodicFile, "") != 0)) {
      WARNING("periodic boundaries may lead to errors in small meshes if element neighbours not set\n");
    
      FILE *file = fopen(periodicFile, "r");
      TEST_EXIT(file)("can't open file %s\n", periodicFile);

      int n;
      int dim = mesh->getDim();

      int el1, el2;
      int *verticesEl1 = GET_MEMORY(int, dim);
      int *verticesEl2 = GET_MEMORY(int, dim);
      int mode = -1; // 0: drop dofs, 1: associate dofs
      BoundaryType boundaryType;

      fscanf(file, "%*s %d", &n);

      fscanf(file, "%*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s");

      PeriodicMap periodicMap;
    
63
      for (int i = 0; i < n; i++) {
64
65
66
67
68
69
70
71
	::std::map<int, int> vertexMapEl1;
	::std::map<int, int> vertexMapEl2;

	TEST_EXIT(fscanf(file, "%d", &mode) == 1)("mode?\n");
      
	TEST_EXIT(fscanf(file, "%d", &boundaryType) == 1)("boundaryType?\n");
      
	TEST_EXIT(fscanf(file, "%d", &el1) == 1)("el1?\n");
72
	for (int j = 0; j < dim; j++) {
73
74
75
	  TEST_EXIT(fscanf(file, "%d", &verticesEl1[j]) == 1)("vertEl1[%d]\n", j);
	}
	TEST_EXIT(fscanf(file, "%d", &el2) == 1)("el2?\n");
76
	for (int j = 0; j < dim; j++) {
77
78
	  TEST_EXIT(fscanf(file, "%d", &verticesEl2[j]) == 1)("vertEl2[%d]\n", j);
	}
79
80
	for (int j = 0; j < dim; j++) {
	  if (mode == 0) {
81
82
83
84
85
86
87
88
89
	    periodicMap.setEntry(melVertex[el1][verticesEl1[j]], 
				 melVertex[el2][verticesEl2[j]]);
	  }
	  vertexMapEl1[verticesEl1[j]] = verticesEl2[j];
	  vertexMapEl2[verticesEl2[j]] = verticesEl1[j];
	}

	// calculate sides of periodic vertices
	int sideEl1 = 0, sideEl2 = 0;
90
	if (dim == 1) {
91
92
93
	  sideEl1 = verticesEl1[0];
	  sideEl2 = verticesEl2[0];
	} else {
94
	  for (int j = 0; j < dim + 1; j++) {
95
96
97
	    sideEl1 += j;
	    sideEl2 += j;
	  }
98
	  for (int j = 0; j < dim; j++) {
99
100
101
102
103
104
	    sideEl1 -= verticesEl1[j];
	    sideEl2 -= verticesEl2[j];
	  }
	}
	
	// create periodic info
105
106
	DimVec<WorldVector<double> > periodicCoordsEl1(dim - 1, NO_INIT);
	DimVec<WorldVector<double> > periodicCoordsEl2(dim - 1, NO_INIT);
107

108
109
	Element *element1 = const_cast<Element*>((*(mel + el1))->getElement());
	Element *element2 = const_cast<Element*>((*(mel + el2))->getElement());
110
111
      
	// for all vertices of this side
112
	for (int j = 0; j < dim; j++) {
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
	  periodicCoordsEl1[element1->getPositionOfVertex(sideEl1, verticesEl1[j])] = 
	    coords[melVertex[el2][vertexMapEl1[verticesEl1[j]]]];
	  periodicCoordsEl2[element2->getPositionOfVertex(sideEl2, verticesEl2[j])] =
	    coords[melVertex[el1][vertexMapEl2[verticesEl2[j]]]];
	}
      
	// decorate leaf data
	ElementData *ld1 = element1->getElementData();
	ElementData *ld2 = element2->getElementData();

	LeafDataPeriodic *ldp1 = dynamic_cast<LeafDataPeriodic*>(ld1->getElementData(PERIODIC));
	LeafDataPeriodic *ldp2 = dynamic_cast<LeafDataPeriodic*>(ld2->getElementData(PERIODIC));

	if (!ldp1) {
	  ldp1 = NEW LeafDataPeriodic(ld1);
	  element1->setElementData(ldp1);
	}

	if (!ldp2) {
	  ldp2 = NEW LeafDataPeriodic(ld2);
	  element2->setElementData(ldp2);
	}

	ldp1->addPeriodicInfo(mode,
			      boundaryType, 
			      sideEl1, 
			      &periodicCoordsEl1);

	ldp2->addPeriodicInfo(mode,
			      boundaryType, 
			      sideEl2, 
			      &periodicCoordsEl2);

	if (mode != 0) {
	  VertexVector *associated = mesh->periodicAssociations[boundaryType];
148

149
150
151
152
153
154
155
156
157
	  if (!associated) {
	    associated = NEW VertexVector(mesh->getVertexAdmin(), "vertex vector");
	    mesh->periodicAssociations[boundaryType] = associated;
	    VertexVector::Iterator it(associated, ALL_DOFS);
	    for (it.reset2(); !it.end(); ++it) {
	      *it = it.getDOFIndex();
	    }
	  }

158
	  for (int j = 0; j < dim; j++) {
159
160
161
162
163
164
165
166
167
168
169
170
	    (*associated)[melVertex[el1][verticesEl1[j]]] =
	      melVertex[el2][vertexMapEl1[verticesEl1[j]]];
	    (*associated)[melVertex[el2][verticesEl2[j]]] =
	      melVertex[el1][vertexMapEl2[verticesEl2[j]]];
	  }
	}
      }    

      FREE_MEMORY(verticesEl1, int, dim);
      FREE_MEMORY(verticesEl2, int, dim);

      // change periodic vertex dofs
171
      for (int i = 0; i < mesh->getNumberOfVertices(); i++) {
172
173
174
175
176
177
178
	if (periodicMap.getEntry(i) != -1) {
	  mesh->freeDOF(dof[i], VERTEX);
	  dof[i] = dof[periodicMap.getEntry(i)];

	  ::std::map<BoundaryType, VertexVector*>::iterator assoc;
	  ::std::map<BoundaryType, VertexVector*>::iterator assocEnd =
	      mesh->periodicAssociations.end();
179
180
181
182
183
184
185
186
187

	  for (assoc = mesh->periodicAssociations.begin(); 
	       assoc != assocEnd; 
	       ++assoc) {

	    DegreeOfFreedom a = (*(assoc->second))[i];
	    if (a != i) {
	      (*(assoc->second))[i] = i;
	      (*(assoc->second))[a] = periodicMap.getEntry(i);
188
	    }
189
190
	  }

191
192
193
194
195
196
197
198
	}
      }

      ::std::map<BoundaryType, VertexVector*>::iterator assoc;
      ::std::map<BoundaryType, VertexVector*>::iterator assocEnd =
	  mesh->periodicAssociations.end();
      for (assoc = mesh->periodicAssociations.begin(); 
	   assoc != assocEnd; 
199
200
201
202
203
204
205
	   ++assoc) {

	for (int i = 0; i < mesh->getNumberOfVertices(); i++) {
	  if (i != (*(assoc->second))[i])
	    MSG("association %d: vertex %d -> vertex %d\n", 
		assoc->first,
		i, (*(assoc->second))[i]);
206
	}
207
208
209
      }

      for (int i = 0; i < mesh->getNumberOfVertices(); i++) {
210
211
212
213
214
	if (periodicMap.getEntry(i) != -1) {
	  MSG("identification : vertex %d is now vertex %d\n", i, periodicMap.getEntry(i));
	}
      }
    }
215

216
217
    // =========================================================

218
219
220
    for (int i = 0; i < mesh->getNumberOfMacros(); i++) {
      for (int k = 0; k < mesh->getGeo(VERTEX); k++) {
	(*(mel + i))->setCoord(k, coords[melVertex[i][k]]);
221

222
	const_cast<Element*>((*(mel+i))->getElement())->
223
	  setDOF(k, dof[melVertex[i][k]]);
224
      }
225
    }
226

227
228
229
    if (!macroInfo->neigh_set) {
      TEST_EXIT(!periodicFile)
	("periodic boundary condition => element neighbours must be set\n");
230
	computeNeighbours(mesh);
231
    } else {
232
233
234
235
	/****************************************************************************/
	/* fill MEL oppVertex values when reading neighbour information form file  */
	/****************************************************************************/

236
237
238
239
240
241
242
243
244
      for (int i = 0; i < mesh->getNumberOfMacros(); i++) {
	for (int k = 0; k < mesh->getGeo(NEIGH); k++) {
	  MacroElement *neigh = const_cast<MacroElement*>(mel[i]->getNeighbour(k));

	  if (neigh) {
	    int j;
	    for (j = 0; j < mesh->getGeo(NEIGH); j++)
	      if (neigh->getNeighbour(j) == *(mel + i))  
		break;
245
	
246
247
248
249
250
	    TEST_EXIT(j < mesh->getGeo(NEIGH))("el %d no neighbour of neighbour %d\n", 
					       mel[i]->getIndex(), neigh->getIndex());
	    mel[i]->setOppVertex(k, j);
	  } else {
	    mel[i]->setOppVertex(k, -1);
251
	  }
252
	}
253
      }
254
    }
255
256
257
258
259
260
261
262
263
264
265
266
267

    if (!macroInfo->bound_set) {
      macroInfo->dirichletBoundary();
    }
  
    if(mesh->getDim() > 1)
      boundaryDOFs(mesh);

    // initial boundary projections
    //if(dim > 1) {
    int numFaces = mesh->getGeo(FACE);
    int dim = mesh->getDim();
    mel = mesh->firstMacroElement();
268
    for (int i = 0; i < mesh->getNumberOfLeaves(); i++) {
269
270
      MacroElement *macroEl = *(mel+i);
      Projection *projector = macroEl->getProjection(0);
271
272
      if (projector && projector->getType() == VOLUME_PROJECTION) {
	for (int j = 0; j <= dim; j++) {
273
274
275
	  projector->project(macroEl->getCoord(j));
	}
      } else {
276
	for (int j = 0; j < mesh->getGeo(EDGE); j++) {
277
	  projector = macroEl->getProjection(numFaces + j);
278
	  if (projector) {
279
280
281
282
283
284
285
286
287
288
289
290
291
	    int vertex0 = Global::getReferenceElement(dim)->getVertexOfEdge(j, 0);
	    int vertex1 = Global::getReferenceElement(dim)->getVertexOfEdge(j, 1);
	    projector->project(macroEl->getCoord(vertex0));
	    projector->project(macroEl->getCoord(vertex1));
	  }
	}
      }
    }
    //}

    macroInfo->fillBoundaryInfo(mesh);

    if (mesh->getNumberOfDOFs(CENTER)) {
292
293
294
295
      for (int i = 0; i < mesh->getNumberOfMacros(); i++) {
	const_cast<Element*>(mel[i]->getElement())->
	  setDOF(mesh->getNode(CENTER),mesh->getDOF(CENTER));
      }
296
297
298
299
300
301
    }

    /****************************************************************************/
    /* domain size                                                              */
    /****************************************************************************/

302
    WorldVector<double> x_min, x_max;
303

304
305
306
307
308
309
310
311
312
313
314
    for (int j = 0; j < Global::getGeo(WORLD); j++) {
      x_min[j] =  1.E30;
      x_max[j] = -1.E30;
    }

    for (int i = 0; i < mesh->getNumberOfVertices(); i++) {
      for (int j = 0; j < Global::getGeo(WORLD); j++) {
	x_min[j] = ::std::min(x_min[j], coords[i][j]);
	x_max[j] = ::std::max(x_max[j], coords[i][j]);
      }
    }
315

316
    for (int j = 0; j < Global::getGeo(WORLD); j++)
317
318
319
320
321
322
      mesh->setDiameter(j, x_max[j] - x_min[j]);

    if (check) {
      checkMesh(mesh);

      if (mesh->getDim() > 1) {
323
324
325
326
327
	char filenew[128];
	strncpy(filenew, filename, 128); 
	filenew[127] = 0;
	strncat(filenew, ".new", 128);   
	filenew[127] = 0;
328
329
330
331
332
333
334
335
336
337
338
339
340
	macroTest(mesh, filenew);
      }
    }

    return(macroInfo);
  }

  /****************************************************************************/
  /*  fill macro info structure and some pointers in mesh ...                 */
  /****************************************************************************/

  void MacroInfo::fill(Mesh *pmesh, int ne, int nv)
  {
341
342
    FUNCNAME("MacroInfo::fill()");

343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
    int      i;
    int      dim=pmesh->getDim();
  
    TEST_EXIT(mesh = pmesh)("no mesh\n");

    mesh->setNumberOfElements(ne);
    mesh->setNumberOfLeaves(ne);
    mesh->setNumberOfVertices(nv);


    for(i = 0; i < ne; i++) {
      MacroElement *newMacro = NEW MacroElement(mesh->getDim());
      mel.push_back(newMacro);
      mesh->addMacroElement(mel[i]);
    }

    dof = GET_MEMORY(DegreeOfFreedom*, nv);

    coords =  NEW WorldVector<double>[nv];
  
    mel_vertex = GET_MEMORY(int*, ne);
    for (i = 0; i < ne; i++) {
      mel_vertex[i]=GET_MEMORY(int, mesh->getGeo(VERTEX));
    }

    for (i = 0; i < nv; i++)
      dof[i] = mesh->getDOF(VERTEX);

    for (i = 0; i < ne; i++) {
      mel[i]->element = mesh->createNewElement();
      (mel)[i]->index = i;

      if (dim == 3) {
	(mel)[i]->elType = 0;
      }
    }
    neigh_set = false;
    bound_set = false;

    return;
  }

  void MacroInfo::clear(int ne, int nv)
  {
    for (int i = 0; i < mesh->getNumberOfMacros(); i++)
      FREE_MEMORY(mel_vertex[i], int, mesh->getGeo(VERTEX));

    FREE_MEMORY(mel_vertex, int*, ne);

    coords = NULL;  /* must no be freed!!! still used in the mesh!!!     */
    mesh = NULL;
    neigh_set = false;
  }

  /****************************************************************************/
  /****************************************************************************/
  /*  tool for reading macro triangulations in ALBERT-format                  */
  /****************************************************************************/
  /****************************************************************************/

  /****************************************************************************/
  /*  read_indices()  reads dim+1 indices from  file  into  id[0-dim],        */
  /*    returns true if dim+1 inputs arguments could be read successfully by  */
  /*    fscanf(), else false                                                  */
  /****************************************************************************/

  int  MacroInfo::read_indices(FILE *file, DimVec<int> &id)
  {
    int dim = mesh->getDim();

    for (int i = 0; i <= dim; i++) {
      if (fscanf(file, "%d", &id[i]) != 1)
	return(false);
    }

    return(true);
  }

#define N_KEYS      14
#define N_MIN_KEYS  7
  static const char *keys[N_KEYS] = {
    "DIM",                   //  0 
    "DIM_OF_WORLD",          //  1
    "number of vertices",    //  2
    "number of elements",    //  3
    "vertex coordinates",    //  4
    "element vertices",      //  5
    "element boundaries",    //  6
    "element neighbours",    //  7
    "element type",          //  8
    "projections",           //  9
    "element region",        // 10
    "surface region",        // 11
    "mesh name",             // 12
    "time"                   // 13
  };

  static int get_key_no(const char *key)
  {
    int     i;

    for (i = 0; i < N_KEYS; i++)
      if (!strcmp(keys[i], key))  return(i);

    return(-1);
  }

#include <ctype.h>

  static const char *read_key(const char *line)
  {
    static char  key[100];
    char         *k = key;

    while (isspace(*line)) 
	line++;
    while ((*k++ = *line++) != ':');
    *--k = '\0';
  
    return(const_cast<const char *>( key));
  }

  /****************************************************************************/
  /*  read_albert_macro():                                                    */
  /*    read macro triangulation from ascii file in ALBERT format             */
  /*    fills macro_info structure                                            */
  /*    called by read_macro(), fills missing information                     */
  /****************************************************************************/


  void MacroInfo::readAMDiSMacro(const char *filename, Mesh* mesh)
  {
    FUNCNAME("MacroInfo::readAMDiSMacro");
    FILE       *file;
    int        dim;
478
    int        dow, nv, ne, j, k;
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
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
    double     dbl;
    char       name[128], line[256];
    int        line_no, n_keys, i_key, sort_key[N_KEYS], nv_key, ne_key;
    int        key_def[N_KEYS] = {0,0,0,0,0,0,0,0,0,0,0,0};
    const char *key;
    DimVec<int> *ind = NULL;

    TEST_EXIT(filename)("no file specified; filename NULL pointer\n");
    //TEST_EXIT(pmesh)("no mesh specified; mesh NULL pointer\n");
    TEST_EXIT(strlen(filename) < static_cast<unsigned int>(127))
      ("can only handle filenames up to 127 characters\n");

    TEST_EXIT((file=fopen(filename,"r")))("cannot open file %s\n",filename);
    strncpy(name, filename, 127);

    /****************************************************************************/
    /*  looking for all keys in the macro file ...                              */
    /****************************************************************************/

    line_no = n_keys = 0;
    while (fgets(line, 255, file)) {
	line_no++;
	if (!strchr(line, ':'))  continue;
	key = read_key(line);
	i_key = get_key_no(key);
	TEST_EXIT(i_key >= 0)
	  ("macro file %s must not contain key %s on line %d\n",
	   name, key, line_no);
	TEST_EXIT(!key_def[i_key])
	  ("key %s defined second time on line %d in file %s\n");

	sort_key[n_keys++] = i_key;
	key_def[i_key] = true;
    }

    fclose(file);
    for (i_key = 0; i_key < N_MIN_KEYS; i_key++) {
	for (j = 0; j < n_keys; j++)
	    if (sort_key[j] == i_key)  break;
	TEST_EXIT(j < n_keys)("You do not have specified data for %s in %s\n",
			      keys[i_key], name);

	for (j = 0; j < n_keys; j++)
	  if (sort_key[j] == 2)  break;
	nv_key = j;
	for (j = 0; j < n_keys; j++)
	  if (sort_key[j] == 3)  break;
	ne_key = j;
    
	switch(i_key) {
	    case 0:
	    case 1:
		TEST_EXIT(sort_key[i_key] < 2)
		    ("You have to specify DIM or mesh->getGeo(WORLD) before all other data\n");
		break;
	    case 4: 
		TEST_EXIT(nv_key < i_key)
		    ("Before reading data for %s, you have to specify the %s in file\n",
		     keys[4], keys[2], name);
		break;
	    case 5: 
		TEST_EXIT(nv_key < i_key  &&  ne_key < i_key)
		    ("Before reading data for %s, you have to specify the %s and %s in file %s\n",
		     keys[5], keys[3], keys[2], name);
	    case 6:
	    case 7:
	    case 8:
		TEST_EXIT(ne_key < i_key)
		    ("Before reading data for %s, you have to specify the %s in file %s\n",
		     keys[i_key], keys[3], name);
	}
    }

    for (i_key = 0; i_key < N_KEYS; i_key++)
      key_def[i_key] = false;

    /****************************************************************************/
    /*  and now, reading data ...                                               */
    /****************************************************************************/
	
    TEST_EXIT((file=fopen(name,"r")))("cannot open file %s\n",name);

    for (i_key = 0; i_key < n_keys; i_key++) {

	switch(sort_key[i_key]) {
	  case 0:
	    TEST_EXIT(fscanf(file, "%*s %d", &dim) == 1)
	      ("cannot read DIM correctly in file %s\n", name);

	    ind = NEW DimVec<int>(dim, NO_INIT);

	    key_def[0] = true;
	    break;
	  case 1:
	    TEST_EXIT(fscanf(file, "%*s %d", &dow) == 1)
	      ("cannot read Global::getGeo(WORLD) correctly in file %s\n", name);
	    TEST_EXIT(dow == Global::getGeo(WORLD))
	      ("dimension of world = %d != Global::getGeo(WORLD) = %d\n", 
	       dow, Global::getGeo(WORLD));

	    key_def[1] = true;
	    break;
	  case 2:
	    TEST_EXIT(fscanf(file, "%*s %*s %*s %d", &nv) == 1)
	      ("cannot read number of vertices correctly in file %s\n", name);
	    TEST_EXIT(nv > 0)
	      ("number of vertices = %d must be bigger than 0\n", nv);

	    key_def[2] = true;
	    if (key_def[3])
	      fill(mesh, ne, nv);
	    break;
	  case 3:
	    TEST_EXIT(fscanf(file, "%*s %*s %*s %d", &ne) == 1)
	      ("cannot read number of elements correctly in file %s\n", name);
	    TEST_EXIT(ne > 0)
	      ("number of elements = %d must be bigger than 0\n", ne);

	    key_def[3] = true;
	    if (key_def[2])
	      fill(mesh, ne, nv);
	    break;
	  case 4:
	    fscanf(file, "%*s %*s");
603
604
605
606
607
	    for (int i = 0; i < nv; i++) {
	      for (j = 0; j <Global::getGeo(WORLD) ; j++) {
		TEST_EXIT(fscanf(file, "%lf", &dbl) == 1)
		  ("error while reading coordinates, check file %s\n", name);
		coords[i][j] = dbl;
608
	      }
609
	    }
610
611
612
613
614
615
616
617
	    key_def[4] = true;
	    break;
	  case 5:
	    fscanf(file, "%*s %*s");
	    /****************************************************************************/
	    /* global number of vertices on a single element                            */
	    /****************************************************************************/

618
	    for (int i = 0; i < ne; i++) {
619
620
621
622
623
624
625
626
627
628
629
630
631
632
		TEST_EXIT(read_indices(file, *ind))
		  ("cannot read vertex indices of element %d in file %s\n",  i, name);

		for (k = 0; k < mesh->getGeo(VERTEX); k++)
		  mel_vertex[i][k] = (*ind)[k];
	      }

	    key_def[5] = true;
	    break;
	  case 6:
	    fscanf(file, "%*s %*s");
	    /****************************************************************************/
	    /* MEL boundary pointers                                                    */
	    /****************************************************************************/
633
	    for (int i = 0; i < ne; i++) {  
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
                // boundary information of ith element 

		TEST_EXIT(read_indices(file, *ind))
		    ("cannot read boundary type of element %d in file %s\n", i, name);

		// fill boundary of macro-element
		MacroReader::fillMelBoundary(mesh, 
					     mel[i], 
					     VecConv<int,NEIGH,PARTS>::convertVec((*ind), mesh));
	    }

	    this->fillBoundaryInfo(mesh);
                   
	    bound_set = true;
	    key_def[6] = true;
	    break;
	  case 7:
	    fscanf(file, "%*s %*s");
	    /****************************************************************************/
	    /* fill MEL neighbour pointers:                                             */
	    /*   if they are specified in the file: read them from file,                */
	    /*   else init them by a call of fill_mel_neighbour()                       */
	    /****************************************************************************/
	    neigh_set = true;
658
	    for (int i = 0; i < ne; i++) {
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
                //  neighbour information about ith element

		if (read_indices(file, *ind))
		  MacroReader::fillMelNeigh(mel[i], mel, 
					    VecConv<int,NEIGH,PARTS>::convertVec((*ind), 
										 mesh));
		else {
		  neigh_set = false; /* setting of neighbours fails :-( */
		  break;
		}
	      }

	    key_def[7] = true;
	    break;
	  case 8:
	    fscanf(file, "%*s %*s");
	    /****************************************************************************/
	    /* MEL elType                                                               */
	    /****************************************************************************/

	    if (dim == 2 || dim == 1)
	      ERROR("there is no element type in 2d and 2d; ignoring data for elType\n");

682
	    for (int i = 0; i < ne; i++) {
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
		TEST_EXIT(fscanf(file, "%d", &j) == 1)
		  ("cannot read elType of element %d in file %s\n",
		   i, name);
		if (dim == 3) {
		  (mel)[i]->elType = j;
		}
	      }

	    key_def[8] = true;
	    break;
	  case 9:
	    {
	      fscanf(file, "%*s");

	      int numFaces = mesh->getGeo(FACE);
	      int numEdgesAtBoundary = 0;

700
	      for (k = 1; k < dim; k++) {
701
702
703
		numEdgesAtBoundary += k;
	      }

704
	      for (int i = 0; i < ne; i++) {
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
		TEST_EXIT(read_indices(file, *ind))
		  ("cannot read boundary projector of element %d in file %s\n", i, name);
	
		Projection *projector = Projection::getProjection((*ind)[0]);

		if(projector && projector->getType() == VOLUME_PROJECTION) {
		  mel[i]->setProjection(0, projector);
		} else { // boundary projection
		  for(j = 0; j < mesh->getGeo(NEIGH); j++) {
		    projector = Projection::getProjection((*ind)[j]);
		    if(projector) {
		      mel[i]->setProjection(j, projector);
		      if(dim > 2) {
			for(k = 0; k < numEdgesAtBoundary; k++) {
			  int edgeNr = Global::getReferenceElement(dim)->getEdgeOfFace(j, k);
			  mel[i]->setProjection(numFaces + edgeNr, projector);
			}
		      }
		    }
		  }
		}
	      }
	    }
	    key_def[9] = true;
	    break;
	  case 10:
	    fscanf(file, "%*s %*s");
	    /****************************************************************************/
	    /* MEL regions                                                              */
	    /****************************************************************************/

736
	    for (int i = 0; i < ne; i++) {
737
738
739
740
741
742
743
744
745
746
747
748
749
750
	      TEST_EXIT(fscanf(file, "%d", &j) == 1)
		("cannot read region of element %d in file %s\n", i, name);
	      if(j >= 0) {
		Element *el = mel[i]->getElement();
		ElementRegion_ED *elementRegion = 
		  NEW ElementRegion_ED(el->getElementData());
		elementRegion->setRegion(j);
		el->setElementData(elementRegion);
	      }
	    }
	    key_def[10] = true;
	    break;
	  case 11:
	    fscanf(file, "%*s %*s");
751
	    for (int i = 0; i < ne; i++) {
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
	      TEST_EXIT(read_indices(file, *ind))
		("cannot read surface regions of element %d in file %s\n", i, name);

	      Element *el = mel[i]->getElement();

	      for(j = 0; j < mesh->getGeo(NEIGH); j++) {
		if((*ind)[j] >= 0) {
		  SurfaceRegion_ED *surfaceRegion = 
		    NEW SurfaceRegion_ED(el->getElementData());
		  surfaceRegion->setSide(j);
		  surfaceRegion->setRegion((*ind)[j]);
		  el->setElementData(surfaceRegion);
		}
	      }
	    }
	    key_def[11] = true;
	    break;
	  case 12:
	    fscanf(file, "%*s %*s %*s");
	    break;
	  case 13:
	    fscanf(file, "%*s %*s");
	    break;
	  }
      }

    fclose(file);
  }


  int macro_type(const char *filename, const char *type)
  {
    const char *fn, *t;
  
    if (strlen(filename) <= strlen(type))
      return(false);
  
    fn = filename;
    while (*fn) fn++;
    t = type;
    while (*t) t++;
  
    while (t != type  &&  *t == *fn) t--;
  
    return(t == type);
  }


  /****************************************************************************/
  /*  sets the boundary of all edges/faces with no neigbour to a straight     */
  /*  line/face with Dirichlet boundary type                                  */
  /****************************************************************************/

  void MacroInfo::dirichletBoundary()
  {
807
808
    for (int i = 0; i < static_cast<int>( mel.size()); i++) {
      for (int k = 0; k < mesh->getGeo(NEIGH); k++) {
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
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
950
951
	if (mel[i]->neighbour[k])
	  mel[i]->boundary[k] = INTERIOR;
	else
	  mel[i]->boundary[k] = DIRICHLET;
      }
    }
    return;
  }


  void MacroInfo::fillBoundaryInfo(Mesh *mesh)
  {
    int i,j,k, nv = mesh->getNumberOfVertices();

    ::std::deque<MacroElement*>::iterator melIt;

    BoundaryType *bound = GET_MEMORY(BoundaryType, nv);

    int dim = mesh->getDim();

    switch(dim) {
    case 1:
      break;
    case 2:
      for (i = 0; i < nv; i++)
	bound[i] = INTERIOR;

      for (i=0, melIt = mesh->firstMacroElement(); 
	   melIt != mesh->endOfMacroElements(); 
	   ++melIt, ++i) 
	{
	  for (j = 0; j < mesh->getGeo(NEIGH); j++) {
	    if ((*melIt)->getBoundary(j) != INTERIOR) {
	      if ((*melIt)->getBoundary(j) >= DIRICHLET) {
		int j1 = mel_vertex[i][(j+1)%3];
		int j2 = mel_vertex[i][(j+2)%3];

		bound[j1] = 
		  max(bound[j1], (*melIt)->getBoundary(j));
		bound[j2] = 
		  max(bound[j2], (*melIt)->getBoundary(j));
	      } 
	      else if ((*melIt)->getBoundary(j) <= NEUMANN) {
		int j1 = mel_vertex[i][(j+1)%3];
		int j2 = mel_vertex[i][(j+2)%3];

		if (bound[j1] != INTERIOR)
		  bound[j1] = 
		    max(bound[j1], (*melIt)->getBoundary(j));
		else
		  bound[j1] = (*melIt)->getBoundary(j);

		if (bound[j2] != INTERIOR)
		  bound[j2] = 
		    max(bound[j2], (*melIt)->getBoundary(j));
		else
		  bound[j2] = (*melIt)->getBoundary(j);
	      }
	    }
	  }
	}

      for (i=0, melIt = mesh->firstMacroElement(); 
	   melIt != mesh->endOfMacroElements(); 
	   ++melIt, i++) 
	{
	  for (j = 0; j < mesh->getGeo(VERTEX); j++)
	    (*melIt)->setBoundary(3 + j, bound[mel_vertex[i][j]]);
	}
      break;
    case 3:
      for (i = 0; i < nv; i++)
	bound[i] = INTERIOR;

      for (i=0, melIt = mesh->firstMacroElement(); 
	   melIt != mesh->endOfMacroElements(); 
	   ++melIt, i++) 
	{
	  for (j = 0; j < mesh->getGeo(NEIGH); j++) {
	    for (k = 1; k < 4; k++)
	      bound[mel_vertex[i][(j+k)%4]] =
		((*melIt)->getBoundary(j) != INTERIOR) ?
		newBound((*melIt)->getBoundary(j),
			 bound[mel_vertex[i][(j+k)%4]]) :
		//(*melIt)->getBoundary(j)->
		//newVal(bound[data->mel_vertex[i][(j+k)%4]]) :
		bound[mel_vertex[i][(j+k)%4]];
	  }
	}

      for (i = 0, melIt = mesh->firstMacroElement(); 
	   melIt != mesh->endOfMacroElements(); 
	   ++melIt, i++) 
	{
	  for (j = 0; j < mesh->getGeo(VERTEX); j++)
	    (*melIt)->setBoundary(10 + j, bound[mel_vertex[i][j]]);
	}
      break;
    default: ERROR_EXIT("invalid dim\n");
    }

    FREE_MEMORY(bound, BoundaryType, nv);
  }

  void MacroReader::computeNeighbours(Mesh *mesh)
  {
    FUNCNAME("MacroReader::computeNeighbours");
    int      i, j, k, l, m;
    int dim = mesh->getDim();

    FixVec<DegreeOfFreedom*, DIMEN>  dof(dim, NO_INIT);

    for (i = 0; i < mesh->getNumberOfLeaves(); i++)
      {
	for (k = 0; k < mesh->getGeo(NEIGH); k++)
	  {
	    mesh->getMacroElement(i)->setOppVertex(k, AMDIS_UNDEFINED);
	    mesh->getMacroElement(i)->setNeighbour(k, NULL);
	  }
      }

    for (i = 0; i < mesh->getNumberOfLeaves(); i++)
      {
	// MSG("search neighbour for element %d\n", i);
	for (k = 0; k < mesh->getGeo(NEIGH); k++)
	  {
	    if(mesh->getMacroElement(i)->getBoundary(k) != INTERIOR) {
	      mesh->getMacroElement(i)->setNeighbour(k, NULL);
	      mesh->getMacroElement(i)->setOppVertex(k, -1);
	      continue;
	    }

	    if (mesh->getMacroElement(i)->getOppVertex(k) == AMDIS_UNDEFINED)
	      {
		if(dim == 1)
		  dof[0] = const_cast<DegreeOfFreedom*>(mesh->getMacroElement(i)->
							getElement()->getDOF(k));
		else
		  for (l = 0; l < dim; l++)
		    dof[l] = const_cast<DegreeOfFreedom*>(mesh->getMacroElement(i)->
							  getElement()->
							  getDOF((k+l+1)%(dim+1)));

952
953
954
955
956
957
958
		for (j = i + 1; j < mesh->getNumberOfLeaves(); j++) {
		  if ((m = mesh->getMacroElement(j)->getElement()->oppVertex(dof)) != -1) {
		    mesh->getMacroElement(i)->setNeighbour(k, mesh->getMacroElement(j));
		    mesh->getMacroElement(j)->setNeighbour(m, mesh->getMacroElement(i));
		    mesh->getMacroElement(i)->setOppVertex(k, m);
		    mesh->getMacroElement(j)->setOppVertex(m, k);
		    break;
959
		  }
960
961
		}

962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
		TEST_EXIT(j < mesh->getNumberOfLeaves())
		  ("could not find neighbour %d of element %d\n", k, i);
	      }
	  }
      }


    return;
  }


  /****************************************************************************/
  /*  boundaryDOFs:                                                           */
  /*  adds dof's at the edges of a given macro triangulation and calculates   */
  /*  the number of edges                                                     */
  /****************************************************************************/

  void MacroReader::boundaryDOFs(Mesh *mesh)
  {
981
982
983
984
985
    FUNCNAME("Mesh::boundaryDOFs()");

    int lnode = mesh->getNode(EDGE);
    int k, lne = mesh->getNumberOfLeaves();
    int max_n_neigh = 0, n_neigh, ov;
986
987
    ::std::deque<MacroElement*>::iterator mel;
    const MacroElement* neigh;
988
    DegreeOfFreedom *dof;
989
990
991
992
993
994
995
996

    mesh->setNumberOfEdges(0);
    mesh->setNumberOfFaces(0);

    int dim = mesh->getDim();

    switch(dim) {
    case 2:
997
      for (mel = mesh->firstMacroElement(); mel != mesh->endOfMacroElements(); mel++) {
998
999
1000
1001
1002
1003
	// check for periodic boundary
	Element *el = const_cast<Element*>((*mel)->getElement());
	ElementData *ed = el->getElementData(PERIODIC);

	DimVec<bool> periodic(dim, DEFAULT_VALUE, false);

1004
	if (ed) {
1005
1006
1007
1008
	  ::std::list<LeafDataPeriodic::PeriodicInfo> &periodicInfos = 
	    dynamic_cast<LeafDataPeriodic*>(ed)->getInfoList();
	  ::std::list<LeafDataPeriodic::PeriodicInfo>::iterator it;
	  ::std::list<LeafDataPeriodic::PeriodicInfo>::iterator end = periodicInfos.end();
1009
1010
	  for (it = periodicInfos.begin(); it != end; ++it) {
	    if (it->type != 0) {
1011
1012
1013
1014
1015
	      periodic[it->elementSide] = true;
	    }
	  }
	}

1016
	for (int i = 0; i < mesh->getGeo(NEIGH); i++) {
1017
	  if (!(*mel)->getNeighbour(i) || 
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
	      ((*mel)->getNeighbour(i)->getIndex() < (*mel)->getIndex())) {

	    mesh->incrementNumberOfEdges(1);

	    if (mesh->getNumberOfDOFs(EDGE)) {
	      dof = el->setDOF(lnode + i, mesh->getDOF(EDGE));
      
	      if ((*mel)->getNeighbour(i)) {
		Element *neigh = const_cast<Element*>((*mel)->getNeighbour(i)->getElement());

		if (periodic[i]) {
		  neigh->setDOF(lnode + (*mel)->getOppVertex(i), mesh->getDOF(EDGE));
		} else {
		  neigh->setDOF(lnode + (*mel)->getOppVertex(i), dof);
1032
1033
		}
	      }
1034
1035
	    }
	  }  
1036
1037
1038
1039
1040
1041
	}
      }
      break;
    case 3:
      lnode = mesh->getNode(FACE);
      mel = mesh->firstMacroElement();
1042
      for (int i = 0; i < lne; i++) {
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131

	// check for periodic boundary
	Element *el = const_cast<Element*>((*(mel+i))->getElement());
	ElementData *ed = el->getElementData(PERIODIC);

	DimVec<bool> periodic(dim, DEFAULT_VALUE, false);
      
	if(ed) {
	  ::std::list<LeafDataPeriodic::PeriodicInfo> &periodicInfos = 
	    dynamic_cast<LeafDataPeriodic*>(ed)->getInfoList();
	  ::std::list<LeafDataPeriodic::PeriodicInfo>::iterator it;
	  ::std::list<LeafDataPeriodic::PeriodicInfo>::iterator end = periodicInfos.end();
	  for(it = periodicInfos.begin(); it != end; ++it) {
	    if(it->type != 0) {
	      periodic[it->elementSide] = true;
	    }
	  }
	}

	for (k = 0; k < mesh->getGeo(EDGE); k++) {      
	  /*********************************************************************/
	  /* check for not counted edges                                       */
	  /*********************************************************************/
	  n_neigh = 1;

	  // 	static int faceOfEdge[6][2] = { {2, 3}, 
	  // 	                                {1, 3},
	  // 					{1, 2},
	  // 					{0, 3},
	  // 					{0, 2},
	  // 					{0, 1} };

	  // 	bool periodicEdge;
	  // 	if(periodic[faceOfEdge[k][0]] || periodic[faceOfEdge[k][1]]) {
	  // 	  periodicEdge = true;
	  // 	} else {
	  // 	  periodicEdge = false;
	  // 	}

	  if (newEdge(mesh, (*(mel+i)), k, &n_neigh/*, periodicEdge*/)) {
	    // 	  if(periodicEdge) {
	    // 	    mesh->incrementNumberOfEdges(2);
	    // 	  } else {
	    mesh->incrementNumberOfEdges(1);
	    // 	  }
	    max_n_neigh = max(max_n_neigh, n_neigh);
	  }
	}
      
	for (k = 0; k < mesh->getGeo(NEIGH); k++) {
	  neigh = (*(mel+i))->getNeighbour(k);
	  /*********************************************************************/
	  /* face is counted and dof is added by the element with bigger index */
	  /*********************************************************************/
	  if (neigh  &&  (neigh->getIndex() > (*(mel+i))->getIndex()))  continue;
	
	  mesh->incrementNumberOfFaces(1);
	
	  if (mesh->getNumberOfDOFs(FACE)) {
	    TEST_EXIT(!(*(mel+i))->getElement()->getDOF(lnode+k))
	      ("dof %d on element %d already set\n", 
	       lnode+k, (*(mel+i))->getIndex());
	  
	    const_cast<Element*>((*(mel+i))->getElement())->setDOF(lnode+k, 
								   mesh->getDOF(FACE));

	    if (neigh) {
	      ov = (*(mel+i))->getOppVertex(k);
	      TEST_EXIT(!neigh->getElement()->getDOF(lnode+ov))
		("dof %d on neighbour %d already set\n", 
		 lnode+ov, neigh->getIndex());
	    
	      Element *neighEl = 
		const_cast<Element*>((*(mel+i))->getNeighbour(k)->getElement());

	      if (periodic[k]) {
		neighEl->setDOF(lnode+ov, mesh->getDOF(FACE));
	      } else {
		neighEl->setDOF(lnode+ov, const_cast<int*>((*(mel+i))->getElement()->
							   getDOF(lnode+k)));
	      }
	    }
	  }
	}
      }
      break;
    default: ERROR_EXIT("invalid dim\n");
    }
    
1132
    if (3 == dim) {
1133
      mesh->setMaxEdgeNeigh(::std::max(8, 2*max_n_neigh));
1134
    } else {
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
      mesh->setMaxEdgeNeigh(dim-1);    
    }

    return;
  }

  /* 
     testet mesh auf auftretende Zyklen
  
     wenn Zyklus auftritt:
     ordnet Eintraege in MacroElement-Struktur um, so dass kein Zyklus auftritt
     erzeugt neue Macro-Datei nameneu mit umgeordnetem Netz 
     (wenn nameneu=NULL wird keine MAcro-Datei erzeugt)
  */      

  void MacroReader::macroTest(Mesh *mesh, const char *nameneu)
  {
    FUNCNAME("MacroReader::macroTest");
 
    int i;
   
    i = macrotest(mesh);

    if (i >= 0)
      {
	ERROR("There is a cycle beginning in macro element %d\n", i);
	ERROR("Entries in MacroElement structures get reordered\n");
	umb(NULL,mesh, umbVkantMacro);

	if (nameneu)
	  {
	    ERROR_EXIT("mesh->feSpace\n");
	    //MacroWriter::writeMacro(mesh, nameneu);
	    MSG("Reordered mesh written to file %s.\n",nameneu);
	  }
      }
    return;
  }
  
  /****************************************************************************/
  /*  macro_test():                              Author: Thomas Kastl (1998)  */
  /****************************************************************************/
  /*
    testet mesh auf auftretende Zyklen
  
    wenn mesh zyklenfrei -> -1
    sonst ->  globaler Index des Macroelementes bei dem ein Zyklus beginnt 
  */

  int MacroReader::macrotest(Mesh *mesh)
  {
    FUNCNAME("MacroReader::macrotest");

    int *test;
    int i;
    int *zykl;
    ::std::deque<MacroElement*>::const_iterator macro,mac;
    int flg;
    ::std::deque<MacroElement*>::const_iterator macrolfd;
    int zykstart;

    int dim = mesh->getDim();

    test=GET_MEMORY(int, mesh->getNumberOfMacros());
    zykl=GET_MEMORY(int, mesh->getNumberOfMacros());
 
    for (i=0; i < mesh->getNumberOfMacros(); i++)
      test[i]=0;

    zykstart=-1;

    macrolfd=mesh->firstMacroElement();

    while (macrolfd != mesh->endOfMacroElements())
      {
	if (test[(*macrolfd)->getIndex()]==1)
	  {
	    macrolfd++;
	  }
	else
	  {
	    for (i=0; i < mesh->getNumberOfMacros(); i++)
	      zykl[i]=0;
    
	    macro=macrolfd;

	    flg=2;
	    do
	      { 
		if (zykl[(*macro)->getIndex()] == 1)
		  {
		    flg=0;
		    zykstart=(*macro)->getIndex();
		  }
		else
		  {
		    zykl[(*macro)->getIndex()]=1;
      
		    if (test[(*macro)->getIndex()]==1)
		      {       
			flg=1;
		      }   
		    else if ((*macro)->getNeighbour(dim) == NULL)
		      {
			flg=1;
			test[(*macro)->getIndex()]=1;
		      }
		    else if ((*macro) == (*macro)->getNeighbour(dim)->getNeighbour(dim))
		      {
			flg=1;
			test[(*macro)->getIndex()]=1;
			test[(*macro)->getNeighbour(dim)->getIndex()]=1;
		      }
		    else
		      {
			for(mac=mesh->firstMacroElement();
			    (*mac)!=(*macro)->getNeighbour(dim);
			    mac++);
			macro=mac;
		      } 
		  }
 
	      } while(flg == 2);
 
	    if (flg == 1)
	      {
		macrolfd++;
	      }
	    else
	      { 
		macrolfd=mesh->endOfMacroElements();
	      }
	  }
      }
  
    FREE_MEMORY(zykl, int, mesh->getNumberOfMacros());
    FREE_MEMORY(test, int, mesh->getNumberOfMacros());
 
    return zykstart;
  }

  //   waehlt geeignete Verfeinerungskanten, so dass kein Zyklus auftritt (recumb)

  //   ele     Integer-Vektor der Dimension Anzahl der Macro-Elemente
  //           zur Speicherung der neuen Verfeinerungskanten
  //           (wird nur benoetigt, wenn umbvk=umb_vkant_macrodat) 
  
  //   umbvk   Fkt. zur Neuordnung der Verfeinerungskanten
  //           = umb_vkant_macro :
  //               Eintraege in MacroElement-Struktur und Eintraege in macro->el
  //               werden tatsaechlich umgeordnet
  //               -> ALBERT-Routine write_macro kann zum erzeugen einer
  //                  neuen Macro-Datei angewendet werden 
  //           = umb_vkant_macrodat :
  //               Eintraege werden nicht veraendert, es werden nur die lokalen
  //               Indices der Kanten, die zu Verfeinerungskanten werden im
  //               Integer-Vektor ele abgespeichert
  //               -> print_Macrodat zur Erzeugung einer zyklenfreien neuen
  //                  Macro-Datei kann angewendet werden

  void MacroReader::umb(int *ele, Mesh *mesh,
			void (*umbvk)(Mesh*,MacroElement*,int,int*))
  {
    FUNCNAME("MacroReader::umb");

    int *test;
    int i;
  
    test=GET_MEMORY(int, mesh->getNumberOfMacros());
  
    for (i=0; i < static_cast<int>(mesh->getNumberOfMacros()); i++)
      test[i]=0;

    recumb(mesh, (*mesh->firstMacroElement()), NULL,test,0,0,ele,umbvk);

    FREE_MEMORY(test, int, mesh->getNumberOfMacros());
  }

  bool MacroReader::newEdge(Mesh *mesh, MacroElement *mel,
			    int mel_edge_no, int *n_neigh)
  {
    FUNCNAME("MacroElement::newEdge"); 
    MacroElement    *nei;
    const DegreeOfFreedom *dof[2];
    DegreeOfFreedom *edge_dof = NULL;
    int             j, k, opp_v, mel_index, node=0;
    BoundaryType    lbound = INTERIOR;
    Projection *lproject = NULL;
    const int       max_no_list_el = 100;
    BoundaryType *list_bound[100];
    Projection **list_project[100];
    Element *el = const_cast<Element*>(mel->getElement());
    int edge_no = mel_edge_no;

    static int  next_el[6][2] = {{3,2},{1,3},{1,2},{0,3},{0,2},{0,1}};

    int vertices = mesh->getGeo(VERTEX);

    mel_index = mel->getIndex();

    list_bound[0] = &(mel->boundary[mesh->getGeo(FACE)+edge_no]);
    list_project[0] = &(mel->projection[mesh->getGeo(FACE)+edge_no]);

    if (mesh->getNumberOfDOFs(EDGE)) {
      node = mesh->getNode(EDGE);
      if (el->getDOF(node+edge_no)) {
	/****************************************************************************/
	/*  edge was counted by another macro element and dof was added on the      */
	/*  complete patch                                                          */
	/****************************************************************************/
	return false;
      } else {
	edge_dof = el->setDOF(node+edge_no,mesh->getDOF(EDGE));
      }
    }

    for (j = 0; j < 2; j++) {
      dof[j] = el->getDOF(el->getVertexOfEdge(edge_no, j));
    }


    /****************************************************************************/
    /*  first look for all neighbours in one direction until a boundary is      */
    /*  reached :-( or we are back to mel :-)                                   */
    /*  if the index of a neighbour is smaller than the element index, the edge */
    /*  is counted by this neighbour, return 0.                                 */
    /*  If we are back to element, return 1, to count the edge                  */
    /****************************************************************************/

    nei = mel->getNeighbour(next_el[edge_no][0]);
    opp_v = mel->getOppVertex(next_el[edge_no][0]);


    if(mel->getBoundary(next_el[edge_no][0])) {
      lbound = newBound(mel->getBoundary(next_el[edge_no][0]), lbound);
      lproject = mel->getProjection(next_el[edge_no][0]);
    }

    while (nei  &&  nei != mel) {
      for (j = 0; j < vertices; j++)
	if (nei->getElement()->getDOF(j) == dof[0])  break;
      for (k = 0; k < vertices; k++)
	if (nei->getElement()->getDOF(k) == dof[1])  break;

      // check for periodic boundary
      if(j == 4 || k == 4) {
	nei = NULL;
	break;
      }

      if (mesh->getNumberOfDOFs(EDGE))
	TEST_EXIT(nei->index > mel_index)
	  ("neighbour index %d < element index %d\n", nei->getIndex(), mel_index);

      if (!mesh->getNumberOfDOFs(EDGE) &&  nei->getIndex() < mel_index)  return false;

    
      edge_no = Tetrahedron::edgeOfDOFs[j][k];

      TEST_EXIT(*n_neigh < max_no_list_el)
	("too many neigbours for local list\n");

      list_bound[(*n_neigh)] = 
	&(nei->boundary[mesh->getGeo(FACE)+edge_no]);

      list_project[(*n_neigh)++] = 
	&(nei->projection[mesh->getGeo(FACE)+edge_no]);

      if (mesh->getNumberOfDOFs(EDGE))
	{
	  //       if(periodic) {
	  // 	nei->element->setDOF(node+edge_no, mesh->getDOF(EDGE));
	  //       } else {
	  nei->element->setDOF(node+edge_no,edge_dof);
	  //       }
	}

      if (next_el[edge_no][0] != opp_v)
	{
	  if(nei->getBoundary(next_el[edge_no][0])) {
	    lbound = newBound(nei->getBoundary(next_el[edge_no][0]), lbound);
	    Projection *neiProject = nei->getProjection(next_el[edge_no][0]);
	    if(!lproject)
	      lproject = neiProject;
	    else {
	      if(neiProject && (lproject->getID() < neiProject->getID())) {
		lproject = neiProject;
	      }
	    }
	  }
	  opp_v = nei->getOppVertex(next_el[edge_no][0]);
	  nei = nei->getNeighbour(next_el[edge_no][0]);
	}
      else
	{
	  if(nei->getBoundary(next_el[edge_no][1])) {
	    lbound = newBound(nei->getBoundary(next_el[edge_no][1]), lbound);
	    Projection *neiProject = nei->getProjection(next_el[edge_no][1]);	
	    if(!lproject)
	      lproject = neiProject;
	    else {
	      if(neiProject && (lproject->getID() < neiProject->getID())) {
		lproject = neiProject;
	      }
	    }
	  }
	  opp_v = nei->getOppVertex(next_el[edge_no][1]);
	  nei = nei->getNeighbour(next_el[edge_no][1]);
	}
    }
    if (!nei)
      {
	/****************************************************************************/
	/*  while looping around the edge the domain's boundary was reached. Now,   */
	/*  loop in the other direction to the domain's boundary		    */
	/****************************************************************************/
	edge_no = mel_edge_no;

	nei = mel->getNeighbour(next_el[edge_no][1]);
	opp_v = mel->getOppVertex(next_el[edge_no][1]);
	if(mel->getBoundary(next_el[edge_no][1])) {
	  lbound = newBound(mel->getBoundary(next_el[edge_no][1]), lbound); 
	  Projection *neiProject =  mel->getProjection(next_el[edge_no][1]);
	  if(!lproject)
	    lproject = neiProject;
	  else {
	    if(neiProject && (lproject->getID() < neiProject->getID())) {
	      lproject = neiProject;
	    }
	  }
	}
	while (nei)
	  {
	    for (j = 0; j < vertices; j++)
	      if (nei->getElement()->getDOF(j) == dof[0])  break;
	    for (k = 0; k < vertices; k++)
	      if (nei->getElement()->getDOF(k) == dof[1])  break;

	    // check for periodic boundary
	    if(j == 4 || k == 4) {
	      return false;
	    }

	    if (mesh->getNumberOfDOFs(EDGE))
	      TEST_EXIT(nei->getIndex() > mel_index)
		("neighbour index %d < element index %d\n", nei->getIndex(),
		 mel_index);

	    if (nei->getIndex() < mel_index)  return false;


	    edge_no = Tetrahedron::edgeOfDOFs[j][k];

	    TEST_EXIT(*n_neigh < max_no_list_el)
	      ("too many neigbours for local list\n");

	    list_bound[(*n_neigh)] = 
	      &(nei->boundary[mesh->getGeo(FACE)+edge_no]);

	    list_project[(*n_neigh)++] = 
	      &(nei->projection[mesh->getGeo(FACE)+edge_no]);

	    if (mesh->getNumberOfDOFs(EDGE)) {
	      TEST_EXIT(!nei->getElement()->getDOF(node+edge_no))
		("dof %d on element %d is already set, but not on element %d\n",
		 node + edge_no, nei->getIndex(), mel_index);
	
	      // 	if(periodic) {
	      // 	  nei->element->setDOF(node+edge_no, mesh->getDOF(EDGE));
	      // 	} else {
	      nei->element->setDOF(node+edge_no,edge_dof);
	      // 	}
	    }

	    if (next_el[edge_no][0] != opp_v)
	      {
		if(nei->getBoundary(next_el[edge_no][0])) {
		  lbound = newBound(nei->getBoundary(next_el[edge_no][0]), lbound);
		  Projection *neiProject = nei->getProjection(next_el[edge_no][0]);
		  if(!lproject)
		    lproject = neiProject;
		  else {
		    if(neiProject &&( lproject->getID() < neiProject->getID())) {
		      lproject = neiProject;
		    }
		  }
		}

		opp_v = nei->getOppVertex(next_el[edge_no][0]);
		nei = nei->getNeighbour(next_el[edge_no][0]);
	      }
	    else {
	      if(nei->getBoundary(next_el[edge_no][1])) {
		lbound = newBound(nei->getBoundary(next_el[edge_no][1]), lbound); 
		Projection *neiProject = nei->getProjection(next_el[edge_no][1]);
		if(!lproject)
		  lproject = neiProject;
		else {
		  if(neiProject && (lproject->getID() < neiProject->getID())) {
		    lproject = neiProject;
		  }
		}
	      }

	      opp_v = nei->getOppVertex(next_el[edge_no][1]);
	      nei = nei->getNeighbour(next_el[edge_no][1]);
	    }
	  }
      }
  
    for (j = 0; j < *n_neigh; j++) {
      *(list_bound[j]) = lbound;
      *(list_project[j]) = lproject;
    }
  
    return true;
  }

  void MacroReader::fillMelBoundary(Mesh *mesh, MacroElement *mel, 
				    FixVec<BoundaryType ,NEIGH> ind)
  {
    int i;
    for(i=0; i < mesh->getGeo(NEIGH); i++) {
      mel->boundary[i] = ind[i];    
    }
  }


  void MacroReader::fillMelNeigh(MacroElement *mel,
				 ::std::deque<MacroElement*>& macro_elements, 
				 FixVec<int,NEIGH> ind)
  {
    int      k;
    int dim = mel->element->getMesh()->getDim();

    for (k = 0; k < Global::getGeo(NEIGH, dim); k++)
      {
	if (ind[k] >= 0) 
	  mel->neighbour[k] = macro_elements[ind[k]];
	else
	  mel->neighbour[k] = NULL;
      }
    return;
  }


  //   ordnet Eintraege in Macro-Element macro bzgl. Verfeinerungskante ka um
  //   (coord, bound, boundary, neigh, oppVertex)

  //   ordnet Eintraege in macro->el bzgl. Verfeinerungskante ka um
  //   (Element-DOF's (macro->el->dof) in Ecken und auf Kanten,
  //    wenn NEIGH_IN_EL macro->el->neigh, macro->el->oppVertex)
  //   (wird fuer ALBERT-Routine write_macro benoetigt)

  //   ele wird nicht benoetigt (es kann NULL uebergeben werden)    


  void MacroReader::umbVkantMacro(Mesh *mesh, MacroElement* me, int ka, int *)
  {
    MacroElement* macr=NEW MacroElement(mesh->getDim());
    int i;
    int n0;
    DegreeOfFreedom *d[7];
  
    int vertices = mesh->getGeo(VERTEX);
    int facesPlusEdges = mesh->getGeo(EDGE) + mesh->getGeo(FACE);

    if (ka == 2);
    else { 
      for (i=0; i < 3; i++) {
	macr->coord[i]=me->coord[i];
	macr->setBoundary(facesPlusEdges + i, me->getBoundary(facesPlusEdges + i));
	macr->setBoundary(i, me->getBoundary(i));
	macr->setNeighbour(i, me->getNeighbour(i));
	macr->setOppVertex(i,me->getOppVertex(i));
      }    
  
      for (i=0; i < 7; i++) {
	d[i]=const_cast<int*>(me->getElement()->getDOF(i));
      }

      if (ka == 1) { 
	me->coord[0] = macr->coord[2];
	me->coord[1] = macr->coord[0];
	me->coord[2] = macr->coord[1];

	me->setBoundary(facesPlusEdges + 0,macr->getBoundary(facesPlusEdges + 2));
	me->setBoundary(facesPlusEdges + 1,macr->getBoundary(facesPlusEdges + 0));
	me->setBoundary(facesPlusEdges + 2,macr->getBoundary(facesPlusEdges + 1));

	me->setBoundary(0, macr->getBoundary(2));
	me->setBoundary(1, macr->getBoundary(0));
	me->setBoundary(2, macr->getBoundary(1));

	me->setNeighbour(0,const_cast<MacroElement*>(macr->getNeighbour(2)));
	me->setNeighbour(1,const_cast<MacroElement*>(macr->getNeighbour(0)));
	me->setNeighbour(2,const_cast<MacroElement*>(macr->getNeighbour(1)));

	me->setOppVertex(0,macr->getOppVertex(2));
	me->setOppVertex(1,macr->getOppVertex(0));
	me->setOppVertex(2,macr->getOppVertex(1));


	if (mesh->getNumberOfDOFs(VERTEX))                /* Ecken */
	  {
	    n0=mesh->getNode(VERTEX);              
        
	    const_cast<Element*>(me->getElement())->setDOF(n0,d[n0+2]);     
	    const_cast<Element*>(me->getElement())->setDOF(n0+1,d[n0]);  
	    const_cast<Element*>(me->getElement())->setDOF(n0+2,d[n0+1]);   
	  }
 
	if (mesh->getNumberOfDOFs(EDGE))                  /* Kanten */
	  { 
	    n0=mesh->getNode(EDGE);    
       
	    const_cast<Element*>(me->getElement())->setDOF(n0,d[n0+2]);  
	    const_cast<Element*>(me->getElement())->setDOF(n0+1,d[n0]);  
	    const_cast<Element*>(me->getElement())->setDOF(n0+2,d[n0+1]);
	  } 

      } else {
	me->coord[0] = macr->coord[1];
	me->coord[1] = macr->coord[2];
	me->coord[2] = macr->coord[0];

	me->setBoundary(facesPlusEdges + 0,macr->getBoundary(facesPlusEdges + 1));
	me->setBoundary(facesPlusEdges + 1,macr->getBoundary(facesPlusEdges + 2));
	me->setBoundary(facesPlusEdges + 2,macr->getBoundary(facesPlusEdges + 0));

	me->setBoundary(0, macr->getBoundary(1));
	me->setBoundary(1, macr->getBoundary(2));
	me->setBoundary(2, macr->getBoundary(0));

	me->setNeighbour(0,const_cast<MacroElement*>(macr->getNeighbour(1)));
	me->setNeighbour(1,const_cast<MacroElement*>(macr->getNeighbour(2)));
	me->setNeighbour(2,const_cast<MacroElement*>(macr->getNeighbour(0)));

	me->setOppVertex(0,macr->getOppVertex(1));
	me->setOppVertex(1,macr->getOppVertex(2));
	me->setOppVertex(2,macr->getOppVertex(0));
    
	if (mesh->getNumberOfDOFs(VERTEX))                /* Ecken */
	  {
	    n0=mesh->getNode(VERTEX);              
        
	    const_cast<Element*>(me->getElement())->setDOF(n0,d[n0+1]);     
	    const_cast<Element*>(me->getElement())->setDOF(n0+1,d[n0+2]);  
	    const_cast<Element*>(me->getElement())->setDOF(n0+2,d[n0]);   
	  }
 
	if (mesh->getNumberOfDOFs(EDGE))                  /* Kanten */
	  { 
	    n0=mesh->getNode(EDGE);    
       
	    const_cast<Element*>(me->getElement())->setDOF(n0,d[n0+1]);  
	    const_cast<Element*>(me->getElement())->setDOF(n0+1,d[n0+2]);  
	    const_cast<Element*>(me->getElement())->setDOF(n0+2,d[n0]);
	  } 
      }
  

      for (i=0; i < vertices; i++)   /* oppVertex der Nachbarn umsetzen*/  
	{
	  if (me->getNeighbour(i))
	    {
	      const_cast<MacroElement*>(me->getNeighbour(i))->setOppVertex(me->getOppVertex(i),i);
	    }
	}
    }
    DELETE macr;
  }


  //   durchlaeuft rek. Macro-Triangulierung mit Start auf Macro-Element macro und
  //   waehlt geignete Verfeinerungskanten, so dass kein Zyklus auftritt
  
  //   (Umbennenung der lokalen Indices der Macro-Elemente
  //    oder Speichern der neuen Verfeinerungskanten mit Fkt. umbvk)
  
  //   waehlt als neue Verfeinerungskante die laengste Kante eines Elementes
  //   fuehrt "fiktiv verlaengerte" Kanten ein, 
  //   wenn ein Element 2 laengste Kanten besitzt  
 
  //   macroalt  Zeiger auf "Rekursions-Vorgaenger"-Macroelement
  //   lg        Laenge der Verfeinerungskante von "Vorgaenger"
  //   ka = 1, wenn Verfeinerungskante von "Vorgaenger" fiktiv verlaengert
  //   ka = 0, sonst
  //   test      Vektor von Flags, die angeben, ob Macro-Element schon getestet (=1)
  //   ele       Integer-Vektor der Dimension Anzahl der Macro-Elemente
  //             zur Speicherung der neuen Verfeinerungskanten
  //             (wird nur benoetigt, wenn umbvk=umb_vkant_macrodat) 

  void MacroReader::recumb(Mesh *mesh,  
			   MacroElement *mel, MacroElement *macroalt,
			   int *test, double lg, int ka, int *ele, 
			   void (*umbvk)(Mesh *mesh, MacroElement*, int k, int *el))
  {
    int i;
    double l[3];
    int v[3];
    int k = 0;
    MacroElement *n;

    int vertices = mesh->getGeo(VERTEX);

    if (!mel || test[mel->getIndex()]==1)
      {
	return;
      }
    else
      {
	test[mel->getIndex()]=1; 
      
	laengstekante(mel->coord,l,v);
    
	if (v[1] == mesh->getGeo(VERTEX))              /*nur eine laengste Kante*/
	  {
	    umbvk(mesh,mel,v[0],ele);      

	    for (i=0; i < vertices; i++) {
	      recumb(mesh,
		     mel->neighbour[i],
		     mel,
		     test,
		     l[0],
		     0,
		     ele,
		     umbvk);
	    }
	    return;
	  }
	else
	  { 
	    if (ka == 1)
	      { 
		if (fabs((l[0]-lg)/lg) < 0.0000001)
		  {  
		    for (i=0; i < vertices; i++)
		      {
			if (mel->neighbour[i] == macroalt)
			  {
			    k=i;
			  }
		      }

		    umbvk(mesh,mel,k,ele);

		    for (i=0; i < vertices; i++) {
		      recumb(mesh,
			     mel->neighbour[i],
			     mel,
			     test,
			     l[0],
			     0,
			     ele,
			     umbvk);
		    }
		    return;
		  }
	      }
      
	    n=const_cast<MacroElement*>(mel->getNeighbour(v[0])); 
	    /*Nachbar an fiktiv verlaengerter Kante*/
	    umbvk(mesh,mel,v[0],ele);   
      
	    recumb(mesh, n, mel,test,l[0],1,ele,umbvk);
	    for (i=0; i < vertices; i++) { 
	      recumb(mesh,
		     mel->neighbour[i],
		     mel,
		     test,
		     l[0],
		     0,
		     ele,
		     umbvk);
	    }
	    return;
	  }
      }             
  }

  //   berechnet aus Koord. der Eckpunkte eines Elementes 
  //   die Laenge der laengsten Kante

  //   l[0] = Laenge der laengsten Kante
  //   v[0] = lokaler Index der laengsten Kante
  //   v[1] = anderer lokaler Index, wenn ex. 2 laengste Kanten
  //        = 3, wenn ex. nur eine laengste Kante
  //   v[2] = dritter lokaler Index, wenn ex. 3 laengste Kanten
  //        = 3, wenn ex. nur eine oder zwei laengste Kanten      

  void MacroReader::laengstekante(FixVec<WorldVector<double>,VERTEX> coord, double *l, int *v)
  {
    int dim = coord.getSize() - 1;

    int i;
    int k;
    double lg;
    double eps;
    double kz; 

    int vertices = Global::getGeo(VERTEX,dim);

    l[0]=absteukl(coord[1],coord[2]);
    l[1]=absteukl(coord[0],coord[2]);
    l[2]=absteukl(coord[0],coord[1]);

    lg=l[0];
    kz=l[0];
    for (i=1; i < vertices; i++)
      {
	if (l[i] > lg) lg=l[i];
	if (l[i] < kz) kz=l[i];
      }

    eps=::std::min(0.000001,kz/10000);
    k=0;
    for (i=0; i < vertices; i++)
      { 
	if (fabs(l[i]-lg) < eps)
	  {
	    v[k]=i;
	    k++;
	  } 
      }
    for (i=k; i < vertices; i++)
      {
	v[i]=Global::getGeo(VERTEX,dim);
      }

    l[0]=lg;
  }

  void MacroReader::checkMesh(Mesh *mesh)
  {
    FUNCNAME("MacroReader::checkMesh()");
    
    int       i, nused, nfree;
    DOFAdmin  *localAdmin=mesh->admin[0];
    Flag     fill_flag;
    int       error_detected = 0;

    MSG("checking mesh\n");

    fill_flag = Mesh::CALL_EVERY_EL_INORDER | Mesh::FILL_NEIGH | Mesh::FILL_BOUND;

    Mesh::traversePtr = mesh;
    error_detected += mesh->traverse(-1, fill_flag|Mesh::FILL_ADD_ALL, basicCheckFct);

    if (mesh->preserveCoarseDOFs)
      fill_flag = Mesh::CALL_EVERY_EL_INORDER;
    else 
      fill_flag = Mesh::CALL_LEAF_EL;
  
    fill_flag |= Mesh::FILL_NEIGH;

    for (mesh->iadmin = 0; 
	 mesh->iadmin < static_cast<int>(mesh->admin.size()); 
	 mesh->iadmin++) {
      localAdmin = mesh->admin[mesh->iadmin];
   
      if (localAdmin->getSize() > 0) {
	if (static_cast<int>(mesh->dof_used.size()) < localAdmin->getSize()) {
	  mesh->dof_used.resize(localAdmin->getSize() + 1000);
	}
	for (i = 0; i < static_cast<int>(mesh->dof_used.size()); i++) 
	  mesh->dof_used[i] = 0;
	
	nused = nfree = 0;
	
	Mesh::traversePtr = mesh;
	error_detected += mesh->traverse(-1, 
					 fill_flag | Mesh::FILL_ADD_ALL, 
					 basicDOFCheckFct);

	  DOFIteratorBase it(localAdmin, USED_DOFS);
	  for(it.reset(); !it.end(); ++it) {
	    nused++;
	    if (!mesh->dof_used[it.getDOFIndex()])  {
	      error_detected++;
	      MSG("dof[%d] not used??\n",it.getDOFIndex());
	    }
	  }

	  DOFIteratorBase freeIt(localAdmin, FREE_DOFS);
	  for(freeIt.reset(); !freeIt.end(); ++freeIt) {
	    nfree++;
	    if(mesh->dof_used[freeIt.getDOFIndex()]) {
	      error_detected++;
	      MSG("dof[%d] used??\n",freeIt.getDOFIndex());
	    }
	  }

	  TEST(nused + nfree == localAdmin->getSize())
	    ("nused = %d, nfree = %d, admin.size = %d ????\n",
	     nused, nfree, localAdmin->getSize());
	  TEST(nused == localAdmin->getUsedDOFs())
	    ("nused = %d, admin.used_count = %d ?????\n",
	     nused, localAdmin->getUsedDOFs());
	}
      }

    if (!error_detected) {
      MSG("checking done; no error detected\n");
    } else {
      MSG("checking done; %d error%s detected\n", error_detected,
	  error_detected == 1 ? "" : "s");

      Mesh::traversePtr = mesh;
      mesh->traverse(-1, Mesh::CALL_EVERY_EL_INORDER, basicNodeFct);
      WAIT_REALLY;
    }

    return;
  }

  int MacroReader::basicCheckFct(ElInfo* elinfo)
  {
    FUNCNAME("MacroReader::basicCheckFct");
    int       i, j, k, opp_v;
    Element        *el = elinfo->getElement();
    const Element  *neig;
    int error_detected=0;

    Mesh* mesh = Mesh::traversePtr;

    int dim = mesh->getDim();

    elinfo->testFlag(Mesh::FILL_NEIGH);

    for (i = 0; i < mesh->getGeo(NEIGH); i++)
      {
	if ((neig = elinfo->getNeighbour(i)))
	  {
	    if(elinfo->getBoundary(i) > 0) { // < 0 => periodic boundary
	      if (!error_detected)
		MSG("error detected!!!\n");
	      error_detected++;
	      MSG("interior (*boundary)[%d] non NULL on element = %d\n", 
		  i, el->getIndex());
	    }
      
	    opp_v = elinfo->getOppVertex(i);
	    if(opp_v < 0  ||  opp_v >= mesh->getGeo(NEIGH))
	      {
		if (!error_detected)
		  MSG("error detected!!!\n");
		error_detected++;
		MSG("opp_v = %d\n", opp_v);
	      }
 
	    if(elinfo->getBoundary(i) > 0) {  // < 0 => periodic boundary
	      if(dim == 1) {
		if(el->getDOF(i) != neig->getDOF(opp_v)) {
		  if (!error_detected)
		    MSG("error detected!!!\n");
		  error_detected++;
		  MSG("neighbour error\n");
		}
	      } else {
		for (j = 1; j < mesh->getGeo(VERTEX); j++) {
		  for (k = 1; k < mesh->getGeo(VERTEX); k++)
		    if (el->getDOF((i+j) % mesh->getGeo(VERTEX)) == 
			neig->getDOF((opp_v+k) % mesh->getGeo(VERTEX))) 
		      break;

		  if (k >= mesh->getGeo(VERTEX)) {
		    if (!error_detected)
		      MSG("error detected!!!\n");
		    error_detected++;
		    MSG("dof %d of el %d at face %d isn't dof of neigh %d at face %d\n",
			el->getDOF((i+j) % 3,0), el->getIndex(), i, neig->getIndex(), 
			opp_v);
		  }	   
		}
	      }
	    }
	  } else {
	  if (elinfo->getBoundary(i) == INTERIOR) {
	    if (!error_detected)
	      MSG("error detected!!!\n");
	    error_detected++;
	    MSG("(*boundary)[%d] on domains boundary is NULL on element = %d\n",
		i, el->getIndex());
	  }
	}
      }

    return error_detected;
  }

  int MacroReader::basicDOFCheckFct(ElInfo* elinfo)
  {
    FUNCNAME("MacroReader::basicDOFCheckFct");
    
    Mesh* mesh = Mesh::traversePtr;
    Element* el = elinfo->getElement();

    const DOFAdmin&  adm = mesh->getDOFAdmin(mesh->iadmin);
    const Element        *neig;
    const DegreeOfFreedom       *dof;
    int       i, j, jdof, ndof, i0, j0, ov;

    if (0 == mesh->dof_used.size()) 
      return 0;

    if ((ndof = adm.getNumberOfDOFs(VERTEX))) {
	j0 = adm.getNumberOfPreDOFs(VERTEX);
	TEST_EXIT(j0 + ndof <= mesh->getNumberOfDOFs(VERTEX))
	  ("adm.getNumberOfPreDOFs(VERTEX) %d + nDOF %d > mesh->nDOF %d\n",
	   j0, ndof, mesh->getNumberOfDOFs(VERTEX));
	i0 = mesh->getNode(VERTEX);
	for (i = 0; i < mesh->getGeo(VERTEX); i++)
	  {
	    if ((dof = el->getDOF(i0+i)) == NULL)
	      ERROR("no vertex dof %d on element %d\n", i, el->getIndex());
	    else
	      for (j = 0; j < ndof; j++)
		{
		  jdof = dof[j0 + j];
		  TEST(jdof >= 0 && jdof < static_cast<int>(mesh->dof_used.size()))
		    ("vertex dof=%d invalid? size=%d\n",jdof, mesh->dof_used.size());
		  mesh->dof_used[jdof]++;
		}
	  }
	/* neighbour vertex dofs have been checked in check_fct() */
      }

  
    if (mesh->getDim() > 1) {
      if ((ndof = adm.getNumberOfDOFs(EDGE))) {
	j0 = adm.getNumberOfPreDOFs(EDGE);

	TEST_EXIT(j0 + ndof <= mesh->getNumberOfDOFs(EDGE))
	  ("adm.getNumberOfPreDOFs(EDGE) %d + nDOF %d > mesh->nDOF %d\n",
	   j0, ndof, mesh->getNumberOfDOFs(EDGE));

	i0 = mesh->getNode(EDGE);
	
	for (i = 0; i < mesh->getGeo(EDGE); i++) {
	  if ((dof = el->getDOF(i0 + i)) == NULL) {
	    ERROR("no edge dof %d on element %d\n", i, el->getIndex());
	  } else {
	    for (j = 0; j < ndof; j++) {
	      jdof = dof[j0 + j];
	      TEST(jdof >= 0 && jdof < static_cast<int>(mesh->dof_used.size()))
		("edge dof=%d invalid? size=%d\n",jdof, mesh->dof_used.size());
	      mesh->dof_used[jdof]++;
	    }
	  }

	  if (el->getFirstChild() == NULL) {
	    if(mesh->getDim() == 2) {
	      if ((neig = elinfo->getNeighbour(i))) {
		ov = elinfo->getOppVertex(i);

		TEST(neig->getDOF(i0 + ov) == dof)
		  ("el %d edge %d dof %8X: wrong dof %8X in neighbour %d edge %d\n",
		   el->getIndex(), i, dof, neig->getDOF(i0 + ov), 
		   neig->getIndex(), ov);
	      }
	    } else { // dim == 3
	      int in, k, found;

	      for (in = 0; in < mesh->getGeo(NEIGH); in++) {
		if ((in != el->getVertexOfEdge(i,0)) && 
		    (in != el->getVertexOfEdge(i,1)) &&
		    (neig = elinfo->getNeighbour(in))) {
		  found = 0;
		  for (