amesh.cpp 42.3 KB
Newer Older
1
#include "amesh.h"
SilverLife's avatar
SilverLife committed
2
#include <iomanip>
3
#include <set>
SilverLife's avatar
SilverLife committed
4
5

using namespace std;
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
32
33
34
35
36
37

/// todo:
/// 1. coarsment
/// 2. strategy for faces/edges with faults
/// 3. geom model support
/// 4. make class abstract virtual for user implementation of refinement and coarsment indicators
/// see in code todo:
namespace INMOST
{
	void CleanupSets(ElementSet set)
	{
		ElementSet::iterator it = set.Begin();
		while(it != set.End())
		{
			if( it->isValid() ) ++it;
			else it = set.Erase(it);
		}
		for(ElementSet child = set.GetChild(); child.isValid(); child = child.GetSibling())
			CleanupSets(child);
	}
	
	void ReduceMax(const Tag & tag, const Element & element, const INMOST_DATA_BULK_TYPE * data, INMOST_DATA_ENUM_TYPE size)
	{
		(void) size;
		element->Integer(tag) = std::max(element->Integer(tag),*((const INMOST_DATA_INTEGER_TYPE *)data));
	}
	
	void ReduceMin(const Tag & tag, const Element & element, const INMOST_DATA_BULK_TYPE * data, INMOST_DATA_ENUM_TYPE size)
	{
		(void) size;
		element->Integer(tag) = std::min(element->Integer(tag),*((const INMOST_DATA_INTEGER_TYPE *)data));
	}
SilverLife's avatar
SilverLife committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51


    void AdaptiveMesh::PrintSetLocal(string offset, ElementSet it, stringstream& ss)
    {
        stringstream ss1;
        ss1 << offset << rank << ": Set : " << setw(5) << it.GetName() << " ";
        for (int i = ss1.str().length(); i < 23; i++) ss1 << " ";
        ss << ss1.str();
        ss << setw(6);
        if (it.GetStatus() == Element::Shared) ss << "shared";
        else if (it.GetStatus() == Element::Ghost) ss << "ghost";
        else if (it.GetStatus() == Element::Owned) ss << "owned";
        else ss << "none";

52
        ss << " tag_owner (" << it.IntegerDF(m->OwnerTag()) << ")";
SilverLife's avatar
SilverLife committed
53
54
55
56

        //ss << "   level (" << level[it.self()] << ")  ";
        ss << " tag_processors (";
        stringstream ss2;
57
        Storage::integer_array arr = it.IntegerArrayDV(m->ProcessorsTag());
SilverLife's avatar
SilverLife committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
        for (int i = 0; i < arr.size(); i++)
            ss2 << arr[i] << " ";
        ss << setw(5) << ss2.str() <<")";
        

        ElementSet::iterator p = it.Begin();
        ss << "     | Refs: ";
        int first = 0;
        while(p != it.End())
        {
        //    if (first++ == 0) ss << endl << offset << "   ";
            string type = "unknw";
            if (p->GetElementType() == CELL) type = "cell";
            if (p->GetElementType() == FACE) type = "face";
            if (p->GetElementType() == EDGE) type = "edge";
            if (p->GetElementType() == NODE) type = "node";
74
            ss << type << "-" << setw(2) << p->GlobalID() << " ";
SilverLife's avatar
SilverLife committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
            p++;
        }
        ss << endl;

        for(ElementSet child = it.GetChild(); child.isValid(); child = child.GetSibling())
        {
            PrintSetLocal(offset + "   ",child,ss);
        }
    }


    void AdaptiveMesh::PrintSet()
    {
        stringstream ss;
89
        for(Mesh::iteratorSet it = m->BeginSet(); it != m->EndSet(); ++it) 
SilverLife's avatar
SilverLife committed
90
91
        {
            if (it->HaveParent()) continue;
92
            PrintSetLocal("",ElementSet(m,*it),ss);
SilverLife's avatar
SilverLife committed
93
94
95
96
        }
        cout << ss.str() << endl;
    }

97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    void PrintRefs(ostream& os, Storage::reference_array refs)
    {
        for(Storage::reference_array::size_type i = 0; i < refs.size(); ++i)
        {
            string type = "unknw";
            if (refs[i].GetElementType() == CELL) type = "cell";
            if (refs[i].GetElementType() == FACE) type = "face";
            if (refs[i].GetElementType() == EDGE) type = "edge";
            if (refs[i].GetElementType() == NODE) type = "node";
            os << "(" << type << "," << refs[i]->GlobalID() << ") ";
			Storage::real xyz[3] = {0,0,0};
            refs[i]->Centroid(xyz);
            os << "(" << xyz[0] << "," << xyz[1] << "," << xyz[2] <<")" <<  endl;
        }


    }

SilverLife's avatar
SilverLife committed
115
116
117
118
119
120
121
    void AdaptiveMesh::PrintMesh(ostream& os, int cell, int face, int edge, int node)
    {
        if (cell + face + edge + node == 0) return;
        stringstream ss;
        ss << "================= " << rank << " =====================" << endl;
        if (cell)
        {
122
123
            ss << "Cells: " << m->NumberOfCells() <<  endl;
            for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it) 
SilverLife's avatar
SilverLife committed
124
            {
125
                ss << rank << ": " << it->GlobalID() << " - " << it->LocalID() << " - ";            
SilverLife's avatar
SilverLife committed
126
127
128
                if (it->GetStatus() == Element::Shared) ss << "shared";
                else if (it->GetStatus() == Element::Ghost) ss << "ghost";
                else ss << "none";
129
130
131
132
133
134
135
136
137
138
                
                /*
                ss << " (";
                Storage::integer_array arr = it->IntegerArrayDV(tag_processors);
                for (int i = 0; i < arr.size(); i++) ss << arr[i] << " ";
                ss << ") ";
*/
                /*
                Storage::reference_array refs = hanging_nodes[it->self()];
                if (refs.size() > 0)
SilverLife's avatar
SilverLife committed
139
                {
140
141
                    ss << endl << "   Hanging nodes: ";
                    PrintRefs(ss,refs);
SilverLife's avatar
SilverLife committed
142
143
                }
                ss << endl;
144
145
146
147
148
149
150
                ss << "   ParentSet: " << ElementSet(this,parent_set[*it]).GetName();
                */
/*
                orage::reference_array refs = ref_tag[it->self()];
                PrintRefs(refs);
                */
                    ss << endl;
SilverLife's avatar
SilverLife committed
151
152
153
154
155
            }
        }

        if (face)
        {
156
157
            ss << "Faces: " << m->NumberOfFaces() <<  endl;
            for(Mesh::iteratorFace it = m->BeginFace(); it != m->EndFace(); ++it) 
SilverLife's avatar
SilverLife committed
158
            {
159
160
                ss << rank << ": " << setw(2) << it->LocalID() << " " << setw(2) << it->GlobalID() << " - " ;            
                ss << setw(6);
SilverLife's avatar
SilverLife committed
161
162
163
164
                if (it->GetStatus() == Element::Shared) ss << "shared";
                else if (it->GetStatus() == Element::Ghost) ss << "ghost";
                else ss << "none";

165
166
167
168
169

                double xyz[3];
                it->Centroid(xyz);
                ss << "   (" << setw(5) << xyz[0] << " " << setw(5) << xyz[1] << " " << setw(5) << xyz[2] << ")";

170
                ss << "  " << m->GetMarker(*it,m->NewMarker());
171
172
173
174
175
176
177
178

                ss << " nc(" << it->getNodes().size() << ": "; 
                ElementArray<Node> nodes = it->getNodes();
                for (ElementArray<Node>::iterator node = nodes.begin(); node != nodes.end(); node++)
                    ss << setw(2) << node->GlobalID() << " ";
                ss << ")";

                /*
SilverLife's avatar
SilverLife committed
179
180
181
182
183
184
185
186
187
188
189
190
191
                Storage::reference_array refs = ref_tag[it->self()];
                if (refs.size() > 0) ss << ". Ref: ";
                for(Storage::reference_array::size_type i = 0; i < refs.size(); ++i)
                {
                    string type = "unknw";
                    if (refs[i].GetElementType() == CELL) type = "cell";
                    if (refs[i].GetElementType() == FACE) type = "face";
                    if (refs[i].GetElementType() == EDGE) type = "edge";
                    if (refs[i].GetElementType() == NODE) type = "node";
                    ss << "(" << type << "," << refs[i]->GlobalID() << ") ";
                }

                ss << endl;
192
193
194
195
196
197
198
199
200
201

                {
                    Storage::reference_array refs = hanging_nodes[it->self()];
                    if (refs.size() > 0)
                    {
                        ss << endl << "   Hanging nodes: ";
                        PrintRefs(ss,refs);
                    }
                    ss << endl;
                }
202
203
                */
                ss << endl;
SilverLife's avatar
SilverLife committed
204
205
206
207
208
            }
        }

        if (edge)
        {
209
210
            ss << "Edges: " << m->NumberOfEdges() <<  endl;
            for(Mesh::iteratorEdge it = m->BeginEdge(); it != m->EndEdge(); ++it) 
SilverLife's avatar
SilverLife committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
            {
                ss << rank << ": " << it->GlobalID() << " - " ;            
                if (it->GetStatus() == Element::Shared) ss << "shared";
                else if (it->GetStatus() == Element::Ghost) ss << "ghost";
                else ss << "none";

                Storage::reference_array refs = ref_tag[it->self()];
                if (refs.size() > 0) ss << ". Ref: ";
                for(Storage::reference_array::size_type i = 0; i < refs.size(); ++i)
                {
                    string type = "unknw";
                    if (refs[i].GetElementType() == CELL) type = "cell";
                    if (refs[i].GetElementType() == FACE) type = "face";
                    if (refs[i].GetElementType() == EDGE) type = "edge";
                    if (refs[i].GetElementType() == NODE) type = "node";
                    ss << "(" << type << "," << refs[i]->GlobalID() << ") ";
                }

                ss << endl;
            }
        }

        if (node)
        {
            ss << "Nodes:" << endl;
236
            for(Mesh::iteratorNode it = m->BeginNode(); it != m->EndNode(); ++it) 
SilverLife's avatar
SilverLife committed
237
            {
238
239
                ss << rank << ": " << setw(2) << it->GlobalID() << " - " ;            
                ss << setw(6);
SilverLife's avatar
SilverLife committed
240
241
242
243
244
245
246
247
248
249
250
                if (it->GetStatus() == Element::Shared) ss << "shared";
                else if (it->GetStatus() == Element::Ghost) ss << "ghost";
                else ss << "none";

                {
                    Storage::reference_array refs = ref_tag[it->self()];
                    if (refs.size() > 0) ss << ". Ref: ";
                    for(Storage::reference_array::size_type i = 0; i < refs.size(); ++i)
                    {
                        string type = "unknw";
                        if (refs[i].GetElementType() == CELL) type = "cell";
251
252
						if (refs[i].GetElementType() == FACE) type = "face";
						if (refs[i].GetElementType() == EDGE) type = "edge";
SilverLife's avatar
SilverLife committed
253
254
255
256
                        if (refs[i].GetElementType() == NODE) type = "node";
                        ss << "(" << type << "," << refs[i]->GlobalID() << ") ";
                        
                    }
257

258
                    ss << "  " << m->GetMarker(*it,m->NewMarker());
259
260

                    ss << "(" << 
261
262
263
                        setw(3) << it->RealArray(m->CoordsTag())[0] << " " << 
                        setw(3) << it->RealArray(m->CoordsTag())[1] << " " << 
                        setw(3) << it->RealArray(m->CoordsTag())[2] << ")";
264

SilverLife's avatar
SilverLife committed
265
266
267
268
269
270
271
272
273
274
275
276
277
278
                }
                ss << endl;
            }
        }

        ss << "=========================================" << endl;
        os << ss.str() << endl;
    }

    void AdaptiveMesh::UpdateStatus()
    {

        for(ElementType mask = CELL; mask >= NODE; mask = PrevElementType(mask))
        {
279
            for(Mesh::iteratorElement it = m->BeginElement(mask); it != m->EndElement(); it++)
SilverLife's avatar
SilverLife committed
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
            {
                int stat = 0;
                if (it->GetStatus() == Element::Shared) stat = 1;
                else if (it->GetStatus() == Element::Ghost)  stat = 2;

                tag_status[it->self()] = stat;
            }
        }
    }
    
    void AdaptiveMesh::PrintSet(ElementSet set, std::string offset)
    {
        std::cout << offset << "Set: " << std::endl;

		ElementSet::iterator it = set.Begin();
		while(it != set.End())
        {
297
		    ElementSet parent(m,parent_set[*it]);
SilverLife's avatar
SilverLife committed
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
            std::cout << offset << it->GlobalID() << " - " << level[*it] << " : ";
		    
            ElementSet::iterator p = parent.Begin();
    		while(p != parent.End())
            {
                std::cout << p->GlobalID() << " ";
                p++;
            }
            std::cout << std::endl;
            it++;
        }

		for(ElementSet child = set.GetChild(); child.isValid(); child = child.GetSibling())
        {
            PrintSet(child,offset + "  ");
        }

    }

317
318
319
    void AdaptiveMesh::SynchronizeSet(ElementSet set)
    {
    #ifdef USE_MPI
320
321
        int size = m->GetProcessorsNumber();
        int rank = m->GetProcessorRank();
322
323
        for (int i = 0; i < size; i++)
        {
324
325
            set.IntegerArray(m->SendtoTag()).push_back(i);
            m->ExchangeMarked();
326
327
328
329
        }
    #endif
    }

SilverLife's avatar
SilverLife committed
330
331
332
333
334
    void AdaptiveMesh::Test()
    {
        std::cout << rank << ": ================" << endl;
        PrintSet(root,"");
    }
335
336
337
338
	
	
	void AdaptiveMesh::ClearData()
	{
Kirill Terekhov's avatar
Kirill Terekhov committed
339
340
341
		level         = m->DeleteTag(level);
		hanging_nodes = m->DeleteTag(hanging_nodes);
		parent_set    = m->DeleteTag(parent_set);
342
343
344
345
346
347
348
349
		root.DeleteSetTree();
	}
	
	void AdaptiveMesh::PrepareSet()
	{
		//retrive set for coarsening, initialize set if is not present
		if( !root.isValid() )
		{
Kirill Terekhov's avatar
Kirill Terekhov committed
350
			root = m->GetSet("ROOT_SET");
351
352
			if( root == InvalidElement() )
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
353
				root = m->CreateSetUnique("ROOT_SET").first;
354
				level[root] = 0;
Kirill Terekhov's avatar
Kirill Terekhov committed
355
				for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it)
356
357
358
359
360
				{
					root.PutElement(it->self());
					parent_set[it->self()] = root.GetHandle();
				}
			}
SilverLife's avatar
SilverLife committed
361
        }
Kirill Terekhov's avatar
Kirill Terekhov committed
362
		if( !m->HaveGlobalID(CELL) ) m->AssignGlobalID(CELL); //for unique set names
363
364
	}
	
Kirill Terekhov's avatar
Kirill Terekhov committed
365
	AdaptiveMesh::AdaptiveMesh(Mesh & _m) : m(&_m)
366
	{
Kirill Terekhov's avatar
Kirill Terekhov committed
367
		model = NULL;
368
		//create a tag that stores maximal refinement level of each element
Kirill Terekhov's avatar
Kirill Terekhov committed
369
		level = m->CreateTag("REFINEMENT_LEVEL",DATA_INTEGER,CELL|FACE|EDGE|NODE|ESET,NONE,1);
370
371
372
		tag_status = m->CreateTag("TAG_STATUS",DATA_INTEGER,CELL|FACE|EDGE|NODE,NONE,1);
		tag_an = m->CreateTag("TAG_AN",DATA_INTEGER,CELL|FACE|EDGE|NODE,NONE,1);
		ref_tag = m->CreateTag("REF",DATA_REFERENCE,CELL|FACE|EDGE|NODE,NONE);
373
		//create a tag that stores links to all the hanging nodes of the cell
Kirill Terekhov's avatar
Kirill Terekhov committed
374
		hanging_nodes = m->CreateTag("HANGING_NODES",DATA_REFERENCE,CELL|FACE,NONE);
375
		//create a tag that stores links to sets
Kirill Terekhov's avatar
Kirill Terekhov committed
376
		parent_set = m->CreateTag("PARENT_SET",DATA_REFERENCE,CELL,NONE,1);
377
378
	    size = m->GetProcessorsNumber();
    	rank = m->GetProcessorRank();
379
380
381
382
383
384
385
386
387
388
	}
	
	AdaptiveMesh::~AdaptiveMesh()
	{
		//do not delete tags, user may want to repetitively use this class
		//as extension of class mesh in limited code span
	}
	
	bool AdaptiveMesh::Refine(TagInteger & indicator)
	{
389
        std::cout << rank << ": IN REFINE" << endl;
390
391
392
393
394
395
396
		static int call_counter = 0;
		int ret = 0; //return number of refined cells
		//initialize tree structure
		PrepareSet();
		int schedule_counter = 1; //indicates order in which refinement will be scheduled
		int scheduled = 1; //indicates that at least one element was scheduled on current sweep
		//0. Extend indicator for edges and faces
Kirill Terekhov's avatar
Kirill Terekhov committed
397
		indicator = m->CreateTag(indicator.GetTagName(),DATA_INTEGER,FACE|EDGE,NONE,1);
398
399
400
		while(scheduled)
		{
			//1.Communicate indicator - it may be not synced
Kirill Terekhov's avatar
Kirill Terekhov committed
401
			m->ExchangeData(indicator,CELL,0);
402
403
			//2.Propogate indicator down to the faces,edges
			//  select schedule for them
Kirill Terekhov's avatar
Kirill Terekhov committed
404
			for(Storage::integer it = 0; it < m->CellLastLocalID(); ++it) if( m->isValidCell(it) )
405
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
406
				Cell c = m->CellByLocalID(it);
407
408
409
410
411
412
413
414
415
416
417
				if( indicator[c] == schedule_counter )
				{
					ElementArray<Element> adj = c.getAdjElements(FACE|EDGE);
					for(ElementArray<Element>::size_type kt = 0; kt < adj.size(); ++kt)
					{
						if( level[adj[kt]] == level[c] ) //do not schedule finer or coarser elements
							indicator[adj[kt]] = schedule_counter; //refine together with current cell
					}
				}
			}
			//3.Communicate indicator on faces and edges
Kirill Terekhov's avatar
Kirill Terekhov committed
418
			m->ExchangeData(indicator,FACE|EDGE,0);
419
420
421
422
			//4.Check for each cell if there is
			//  any hanging node with adjacent in a need to refine,
			//  schedule for refinement earlier.
			scheduled = 0;
Kirill Terekhov's avatar
Kirill Terekhov committed
423
			for(Storage::integer it = 0; it < m->CellLastLocalID(); ++it) if( m->isValidCell(it) )
424
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
425
				Cell c = m->CellByLocalID(it);
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
				//already scheduled cells may be required to be refined first
				//if( indicator[c] == 0 ) //some optimization
				{
					bool scheduled_c = false;
					//any finer level edge is scheduled to be refined first
					ElementArray<Edge> edges = c->getEdges();
					for(ElementArray<Edge>::size_type kt = 0; kt < edges.size() && !scheduled_c; ++kt)
					{
						//if a finer edge is scheduled
						//then this cell should be refined first
						if( indicator[edges[kt]] != 0 &&
							level[edges[kt]] > level[c] &&
							indicator[edges[kt]] >= indicator[c] )
						{
							indicator[c] = schedule_counter+1;
							scheduled++;
							scheduled_c = true;
						}
					}
				}
			}
			//5.Go back to 1 until no new elements scheduled
Kirill Terekhov's avatar
Kirill Terekhov committed
448
			scheduled = m->Integrate(scheduled);
449
450
			if( scheduled ) schedule_counter++;
		}
451
452
		m->ExchangeData(indicator,CELL | FACE | EDGE,0);
		m->Save("indicator.pmf");
453
		//6.Refine
Kirill Terekhov's avatar
Kirill Terekhov committed
454
		m->BeginModification();
455
456
457
458
		while(schedule_counter)
		{
			Storage::real xyz[3] = {0,0,0};
			//7.split all edges of the current schedule
Kirill Terekhov's avatar
Kirill Terekhov committed
459
			for(Storage::integer it = 0; it < m->EdgeLastLocalID(); ++it) if( m->isValidEdge(it) )
460
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
461
				Edge e = m->EdgeByLocalID(it);
462
463
464
465
466
				if( !e.Hidden() && indicator[e] == schedule_counter )
				{
					//remember adjacent faces that should get information about new hanging node
					ElementArray<Face> edge_faces = e.getFaces();
					//location on the center of the edge
Kirill Terekhov's avatar
Kirill Terekhov committed
467
					for(Storage::integer d = 0; d < m->GetDimensions(); ++d)
468
469
470
						xyz[d] = (e.getBeg().Coords()[d]+e.getEnd().Coords()[d])*0.5;
					//todo: request transformation of node location according to geometrical model
					//create middle node
Kirill Terekhov's avatar
Kirill Terekhov committed
471
					Node n = m->CreateNode(xyz);
472
					//set increased level for new node
473
					level[n] = level[e.getBeg()] = level[e.getEnd()] = level[e]+1;
474
475
476
477
					//for each face provide link to a new hanging node
					for(ElementArray<Face>::size_type kt = 0; kt < edge_faces.size(); ++kt)
						hanging_nodes[edge_faces[kt]].push_back(n);
					//split the edge by the middle node
Kirill Terekhov's avatar
Kirill Terekhov committed
478
					ElementArray<Edge> new_edges = Edge::SplitEdge(e,ElementArray<Node>(m,1,n.GetHandle()),0);
479
480
481
482
483
					//set increased level for new edges
					level[new_edges[0]] = level[new_edges[1]] = level[e]+1;
				}
			}
			//8.split all faces of the current schedule, using hanging nodes on edges
Kirill Terekhov's avatar
Kirill Terekhov committed
484
			for(Storage::integer it = 0; it < m->FaceLastLocalID(); ++it) if( m->isValidFace(it) )
485
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
486
				Face f = m->FaceByLocalID(it);
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
				if( !f.Hidden() && indicator[f] == schedule_counter )
				{
					//connect face center to hanging nodes of the face
					Storage::reference_array face_hanging_nodes = hanging_nodes[f];
					//remember adjacent cells that should get information about new hanging node
					//and new hanging edges
					ElementArray<Cell> face_cells = f.getCells();
					//create node at face center
					//f->Centroid(xyz);
					for(int d = 0; d < 3; ++d) xyz[d] = 0.0;
					for(Storage::reference_array::size_type kt = 0; kt < face_hanging_nodes.size(); ++kt)
						for(int d = 0; d < 3; ++d) xyz[d] += face_hanging_nodes[kt].getAsNode().Coords()[d];
					for(int d = 0; d < 3; ++d) xyz[d] /= (Storage::real)face_hanging_nodes.size();
					//todo: request transformation of node location according to geometrical model
					//create middle node
Kirill Terekhov's avatar
Kirill Terekhov committed
502
					Node n = m->CreateNode(xyz);
503
					//set increased level for the new node
504
					level[n] = level[f]+1;
505
506
507
					//for each cell provide link to new hanging node
					for(ElementArray<Face>::size_type kt = 0; kt < face_cells.size(); ++kt)
						hanging_nodes[face_cells[kt]].push_back(n);
Kirill Terekhov's avatar
Kirill Terekhov committed
508
509
					ElementArray<Node> edge_nodes(m,2); //to create new edges
					ElementArray<Edge> hanging_edges(m,face_hanging_nodes.size());
510
511
512
513
					edge_nodes[0] = n;
					for(Storage::reference_array::size_type kt = 0; kt < face_hanging_nodes.size(); ++kt)
					{
						edge_nodes[1] = face_hanging_nodes[kt].getAsNode();
Kirill Terekhov's avatar
Kirill Terekhov committed
514
						hanging_edges[kt] = m->CreateEdge(edge_nodes).first;
515
516
517
518
519
520
521
522
523
524
525
						//set increased level for new edges
						level[hanging_edges[kt]] = level[f]+1;
					}
					//split the face by these edges
					ElementArray<Face> new_faces = Face::SplitFace(f,hanging_edges,0);
					//set increased level to new faces
					for(ElementArray<Face>::size_type kt = 0; kt < new_faces.size(); ++kt)
						level[new_faces[kt]] = level[f]+1;
				}
			}
			//this tag helps recreate internal face
Kirill Terekhov's avatar
Kirill Terekhov committed
526
			TagReferenceArray internal_face_edges = m->CreateTag("INTERNAL_FACE_EDGES",DATA_REFERENCE,NODE,NODE,4);
527
			//this marker helps detect edges of current cell only
Kirill Terekhov's avatar
Kirill Terekhov committed
528
			MarkerType mark_cell_edges = m->CreateMarker();
529
			//this marker helps detect nodes hanging on edges of unrefined cell
Kirill Terekhov's avatar
Kirill Terekhov committed
530
			MarkerType mark_hanging_nodes = m->CreateMarker();
531
			//9.split all cells of the current schedule
Kirill Terekhov's avatar
Kirill Terekhov committed
532
			for(Storage::integer it = 0; it < m->CellLastLocalID(); ++it) if( m->isValidCell(it) )
533
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
534
				Cell c = m->CellByLocalID(it);
535
536
537
538
539
540
541
542
543
544
545
				if( !c.Hidden() && indicator[c] == schedule_counter )
				{
					Storage::reference_array cell_hanging_nodes = hanging_nodes[c]; //nodes to be connected
					//create node at cell center
					for(int d = 0; d < 3; ++d) xyz[d] = 0.0;
					for(Storage::reference_array::size_type kt = 0; kt < cell_hanging_nodes.size(); ++kt)
						for(int d = 0; d < 3; ++d) xyz[d] += cell_hanging_nodes[kt].getAsNode().Coords()[d];
					for(int d = 0; d < 3; ++d) xyz[d] /= (Storage::real)cell_hanging_nodes.size();
					//c->Centroid(xyz);
					//todo: request transformation of node location according to geometrical model
					//create middle node
Kirill Terekhov's avatar
Kirill Terekhov committed
546
					Node n = m->CreateNode(xyz);
547
					//set increased level for the new node
548
					level[n] = level[c]+1;
549
550
551
552
553
					//retrive all edges of current face to mark them
					ElementArray<Edge> cell_edges = c.getEdges();
					//mark all edges so that we can retive them later
					cell_edges.SetMarker(mark_cell_edges);
					//connect face center to centers of faces by edges
Kirill Terekhov's avatar
Kirill Terekhov committed
554
555
					ElementArray<Node> edge_nodes(m,2);
					ElementArray<Edge> edges_to_faces(m,cell_hanging_nodes.size());
556
557
558
559
560
561
					edge_nodes[0] = n;
					for(Storage::reference_array::size_type kt = 0; kt < cell_hanging_nodes.size(); ++kt)
					{
						assert(cell_hanging_nodes[kt].isValid());
						//todo: unmark hanging node on edge if no more cells depend on it
						edge_nodes[1] = cell_hanging_nodes[kt].getAsNode();
Kirill Terekhov's avatar
Kirill Terekhov committed
562
						edges_to_faces[kt] = m->CreateEdge(edge_nodes).first;
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
						//set increased level for new edges
						level[edges_to_faces[kt]] = level[c]+1;
						//for each node other then the hanging node of the face
						//(this is hanging node on the edge)
						//we record a pair of edges to reconstruct internal faces
						ElementArray<Edge> hanging_edges = cell_hanging_nodes[kt].getEdges(mark_cell_edges,0);
						for(ElementArray<Edge>::size_type lt = 0; lt < hanging_edges.size(); ++lt)
						{
							//get hanging node on the edge
							assert(hanging_edges[lt].getBeg() == cell_hanging_nodes[kt] || hanging_edges[lt].getEnd() == cell_hanging_nodes[kt]);
							Node v = hanging_edges[lt].getBeg() == cell_hanging_nodes[kt]? hanging_edges[lt].getEnd() : hanging_edges[lt].getBeg();
							//mark so that we can collect all of them
							v.SetMarker(mark_hanging_nodes);
							//fill the edges
							Storage::reference_array face_edges = internal_face_edges[v];
							//fill first two in forward order
							//this way we make a closed loop
							assert(face_edges[0] == InvalidElement() || face_edges[2] == InvalidElement());
							if( face_edges[0] == InvalidElement() )
							{
								face_edges[0] = edges_to_faces[kt];
								face_edges[1] = hanging_edges[lt];
							}
							else //last two in reverse
							{
								assert(face_edges[2] ==InvalidElement());
								face_edges[2] = hanging_edges[lt];
								face_edges[3] = edges_to_faces[kt];
							}
						}
					}
					//remove marker from cell edges
					cell_edges.RemMarker(mark_cell_edges);
					//now we have to create internal faces
					ElementArray<Node> edge_hanging_nodes = c.getNodes(mark_hanging_nodes,0);
Kirill Terekhov's avatar
Kirill Terekhov committed
598
					ElementArray<Face> internal_faces(m,edge_hanging_nodes.size());
599
600
601
602
603
604
605
606
607
608
					//unmark hanging nodes on edges
					edge_hanging_nodes.RemMarker(mark_hanging_nodes);
					for(ElementArray<Node>::size_type kt = 0; kt < edge_hanging_nodes.size(); ++kt)
					{
						//create a face based on collected edges
						Storage::reference_array face_edges = internal_face_edges[edge_hanging_nodes[kt]];
						assert(face_edges[0].isValid());
						assert(face_edges[1].isValid());
						assert(face_edges[2].isValid());
						assert(face_edges[3].isValid());
Kirill Terekhov's avatar
Kirill Terekhov committed
609
						internal_faces[kt] = m->CreateFace(ElementArray<Edge>(m,face_edges.begin(),face_edges.end())).first;
610
611
612
613
614
615
616
617
						//set increased level
						level[internal_faces[kt]] = level[c]+1;
						//clean up structure, so that other cells can use it
						edge_hanging_nodes[kt].DelData(internal_face_edges);
					}
					//split the cell
					ElementArray<Cell> new_cells = Cell::SplitCell(c,internal_faces,0);
					//retrive parent set
Kirill Terekhov's avatar
Kirill Terekhov committed
618
					ElementSet parent(m,parent_set[c]);
619
620
621
					//create set corresponding to old coarse cell
					std::stringstream set_name;
					set_name << parent.GetName() << "_C" << c.GlobalID(); //rand may be unsafe
Kirill Terekhov's avatar
Kirill Terekhov committed
622
					ElementSet cell_set = m->CreateSetUnique(set_name.str()).first;
623
624
625
626
627
628
629
630
631
632
633
634
635
					level[cell_set] = level[c]+1;
					//set up increased level for the new cells
					for(ElementArray<Cell>::size_type kt = 0; kt < new_cells.size(); ++kt)
					{
						level[new_cells[kt]] = level[c]+1;
						cell_set.PutElement(new_cells[kt]);
						parent_set[new_cells[kt]] = cell_set.GetHandle();
					}
					parent.AddChild(cell_set);
					//increment number of refined cells
					ret++;
				}
			}
Kirill Terekhov's avatar
Kirill Terekhov committed
636
637
638
			m->ReleaseMarker(mark_hanging_nodes);
			m->ReleaseMarker(mark_cell_edges);
			m->DeleteTag(internal_face_edges);
639
640
641
			//10.jump to later schedule, and go to 7.
			schedule_counter--;
		}
SilverLife's avatar
SilverLife committed
642

643
		//free created tag
Kirill Terekhov's avatar
Kirill Terekhov committed
644
		m->DeleteTag(indicator,FACE|EDGE);
645
646
647
648
649
650
651
652
653
654
655
		//restore face orientation
		//BUG: bad orientation not fixed automatically
		int nfixed = 0;
		for(Mesh::iteratorFace it = m->BeginFace(); it != m->EndFace(); ++it) 
			if( !it->CheckNormalOrientation() )
			{
				it->FixNormalOrientation();
				nfixed++;
			}
			//std::cout << "Face " << it->LocalID() << " oriented incorrectly " << std::endl;
		if( nfixed ) std::cout << "fixed " << nfixed << " faces" << std::endl;
SilverLife's avatar
SilverLife committed
656
657


658
659
        MarkerType marker_new = m->CreateMarker();
        for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it) 
SilverLife's avatar
SilverLife committed
660
        {
661
            if (it->GetMarker(m->NewMarker()) == false) continue;
662
663
664
665
            it->SetMarker(marker_new);

        }

666
        for(Mesh::iteratorFace it = m->BeginFace(); it != m->EndFace(); ++it) 
667
        {
668
            if (it->GetMarker(m->NewMarker()) == false) continue;
669
670
            it->SetMarker(marker_new);
        }
SilverLife's avatar
SilverLife committed
671

672
        for(Mesh::iteratorEdge it = m->BeginEdge(); it != m->EndEdge(); ++it) 
673
        {
674
            if (it->GetMarker(m->NewMarker()) == false) continue;
675
            it->SetMarker(marker_new);
SilverLife's avatar
SilverLife committed
676
        }
677

678
        for(Mesh::iteratorNode it = m->BeginNode(); it != m->EndNode(); ++it) 
SilverLife's avatar
SilverLife committed
679
        {
680
            if (it->GetMarker(m->NewMarker()) == false) continue;
681
            it->SetMarker(marker_new);
SilverLife's avatar
SilverLife committed
682
683
684
        }


685
		//11. Restore parallel connectivity, global ids
686
        m->ResolveShared(true);
SilverLife's avatar
SilverLife committed
687
        //if (call_counter == 0)
688
		m->ResolveModification(false);
689
        //ExchangeGhost(3,NODE); // Construct Ghost cells in 2 layers connected via nodes
690
691
		//12. Let the user update their data
		//todo: call back function for New() cells
Kirill Terekhov's avatar
Kirill Terekhov committed
692
		if( model ) model->Adaptation(*m);
693
		//13. Delete old elements of the mesh
Kirill Terekhov's avatar
Kirill Terekhov committed
694
		m->ApplyModification();
695
		//14. Done
SilverLife's avatar
SilverLife committed
696
        //cout << rank << ": Before end " << endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
697
		m->EndModification();
698
		//ExchangeData(hanging_nodes,CELL | FACE,0);
699
        m->ResolveSets();
700

701
		m->CheckCentroids();
702

703
704
705
706
707
        m->BeginModification();
            m->ExchangeGhost(1,NODE,&marker_new); // Construct Ghost cells in 2 layers connected via nodes
            m->ReleaseMarker(marker_new,CELL|FACE|EDGE|NODE);
		m->ApplyModification();
    	m->EndModification();
708
709

        //ExchangeData(hanging_nodes,CELL | FACE,0);
SilverLife's avatar
SilverLife committed
710
        //cout << rank << ": After end " << endl;
711
		//reorder element's data to free up space
Kirill Terekhov's avatar
Kirill Terekhov committed
712
		m->ReorderEmpty(CELL|FACE|EDGE|NODE);
713
714
		//return number of refined cells
		call_counter++;
715
        std::cout << rank << ": END REFINE " << (ret != 0) << endl;
716
717
		return ret != 0;
	}
718
719
720
721
722
723
724
725
726
727
728
729

    void OperationMin(const Tag & tag, const Element & element, const INMOST_DATA_BULK_TYPE * data, INMOST_DATA_ENUM_TYPE size)
    {
        int value  =  (int)*((int*)data);


        if (value < element->Integer(tag))
        {
            element->Integer(tag) = value;
        }
        (void)size;
    }
730
	
731
732
    void AdaptiveMesh::SynchronizeIndicated(TagInteger& indicator)
    {
733
734
        if (m->GetProcessorsNumber() == 1) return;
        int rank = m->GetProcessorRank();
735
736

        // Check all sets. All elements in sets must be indicated. At first we check indicator in local processor, and second integrate data
737
738
        TagInteger tag_indicated = m->CreateTag("INDICATED",DATA_INTEGER,ESET,NONE,1);
        for(Mesh::iteratorSet it = m->BeginSet(); it != m->EndSet(); ++it) 
739
        {
740
            ElementSet set = ElementSet(m,*it);
741
742
743
744
745
746
747
            set.Integer(tag_indicated) = 1;
            ElementSet::iterator p = set.Begin();
            while(p != set.End())
            {
                if (indicator[*p] == 0)
                {
                    tag_indicated[set] = 0;
748
                    //std::cout << rank << ": Set " << set.GetName() << " not all indicated" << endl;
749
750
751
752
753
754
755
                    break;
                }

                p++;
            }
        }

756
757
        m->ReduceData(tag_indicated,ESET,0,OperationMin);
        m->ExchangeData(tag_indicated,ESET,0);
758

759
        for(Mesh::iteratorSet it = m->BeginSet(); it != m->EndSet(); ++it) 
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
            if (it->Integer(tag_indicated) == 0)
            {
                ElementSet::iterator p = it->Begin();
                while(p != it->End())
                {
                    p->Integer(indicator) = 0;
                    p++;
                }
            }
        /*
                stringstream ss;
        for(Mesh::iteratorSet it = BeginSet(); it != EndSet(); ++it) 
        {
            ss << it->GetName() << " - " << it->Integer(tag_indicated) << endl;;
        }
775
        cout << rank << " Sets: \n" << ss.str() << endl;
776
777
778
        */
    }

779
780
	bool AdaptiveMesh::Coarse(TagInteger & indicator)
	{
781
        std::cout << rank << ": BEGIN COARSE\n";
782
783
784
        SynchronizeIndicated(indicator);
        return false;

785
786
787
788
789
790
791
792
		static int call_counter = 0;
		//return number of coarsened cells
		int ret = 0;
		//initialize tree structure
		PrepareSet();
		int schedule_counter = 1; //indicates order in which refinement will be scheduled
		int scheduled = 1, unscheduled = 0; //indicates that at least one element was scheduled on current sweep
		//TagInteger coarsened = CreateTag("COARSENED",DATA_INTEGER,CELL,NONE,1);
Kirill Terekhov's avatar
Kirill Terekhov committed
793
		TagInteger coarse_indicator = m->CreateTag("COARSE_INDICATOR",DATA_INTEGER,EDGE,NONE,1); //used to find on fine cells indicator on coarse cells
794
		//0. Extend indicator for sets, edges and faces
Kirill Terekhov's avatar
Kirill Terekhov committed
795
		indicator = m->CreateTag(indicator.GetTagName(),DATA_INTEGER,FACE|EDGE,NONE,1);
796
797
798
799
800
801
802
803
		while(scheduled || unscheduled)
		{
			// rules
			// a) If there is adjacent finer edge that is not marked for coarsening
			// then this cell should not be coarsened
			// b) If there is adjacent coarser cell, then this cell should be coarsened
			// first
			//0.Communicate indicator - it may be not synced
Kirill Terekhov's avatar
Kirill Terekhov committed
804
			m->ExchangeData(indicator,CELL,0);
805
806
807
808
809
810
811
			//1. Mark each adjacent face/edge for coarsement schedule
			// problem: should mark so that if every adjacent cell is coarsened
			// then adjacent face/edge are also coarsened
			for(ElementType etype = EDGE; etype <= FACE; etype = NextElementType(etype))
			{
				//for(Storage::integer it = 0; it < LastLocalID(etype); ++it) if( isValidElement(etype,it) )
				//	indicator[ElementByLocalID(etype,it)] = 0;
Kirill Terekhov's avatar
Kirill Terekhov committed
812
				for(Storage::integer it = 0; it < m->LastLocalID(etype); ++it) if( m->isValidElement(etype,it) )
813
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
814
					Element e = m->ElementByLocalID(etype,it);
815
816
817
818
					ElementArray<Cell> adj = e.getCells();
					indicator[e] = INT_MAX;
					for(ElementArray<Element>::size_type kt = 0; kt < adj.size(); ++kt)
						if( level[e] == level[adj[kt]]) indicator[e] = std::min(indicator[e],indicator[adj[kt]]);
819
					//if (indicator[e] == INT_MAX) cout << rank << ": " << ElementTypeName(e.GetElementType()) << e.GlobalID() << endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
820
					//assert(indicator[e] != INT_MAX);
821
822
823
				}
			}
			//2.Communicate indicator on faces and edges
Kirill Terekhov's avatar
Kirill Terekhov committed
824
			m->ReduceData(indicator,FACE|EDGE,0,ReduceMin);
825
			m->ExchangeData(indicator,FACE|EDGE,0);
826
827
828
			//3.If there is adjacent finer edge that are not marked for coarsening
			// then this cell should not be coarsened
			unscheduled = scheduled = 0;
Kirill Terekhov's avatar
Kirill Terekhov committed
829
			for(Storage::integer it = 0; it < m->CellLastLocalID(); ++it) if( m->isValidCell(it) )
830
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
831
				Cell c = m->CellByLocalID(it);
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
				if( indicator[c] )
				{
					ElementArray<Edge> edges = c.getEdges();
					for(ElementArray<Edge>::size_type kt = 0; kt < edges.size(); ++kt)
					{
						if( level[edges[kt]] > level[c] && indicator[edges[kt]] == 0 )
						{
							indicator[c] = 0;
							unscheduled++;
						}
					}
				}
			}
			//4. Propogate coarsement info over set tree to detect valid coarsenings.
			// go down over sets, if set does not have children and all of the cells
			// of the set are marked for coarsening, then mark the set for coarsement
			// otherwise unmark.
			// Unmark all cells that are not to be coarsened
Kirill Terekhov's avatar
Kirill Terekhov committed
850
			for(Storage::integer it = 0; it < m->CellLastLocalID(); ++it) if( m->isValidCell(it) )
851
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
852
				Cell c = m->CellByLocalID(it);
853
                //if (!isValidElement(c.GetHandle())) continue;
854
855
				if( indicator[c] )
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
856
					ElementSet parent(m,parent_set[c]);
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
					//intermediate cell may not be coarsened
					//root set may not have coarsening cells
					if( parent.HaveChild() || !parent.HaveParent() )
					{
						indicator[c] = 0;
						unscheduled++;
					}
					else
					{
						Storage::integer schedule_first = 0;
						bool check = true;
						//check that all elements of the set are to be coarsened
						for(ElementSet::iterator it = parent.Begin(); it != parent.End(); ++it)
						{
							check &= (indicator[it->self()] != 0);
							schedule_first = std::max(schedule_first,indicator[it->self()]);
						}
						if(!check)
						{
							indicator[c] = 0;
							unscheduled++;
						}
						else if( indicator[c] != schedule_first )
						{
							indicator[c] = schedule_first;
							unscheduled++;
						}
					}
				}
			}
			//5.If there is an adjacent coarser element to be refined, then
			//   this one should be scheduled to be refined first
			//a) clean up coarse indicator tag
Kirill Terekhov's avatar
Kirill Terekhov committed
890
891
			for(Storage::integer it = 0; it < m->EdgeLastLocalID(); ++it) if( m->isValidEdge(it) )
				coarse_indicator[m->EdgeByLocalID(it)] = 0;
892
			//b) each cell mark it's finer edges with cell's schedule
Kirill Terekhov's avatar
Kirill Terekhov committed
893
			for(Storage::integer it = 0; it < m->CellLastLocalID(); ++it) if( m->isValidCell(it) )
894
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
895
				Cell c = m->CellByLocalID(it);
896
897
898
899
900
901
902
903
904
905
906
				if( indicator[c] )
				{
					ElementArray<Element> adj = c.getAdjElements(EDGE);
					for(ElementArray<Element>::size_type kt = 0; kt < adj.size(); ++kt)
					{
						if( level[adj[kt]] > level[c] ) //only finer edges
							coarse_indicator[adj[kt]] = std::max(coarse_indicator[adj[kt]],indicator[c]);
					}
				}
			}
			//c) data reduction to get maximum over mesh partition
Kirill Terekhov's avatar
Kirill Terekhov committed
907
			m->ReduceData(coarse_indicator,EDGE,0,ReduceMax);
908
			m->ExchangeData(coarse_indicator,EDGE,0);
909
			//d) look from cells if any edge is coarsened earlier
Kirill Terekhov's avatar
Kirill Terekhov committed
910
			for(Storage::integer it = 0; it < m->CellLastLocalID(); ++it) if( m->isValidCell(it) )
911
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
912
				Cell c = m->CellByLocalID(it);
913
914
915
916
917
918
919
920
921
922
923
924
925
926
				if( indicator[c] )
				{
					ElementArray<Element> adj = c.getAdjElements(EDGE);
					for(ElementArray<Element>::size_type kt = 0; kt < adj.size(); ++kt)
					{
						if( level[c] == level[adj[kt]] && //do not look from coarse cell onto finer edge
						    indicator[c] <= coarse_indicator[adj[kt]])
						{
							indicator[c] = coarse_indicator[adj[kt]]+1;
							scheduled++;
						}
					}
				}
			}
927
			m->ExchangeData(indicator,CELL|FACE|EDGE,0);
928
			//5.Go back to 1 until no new elements scheduled
Kirill Terekhov's avatar
Kirill Terekhov committed
929
930
			scheduled = m->Integrate(scheduled);
			unscheduled = m->Integrate(unscheduled);
931
932
933
			if( scheduled ) schedule_counter++;
		}
		//cleanup
Kirill Terekhov's avatar
Kirill Terekhov committed
934
		coarse_indicator = m->DeleteTag(coarse_indicator);
935
		//Make schedule which elements should be refined earlier.
Kirill Terekhov's avatar
Kirill Terekhov committed
936
		m->BeginModification();
937
938
939
940
941
942
		while(schedule_counter)
		{
			//unite cells
			//should find and set hanging nodes on faces
			//find single node at the center, all other nodes,
			//adjacent over edge are hanging nodes
Kirill Terekhov's avatar
Kirill Terekhov committed
943
			for(Storage::integer it = 0; it < m->CellLastLocalID(); ++it) if( m->isValidCell(it) )
944
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
945
				Cell c = m->CellByLocalID(it);
946
947
948
				if( !c.Hidden() && indicator[c] == schedule_counter )
				{
					//this set contains all the cells to be united
Kirill Terekhov's avatar
Kirill Terekhov committed
949
950
					ElementSet parent(m,parent_set[c]);
					ElementArray<Cell> unite_cells(m,parent.Size());
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
					//unmark indicator to prevent coarsement with next element
					Storage::integer kt = 0;
					for(ElementSet::iterator jt = parent.Begin(); jt != parent.End(); ++jt)
					{
						unite_cells[kt++] = jt->getAsCell();
						indicator[jt->self()] = 0; //prevent algorithm from visiting again
					}
					//find a node common to all the cells
					ElementArray<Node> center_node = unite_cells[0].getNodes();
					for(kt = 1; kt < unite_cells.size(); ++kt)
						center_node.Intersect(unite_cells[kt].getNodes());
					//only one should be found
					assert(center_node.size() == 1);
					ElementArray<Node> hanging = center_node[0].BridgeAdjacencies2Node(EDGE);
					Cell v = Cell::UniteCells(unite_cells,0);
					//connect hanging nodes to the cell
					assert(hanging_nodes[v].size() == 0);
					for(ElementArray<Node>::size_type kt = 0; kt < hanging.size(); ++kt)
						hanging_nodes[v].push_back(hanging[kt]);
					//set new parent
					parent_set[v] = parent.GetParent().GetHandle();
					//add cell to parent set
Kirill Terekhov's avatar
Kirill Terekhov committed
973
					ElementSet(m,parent_set[v]).PutElement(v);
974
975
976
977
978
979
980
981
982
983
984
985
986
987
					//set level for new cell
					level[v] = level[c]-1;
					//delete set that contained cells
					//tree structure should be resolved on ApplyModification
					parent.DeleteSet();
					//increment number of coarsened cells
					ret++;
				}
			}
			//unite faces
			//should find and set hanging nodes on edges
			//find single node at the center, all other nodes,
			//adjacent over edge of the face are hanging nodes
			int numcoarsened = 0;
Kirill Terekhov's avatar
Kirill Terekhov committed
988
			for(Storage::integer it = 0; it < m->FaceLastLocalID(); ++it) if( m->isValidFace(it) )
989
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
990
				Face f = m->FaceByLocalID(it);
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
				if( !f.Hidden() && indicator[f] == schedule_counter )
				{
					//one (or both) of the adjacent cells were coarsened and has lower level
					bool visited = false;
					ElementArray<Cell> cells = f.getCells();
					for(ElementArray<Cell>::size_type kt = 0; kt < cells.size(); ++kt)
					{
						assert(level[cells[kt]] < level[f]);
					}
					for(ElementArray<Cell>::size_type kt = 0; kt < cells.size(); ++kt)
					{
						if( level[cells[kt]] < level[f] )
						{
							//cell has one hanging node in common with current face
							ElementArray<Node> nodes = f.getNodes();
							Storage::reference_array search_hanging = hanging_nodes[cells[kt]];
							nodes.Intersect(search_hanging.data(),search_hanging.size());
							assert(nodes.size() == 1);
							//faces that hanging node shares with the cell are
							//those to be united
							ElementArray<Face> unite_faces = cells[kt].getFaces();
							unite_faces.Intersect(nodes[0].getFaces());
							//unmark faces to prevent visit
							for(ElementArray<Face>::size_type lt = 0; lt < unite_faces.size(); ++lt)
								indicator[unite_faces[lt]] = 0;
							//nodes connected by edges to hanging node and
							//common to the cell are hanging nodes on edges
							ElementArray<Node> hanging = cells[kt].getNodes();
							hanging.Intersect(nodes[0].BridgeAdjacencies(EDGE,NODE));
							//unite faces
							Face v = Face::UniteFaces(unite_faces,0);
							//set level for new face
							level[v] = level[f]-1;
							//connect new face to hanging nodes
							for(ElementArray<Node>::size_type lt = 0; lt < hanging.size(); ++lt)
								hanging_nodes[v].push_back(hanging[lt]);
							visited = true;
							numcoarsened++;
							break; //no need to visit the other cell
						}
					}
					assert(visited);
				}
			}
			//unite edges
Kirill Terekhov's avatar
Kirill Terekhov committed
1036
			for(Storage::integer it = 0; it < m->EdgeLastLocalID(); ++it) if( m->isValidEdge(it) )
1037
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
1038
				Edge e = m->EdgeByLocalID(it);
1039
1040
1041
1042
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
				if( !e.Hidden() && indicator[e] == schedule_counter )
				{
					//at least one face must have lower level
					bool visited = false;
					ElementArray<Face> faces = e.getFaces();
					for(ElementArray<Face>::size_type kt = 0; kt < faces.size(); ++kt)
					{
						if( level[faces[kt]] < level[e] )
						{
							//face has one hanging node in common with current edge
							ElementArray<Node> nodes = e.getNodes();
							Storage::reference_array search_hanging = hanging_nodes[faces[kt]];
							nodes.Intersect(search_hanging.data(),search_hanging.size());
							assert(nodes.size() == 1);
							//edges that hanging node shares with the face are those to
							//be united
							ElementArray<Edge> unite_edges = faces[kt].getEdges();
							unite_edges.Intersect(nodes[0].getEdges());
							//unmark edges to prevent visit
							for(ElementArray<Edge>::size_type lt = 0; lt < unite_edges.size(); ++lt)
								indicator[unite_edges[lt]] = 0;
							//unite edges
							Edge v = Edge::UniteEdges(unite_edges,0);
							//set level for new edge
							level[v] = level[e]-1;
							visited = true;
							break; //no need to visit any other face
						}
					}
					assert(visited);
				}
			}
Kirill Terekhov's avatar
Kirill Terekhov committed
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
			/*
			for(Storage::integer it = 0; it < NodeLastLocalID(); ++it) if( isValidNode(it) )
			{
				Node e = NodeByLocalID(it);
				if( !e.Hidden() )
				{
					int my_level = -1;
					ElementArray<Edge> edges = e.getEdges();
					for(ElementArray<Edge>::iterator kt = edges.begin(); kt != edges.end(); ++kt)
						my_level = std::max(my_level,level[*kt]);
					level[e] = my_level;
				}
			}
			*/
1085
1086
1087
1088
			//jump to later schedule
			schedule_counter--;
		}
		//free created tag
Kirill Terekhov's avatar
Kirill Terekhov committed
1089
		m->DeleteTag(indicator,FACE|EDGE);
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
		//restore face orientation
		//BUG: bad orientation not fixed automatically
		int nfixed = 0;
		for(Mesh::iteratorFace it = m->BeginFace(); it != m->EndFace(); ++it) 
			if( !it->CheckNormalOrientation() )
			{
				it->FixNormalOrientation();
				nfixed++;
			}
			//std::cout << "Face " << it->LocalID() << " oriented incorrectly " << std::endl;
		if( nfixed ) std::cout << "fixed " << nfixed << " faces" << std::endl;
1101
		//todo:
1102
1103
1104
    	m->ResolveShared(true);
		m->ResolveModification(false);
		m->CheckCentroids();
1105
1106
		//todo:
		//let the user update their data
Kirill Terekhov's avatar
Kirill Terekhov committed
1107
1108
		if( model ) model->Adaptation(*m);
		m->ApplyModification();
1109
		//done
Kirill Terekhov's avatar
Kirill Terekhov committed
1110
		m->EndModification();
1111
		//CheckCentroids();
Kirill Terekhov's avatar
Kirill Terekhov committed
1112
        //ExchangeData(hanging_nodes,CELL | FACE,0);
1113
1114
1115
		//cleanup null links to hanging nodes
		for(ElementType etype = FACE; etype <= CELL; etype = NextElementType(etype))
		{
Kirill Terekhov's avatar
Kirill Terekhov committed
1116
			for(Storage::integer it = 0; it < m->LastLocalID(etype); ++it) if( m->isValidElement(etype,it) )
1117
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
1118
				Storage::reference_array arr = hanging_nodes[m->ElementByLocalID(etype,it)];
1119
1120
1121
1122
1123
1124
1125
1126
1127
				Storage::reference_array::size_type jt = 0;
				for(Storage::reference_array::size_type kt = 0; kt < arr.size(); ++kt)
					if( arr[kt] != InvalidElement() ) arr[jt++] = arr[kt];
				arr.resize(jt);
			}
		}
		//cleanup null links in sets
		CleanupSets(root);
		//reorder element's data to free up space
Kirill Terekhov's avatar
Kirill Terekhov committed
1128
		m->ReorderEmpty(CELL|FACE|EDGE|NODE|ESET);
1129
1130
		
		call_counter++;
1131
        std::cout << rank << ": END COARSE\n";
1132
1133
		return ret != 0;
	}
SilverLife's avatar
SilverLife committed
1134
}