partitioner.cpp 58 KB
Newer Older
Kirill Terekhov's avatar
Kirill Terekhov committed
1
2
#include "inmost.h"

3
4
5
#if defined(_WIN32) || defined(_WIN64) || defined(WIN32) || defined(WIN64)
__declspec( dllexport ) void partitioner_stub(){} //to avoid LNK4221 warning
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
6
7
8
9
10
11

#if defined(USE_PARTITIONER)

#if defined(USE_PARTITIONER_ZOLTAN)
#include <zoltan.h>
#endif
12
13
14
15
#if defined(USE_PARTITIONER_METIS)
#define METIS_EXPORT
#include <metis.h>
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
16
#if defined(USE_PARTITIONER_PARMETIS)
17
#if !defined(USE_PARTITIONER_METIS)
18
#define METIS_EXPORT
Kirill Terekhov's avatar
Kirill Terekhov committed
19
#include <metis.h>
20
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <parmetis.h>
#endif
#include <sstream>
#include <deque>
#define ZOLTAN_CHKERR(x) if( x != ZOLTAN_OK )  {throw ErrorInPartitioner;}


#if defined(USE_PARALLEL_WRITE_TIME)
#define REPORT_MPI(x) {m->WriteTab(m->GetStream()) << "<MPI><![CDATA[" << #x << "]]></MPI>" << std::endl; x;}
#define REPORT_STR(x) {m->WriteTab(m->GetStream()) << "<TEXT><![CDATA[" << x << "]]></TEXT>" << std::endl;}
#define REPORT_VAL(str,x) {m->WriteTab(m->GetStream()) << "<VALUE name=\"" << str << "\"> <CONTENT><![CDATA[" << x << "]]> </CONTENT><CODE><![CDATA[" << #x << "]]></CODE></VALUE>" << std::endl;}
#define ENTER_FUNC() long double all_time = Timer(); m->WriteTab(m->GetStream()) << "<FUNCTION name=\"" << __FUNCTION__ << "\" id=\"func" << m->GetFuncID()++ << "\">" << std::endl; m->Enter();
#define EXIT_FUNC() m->WriteTab(m->GetStream()) << "<TIME>" << Timer() - all_time << "</TIME>" << std::endl; m->Exit(); m->WriteTab(m->GetStream()) << "</FUNCTION>" << std::endl;
#else
#define REPORT_MPI(x) x
Kirill Terekhov's avatar
Kirill Terekhov committed
36
37
38
39
#define REPORT_STR(x) {}
#define REPORT_VAL(str,x) {}
#define ENTER_FUNC() {}
#define EXIT_FUNC() {}
Kirill Terekhov's avatar
Kirill Terekhov committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#endif

namespace INMOST
{
#if defined(USE_PARTITIONER_ZOLTAN)
	static int get_number_of_objects(void *data, int *ierr)
	{
		Partitioner * p = static_cast<Partitioner *>(data);
		Mesh * m = p->GetMesh();
		*ierr = ZOLTAN_OK;
		int num = 0;
		for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); it++)
			if( it->GetStatus() != Element::Ghost ) num++;
		return num;
	}
	
	static void get_object_list(void *data, int sizeGID, int sizeLID,
								ZOLTAN_ID_PTR globalID, ZOLTAN_ID_PTR localID,
								int wgt_dim, float *obj_wgts, int *ierr)
	{
		Partitioner * p = static_cast<Partitioner *>(data);
		Mesh * m = p->GetMesh();
		*ierr = ZOLTAN_OK;
		int i = 0;	 
		for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); it++)
			if( it->GetStatus() != Element::Ghost )
			{
				globalID[i] = it->GlobalID();
				localID[i] = i;
				for(int j = 0; j < wgt_dim; j++)
70
					 obj_wgts[i] = static_cast<float>(it->RealArray(p->GetWeight())[j]);
Kirill Terekhov's avatar
Kirill Terekhov committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
				i++;
			}
	}
	
	static int get_num_geometry(void *data, int *ierr)
	{
		Partitioner * p = static_cast<Partitioner *>(data);
		Mesh * m = p->GetMesh();
		*ierr = ZOLTAN_OK;
		return m->GetDimensions();
	}
	
	static void get_geometry_list(void *data, int sizeGID, int sizeLID,
								  int num_obj,
								  ZOLTAN_ID_PTR globalID, ZOLTAN_ID_PTR localID,
								  int num_dim, double *geom_vec, int *ierr)
	{
		Partitioner * p = static_cast<Partitioner *>(data);
		Mesh * m = p->GetMesh();
		int dim = m->GetDimensions();
		if ( (sizeGID != 1) || (sizeLID != 1) || (num_dim != dim))
		{
			*ierr = ZOLTAN_FATAL;
			return;
		}
		
		*ierr = ZOLTAN_OK;
		
		
		int i = 0;
		std::vector<Storage::real> coords(dim);
		for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); it++)
			if( it->GetStatus() != Element::Ghost )
			{
				it->Centroid(&coords[0]);
				for(int j = 0; j < dim; j++)
					geom_vec[dim*i + j] = coords[j];
				i++;
			}
		return;
	}
	
	static void get_num_edges_list(void *data, int sizeGID, int sizeLID,
								   int num_obj,
								   ZOLTAN_ID_PTR globalID, ZOLTAN_ID_PTR localID,
								   int *numEdges, int *ierr)
	{
		Partitioner * p = static_cast<Partitioner *>(data);
		Mesh * m = p->GetMesh();
		
		if ( (sizeGID != 1) || (sizeLID != 1))
		{
			*ierr = ZOLTAN_FATAL;
			return;
		}
		
		int i = 0;	
		for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); it++)
			if( it->GetStatus() != Element::Ghost )
			{
				numEdges[i] = 0;
132
133
				ElementArray<Face> faces = it->getFaces();
				for(ElementArray<Face>::iterator jt = faces.begin(); jt != faces.end(); jt++)
Kirill Terekhov's avatar
Kirill Terekhov committed
134
				{
135
136
					Cell n = it->Neighbour(jt->self());
					if( n.isValid() ) numEdges[i]++;
Kirill Terekhov's avatar
Kirill Terekhov committed
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
				}		
				i++;
			}
		
		*ierr = ZOLTAN_OK;
		return;
	}
	
	static void get_edge_list(void *data, int sizeGID, int sizeLID,
							  int num_obj, ZOLTAN_ID_PTR globalID, ZOLTAN_ID_PTR localID,
							  int *num_edges,
							  ZOLTAN_ID_PTR nborGID, int *nborProc,
							  int wgt_dim, float *ewgts, int *ierr)
	{
		int *nextProc;
		float * nextWgt;
		ZOLTAN_ID_TYPE *nextNbor;
		
		Partitioner * p = static_cast<Partitioner *>(data);
		Mesh * m = p->GetMesh();
		*ierr = ZOLTAN_OK;
		
		if ( (sizeGID != 1) || (sizeLID != 1))
		{
			*ierr = ZOLTAN_FATAL;
			return;
		}
		
		nextNbor = nborGID;
		nextProc = nborProc;
		nextWgt = ewgts;
		
		int i = 0;
		for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); it++)
			if( it->GetStatus() != Element::Ghost )
			{
173
174
				ElementArray<Face> faces = it->getFaces();
				for(ElementArray<Face>::iterator jt = faces.begin(); jt != faces.end(); jt++)
Kirill Terekhov's avatar
Kirill Terekhov committed
175
				{
176
177
					Cell n = it->Neighbour(jt->self());
					if( n.isValid() )
Kirill Terekhov's avatar
Kirill Terekhov committed
178
179
180
181
					{
						*nextNbor++ = n->GlobalID();
						*nextProc++ = n->Integer(m->OwnerTag());
						for(int j = 0; j < wgt_dim; j++)
182
							*nextWgt++ = static_cast<float>(jt->RealArray(p->GetWeight())[j]);
Kirill Terekhov's avatar
Kirill Terekhov committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
					}
				}		
				i++;
			}
		return;
	}
#endif
	
	Partitioner::Partitioner(Mesh * _m)
	{
		m = _m;
		if( m->GetMeshState() == Mesh::Serial ) m->ResolveShared();
		pzz = NULL;
	}
	
	Partitioner::Partitioner(const Partitioner & other)
	{
#if defined(USE_PARTITIONER_ZOLTAN)
		if( pt == Zoltan_Parmetis || pt == Zoltan_Scotch || pt == Zoltan_PHG || pt == Zoltan_RCB || pt == Zoltan_RIB || pt == Zoltan_HSFC )
		{
			if( other.pzz != NULL ) pzz = static_cast<void *>(Zoltan_Copy(static_cast<struct Zoltan_Struct *>(other.pzz)));
			else pzz = NULL;
		}
#endif
		m = other.m;
		weight_tag = other.weight_tag;
	}
	
	Partitioner & Partitioner::operator = (Partitioner const & other)
	{
#if defined(USE_PARTITIONER_ZOLTAN)
		if( pt == Zoltan_Parmetis || pt == Zoltan_Scotch || pt == Zoltan_PHG || pt == Zoltan_RCB || pt == Zoltan_RIB || pt == Zoltan_HSFC )
		{
			if( other.pzz != NULL ) 
			{
				if( pzz == NULL ) pzz = static_cast<void *>(Zoltan_Copy(static_cast<struct Zoltan_Struct *>(other.pzz)));
				else Zoltan_Copy_To(static_cast<struct Zoltan_Struct *>(pzz),static_cast<struct Zoltan_Struct *>(other.pzz));
			}
			else pzz = NULL;
		}
#endif
		m = other.m;
		weight_tag = other.weight_tag;
		return *this;
	}
	
	Partitioner::~Partitioner()
	{
#if defined(USE_PARTITIONER_ZOLTAN)
		if( pt == Zoltan_Parmetis || pt == Zoltan_Scotch || pt == Zoltan_PHG || pt == Zoltan_RCB || pt == Zoltan_RIB || pt == Zoltan_HSFC )
		{
			if( pzz != NULL )
			{
				struct Zoltan_Struct * zz = static_cast<struct Zoltan_Struct *>(pzz);
				Zoltan_Destroy(&zz);
				pzz = static_cast<void *>(zz);
			}
		}
#endif
	}
	
	void Partitioner::Initialize(int * argc, char *** argv)
	{
Kirill Terekhov's avatar
Fixes    
Kirill Terekhov committed
246
247
		(void) argc;
		(void) argv;
Kirill Terekhov's avatar
Kirill Terekhov committed
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#if defined(USE_PARTITIONER_ZOLTAN)
		float ver;
		Zoltan_Initialize(*argc,*argv,&ver);
#endif
	}
	
	void Partitioner::Finalize()
	{
	}
	
	
	void Partitioner::Evaluate()
	{
		ENTER_FUNC();
		int package = 0;
		switch(pt)
		{
265
			case INNER_RCM:
Kirill Terekhov's avatar
Kirill Terekhov committed
266
267
268
269
270
271
272
273
274
275
276
277
278
				package = 0;
				break;
			case Zoltan_Parmetis:
			case Zoltan_PHG:
			case Zoltan_RIB:
			case Zoltan_RCB:
			case Zoltan_HSFC:
			case Zoltan_Scotch:
				package = 1;
				break;
			case Parmetis:
				package = 2;
				break;
279
280
			case INNER_KMEANS:
				package = 3;
281
282
283
284
285
286
287
288
289
290
			case MetisRec:
				package = 4;
				break;
			case MetisRecContig:
				package = 5;
			case MetisKway:
				package = 6;
				break;
			case MetisKwayContig:
				package = 7;
291
				break;
Kirill Terekhov's avatar
Kirill Terekhov committed
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
		}
		if( package == 0 )
		{
#if defined(USE_MPI)
			if( m->GetMeshState() == Mesh::Serial ) m->ResolveShared();
			
			unsigned mpisize = m->GetProcessorsNumber();
			
//~ #if defined(NDEBUG)
			//Check!!
			unsigned ncell = m->NumberOfCells();
			std::vector<unsigned> ncells(mpisize);
			REPORT_MPI(MPI_Allgather(&ncell,1,MPI_UNSIGNED,&ncells[0],1,MPI_UNSIGNED,m->GetCommunicator()));
			unsigned nhave = 0;
			for(unsigned k = 0; k < mpisize; k++) if( ncells[k] ) nhave++;
			if( nhave > 1 )
			{
				std::cout << "currently only non-distributed meshes are supported by reverse cuthill-mckee algorithm" << std::endl;
				throw NotImplemented;
			}
//~ #endf
			
			
			Tag index = m->CreateTag("CM_INDEX",DATA_INTEGER,CELL,NONE,1);
			Tag order = m->CreateTag("ORDER",DATA_INTEGER,CELL,NONE,1);
			
			
			for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it)
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
321
322
				ElementArray<Face> f = it->getFaces();
				for(ElementArray<Face>::iterator jt = f.begin(); jt != f.end(); ++jt)
Kirill Terekhov's avatar
Kirill Terekhov committed
323
324
325
326
327
					if( !jt->Boundary() ) it->Integer(order)++;
			}
			
			Storage::integer visited = 1;
			Storage::integer chunk = m->NumberOfCells() / mpisize + 1;
Kirill Terekhov's avatar
Kirill Terekhov committed
328
329
330
			std::deque<HandleType> queue;
			ElementArray<Element> around(m);
			HandleType select;
Kirill Terekhov's avatar
Kirill Terekhov committed
331
332
			while(visited != static_cast<Storage::integer>(m->NumberOfCells()+1) )
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
333
334
				select = InvalidHandle();
				Mesh::iteratorCell halt_it;
Kirill Terekhov's avatar
Kirill Terekhov committed
335
336
337
338
				for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it)
				{
					if( it->Integer(index) == 0 )
					{
Kirill Terekhov's avatar
Kirill Terekhov committed
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
						select = *it;
						halt_it = it;
						break;
					}
				}
				if( select == InvalidHandle() ) break;
				Storage::integer sorder = m->Integer(select,order);
				for(Mesh::iteratorCell it = halt_it; it != m->EndCell(); ++it)
				{
					if( it->Integer(index) == 0 )
					{
						Storage::integer norder = it->Integer(order);
						if( norder < sorder ) 
						{
							select = *it;
							sorder = norder;
						}
Kirill Terekhov's avatar
Kirill Terekhov committed
356
357
358
					}
				}
				queue.push_back(select);
Kirill Terekhov's avatar
Kirill Terekhov committed
359
				m->Integer(queue.back(),index) = visited++;
Kirill Terekhov's avatar
Kirill Terekhov committed
360
361
				while(!queue.empty())
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
362
					around = Cell(m,queue.front())->BridgeAdjacencies(FACE,CELL);
Kirill Terekhov's avatar
Kirill Terekhov committed
363
					queue.pop_front();
Kirill Terekhov's avatar
Fixes    
Kirill Terekhov committed
364
					std::sort(around.data(),around.data()+around.size(),Mesh::IntegerComparator(m,order));
Kirill Terekhov's avatar
Kirill Terekhov committed
365
					for(ElementArray<Element>::iterator it = around.begin(); it != around.end(); ++it)
Kirill Terekhov's avatar
Kirill Terekhov committed
366
367
368
					{
						if( it->Integer(index) == 0 )
						{
Kirill Terekhov's avatar
Kirill Terekhov committed
369
370
							queue.push_back(*it);
							m->Integer(queue.back(),index) = visited++;
Kirill Terekhov's avatar
Kirill Terekhov committed
371
372
373
374
375
376
377

							if( visited % chunk == 0 ) 
							{
								queue.clear();
								break;
							}

Kirill Terekhov's avatar
Kirill Terekhov committed
378
379
						}
					}
Kirill Terekhov's avatar
Kirill Terekhov committed
380
381
					//this may not fire properly
					//if( visited % chunk == 0 ) queue.clear();
Kirill Terekhov's avatar
Kirill Terekhov committed
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
				}
			}
			m->DeleteTag(order);
			//index may be used
			
			//reverse
			//for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it)
			//	it->Integer(index) = m->NumberOfCells() - it->Integer(index);
				
			
			
			Tag redist = m->RedistributeTag();
			
			for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it)
			{
				it->Integer(redist) = it->Integer(index)/chunk;
				//~ std::cout << it->Integer(index) << " -> " <<  it->Integer(redist) << std::endl;
			}

			m->DeleteTag(index);
#else
			throw NotImplemented;
#endif
		}
		if( package == 1 )
		{
#if defined(USE_PARTITIONER_ZOLTAN)
			int changes, numGidEntries, numLidEntries, numImport, numExport;
			ZOLTAN_ID_PTR importGlobalGids, importLocalGids, exportGlobalGids, exportLocalGids;
			int *importProcs, *importToPart, *exportProcs, *exportToPart;
			int rc;
413
			if( m->Integer(m->GetHandle(),m->LayersTag()) == 0 ) m->ExchangeGhost(1,FACE);
Kirill Terekhov's avatar
Kirill Terekhov committed
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
			
			rc = Zoltan_LB_Partition(static_cast<struct Zoltan_Struct *>(pzz), /* input (all remaining fields are output) */
									 &changes,        /* 1 if partitioning was changed, 0 otherwise */ 
									 &numGidEntries,  /* Number of integers used for a global ID */
									 &numLidEntries,  /* Number of integers used for a local ID */
									 &numImport,      /* Number of vertices to be sent to me */
									 &importGlobalGids,  /* Global IDs of vertices to be sent to me */
									 &importLocalGids,   /* Local IDs of vertices to be sent to me */
									 &importProcs,    /* Process rank for source of each incoming vertex */
									 &importToPart,   /* New partition for each incoming vertex */
									 &numExport,      /* Number of vertices I must send to other processes*/
									 &exportGlobalGids,  /* Global IDs of the vertices I must send */
									 &exportLocalGids,   /* Local IDs of the vertices I must send */
									 &exportProcs,    /* Process to which I send each of the vertices */
									 &exportToPart);  /* Partition to which each vertex will belong */
			ZOLTAN_CHKERR(rc);		
			
			if( changes )
			{
				std::vector<int> new_distribution;
				for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); it++)
					if( it->GetStatus() != Element::Ghost )
						new_distribution.push_back(it->Integer(m->OwnerTag()));	
				for(int i = 0; i < numExport; i++)
					new_distribution[exportLocalGids[i]] = exportToPart[i];
				
				Tag redist = m->RedistributeTag();
				int i = 0;
				for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); it++)
					if( it->GetStatus() != Element::Ghost )
						it->Integer(redist) = new_distribution[i++];
			}
			Zoltan_LB_Free_Part(&importGlobalGids, &importLocalGids, 
								&importProcs, &importToPart);
			Zoltan_LB_Free_Part(&exportGlobalGids, &exportLocalGids, 
								&exportProcs, &exportToPart);
#endif
		}
452
		if( package == 2 || package == 4 || package == 5 || package == 6 || package == 7)
Kirill Terekhov's avatar
Kirill Terekhov committed
453
		{
454
#if defined(USE_PARTITIONER_PARMETIS) || defined(USE_PARTITIONER_METIS)
Kirill Terekhov's avatar
Kirill Terekhov committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
			INMOST_DATA_ENUM_TYPE dim = m->GetDimensions();
			double time;
			bool debug_output = false;
			bool time_output = false;
			int result;
			int rank = m->GetProcessorRank();
			int size = m->GetProcessorsNumber();
			int have_vwgt = 0, have_adjwgt = 0, have_mwgt = 0;
			int nreserve = 32;
			idx_t nparts;
			//Array storing parts indexes
			std::vector<unsigned int> xparts;
			//These arrays determine local sparse matrix
			std::vector<idx_t> vtxdist;
			std::vector<idx_t> xadj;
			std::vector<idx_t> adjncy;
			//These arrays determine weights defined for vertices
			std::vector<idx_t> vwgt; //unused yet
			std::vector<idx_t> adjwgt; //unused yet
			idx_t wgtflag = 0;
			idx_t numflag = 0;
			idx_t ndims = m->GetDimensions();
			std::vector<real_t> xyz;
			//This sets weight for every part set in respect to according weight and tolerance
			idx_t ncon = 1;
			std::vector<real_t> tpwgts;
			std::vector<real_t> ubvec;
			//set options
			std::vector<idx_t> options(3,0);
			//number of edgecuts
			idx_t edgecut;
			//output data - which entity should belong to which part
			std::vector<idx_t> part;
			real_t itr = 1000.0;
			//send data to processors with zero nodes
			std::vector<unsigned int> send;
			idx_t mysize;
			//to estimate memory used by entities
			std::vector<idx_t> vsize; //unused yet
			
			//compute part ranges for every processor
			//and total number of parts
			xparts.resize(size+1);
			xparts[0] = 0;
			
			for(unsigned int i = 1; i < xparts.size(); i++)
				xparts[i] = i;
				
			
			nparts = xparts[xparts.size()-1];
			
			
			//set graph size
			vtxdist.resize(size+1);
			
			


			//set options
			if( debug_output )
			{	
				options[0] = 1;
				options[1] = 1;
				options[2] = 15;
			}
			
			
			if( time_output ) time = Timer();
			//set ghost boundaries so we certanly know we can access adjacencies
			
			if( m->GetMeshState() != Mesh::Parallel )  
				m->ResolveShared();
Kirill Terekhov's avatar
Kirill Terekhov committed
527
			if( m->Integer(m->GetHandle(),m->LayersTag()) == 0 ) 
Kirill Terekhov's avatar
Kirill Terekhov committed
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
				m->ExchangeGhost(1,FACE);
			//~ if( !m->GlobalIDTag().isValid() || !m->GlobalIDTag().isDefined(CELL) )
				m->AssignGlobalID(CELL);
			

			
			
			if( time_output ) time = Timer();
			
			
			mysize = 0;
			for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it) if( it->GetStatus() != Element::Ghost ) mysize++;
			vtxdist[0] = 0;
			REPORT_MPI(result = MPI_Allgather(&mysize,1,IDX_T,&vtxdist[1],1,IDX_T,m->GetCommunicator()));
			if( result != MPI_SUCCESS ) throw Impossible;
543
544
545
546
547
548
549
550
551
552
553
554
555
556
			
#if defined(USE_PARTITIONER_METIS)
			if( package == 4 || package == 5 )
			{
				for(unsigned int i = 2; i < vtxdist.size(); i++)
					if( vtxdist[i] )
					{
						std::cout << "For METIS the entire mesh has to be on zero-th processor" << std::endl;
						throw Impossible;
					}
			}
#endif
			
			
Kirill Terekhov's avatar
Kirill Terekhov committed
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
			for(unsigned int i = 2; i < vtxdist.size(); i++)
				vtxdist[i] += vtxdist[i-1];
				
				
			if( time_output )
			{
				time = Timer()-time;
				REPORT_STR("time to compute graph information");
				REPORT_VAL("time",time);
			}


			{	
				xadj.resize(mysize+1);
				adjncy.reserve(mysize*nreserve); //preallocate array
				xadj[0] = 0;
			}
			
			xyz.resize(mysize*dim);
Kirill Terekhov's avatar
Kirill Terekhov committed
576
			part.resize(mysize,rank);
Kirill Terekhov's avatar
Kirill Terekhov committed
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
									
			
			if( time_output ) time = Timer();
			
			//compute itr parameter
			{
				itr = 1000; //communication time to distribution time
			}


			
			
			//estimate storage space
			if( pa == Repartition ) 
			{
				vsize.resize(mysize,1);
Kirill Terekhov's avatar
Kirill Terekhov committed
593
594
595
596
597
				int k = 0;
				for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it) if( it->GetStatus() != Element::Ghost )
				{
					vsize[k++] = m->MemoryUsage(*it);
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
			}
			
			
			
			
			{
				if( GetWeight().isValid() && GetWeight().GetSize() != ENUMUNDEF )
				{
					if( GetWeight().isDefined(MESH) ) have_mwgt = 1;
					if( GetWeight().isDefined(CELL) && !GetWeight().isSparse(CELL) ) have_vwgt = 1;
					if( GetWeight().isDefined(FACE) && !GetWeight().isSparse(FACE) ) have_adjwgt = 1;
					if( have_vwgt + have_adjwgt ) ncon = GetWeight().GetSize();
				}
				
				
				if( have_vwgt ) vwgt.resize(mysize*ncon);
				if( have_adjwgt) adjwgt.reserve(mysize*ncon*nreserve);
				if( !have_adjwgt && !have_vwgt ) ncon = 1;
				//set constraint tolerances
Kirill Terekhov's avatar
Kirill Terekhov committed
617
618
				const real_t v = static_cast<real_t>(1.05);
				ubvec.resize(ncon,v);
Kirill Terekhov's avatar
Kirill Terekhov committed
619
620
621
				if( have_mwgt )
				{
					std::vector<real_t> l_tpwgts(ncon);
Kirill Terekhov's avatar
Kirill Terekhov committed
622
					for(idx_t q = 0; q < ncon; q++) l_tpwgts[q] = static_cast<real_t>(m->RealArray(m->GetHandle(),GetWeight())[q]);
Kirill Terekhov's avatar
Kirill Terekhov committed
623
624
625
626
627
628
629
630
631
632
633
					REPORT_MPI(MPI_Allgather(&l_tpwgts[0],ncon,IDX_T,&tpwgts[0],ncon,IDX_T,m->GetCommunicator()));
					
					for(idx_t j = 0; j < ncon; j++)
					{
						real_t sum_tpwgts = 0;
						for(unsigned i = 0; i < tpwgts.size()/ncon; i++) sum_tpwgts += tpwgts[i*ncon+j];
						for(unsigned i = 0; i < tpwgts.size()/ncon; i++) tpwgts[i*ncon+j] /= sum_tpwgts;
					}
				}
				else
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
634
					real_t c = static_cast<real_t>(1.0/static_cast<real_t>(nparts));
Kirill Terekhov's avatar
Kirill Terekhov committed
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
					tpwgts.resize(nparts*ncon,c);
				}
			}			
			
			if( time_output ) time = Timer();
			
			//get part tag
			
			
			if( time_output )
			{
				time = Timer()-time;
				REPORT_STR("time to compute weights");
				REPORT_VAL("time",time);
			}
			
			REPORT_STR("start making graph, number of local elements:");
			REPORT_VAL("local_size",mysize);
			
			
			if( time_output ) time = Timer();
			
			
			//make graph
			int k = 0;
			for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it)
			if( it->GetStatus() != Element::Ghost )
			{
				idx_t sum = 0;
				if( pa == Partition )
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
666
667
668
669
670
671
672
673
					Storage::real xyz_temp[3] = {0.0,0.0,0.0};
					it->Centroid(xyz_temp);
					for(int q = 0; q < m->GetDimensions(); ++q)
						xyz[k*dim+q] = static_cast<real_t>(xyz_temp[q]);
				}
				{
					ElementArray<Face> faces = it->getFaces();
					for(ElementArray<Face>::iterator jt = faces.begin(); jt != faces.end(); ++jt)
Kirill Terekhov's avatar
Kirill Terekhov committed
674
					{
Kirill Terekhov's avatar
Kirill Terekhov committed
675
676
						Cell n = it->Neighbour(jt->self());
						if( n.isValid() )
Kirill Terekhov's avatar
Kirill Terekhov committed
677
678
679
680
681
						{
							adjncy.push_back(n->GlobalID());
							if( have_adjwgt ) 
							{
								for(idx_t q = 0; q < ncon; q++) 
Kirill Terekhov's avatar
Kirill Terekhov committed
682
									adjwgt.push_back(jt->RealArray(GetWeight())[q]); //why adjwgt is not real???
Kirill Terekhov's avatar
Kirill Terekhov committed
683
684
685
686
687
688
689
690
691
692
693
							}
							sum++;
						}
					}
					
					xadj[k+1] = xadj[k] + sum;
					
					//Fill weight arrays here
					if( have_vwgt )
					{
						for(idx_t q = 0; q < ncon; q++)
Kirill Terekhov's avatar
Kirill Terekhov committed
694
							vwgt[k*ncon+q] = it->RealArrayDF(GetWeight())[q]; //why vwgt is not real???
Kirill Terekhov's avatar
Kirill Terekhov committed
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
					}
				}
				k++;
			}
			
			REPORT_STR("graph made, number of adjacencies: ");
			REPORT_VAL("adjacencies_size",adjncy.size());
			
			
			if( time_output )
			{
				time = Timer()-time;
				REPORT_STR("time to compute graph");
				REPORT_VAL("time",time);
			}
			
			
712
713
			wgtflag = have_vwgt*2 + have_adjwgt;
			//std::cout << "wgtflag: " <<wgtflag << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
714
			
Kirill Terekhov's avatar
Kirill Terekhov committed
715
			//debug_output = true;
Kirill Terekhov's avatar
Kirill Terekhov committed
716
			
Kirill Terekhov's avatar
Kirill Terekhov committed
717
718
			if( debug_output )
			{
Kirill Terekhov's avatar
Kirill Terekhov committed
719
720
721
722
723
724
				std::stringstream name;
				name << "before" << rank << ".txt";
				std::fstream f(name.str().c_str(),std::ios::out);
				//m->BeginSequentialCode();
				f << "on processor " << rank << std::endl;
				f << "vtxdist: " << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
725
726
				for(unsigned int i = 0; i < vtxdist.size(); i++)
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
727
728
					f << vtxdist[i] << " ";
					if( (i+1)%30 == 0 ) f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
729
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
730
731
				f << std::endl;
				f << "local size: " << vtxdist[rank+1]-vtxdist[rank] << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
732
733
				
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
734
					f << "xadj size " << xadj.size() << ":" << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
735
736
					for(unsigned int i = 0; i < xadj.size(); i++)
					{
Kirill Terekhov's avatar
Kirill Terekhov committed
737
738
						f << xadj[i] << " ";
						if( (i+1)%30 == 0 ) f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
739
					}
Kirill Terekhov's avatar
Kirill Terekhov committed
740
741
					f << std::endl;
					f << "adjncy size " << adjncy.size() << ":" << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
742
743
					for(unsigned int i = 0; i < adjncy.size(); i++)
					{
Kirill Terekhov's avatar
Kirill Terekhov committed
744
745
						f << adjncy[i] << " ";
						if( (i+1)%30 == 0 ) f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
746
					}
Kirill Terekhov's avatar
Kirill Terekhov committed
747
					f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
748
749
					if( have_vwgt )
					{
Kirill Terekhov's avatar
Kirill Terekhov committed
750
						f << "vwgt: " << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
751
752
						for(unsigned int i = 0; i < vwgt.size(); i++)
						{
Kirill Terekhov's avatar
Kirill Terekhov committed
753
754
							f << vwgt[i] << " ";
							if( (i+1)%30 == 0 ) f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
755
						}
Kirill Terekhov's avatar
Kirill Terekhov committed
756
						f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
757
758
759
					}
					if( have_adjwgt )
					{
Kirill Terekhov's avatar
Kirill Terekhov committed
760
						f << "adjwgt: " << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
761
762
						for(unsigned int i = 0; i < adjwgt.size(); i++)
						{
Kirill Terekhov's avatar
Kirill Terekhov committed
763
764
							f << adjwgt[i] << " ";
							if( (i+1)%30 == 0 ) f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
765
						}
Kirill Terekhov's avatar
Kirill Terekhov committed
766
						f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
767
768
769
					}
					if( pa == Repartition )
					{
Kirill Terekhov's avatar
Kirill Terekhov committed
770
						f << "vsize: " << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
771
772
						for(unsigned int i = 0; i < vsize.size(); i++)
						{
Kirill Terekhov's avatar
Kirill Terekhov committed
773
774
							f << vsize[i] << " ";
							if( (i+1)%30 == 0 ) f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
775
						}
Kirill Terekhov's avatar
Kirill Terekhov committed
776
						f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
777
778
779
780
781
782
783
784
785
					}
					f << "part size " << part.size() << ":" << std::endl;
					for(unsigned int i = 0; i < part.size(); i++)
					{
						f << part[i] << " ";
						if( (i+1)%30 == 0 ) f << std::endl;
					}
					f << std::endl;
					
Kirill Terekhov's avatar
Kirill Terekhov committed
786
787
					f << "wgtflag = " << wgtflag << std::endl;
					f << "numflag = " << numflag << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
788
789
790
				}
				if( pa == Partition )
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
791
792
					f << "ndims = " << ndims << std::endl;
					f << "xyz: " << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
793
794
					for(unsigned int i = 0; i < xyz.size(); i++)
					{
Kirill Terekhov's avatar
Kirill Terekhov committed
795
796
						f << xyz[i] << " ";
						if( (i+1)%30 == 0 ) f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
797
					}
Kirill Terekhov's avatar
Kirill Terekhov committed
798
					f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
799
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
800
801
802
				f << "ncon = " << ncon << std::endl;
				f << "nparts = " << nparts << std::endl;
				f << "tpwgts: " << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
803
804
				for(unsigned int i = 0; i < tpwgts.size(); i++)
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
805
806
					f << tpwgts[i] << " ";
					if( (i+1)%30 == 0 ) f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
807
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
808
809
				f << std::endl;
				f << "ubvec: " << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
810
811
				for(unsigned int i = 0; i < ubvec.size(); i++)
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
812
813
					f << ubvec[i] << " ";
					if( (i+1)%30 == 0 ) f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
814
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
815
816
				f << std::endl;
				f << "options: " << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
817
818
				for(unsigned int i = 0; i < options.size(); i++)
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
819
820
					f << options[i] << " ";
					if( (i+1)%30 == 0 ) f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
821
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
822
823
824
				f << std::endl;
				//m->EndSequentialCode();
				f.close();
Kirill Terekhov's avatar
Kirill Terekhov committed
825
826
827
828
829
830
			}
			
			//redistribute entities;
			if( time_output ) time = Timer();
			
			
831
832
#if defined(USE_PARTITIONER_PARMETIS)
			if( package == 2 ) //parmetis expects non-empty graph on all processors
Kirill Terekhov's avatar
Kirill Terekhov committed
833
834
835
836
			{
				int it,jt,kt,flag;
				unsigned int fill[3];
				
Kirill Terekhov's avatar
Kirill Terekhov committed
837
838
				
				
Kirill Terekhov's avatar
Kirill Terekhov committed
839
				send.reserve(3*nparts*2);
Kirill Terekhov's avatar
Kirill Terekhov committed
840
841
				
				if( debug_output && rank == 0 )
Kirill Terekhov's avatar
Kirill Terekhov committed
842
843
844
845
846
847
848
849
850
				{
					std::cout << "initial" << std::endl;
					for(it = 1; it <= size; it++) std::cout << it << " " << vtxdist[it]-vtxdist[it-1] << std::endl;
					std::cout << " total " << vtxdist[size]-vtxdist[0] << std::endl;
					
					std::cout << "vtxdist";
					for(it = 0; it <= size; it++) std::cout << " " << vtxdist[it];
					std::cout << std::endl;
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
851
				
Kirill Terekhov's avatar
Kirill Terekhov committed
852
				std::vector<idx_t> vtxdistbase = vtxdist;
Kirill Terekhov's avatar
Kirill Terekhov committed
853
854
855
856
				for(it = size; it >= 1; it--)
				{
					if( vtxdist[it]-vtxdist[it-1] == 0 )
					{
Kirill Terekhov's avatar
Kirill Terekhov committed
857
						if( debug_output && rank == 0 ) std::cout << "bkw send data to " << it-1;
Kirill Terekhov's avatar
Kirill Terekhov committed
858
859
860
861
						fill[0] = it - 1; //to
						flag = 0;
						for(jt = it-1; jt >= 1; jt--)
						{
Kirill Terekhov's avatar
Kirill Terekhov committed
862
							if( vtxdist[jt]-vtxdist[jt-1] > 1 )
Kirill Terekhov's avatar
Kirill Terekhov committed
863
							{
Kirill Terekhov's avatar
Kirill Terekhov committed
864
								if( debug_output && rank == 0 ) std::cout << " from " << jt-1 << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
865
								fill[1] = jt - 1; //from
Kirill Terekhov's avatar
Kirill Terekhov committed
866
								fill[2] = vtxdist[jt]-1-vtxdistbase[rank]; //id
Kirill Terekhov's avatar
Kirill Terekhov committed
867
								send.insert(send.end(),fill,fill+3);
Kirill Terekhov's avatar
Kirill Terekhov committed
868
								for(kt = jt; kt < it; kt++) vtxdist[kt]--;
Kirill Terekhov's avatar
Kirill Terekhov committed
869
870
871
872
								flag = 1;
								break;
							}
						}
Kirill Terekhov's avatar
Kirill Terekhov committed
873
874
875
						
						if( !flag )
						{
Kirill Terekhov's avatar
Kirill Terekhov committed
876
							if(debug_output && rank == 0)std::cout << "no bkw data for " << fill[0] << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
877
878
							break;
						}
Kirill Terekhov's avatar
Kirill Terekhov committed
879
880
881
					}
				}
				
Kirill Terekhov's avatar
Kirill Terekhov committed
882
883
884
885
				for(it = 1; it <= size; it++)
				{
					if( vtxdist[it]-vtxdist[it-1] == 0 )
					{
Kirill Terekhov's avatar
Kirill Terekhov committed
886
						if( debug_output && rank == 0 ) std::cout << "fwd send data to " << it-1;
Kirill Terekhov's avatar
Kirill Terekhov committed
887
888
889
890
891
892
893
						fill[0] = it - 1; //to
						flag = 0;
						
						for(jt = it+1; jt <= size; jt++)
						{
							if( vtxdist[jt]-vtxdist[jt-1] > 1 )
							{
Kirill Terekhov's avatar
Kirill Terekhov committed
894
								if( debug_output && rank == 0 ) std::cout << " from " << jt-1 << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
895
896
897
898
899
900
901
902
903
904
905
906
								fill[1] = jt - 1; //from
								fill[2] = vtxdist[jt-1]-vtxdistbase[rank]; //id
								send.insert(send.end(),fill,fill+3);
								for(kt = it; kt < jt; kt++) vtxdist[kt]++;
								flag = 1;
								break;
							}
						}
						
						
						if( !flag )
						{
Kirill Terekhov's avatar
Kirill Terekhov committed
907
							if(debug_output && rank == 0)std::cout << "no fwd data for " << fill[0] << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
908
909
910
911
912
							break;
							//throw Impossible;
						}
					}
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
913
914
				
				if(debug_output &&  rank == 0 )
Kirill Terekhov's avatar
Kirill Terekhov committed
915
916
917
918
919
920
921
922
923
				{
					std::cout << "redistr" << std::endl;
					for(it = 1; it <= size; it++) std::cout << it << " " << vtxdist[it]-vtxdist[it-1] << std::endl;
					std::cout << " total " << vtxdist[size]-vtxdist[0] << std::endl;
					
					std::cout << "vtxdist";
					for(it = 0; it <= size; it++) std::cout << " " << vtxdist[it];
					std::cout << std::endl;
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
924
				
Kirill Terekhov's avatar
Kirill Terekhov committed
925
926
927
928
929
930
931
932
933
934
935
936
937
938
				REPORT_STR("redistribute graph:");
				REPORT_VAL("send_size",send.size()/3);
				
				
				for(unsigned int i = 0; i < send.size()/3; i++)
				{
					idx_t trans_adjncy_size;
					real_t trans_xyz[3];
					std::vector<idx_t> trans_adjncy;
					if( send[i*3+0] == send[i*3+1] ) throw Impossible;
					if( send[i*3+1] == static_cast<unsigned int>(rank) )
					{	
						{
							trans_adjncy_size = xadj[send[i*3+2]+1]-xadj[send[i*3+2]];
Kirill Terekhov's avatar
Kirill Terekhov committed
939
							int size = 0;
Kirill Terekhov's avatar
Kirill Terekhov committed
940
							for(jt = xadj[send[i*3+2]]; jt < xadj[send[i*3+2]+1]; jt++)
Kirill Terekhov's avatar
Kirill Terekhov committed
941
							{
Kirill Terekhov's avatar
Kirill Terekhov committed
942
								trans_adjncy.push_back(adjncy[jt]);
Kirill Terekhov's avatar
Kirill Terekhov committed
943
944
								size++;
							}
Kirill Terekhov's avatar
Kirill Terekhov committed
945
							trans_adjncy.push_back(part[send[i*3+2]]);
Kirill Terekhov's avatar
Kirill Terekhov committed
946
							//adjncy.erase(adjancy.begin()+xadj[send[i*3+2]],adjancy.begin()+xadj[send[i*3+2]+1]);
Kirill Terekhov's avatar
Kirill Terekhov committed
947
							if( have_adjwgt )
Kirill Terekhov's avatar
Kirill Terekhov committed
948
							{
Kirill Terekhov's avatar
Kirill Terekhov committed
949
								for(jt = xadj[send[i*3+2]]; jt < xadj[send[i*3+2]+1]; jt++)
Kirill Terekhov's avatar
Kirill Terekhov committed
950
								{
Kirill Terekhov's avatar
Kirill Terekhov committed
951
									trans_adjncy.push_back(adjwgt[jt]);
Kirill Terekhov's avatar
Kirill Terekhov committed
952
953
954
955
									size++;
								}
								//adjwgt.erase(adjwgt.begin()+xadj[send[i*3+2]],adjwgt.begin()+xadj[send[i*3+2]+1]);
							}
Kirill Terekhov's avatar
Kirill Terekhov committed
956
							
Kirill Terekhov's avatar
Kirill Terekhov committed
957
							if( have_vwgt )
Kirill Terekhov's avatar
Kirill Terekhov committed
958
							{
Kirill Terekhov's avatar
Kirill Terekhov committed
959
								trans_adjncy.push_back(vwgt[send[i*3+2]]);
Kirill Terekhov's avatar
Kirill Terekhov committed
960
961
962
								//vwgt.erase(vwgt.begin()+vwgt[send[i*3+2]]);
								size++;
							}
Kirill Terekhov's avatar
Kirill Terekhov committed
963
964
							//part.erase(part.begin()+send[i*3+2]);
							size++;
Kirill Terekhov's avatar
Kirill Terekhov committed
965
							REPORT_VAL("to",send[i*3+0]);
Kirill Terekhov's avatar
Kirill Terekhov committed
966
967
							REPORT_VAL("send_size",size);
							REPORT_MPI(result = MPI_Send(&trans_adjncy[0],size,IDX_T,send[i*3+0],2,m->GetCommunicator()));
Kirill Terekhov's avatar
Kirill Terekhov committed
968
969
970
971
972
973
974
							if( result != MPI_SUCCESS ) 
								throw Impossible;
						}
						if( pa == Partition )
						{
							for(jt = 0; jt < static_cast<int>(dim); jt++)
								trans_xyz[jt] = xyz[send[i*3+2]*dim+jt];
Kirill Terekhov's avatar
Kirill Terekhov committed
975
							//xyz.erase(send[i*3+2]*dim,(send[i*3+2]+1)*dim);
Kirill Terekhov's avatar
Kirill Terekhov committed
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
							REPORT_VAL("to",send[i*3+0]);
							REPORT_MPI(result = MPI_Send(trans_xyz,dim,REAL_T,send[i*3+0],3,m->GetCommunicator()));
							if( result != MPI_SUCCESS ) throw Impossible;
						}
					}
					else if( send[i*3+0] == static_cast<unsigned int>(rank) )
					{
						MPI_Status stat;
						int msgsize;
						
						{
							REPORT_VAL("from",send[i*3+1]);
							REPORT_MPI(result = MPI_Probe(send[i*3+1],2,m->GetCommunicator(),&stat));
							if( result != MPI_SUCCESS ) throw Impossible;
							result = MPI_Get_count(&stat,IDX_T,&msgsize);
							if( result != MPI_SUCCESS ) throw Impossible;
Kirill Terekhov's avatar
Kirill Terekhov committed
992
							trans_adjncy_size = (msgsize-have_vwgt-1)/(1+have_adjwgt);
Kirill Terekhov's avatar
Kirill Terekhov committed
993
							trans_adjncy.resize(msgsize);
Kirill Terekhov's avatar
Kirill Terekhov committed
994
							REPORT_VAL("size",trans_adjncy_size);
Kirill Terekhov's avatar
Kirill Terekhov committed
995
996
997
998
999
1000
1001
							REPORT_MPI(result = MPI_Recv(&trans_adjncy[0],msgsize,IDX_T,send[i*3+1],2,m->GetCommunicator(),&stat));
							if( result != MPI_SUCCESS ) throw Impossible;
							xadj.resize(2);
							xadj[0] = 0;
							xadj[1] = trans_adjncy_size;
							for(jt = 0; jt < trans_adjncy_size; jt++)
								adjncy.push_back(trans_adjncy[jt]);
Kirill Terekhov's avatar
Kirill Terekhov committed
1002
							part.push_back(trans_adjncy[trans_adjncy_size]);
Kirill Terekhov's avatar
Kirill Terekhov committed
1003
1004
							if( have_adjwgt )
								for(jt = 0; jt < trans_adjncy_size; jt++)
Kirill Terekhov's avatar
Kirill Terekhov committed
1005
									adjwgt.push_back(trans_adjncy[jt+trans_adjncy_size+1]);
Kirill Terekhov's avatar
Kirill Terekhov committed
1006
							if( have_vwgt )
Kirill Terekhov's avatar
Kirill Terekhov committed
1007
1008
								vwgt.push_back(trans_adjncy[trans_adjncy_size+1+(have_adjwgt?trans_adjncy_size:0)]);
							
Kirill Terekhov's avatar
Kirill Terekhov committed
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
						}
						if( pa == Partition )
						{
							REPORT_VAL("from",send[i*3+1]);
							REPORT_MPI(result = MPI_Recv(&trans_xyz,dim,REAL_T,send[i*3+1],3,m->GetCommunicator(),&stat));
							if( result != MPI_SUCCESS ) throw Impossible;
							xyz.resize(dim);
							for(jt = 0; jt < static_cast<int>(dim); jt++)
								xyz[jt] = trans_xyz[jt];
						}
					}
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
				//cleanup
				{
					std::vector<int> erase;
					for(unsigned int i = 0; i < send.size()/3; i++)
					{
						if( send[i*3+1] == static_cast<unsigned int>(rank) )
							erase.push_back(send[i*3+2]);
					}
					std::sort(erase.rbegin(),erase.rend());
					for(unsigned int i = 0; i < erase.size(); ++i)
					{
						int pos = erase[i];
						idx_t trans_adjncy_size = xadj[pos+1]-xadj[pos];
						adjncy.erase(adjncy.begin()+xadj[pos],adjncy.begin()+xadj[pos+1]);
						if( have_adjwgt )
							adjwgt.erase(adjwgt.begin()+xadj[pos],adjwgt.begin()+xadj[pos+1]);
						if( have_vwgt )
							vwgt.erase(vwgt.begin()+pos);
						if( pa == Repartition )
							part.erase(part.begin()+pos);
						if( pa == Partition )
							xyz.erase(xyz.begin()+pos*dim,xyz.begin()+(pos+1)*dim);
						
						for(it = pos+1; it < xadj.size(); ++it) xadj[it] -= trans_adjncy_size;
						xadj.erase(xadj.begin()+pos);
					}
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
1048
1049
				REPORT_STR("graph redistributed");
			}
1050
#endif //USE_PARTITIONER_PARMETIS
Kirill Terekhov's avatar
Kirill Terekhov committed
1051
			
Kirill Terekhov's avatar
Kirill Terekhov committed
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
			if( debug_output )
			{
				std::stringstream name;
				name << "after" << rank << ".txt";
				std::fstream f(name.str().c_str(),std::ios::out);
				//m->BeginSequentialCode();
				f << "on processor " << rank << std::endl;
				f << "vtxdist: " << std::endl;
				for(unsigned int i = 0; i < vtxdist.size(); i++)
				{
					f << vtxdist[i] << " ";
					if( (i+1)%30 == 0 ) f << std::endl;
				}
				f << std::endl;
				f << "local size: " << vtxdist[rank+1]-vtxdist[rank] << std::endl;
				
				{
					f << "xadj size " << xadj.size() << ":" << std::endl;
					for(unsigned int i = 0; i < xadj.size(); i++)
					{
						f << xadj[i] << " ";
						if( (i+1)%30 == 0 ) f << std::endl;
					}
					f << std::endl;
					f << "adjncy size " << adjncy.size() << ":" << std::endl;
					for(unsigned int i = 0; i < adjncy.size(); i++)
					{
						f << adjncy[i] << " ";
						if( (i+1)%30 == 0 ) f << std::endl;
					}
					f << std::endl;
					if( have_vwgt )
					{
						f << "vwgt: " << std::endl;
						for(unsigned int i = 0; i < vwgt.size(); i++)
						{
							f << vwgt[i] << " ";
							if( (i+1)%30 == 0 ) f << std::endl;
						}
						f << std::endl;
					}
					if( have_adjwgt )
					{
						f << "adjwgt: " << std::endl;
						for(unsigned int i = 0; i < adjwgt.size(); i++)
						{
							f << adjwgt[i] << " ";
							if( (i+1)%30 == 0 ) f << std::endl;
						}
						f << std::endl;
					}
					if( pa == Repartition )
					{
						f << "vsize: " << std::endl;
						for(unsigned int i = 0; i < vsize.size(); i++)
						{
							f << vsize[i] << " ";
							if( (i+1)%30 == 0 ) f << std::endl;
						}
						f << std::endl;
					}
Kirill Terekhov's avatar
Kirill Terekhov committed
1113
1114
1115
1116
1117
1118
1119
					f << "part size " << part.size() << ":" << std::endl;
					for(unsigned int i = 0; i < part.size(); i++)
					{
						f << part[i] << " ";
						if( (i+1)%30 == 0 ) f << std::endl;
					}
					f << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
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
					f << "wgtflag = " << wgtflag << std::endl;
					f << "numflag = " << numflag << std::endl;
				}
				if( pa == Partition )
				{
					f << "ndims = " << ndims << std::endl;
					f << "xyz: " << std::endl;
					for(unsigned int i = 0; i < xyz.size(); i++)
					{
						f << xyz[i] << " ";
						if( (i+1)%30 == 0 ) f << std::endl;
					}
					f << std::endl;
				}
				f << "ncon = " << ncon << std::endl;
				f << "nparts = " << nparts << std::endl;
				f << "tpwgts: " << std::endl;
				for(unsigned int i = 0; i < tpwgts.size(); i++)
				{
					f << tpwgts[i] << " ";
					if( (i+1)%30 == 0 ) f << std::endl;
				}
				f << std::endl;
				f << "ubvec: " << std::endl;
				for(unsigned int i = 0; i < ubvec.size(); i++)
				{
					f << ubvec[i] << " ";
					if( (i+1)%30 == 0 ) f << std::endl;
				}
				f << std::endl;
				f << "options: " << std::endl;
				for(unsigned int i = 0; i < options.size(); i++)
				{
					f << options[i] << " ";
					if( (i+1)%30 == 0 ) f << std::endl;
				}
				f << std::endl;
				//m->EndSequentialCode();
				f.close();
			}
			
Kirill Terekhov's avatar
Kirill Terekhov committed
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
			if( time_output )
			{
				time = Timer()-time;
				REPORT_STR("time to redistribute graph");
				REPORT_VAL("time",time);
			}
			
			REPORT_STR("BEGIN PARMETIS");
			
			if( time_output ) time = Timer();
			
			MPI_Comm comm = m->GetCommunicator();
			
Kirill Terekhov's avatar
Kirill Terekhov committed
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
			idx_t  * link_vtxdist = vtxdist.empty() ? NULL : &vtxdist[0];
			idx_t  * link_xadj    = xadj.empty()    ? NULL : &xadj[0];
			idx_t  * link_adjncy  = adjncy.empty()  ? NULL : &adjncy[0];
			idx_t  * link_vwgt    = vwgt.empty()    ? NULL : &vwgt[0];
			idx_t  * link_adjwgt  = adjwgt.empty()  ? NULL : &adjwgt[0];
			real_t * link_tpwgts  = tpwgts.empty()  ? NULL : &tpwgts[0];
			real_t * link_ubvec   = ubvec.empty()   ? NULL : &ubvec[0];
			idx_t  * link_options = options.empty() ? NULL : &options[0];
			idx_t  * link_part    = part.empty()    ? NULL : &part[0];
			real_t * link_xyz     = xyz.empty()     ? NULL : &xyz[0];
			idx_t  * link_vsize   = vsize.empty()   ? NULL : &vsize[0];
			
			REPORT_VAL("vtxdist",link_vtxdist);
			REPORT_VAL("xadj",link_xadj);
			REPORT_VAL("adjncy",link_adjncy);
			REPORT_VAL("vwgt",link_vwgt);
			REPORT_VAL("adjwgt",link_adjwgt);
			REPORT_VAL("tpwgts",link_tpwgts);
			REPORT_VAL("ubvec",link_ubvec);
			REPORT_VAL("options",link_options);
			REPORT_VAL("part",link_part);
			REPORT_VAL("xyz",link_xyz);
			REPORT_VAL("vsize",link_vsize);

1198
1199
#if defined(USE_PARTITIONER_PARMETIS)
			if( package == 2 )
Kirill Terekhov's avatar
Kirill Terekhov committed
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
				switch(pa)
				{
					 //case Partition:
					 //result = ParMETIS_V3_PartKway(&vtxdist[0],&xadj[0],&adjncy[0],&vwgt[0],&adjwgt[0],
						//						   &wgtflag,&numflag,&ncon,&nparts,&tpwgts[0],
						//						   &ubvec[0],&options[0],&edgecut,&part[0],&comm);
					 break;
					case Refine:
					REPORT_STR("run refine");
					result = ParMETIS_V3_RefineKway(link_vtxdist,link_xadj,link_adjncy,link_vwgt,link_adjwgt,
													&wgtflag,&numflag,&ncon,&nparts,link_tpwgts,
													link_ubvec,link_options,&edgecut,link_part,&comm);	
					break;
					case Partition:
					REPORT_STR("run partition");
					result = ParMETIS_V3_PartGeomKway(link_vtxdist,link_xadj,link_adjncy,link_vwgt,link_adjwgt,
													  &wgtflag,&numflag,&ndims,link_xyz,&ncon,&nparts,link_tpwgts,
													  link_ubvec,link_options,&edgecut,link_part,&comm);
					break;
					//~ case P_PartGeom:
					//~ result = ParMETIS_V3_PartGeom(&vtxdist[0],&ndims,&xyz[0],&part[0],&comm);
					//~ break;
					case Repartition:
					REPORT_STR("run repartition");
					result = ParMETIS_V3_AdaptiveRepart(link_vtxdist,link_xadj,link_adjncy,link_vwgt,link_vsize,
														link_adjwgt,&wgtflag,&numflag,&ncon,&nparts,link_tpwgts,
														link_ubvec,&itr,link_options,&edgecut,link_part,&comm);
					break;
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
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
#endif //USE_PARTITIONER_PARMETIS
#if defined(USE_PARTITIONER_METIS)
			if( package == 4 || package == 5  || package == 6 || package == 7)
			{
				if( m->GetProcessorRank() == 0 )
				{
					idx_t options[METIS_NOPTIONS];
					idx_t nvtxs = vtxdist[1] - vtxdist[0];
					METIS_SetDefaultOptions(options);
					options[METIS_OPTION_CONTIG] = package % 2;
					if( package == 4 || package == 5 )
					{
						result = METIS_PartGraphRecursive(&nvtxs, &ncon, link_xadj, 
														  link_adjncy, link_vwgt, link_vsize, link_adjwgt, 
														  &nparts, link_tpwgts, link_ubvec, options, 
														  &edgecut, link_part);
					}
					if( package == 6 || package == 7 )
					{
						result = METIS_PartGraphKway(&nvtxs, &ncon, link_xadj, 
													 link_adjncy, link_vwgt, link_vsize, link_adjwgt, 
													 &nparts, link_tpwgts, link_ubvec, options, 
													 &edgecut, link_part);
					}
				}
			}
#endif //USE_PARTITIONER_METIS
Kirill Terekhov's avatar
Kirill Terekhov committed
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
			
			
			
			if( time_output )
			{
				time = Timer()-time;
				REPORT_STR("time in parmetis");
				REPORT_VAL("time",time);
			}
			
			REPORT_STR("END PARMETIS");

			if( time_output ) time = Timer();

			//distribute computed parts back
1273
1274
#if defined(USE_PARTITIONER_PARMETIS)
			if( package == 2 )
Kirill Terekhov's avatar
Kirill Terekhov committed
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
			{
				REPORT_VAL("send_size",send.size()/3);
				for(unsigned int i = 0; i < send.size()/3; i++)
				{
					if( send[i*3+0] == static_cast<unsigned int>(rank) )
					{
						REPORT_VAL("send_part",part[0]);
						REPORT_MPI(result = MPI_Send(&part[0],1,IDX_T,send[i*3+1],4,m->GetCommunicator()));
						if( result != MPI_SUCCESS ) throw Impossible;
						part.clear();
					}
					else if( send[i*3+1] == static_cast<unsigned int>(rank) )
					{ 
						REPORT_MPI(result = MPI_Recv(&part[send[i*3+2]],1,IDX_T,send[i*3+0],4,m->GetCommunicator(),MPI_STATUS_IGNORE));
						REPORT_VAL("recv_part",part[send[i*3+2]]);
						REPORT_VAL("from",part[send[i*3+0]]);
						if( result != MPI_SUCCESS ) throw Impossible;
					}
				}
			}
1295
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
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

			if( time_output )
			{
				time = Timer()-time;
				REPORT_STR("redistribute graph back");
				REPORT_VAL("time",time);
			}
									 
			//debug
			if( debug_output )
			{
				m->BeginSequentialCode();
				std::cout << "distribution on " << rank << std::endl;
				for(unsigned int i = 0; i < part.size(); i++)
				{
					std::cout << part[i] << " ";
					if( (i+1)%30 == 0 ) std::cout << std::endl;
				}
				std::cout << std::endl;
				m->EndSequentialCode();
			}

			//assign entities to part sets
			{
				
				Tag redist = m->RedistributeTag();
				
				int k = 0;
				for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it) 
					if( it->GetStatus() != Element::Ghost ) 
						it->Integer(redist) = part[k++];
				
				
			}
#endif
1331
1332
1333
		}
		if( package == 3 ) //KMEANS
		{
Kirill Terekhov's avatar
Kirill Terekhov committed
1334
			
1335
			int total_points = 0;
Kirill Terekhov's avatar
Kirill Terekhov committed
1336
			int K = (int)m->GetProcessorsNumber(), rank = (int)m->GetProcessorRank(); //number of clusters
Kirill Terekhov's avatar
Kirill Terekhov committed
1337
			//std::cout << "Start K-means on " << m->GetProcessorRank() << " clusters " << K << std::endl;
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
			int max_iterations = 100;
#if defined(USE_OMP)
#pragma omp parallel for reduction(+:total_points)
#endif
			for(int q = 0; q < m->CellLastLocalID(); ++q) if( m->isValidCell(q) )
			{
				Cell n = m->CellByLocalID(q);
				if( n->GetStatus() != Element::Ghost ) total_points++;
			}
			std::vector< int > points_node(total_points);
			std::vector< double > points_center(total_points*3);
			std::vector< int > points_cluster(total_points,-1);
Kirill Terekhov's avatar
Kirill Terekhov committed
1350
1351
			std::vector< double > cluster_center(K*3,0.0);
			std::vector< int > cluster_npoints(K,0);
1352
			std::vector< double > cluster_weight(K,1/(double)K);
Kirill Terekhov's avatar
Kirill Terekhov committed
1353
1354
1355
1356
1357
			std::vector< double > cluster_shift(K*3,0);
#if defined(USE_MPI)
			std::vector< double > cluster_center_tmp(K*3);
			std::vector< int > cluster_npoints_tmp(K);
#endif
1358
1359
1360
1361
1362
1363
1364
			
			int k = 0;
			for(int q = 0; q < m->CellLastLocalID(); ++q) if( m->isValidCell(q) )
			{
				Cell n = m->CellByLocalID(q);
				if( n->GetStatus() != Element::Ghost ) points_node[k++] = n->LocalID();
			}
Kirill Terekhov's avatar
Kirill Terekhov committed
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
#if defined(USE_OMP)
#pragma omp parallel for			
#endif
			for(int q = 0; q < total_points; ++q)
			{
				Cell n = m->CellByLocalID(points_node[q]);
				double cnt[3];
				n->Centroid(cnt);
				points_center[q*3+0] = cnt[0];
				points_center[q*3+1] = cnt[1];
				points_center[q*3+2] = cnt[2];
				cluster_center[rank*3+0] += cnt[0];
				cluster_center[rank*3+1] += cnt[1];
				cluster_center[rank*3+2] += cnt[2];
			}
			
1381
			
Kirill Terekhov's avatar
Kirill Terekhov committed
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
			double pmax[3] = {-1.0e+100,-1.0e+100,-1.0e+100};
			double pmin[3] = {+1.0e+100,+1.0e+100,+1.0e+100};
			
#if defined(USE_OMP)
#pragma omp parallel
#endif
			{
				double pmaxl[3] = {-1.0e+100,-1.0e+100,-1.0e+100};
				double pminl[3] = {+1.0e+100,+1.0e+100,+1.0e+100};
#if defined(USE_OMP)
#pragma omp	for
#endif
				for(int q = 0; q < total_points; ++q)
				{
					Cell n = m->CellByLocalID(points_node[q]);
					if( pmaxl[0] < points_center[q*3+0] ) pmaxl[0] = std::max(pmaxl[0],points_center[q*3+0]);
					if( pmaxl[1] < points_center[q*3+1] ) pmaxl[1] = std::max(pmaxl[1],points_center[q*3+1]);
					if( pmaxl[2] < points_center[q*3+2] ) pmaxl[2] = std::max(pmaxl[2],points_center[q*3+2]);
					if( pminl[0] > points_center[q*3+0] ) pminl[0] = std::min(pminl[0],points_center[q*3+0]);
					if( pminl[1] > points_center[q*3+1] ) pminl[1] = std::min(pminl[1],points_center[q*3+1]);
					if( pminl[2] > points_center[q*3+2] ) pminl[2] = std::min(pminl[2],points_center[q*3+2]);
				}
1404
#if defined(USE_OMP)
Kirill Terekhov's avatar
Kirill Terekhov committed
1405
#pragma omp	critical
1406
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
				{
					if( pmax[0] < pmaxl[0] ) pmax[0] = std::max(pmax[0],pmaxl[0]);
					if( pmax[1] < pmaxl[1] ) pmax[1] = std::max(pmax[1],pmaxl[1]);
					if( pmax[2] < pmaxl[2] ) pmax[2] = std::max(pmax[2],pmaxl[2]);
					if( pmin[0] > pminl[0] ) pmin[0] = std::min(pmin[0],pminl[0]);
					if( pmin[1] > pminl[1] ) pmin[1] = std::min(pmin[1],pminl[1]);
					if( pmin[2] > pminl[2] ) pmin[2] = std::min(pmin[2],pminl[2]);
				}
			}
			m->AggregateMax(pmax,3);
			m->AggregateMin(pmin,3);
			
			double mesh_dist = (pmax[0]-pmin[0])*(pmax[0]-pmin[0]) + (pmax[1]-pmin[1])*(pmax[1]-pmin[1]) + (pmax[2]-pmin[2])*(pmax[2]-pmin[2]);
			mesh_dist /= (double)K*3.0;
1421
			
Kirill Terekhov's avatar
Kirill Terekhov committed
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
			//mesh_dist *= 10;
			/*
			if( m->GetProcessorRank() == 0)
			{
				std::cout << "mesh dist " << mesh_dist;
				std::cout << " " << pmin[0] << ":" << pmax[0];
				std::cout << " " << pmin[1] << ":" << pmax[1];
				std::cout << " " << pmin[2] << ":" << pmax[2];
				std::cout << " K " << K << std::endl;
			}
			*/
1433
1434
1435
1436
1437
1438
1439
1440
1441
#if defined(USE_MPI)
			cluster_npoints[rank] = total_points;
			MPI_Allreduce(&cluster_center[0],&cluster_center_tmp[0],K*3,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
			MPI_Allreduce(&cluster_npoints[0],&cluster_npoints_tmp[0],K,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
			cluster_center.swap(cluster_center_tmp);
			cluster_npoints.swap(cluster_npoints_tmp);
#endif
			
			for(int i = 0; i < K; ++i)
1442
			{
1443
1444
1445
				cluster_center[i*3+0] /= (double) cluster_npoints[i];
				cluster_center[i*3+1] /= (double) cluster_npoints[i];
				cluster_center[i*3+2] /= (double) cluster_npoints[i];
1446
1447
			}
			
1448
			int total_global_points = total_points;
1449
1450
1451
1452
#if defined(USE_MPI)
			std::vector<int> displs(m->GetProcessorsNumber());
			std::vector<int> counts(m->GetProcessorsNumber());
			std::vector<int> npoints(m->GetProcessorsNumber());
1453
			total_global_points = 0;
1454
1455
1456
1457
1458
1459
1460
1461
			int total_local_points = 0;
			bool balance = false;
			MPI_Allgather(&total_points,1,MPI_INT,&npoints[0],1,MPI_INT,MPI_COMM_WORLD);
			double imbalance = 1;
			for(int k = 0; k < (int) m->GetProcessorsNumber(); ++k)
			{
				for(int l = k+1; l < (int) m->GetProcessorsNumber(); ++l)
				{
1462
1463
					imbalance = std::max(imbalance,(npoints[k]+1.0e-15)/(npoints[l]+1.0e-15));
					imbalance = std::max(imbalance,(npoints[l]+1.0e-15)/(npoints[k]+1.0e-15));
1464
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
1465
				total_global_points += npoints[k];
1466
1467
1468
1469
1470
1471
1472
			}
			//if( m->GetProcessorRank() == 0 )
			//	std::cout << "Imbalance is " << imbalance << std::endl;
			if( imbalance > 1.2 )
				balance = true;
			if( balance )//redistribute points
			{
1473
				total_local_points = (int)floor((double)total_global_points/(double)m->GetProcessorsNumber());
1474
				//std::cout << total_global_points << " " << total_local_points << " " << m->GetProcessorRank() << " " <<  total_global_points - (m->GetProcessorsNumber()-1)*total_local_points << std::endl;
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
				
				std::vector<double> points_center_global(m->GetProcessorRank() == 0 ? total_global_points*3 : 1);
				displs[0] = 0;
				counts[0] = npoints[0]*3;
				for(int k = 1; k < (int) m->GetProcessorsNumber(); ++k)
				{
					displs[k] = displs[k-1] + counts[k-1];
					counts[k] = npoints[k]*3;
				}
				MPI_Gatherv(&points_center[0],total_points*3,MPI_DOUBLE,&points_center_global[0],&counts[0],&displs[0],MPI_DOUBLE,0,MPI_COMM_WORLD);
				displs[0] = 0;
				counts[0] = total_local_points*3;
				for(int k = 1; k < (int) m->GetProcessorsNumber(); ++k)
				{
					displs[k] = displs[k-1] + counts[k-1];
					counts[k] = total_local_points*3;
				}
				counts.back() = total_global_points*3 - displs.back();
				total_points = counts[m->GetProcessorRank()]/3;
				points_center.resize(total_points*3);
				MPI_Scatterv(&points_center_global[0],&counts[0],&displs[0],MPI_DOUBLE,&points_center[0],total_points*3,MPI_DOUBLE,0,MPI_COMM_WORLD);
				points_cluster.resize(total_points,-1);
			}
#endif
			
			
			
			
Kirill Terekhov's avatar
Kirill Terekhov committed
1503
1504
			//if( m->GetProcessorRank() == 0 )
			//	std::cout << "Global number of points " << total_global_points << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
1505
			//std::cout << " local points on " << m->GetProcessorRank() << " is " << total_points << std::endl;
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
			
			//if( m->GetProcessorRank() == 0 )
			//	std::cout << "Init clusters" << std::endl;
			
			// choose K distinct values for the centers of the clusters
			{
				int Kpart = (int)ceil((double)K/(double)m->GetProcessorsNumber());
				int Kstart = Kpart * m->GetProcessorRank();
				int Kend = Kstart + Kpart;
				if( Kend > K ) Kend = K;
1516
				srand(0);
Kirill Terekhov's avatar
Kirill Terekhov committed
1517
				for(int i = Kstart; i < Kend; i++) if( cluster_npoints[i] == 0 )
1518
				{
1519
					if( total_points )
1520
					{
1521
						while(true)
1522
						{
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
							int index_point = rand() % total_points;
							if(points_cluster[index_point]==-1)
							{
								cluster_center[i*3+0] = points_center[index_point*3+0];
								cluster_center[i*3+1] = points_center[index_point*3+1];
								cluster_center[i*3+2] = points_center[index_point*3+2];
								cluster_npoints[i]++;
								points_cluster[index_point] = i;
								break;
							}
1533
1534
						}
					}
1535
1536
1537