incident_matrix.hpp 39.5 KB
Newer Older
Kirill Terekhov's avatar
Kirill Terekhov committed
1 2 3 4
#include "inmost.h"
#include <stack>
#if defined(USE_MESH)

5 6
//#define NEW_ALGORITHM
//#define RECORD_PATH
Kirill Terekhov's avatar
Kirill Terekhov committed
7
//#define DEEP_RECURSE
Kirill Terekhov's avatar
Kirill Terekhov committed
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
//TODO:
// incident_matrix class should measure for minimal volume,
// possibly check and update from projects/OctreeCutcell/octgrid.cpp

namespace INMOST
{

	__INLINE void make_vec(const Storage::real p1[3], const Storage::real p2[3], Storage::real out[3])
	{
		out[0] = p1[0] - p2[0];
		out[1] = p1[1] - p2[1];
		out[2] = p1[2] - p2[2];
	}

	__INLINE void cross_prod(const Storage::real v1[3],const Storage::real v2[3], Storage::real out[3])
	{
		out[0] = v1[1]*v2[2] - v1[2]*v2[1];
		out[1] = v1[2]*v2[0] - v1[0]*v2[2];
		out[2] = v1[0]*v2[1] - v1[1]*v2[0];
	}

	__INLINE Storage::real __det3d(Storage::real a, Storage::real b, Storage::real c,
	                             Storage::real d, Storage::real e, Storage::real f,
	                             Storage::real g, Storage::real h, Storage::real i ) 
	{
		return a*e*i - c*e*g + b*f*g - a*f*h + c*d*h - b*d*i;
	}
	
	__INLINE Storage::real __det3v(const Storage::real * x,const Storage::real * y,const Storage::real * z) 
	{
		return __det3d(x[0], x[1], x[2],  y[0], y[1], y[2],  z[0], z[1], z[2]);
	}

	__INLINE Storage::real dot_prod(const Storage::real v1[3],const Storage::real v2[3])
	{
		return v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2];
	}
	
	typedef struct orient_face_t
	{
		Edge bridge;
		Node first;
		Face face;
		orient_face_t(Edge _bridge, Node _first, Face _face)
		:bridge(_bridge),first(_first),face(_face)
		{
		}
	} orient_face;
	
Kirill Terekhov's avatar
Kirill Terekhov committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
	class AbstractCoords
	{
	public:
		virtual Storage::real_array Get(const Node & s) const = 0;
		virtual AbstractCoords * Copy() const = 0;
		virtual ~AbstractCoords() {}
	};
	
	class GridCoords : public AbstractCoords
	{
	public:
		Storage::real_array Get(const Node & s) const
		{
			return s.Coords();
		}
		AbstractCoords * Copy() const {return new GridCoords(*this);}
	};
	
	class TagCoords : public AbstractCoords
	{
		Tag t;
	public:
		TagCoords(Tag _t) : t(_t) {}
		TagCoords & operator =(TagCoords const & b) {t = b.t; return *this;}
		TagCoords(const TagCoords & b) : t(b.t) {}
		Storage::real_array Get(const Node & s) const
		{
			return s.RealArray(t);
		}
		AbstractCoords * Copy() const {return new TagCoords(*this);}
	};
	
89
#if !defined(NEW_ALGORITHM)
Kirill Terekhov's avatar
Kirill Terekhov committed
90 91 92 93 94 95
	template<class T>
	class incident_matrix
	{
		Mesh * mesh;
		dynarray< unsigned char, 4096 > matrix;
		dynarray< char ,256 > visits;
Kirill Terekhov's avatar
Kirill Terekhov committed
96
		dynarray< char ,256 > visits0;
Kirill Terekhov's avatar
Kirill Terekhov committed
97 98 99 100 101 102 103 104 105
		dynarray<HandleType, 256> head_column;
		dynarray<HandleType, 256> head_row;
		dynarray<unsigned char ,256> head_row_count;
		dynarray<unsigned, 256> insert_order;
		bool exit_recurse;
		ElementArray<T> min_loop, temp_loop; //used as return
		dynarray< char , 256 > hide_column;
		dynarray< char , 256 > hide_row;
		dynarray< char , 256 > stub_row;
106
#if defined(RECORD_PATH)
107
		std::vector< std::pair<std::vector<int>,double> > remember;
108
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
109
		double min_loop_measure;
Kirill Terekhov's avatar
Kirill Terekhov committed
110
		bool print;
Kirill Terekhov's avatar
Kirill Terekhov committed
111
		AbstractCoords * coords;
Kirill Terekhov's avatar
Kirill Terekhov committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
		
		bool do_hide_row(unsigned k)
		{
			if( hide_column[k] == 0 )
			{
				hide_column[k] = 1;
				for(unsigned i = 0; i < head_row_count.size(); i++)
					if( matrix[k*head_row_count.size()+i] == 1 )
					{
						head_row_count[i] -= 1;
						if( head_row_count[i] == 0 )
						{
							hide_row[i] = 1;
							stub_row[i] = 0;
						}
					}
				insert_order.pop_back();
			}
			return true;
		}
		
		bool do_show_row(unsigned k)
		{
			if( hide_column[k] == 1 )
			{
				hide_column[k] = 0;
				
				bool success = true;
				for(unsigned i = 0; i < head_row_count.size(); i++)
					if( matrix[k*head_row_count.size()+i] == 1 )
					{
						head_row_count[i] += 1;
						if( head_row_count[i] > 0 ) hide_row[i] = 0;
						if( head_row_count[i] > 2 ) success = false;
					}
147 148 149 150 151 152 153 154 155
				if( print )
				{
					std::cout << (success? "ok":"fail") << std::endl;
					std::cout << "row count:";
					for(unsigned i = 0; i < head_row_count.size(); i++)
						std::cout << " " << (int)head_row_count[i];
					std::cout << std::endl;
					//std::cout << " success? " << (success?"yes":"no") << std::endl;
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
				insert_order.push_back(k);
				if( !success ) do_hide_row(k);
				return success;
				
			} else return true;
		}
		bool test_success()
		{
			bool success = true;
			for(unsigned j = 0; j < head_row_count.size(); j++)
			{
				if( head_row_count[j] == 1 )
				{
					success = false;
					break;
				}
			}
			return success;
		}
		Storage::real compute_measure(ElementArray<T> & data)
		{
			Storage::real measure = 0;
			if( data[0]->GetElementDimension() == 1 ) //this is edge //use geometric dimension here for 2d compatibility
			{
				//calculate area
Kirill Terekhov's avatar
Kirill Terekhov committed
181
				//int mdim = data[0]->GetMeshLink()->GetDimensions();
Kirill Terekhov's avatar
Kirill Terekhov committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
				ElementArray<Node> nodes,n1,n2;
				n1 = data[0]->getNodes();
				n2 = data[1]->getNodes();
				if( n1[0] == n2[0] || n1[0] == n2[1])
				{
					nodes.push_back(n1[1]);
					nodes.push_back(n1[0]);
				}
				else
				{
					nodes.push_back(n1[0]);
					nodes.push_back(n1[1]);
				}
				for(typename ElementArray<T>::size_type j = 1; j < data.size(); j++)
				{
					n1 = data[j]->getNodes();
198
					assert((nodes.back() == n1[0] || nodes.back() == n1[1]));
Kirill Terekhov's avatar
Kirill Terekhov committed
199 200 201 202 203 204 205
					if( nodes.back() == n1[0] )
						nodes.push_back(n1[1]);
					else
						nodes.push_back(n1[0]);
				}
				
				Storage::real x[3] = {0,0,0};
Kirill Terekhov's avatar
Kirill Terekhov committed
206 207
				Storage::real_array x0 = coords->Get(nodes[0]);
				for(unsigned i = 1; i < nodes.size()-1; i++)
Kirill Terekhov's avatar
Kirill Terekhov committed
208
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
209 210 211
					Storage::real_array v1 = coords->Get(nodes[i]);
					Storage::real_array v2 = coords->Get(nodes[i+1]);
					if( v1.size() == 3 && v2.size() == 3 )
Kirill Terekhov's avatar
Kirill Terekhov committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
					{
						x[0] += (v1[1]-x0[1])*(v2[2]-x0[2]) - (v1[2]-x0[2])*(v2[1]-x0[1]);
						x[1] += (v1[2]-x0[2])*(v2[0]-x0[0]) - (v1[0]-x0[0])*(v2[2]-x0[2]);
					}
					x[2] += (v1[0]-x0[0])*(v2[1]-x0[1]) - (v1[1]-x0[1])*(v2[0]-x0[0]);
				}
				measure = sqrt(x[0]*x[0]+x[1]*x[1]+x[2]*x[2])*0.5;
				
			}
			else //this is 3d face
			{
				//firstly, have to figure out orientation of each face
				//mark all faces, so that we can perform adjacency retrival
				MarkerType mrk = mesh->CreatePrivateMarker();
				MarkerType rev = mesh->CreatePrivateMarker(); //reverse orientation
Kirill Terekhov's avatar
Kirill Terekhov committed
227 228
				for(int k = 1; k < data.size(); ++k)
					data[k]->SetPrivateMarker(mrk); //0-th face orientation is default
Kirill Terekhov's avatar
Kirill Terekhov committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
				Node n1,n2; //to retrive edge
				bool reverse = false; //reverse orientation in considered face
				std::deque< orient_face > stack; //edge and first node and face for visiting
				//todo: can do faster by retriving edges and going over their nodes
				//should not use FindSharedAdjacency
				ElementArray<Edge> edges = data[0]->getEdges();
				do
				{
					//figure out starting node order
					if( edges[0]->getBeg() == edges[1]->getBeg() ||
					    edges[0]->getBeg() == edges[1]->getEnd() )
					{
						n1 = edges[0]->getEnd();
						n2 = edges[0]->getBeg();
					}
					else
					{
						n1 = edges[0]->getBeg();
						n2 = edges[0]->getEnd();
					}
					//schedule unvisited adjacent faces
					for(typename ElementArray<Edge>::size_type j = 0; j < edges.size(); j++)
					{
						//schedule face adjacent to considered edge
						ElementArray<Face> adjacent = edges[j]->getFaces(mrk);
						assert(adjacent.size() <= 1);
						if( !adjacent.empty() && adjacent[0].GetPrivateMarker(mrk))
						{
							adjacent.RemPrivateMarker(mrk);
							stack.push_back(orient_face(edges[j],reverse ? n2 : n1,adjacent[0]));
						}
						//update edge nodes
						n1 = n2; //current end is new begin
						//find new end
Kirill Terekhov's avatar
Kirill Terekhov committed
263 264
						if( n2 == edges[(j+1)%edges.size()]->getBeg() )
							n2 = edges[(j+1)%edges.size()]->getEnd();
Kirill Terekhov's avatar
Kirill Terekhov committed
265
						else
Kirill Terekhov's avatar
Kirill Terekhov committed
266
							n2 = edges[(j+1)%edges.size()]->getBeg();
Kirill Terekhov's avatar
Kirill Terekhov committed
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
					}
					if( stack.empty() ) break;
					//get entry from stack
					orient_face r = stack.front();
					//remove face from stack
					stack.pop_front();
					//retrive edges for new face
					edges = r.face->getEdges();
					reverse = false;
					//figure out starting node order
					if( edges[0]->getBeg() == edges[1]->getBeg() ||
					    edges[0]->getBeg() == edges[1]->getEnd() )
					{
						n1 = edges[0]->getEnd();
						n2 = edges[0]->getBeg();
					}
					else
					{
						n1 = edges[0]->getBeg();
						n2 = edges[0]->getEnd();
					}
					//find out common edge orientation
					for(typename ElementArray<Node>::size_type j = 0; j < edges.size(); j++)
					{
						if( edges[j] == r.bridge ) //found the edge
						{
							//reverse ordering on this face
							if( r.first == n1 )
							{
								r.face->SetPrivateMarker(rev);
								reverse = true;
							}
							break;
						}
						//update edge nodes
						n1 = n2; //current end is new begin
						//find new end
Kirill Terekhov's avatar
Kirill Terekhov committed
304 305
						if( n2 == edges[(j+1)%edges.size()]->getBeg() )
							n2 = edges[(j+1)%edges.size()]->getEnd();
Kirill Terekhov's avatar
Kirill Terekhov committed
306
						else
Kirill Terekhov's avatar
Kirill Terekhov committed
307
							n2 = edges[(j+1)%edges.size()]->getBeg();
Kirill Terekhov's avatar
Kirill Terekhov committed
308 309 310
					}
				} while(true);
				data.RemPrivateMarker(mrk);
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
				Storage::real fnrm[3], fcnt[3], ccnt[3] = {0,0,0}, nnodes = 0;
				Storage::real_array x0,a,b;
				//find cell centroid
				for(typename ElementArray<T>::size_type j = 0; j < data.size(); j++)
				{
					ElementArray<Node> nodes = data[j]->getAsFace()->getNodes(mrk,true);
					nodes.SetPrivateMarker(mrk);
					for(ElementArray<Node>::iterator qt = nodes.begin(); qt != nodes.end(); ++qt)
					{
						x0 = coords->Get(qt->self());
						ccnt[0] += x0[0];
						ccnt[1] += x0[1];
						ccnt[2] += x0[2];
						nnodes += 1;
					}
				}
				ccnt[0] /= nnodes;
				ccnt[1] /= nnodes;
				ccnt[2] /= nnodes;
Kirill Terekhov's avatar
Kirill Terekhov committed
330 331
				for(typename ElementArray<T>::size_type j = 0; j < data.size(); j++)
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
332 333
					//compute normal to face
					ElementArray<Node> nodes = data[j]->getAsFace()->getNodes();
334 335 336 337 338 339
					nodes.RemPrivateMarker(mrk);
					fnrm[0] = fnrm[1] = fnrm[2] = 0;
					fcnt[0] = fcnt[1] = fcnt[2] = 0;
					nnodes = 0;
					x0 = coords->Get(nodes[0]);
					a = x0;
Kirill Terekhov's avatar
Kirill Terekhov committed
340 341
					for(unsigned i = 0; i < nodes.size(); i++)
					{
342 343 344 345 346 347 348 349 350 351 352 353
						b = coords->Get(nodes[(i+1)%nodes.size()]);
						fnrm[0] += (a[1]-x0[1])*(b[2]-x0[2]) - (a[2]-x0[2])*(b[1]-x0[1]);
						fnrm[1] += (a[2]-x0[2])*(b[0]-x0[0]) - (a[0]-x0[0])*(b[2]-x0[2]);
						fnrm[2] += (a[0]-x0[0])*(b[1]-x0[1]) - (a[1]-x0[1])*(b[0]-x0[0]);
						
						fcnt[0] += a[0];
						fcnt[1] += a[1];
						fcnt[2] += a[2];
						
						a.swap(b);
						
						nnodes += 1;
Kirill Terekhov's avatar
Kirill Terekhov committed
354
					}
355 356 357 358 359 360 361 362 363
					fnrm[0] *= 0.5;
					fnrm[1] *= 0.5;
					fnrm[2] *= 0.5;
					fcnt[0] /= nnodes;
					fcnt[1] /= nnodes;
					fcnt[2] /= nnodes;
					for(int r = 0; r < 3; ++r)
						fcnt[r] = fcnt[r]-ccnt[r];
					measure += (data[j]->GetPrivateMarker(rev) ? -1.0 : 1.0)*dot_prod(fcnt,fnrm);
Kirill Terekhov's avatar
Kirill Terekhov committed
364
				}
365
				mesh->ReleasePrivateMarker(mrk);
Kirill Terekhov's avatar
Kirill Terekhov committed
366 367
				data.RemPrivateMarker(rev);
				mesh->ReleasePrivateMarker(rev);
Kirill Terekhov's avatar
Kirill Terekhov committed
368
				measure /= 3.0;
Kirill Terekhov's avatar
Kirill Terekhov committed
369 370 371 372 373 374
				measure = fabs(measure);
			}
			return measure;
		}
		void recursive_find(unsigned node, unsigned length)
		{
375 376 377
#if !defined(DEEP_RECURSE)
			if( !min_loop.empty() && length > min_loop.size() ) return;
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
378
			bool success = false;
379 380 381 382 383 384 385 386
			
			if( print )
			{
				std::cout << "current loop:";
				for(unsigned j = 0; j < insert_order.size(); j++)
					std::cout << " " << ElementTypeName(GetHandleElementType(head_column[insert_order[j]])) << ":" << GetHandleID(head_column[insert_order[j]]);
				std::cout << " try add " << ElementTypeName(GetHandleElementType(head_column[node])) << ":" << GetHandleID(head_column[node]) << " (" <<(int)hide_column[node] << ") ";
			}
Kirill Terekhov's avatar
Kirill Terekhov committed
387 388
			if( do_show_row(node) )
			{
389
				//if( print ) std::cout << "ok" << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
390 391 392 393
				success = test_success();
				
				if( success )
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
394
					//if( min_loop.empty() || min_loop.size() >= length )
Kirill Terekhov's avatar
Kirill Terekhov committed
395 396 397 398 399 400
					{
						
						
						temp_loop.resize(length);
						for(unsigned j = 0; j < insert_order.size(); j++)
							temp_loop.at(j) = head_column[insert_order[j]];
Kirill Terekhov's avatar
Kirill Terekhov committed
401 402
						Storage::real measure = compute_measure(temp_loop);
						
Kirill Terekhov's avatar
Kirill Terekhov committed
403 404 405 406
						if( print )
						{
							std::cout << "found loop [" << temp_loop.size() <<"]: ";
							for(unsigned j = 0; j < temp_loop.size(); ++j)
407
								std::cout << ElementTypeName(GetHandleElementType(head_column[insert_order[j]])) << ":" << GetHandleID(head_column[insert_order[j]]) << " ";
Kirill Terekhov's avatar
Kirill Terekhov committed
408 409 410 411
							std::cout << "measure " << measure << std::endl;
						}
						
						if( min_loop.empty() || min_loop_measure + 1.0e-6 >= measure )
Kirill Terekhov's avatar
Kirill Terekhov committed
412
						{
Kirill Terekhov's avatar
Kirill Terekhov committed
413 414 415 416 417 418
							if( !(fabs(min_loop_measure-measure) < 1.0e-6 && min_loop.size() < temp_loop.size()) )
							{
								min_loop.swap(temp_loop);
								min_loop_measure = measure;
								if( print ) std::cout << "selected as current loop" << std::endl;
							}
Kirill Terekhov's avatar
Kirill Terekhov committed
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
							//~ if( min_loop.size() == head_column.size() ) // all elements were visited
							//~ {
							//~ unsigned num = 0;
							//~ for(unsigned j = 0; j < head_row.size(); j++) //check that all bridge elements were visited - we don't have any other loop then
							//~ num += hide_row[j];
							//~ if( num == head_row.size() ) exit_recurse = true; //exit recursive loop
							//~ }
						}
					}
				}
				else
				{
					bool stub = false;
					for(dynarray<unsigned char,256>::size_type j = 0; j < head_row_count.size() && !exit_recurse; j++) //first try follow the order
					{
						if( stub_row[j] == 0 && matrix[node*head_row_count.size()+j] == 1 && head_row_count[j] == 1 )
						{
							for(dynarray<HandleType,256>::size_type q = 0; q < head_column.size() && !exit_recurse; q++)
							{
								if( visits[q] > 0 && matrix[q*head_row_count.size()+j] == 1 && hide_column[q] == 1 )
								{
									recursive_find(static_cast<unsigned>(q),length+1);
								}
							}
							if( head_row_count[j] == 1 )
							{
								stub_row[j] = 1;
								stub = true;
								break; //this is a stub path
							}
						}
					}
					
					if( !stub ) for(dynarray<unsigned char,256>::size_type j = 0; j < head_row_count.size() && !exit_recurse; j++)
					{
						if( stub_row[j] == 0 && matrix[node*head_row_count.size()+j] == 0 && head_row_count[j] == 1 )
						{
							for(dynarray<HandleType,256>::size_type q = 0; q < head_column.size() && !exit_recurse; q++)
							{
								if( visits[q] > 0 && matrix[q*head_row_count.size()+j] == 1 && hide_column[q] == 1 )
								{
									recursive_find(static_cast<unsigned>(q),length+1);
								}
							}
							if( head_row_count[j] == 1 )
							{
								stub_row[j] = 1;
								stub = true;
								break; //this is a stub path
							}
						}
					}
					
				}
				do_hide_row(node);
			}
475
			//else if( print ) std::cout << "fail" << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
			if( length == 1 )
			{
				for(dynarray<HandleType,256>::size_type j = 0; j < head_row.size(); j++)
					stub_row[j] = 0;
			}
		}
	public:
		bool all_visited()
		{
			for(dynarray<char,256>::size_type k = 0; k < visits.size(); k++)
				if( visits[k] != 0 ) return false;
			return true;
		}
		void print_matrix()
		{
			Storage::real cnt[3];
			for(dynarray<HandleType,256>::size_type k = 0; k < head_column.size(); k++)
			{
				for(dynarray<HandleType,256>::size_type j = 0; j < head_row.size(); j++)
					std::cout << static_cast<int>(matrix[k*head_row.size()+ j]);
Kirill Terekhov's avatar
Kirill Terekhov committed
496
				std::cout << " " << (int)visits[k] << " " << (int)visits0[k];
Kirill Terekhov's avatar
Kirill Terekhov committed
497 498
				Element(mesh,head_column[k])->Centroid(cnt);
				std::cout << " " << cnt[0] << " " << cnt[1] << " " << cnt[2];
499 500
				std::cout << " " << ElementTypeName(GetHandleElementType(head_column[k]));
				std::cout << ":" << GetHandleID(head_column[k]);
Kirill Terekhov's avatar
Kirill Terekhov committed
501 502
				std::cout << std::endl;
			}
503
#if defined(RECORD_PATH)
Kirill Terekhov's avatar
Kirill Terekhov committed
504 505 506 507 508
			std::cout << "loops [" << remember.size() << "]:" << std::endl;
			for(size_t k = 0; k < remember.size(); ++k)
			{
				std::cout << k << " size " << remember[k].first.size() << ": ";
				for(size_t l = 0; l < remember[k].first.size()-1; ++l)
509 510
					std::cout << ElementTypeName(GetHandleElementType(head_column[remember[k].first[l]])) << ":" << GetHandleID(head_column[remember[k].first[l]]) << ", ";
				std::cout << ElementTypeName(GetHandleElementType(head_column[remember[k].first.back()])) << ":" << GetHandleID(head_column[remember[k].first.back()]) << " measure " << remember[k].second << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
511
			}
512
#endif
513
			
Kirill Terekhov's avatar
Kirill Terekhov committed
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
			if( GetHandleElementType(head_column[0]) == EDGE )
			{
				std::cout << "edges [" << head_column.size() << "]" << std::endl;
				for(int k = 0; k < (int)head_column.size(); ++k)
				{
					Edge e(mesh,head_column[k]);
					std::cout << "(" << e->getBeg()->Coords()[0] << "," << e->getBeg()->Coords()[1] << "," << e->getBeg()->Coords()[2] << ") <-> (" << e->getEnd()->Coords()[0] << "," << e->getEnd()->Coords()[1] << "," << e->getEnd()->Coords()[2] << ")" << std::endl;
				}
				std::cout << "edges [" << head_column.size() << "]" << std::endl;
				for(int k = 0; k < (int)head_column.size(); ++k)
				{
					Edge e(mesh,head_column[k]);
					std::cout << e->getBeg()->GetHandle() << " <-> " << e->getEnd()->GetHandle() << std::endl;
				}
			}
Kirill Terekhov's avatar
Kirill Terekhov committed
529 530
		}
		template<typename InputIterator>
Kirill Terekhov's avatar
Kirill Terekhov committed
531 532
		incident_matrix(Mesh * mesh, InputIterator beg, InputIterator end, typename ElementArray<T>::size_type num_inner, const AbstractCoords & _coords = GridCoords(), bool print = false)
		: mesh(mesh), head_column(beg,end), min_loop(), print(print), coords(_coords.Copy())
Kirill Terekhov's avatar
Kirill Terekhov committed
533 534 535 536 537 538
		{
			min_loop.SetMeshLink(mesh);
			temp_loop.SetMeshLink(mesh);
			//isInputForwardIterators<T,InputIterator>();
			if( !head_column.empty() )
			{
539
				MarkerType hide_marker = mesh->CreatePrivateMarker();
Kirill Terekhov's avatar
Kirill Terekhov committed
540 541
				
				visits.resize(head_column.size());
Kirill Terekhov's avatar
Kirill Terekhov committed
542
				visits0.resize(head_column.size());
543 544 545 546 547 548 549 550 551
				/*
				for(typename dynarray<HandleType, 256>::size_type it = 0; it < head_column.size(); ++it)
				{
					Element::adj_type const & sub = mesh->LowConn(head_column[it]);
					for(Element::adj_type::size_type jt = 0; jt < sub.size(); ++jt)
						if( mesh->GetPrivateMarker(sub[jt],hide_marker) )
							printf("element %s:%d already have marker %d\n",ElementTypeName(GetHandleElementType(sub[jt])),GetHandleID(sub[jt]),hide_marker);
				}
				 */
Kirill Terekhov's avatar
Kirill Terekhov committed
552 553 554
				for(typename dynarray<HandleType, 256>::size_type it = 0; it < head_column.size(); ++it)
				{
					visits[it] = it < num_inner ? 2 : 1;
Kirill Terekhov's avatar
Kirill Terekhov committed
555
					visits0[it] = visits[it];
Kirill Terekhov's avatar
Kirill Terekhov committed
556 557 558
					Element::adj_type const & sub = mesh->LowConn(head_column[it]);
					for(Element::adj_type::size_type jt = 0; jt < sub.size(); ++jt)
					{
559
						if( !mesh->GetPrivateMarker(sub[jt],hide_marker) )
Kirill Terekhov's avatar
Kirill Terekhov committed
560 561
						{
							head_row.push_back(sub[jt]);
562
							mesh->SetPrivateMarker(sub[jt],hide_marker);
Kirill Terekhov's avatar
Kirill Terekhov committed
563 564 565 566 567 568
						}
					}
				}
				tiny_map<HandleType,int,256> mat_num;
				for(dynarray<HandleType,256>::size_type it = 0; it < head_row.size(); ++it)
				{
569
					mesh->RemPrivateMarker(head_row[it],hide_marker);
Kirill Terekhov's avatar
Kirill Terekhov committed
570 571 572
					mat_num[head_row[it]] = static_cast<int>(it);
				}
				
573
				mesh->ReleasePrivateMarker(hide_marker);
Kirill Terekhov's avatar
Kirill Terekhov committed
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
				
				matrix.resize(head_row.size()*head_column.size(),0);
				
				
				
				for(typename dynarray<HandleType,256>::size_type it = 0; it < head_column.size(); ++it)
				{
					Element::adj_type const & sub = mesh->LowConn(head_column[it]);
					for(Element::adj_type::size_type jt = 0; jt < sub.size(); ++jt)
					{
						matrix[(it)*head_row.size()+mat_num[sub[jt]]] = 1;
					}
				}
				head_row_count.resize(head_row.size(),0);
				stub_row.resize(head_row.size(),0);
				hide_row.resize(head_row.size(),1);
				hide_column.resize(head_column.size(),1);
			}
		}
		incident_matrix(const incident_matrix & other)
		: mesh(other.mesh), matrix(other.matrix), head_column(other.head_column), head_row(other.head_row),
		head_row_count(other.head_row_count), min_loop(other.min_loop),
		hide_row(other.hide_row), hide_column(other.hide_column),
Kirill Terekhov's avatar
Kirill Terekhov committed
597
		stub_row(other.stub_row), coords(other.coords->Copy())
Kirill Terekhov's avatar
Kirill Terekhov committed
598 599 600 601 602 603 604 605 606 607 608 609 610
		{
		}
		incident_matrix & operator =(const incident_matrix & other)
		{
			mesh = other.mesh;
			matrix = other.matrix;
			head_column = other.head_column;
			head_row = other.head_row;
			head_row_count = other.head_row_count;
			min_loop = other.min_loop;
			hide_row = other.hide_row;
			hide_column = other.hide_column;
			stub_row = other.stub_row;
Kirill Terekhov's avatar
Kirill Terekhov committed
611
			coords = other.coords->Copy();
Kirill Terekhov's avatar
Kirill Terekhov committed
612 613 614 615
			return *this;
		}
		~incident_matrix()
		{
Kirill Terekhov's avatar
Kirill Terekhov committed
616
			delete coords;
Kirill Terekhov's avatar
Kirill Terekhov committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
		}
		bool find_shortest_loop(ElementArray<T> & ret)
		{
			ret.clear();
			exit_recurse = false;
			unsigned first = UINT_MAX;
			do
			{
				first = UINT_MAX;
				for(unsigned q = 0; q < head_column.size(); q++)
					if( visits[q] == 1 )
					{
						first = q;
						break;
					}
				if( first != UINT_MAX )
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
634
					min_loop_measure = 1.0e+20;
Kirill Terekhov's avatar
Kirill Terekhov committed
635 636
					recursive_find(first,1);
					if( min_loop.empty() )
Kirill Terekhov's avatar
Kirill Terekhov committed
637 638
					{
						if( print ) std::cout << "abandon " << first << std::endl;
639
#if defined(RECORD_PATH)
640
						remember.push_back(std::make_pair(std::vector<int>(1,first),-1.0));
641
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
642
						visits[first]--; //don't start again from this element
Kirill Terekhov's avatar
Kirill Terekhov committed
643
					}
Kirill Terekhov's avatar
Kirill Terekhov committed
644 645 646
				}
			} while( min_loop.empty() && first != UINT_MAX );
			
Kirill Terekhov's avatar
Kirill Terekhov committed
647 648

			
Kirill Terekhov's avatar
Kirill Terekhov committed
649 650 651 652 653
			ret.insert(ret.end(),min_loop.begin(),min_loop.end());
			min_loop.clear();
			
			if( !ret.empty() )
			{
654
#if defined(RECORD_PATH)
655 656
				std::vector<int> add_remember;
				add_remember.reserve(min_loop.size());
657
#endif
658 659
				MarkerType hide_marker = mesh->CreatePrivateMarker();
				for(typename ElementArray<T>::size_type k = 0; k < ret.size(); k++) mesh->SetPrivateMarker(ret.at(k),hide_marker);
Kirill Terekhov's avatar
Kirill Terekhov committed
660
				if( print ) std::cout << "return loop [" << ret.size() << "]:";
Kirill Terekhov's avatar
Kirill Terekhov committed
661
				for(dynarray<HandleType,256>::size_type k = 0; k < head_column.size(); k++)
662
					if( mesh->GetPrivateMarker(head_column[k],hide_marker) )
Kirill Terekhov's avatar
Kirill Terekhov committed
663 664
					{
						visits[k]--;
665
#if defined(RECORD_PATH)
666
						add_remember.push_back((int)k);
667
#endif
668
						if( print ) std::cout << ElementTypeName(GetHandleElementType(head_column[k])) << ":" << GetHandleID(head_column[k]) << " ";
Kirill Terekhov's avatar
Kirill Terekhov committed
669 670
					}
				if( print ) std::cout << std::endl;
671 672
				for(typename ElementArray<T>::size_type k = 0; k < ret.size(); k++) mesh->RemPrivateMarker(ret.at(k),hide_marker);
				mesh->ReleasePrivateMarker(hide_marker);
673
#if defined(RECORD_PATH)
674
				remember.push_back(std::make_pair(add_remember,min_loop_measure));
675
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
676 677 678 679 680 681 682 683
				return true;
			}
			return false;
		}
		
		Element get_element(unsigned k) {return Element(mesh,head_column[k]);}
		void set_visit(unsigned k, char vis ) { visits[k] = vis; }
	};
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982

#else // NEW_ALGORITHM
	template<class T>
	class incident_matrix
	{
		Mesh * mesh;
		dynarray< unsigned char, 4096 > matrix;
		dynarray< char ,256 > visits;
		dynarray< char ,256 > visits0;
		dynarray<HandleType, 256> head_column;
		dynarray<HandleType, 256> head_row;
		dynarray<unsigned char ,256> head_row_count;
		dynarray<unsigned, 256> insert_order;
		bool exit_recurse;
		ElementArray<T> min_loop, temp_loop; //used as return
		dynarray< char , 256 > hide_column;
		dynarray< char , 256 > hide_row;
		dynarray< char , 256 > stub_row;
#if defined(RECORD_PATH)
		std::vector< std::pair<std::vector<int>,double> > remember;
#endif
		double min_loop_measure;
		bool print;
		AbstractCoords * coords;
		
		bool do_hide_row(unsigned k)
		{
			if( hide_column[k] == 0 )
			{
				hide_column[k] = 1;
				for(unsigned i = 0; i < head_row_count.size(); i++)
					if( matrix[k*head_row_count.size()+i] == 1 )
					{
						head_row_count[i] -= 1;
						if( head_row_count[i] == 0 )
						{
							hide_row[i] = 1;
							stub_row[i] = 0;
						}
					}
				insert_order.pop_back();
			}
			return true;
		}
		
		bool do_show_row(unsigned k)
		{
			if( hide_column[k] == 1 )
			{
				hide_column[k] = 0;
				
				bool success = true;
				for(unsigned i = 0; i < head_row_count.size(); i++)
					if( matrix[k*head_row_count.size()+i] == 1 )
					{
						head_row_count[i] += 1;
						if( head_row_count[i] > 0 ) hide_row[i] = 0;
						if( head_row_count[i] > 2 ) success = false;
					}
				insert_order.push_back(k);
				if( !success ) do_hide_row(k);
				return success;
				
			} else return true;
		}
		bool test_success()
		{
			bool success = true;
			for(unsigned j = 0; j < head_row_count.size(); j++)
			{
				if( head_row_count[j] == 1 )
				{
					success = false;
					break;
				}
			}
			return success;
		}
		Storage::real compute_measure(ElementArray<T> & data)
		{
			Storage::real measure = 0;
			if( data[0]->GetElementDimension() == 1 ) //this is edge //use geometric dimension here for 2d compatibility
			{
				//calculate area
				//int mdim = data[0]->GetMeshLink()->GetDimensions();
				ElementArray<Node> nodes,n1,n2;
				n1 = data[0]->getNodes();
				n2 = data[1]->getNodes();
				if( n1[0] == n2[0] || n1[0] == n2[1])
				{
					nodes.push_back(n1[1]);
					nodes.push_back(n1[0]);
				}
				else
				{
					nodes.push_back(n1[0]);
					nodes.push_back(n1[1]);
				}
				for(typename ElementArray<T>::size_type j = 1; j < data.size(); j++)
				{
					n1 = data[j]->getNodes();
					assert((nodes.back() == n1[0] || nodes.back() == n1[1]));
					if( nodes.back() == n1[0] )
						nodes.push_back(n1[1]);
					else
						nodes.push_back(n1[0]);
				}
				
				Storage::real x[3] = {0,0,0};
				Storage::real_array x0 = coords->Get(nodes[0]);
				for(unsigned i = 1; i < nodes.size()-1; i++)
				{
					Storage::real_array v1 = coords->Get(nodes[i]);
					Storage::real_array v2 = coords->Get(nodes[i+1]);
					if( v1.size() == 3 && v2.size() == 3 )
					{
						x[0] += (v1[1]-x0[1])*(v2[2]-x0[2]) - (v1[2]-x0[2])*(v2[1]-x0[1]);
						x[1] += (v1[2]-x0[2])*(v2[0]-x0[0]) - (v1[0]-x0[0])*(v2[2]-x0[2]);
					}
					x[2] += (v1[0]-x0[0])*(v2[1]-x0[1]) - (v1[1]-x0[1])*(v2[0]-x0[0]);
				}
				measure = sqrt(x[0]*x[0]+x[1]*x[1]+x[2]*x[2])*0.5;
				
			}
			else //this is 3d face
			{
				//firstly, have to figure out orientation of each face
				//mark all faces, so that we can perform adjacency retrival
				MarkerType mrk = mesh->CreatePrivateMarker();
				MarkerType rev = mesh->CreatePrivateMarker(); //reverse orientation
				for(int k = 1; k < data.size(); ++k)
					data[k]->SetPrivateMarker(mrk); //0-th face orientation is default
				Node n1,n2; //to retrive edge
				bool reverse = false; //reverse orientation in considered face
				std::deque< orient_face > stack; //edge and first node and face for visiting
				//todo: can do faster by retriving edges and going over their nodes
				//should not use FindSharedAdjacency
				ElementArray<Edge> edges = data[0]->getEdges();
				do
				{
					//figure out starting node order
					if( edges[0]->getBeg() == edges[1]->getBeg() ||
					   edges[0]->getBeg() == edges[1]->getEnd() )
					{
						n1 = edges[0]->getEnd();
						n2 = edges[0]->getBeg();
					}
					else
					{
						n1 = edges[0]->getBeg();
						n2 = edges[0]->getEnd();
					}
					//schedule unvisited adjacent faces
					for(typename ElementArray<Edge>::size_type j = 0; j < edges.size(); j++)
					{
						//schedule face adjacent to considered edge
						ElementArray<Face> adjacent = edges[j]->getFaces(mrk);
						assert(adjacent.size() <= 1);
						if( !adjacent.empty() && adjacent[0].GetPrivateMarker(mrk))
						{
							adjacent.RemPrivateMarker(mrk);
							stack.push_back(orient_face(edges[j],reverse ? n2 : n1,adjacent[0]));
						}
						//update edge nodes
						n1 = n2; //current end is new begin
						//find new end
						if( n2 == edges[(j+1)%edges.size()]->getBeg() )
							n2 = edges[(j+1)%edges.size()]->getEnd();
						else
							n2 = edges[(j+1)%edges.size()]->getBeg();
					}
					if( stack.empty() ) break;
					//get entry from stack
					orient_face r = stack.front();
					//remove face from stack
					stack.pop_front();
					//retrive edges for new face
					edges = r.face->getEdges();
					reverse = false;
					//figure out starting node order
					if( edges[0]->getBeg() == edges[1]->getBeg() ||
					   edges[0]->getBeg() == edges[1]->getEnd() )
					{
						n1 = edges[0]->getEnd();
						n2 = edges[0]->getBeg();
					}
					else
					{
						n1 = edges[0]->getBeg();
						n2 = edges[0]->getEnd();
					}
					//find out common edge orientation
					for(typename ElementArray<Node>::size_type j = 0; j < edges.size(); j++)
					{
						if( edges[j] == r.bridge ) //found the edge
						{
							//reverse ordering on this face
							if( r.first == n1 )
							{
								r.face->SetPrivateMarker(rev);
								reverse = true;
							}
							break;
						}
						//update edge nodes
						n1 = n2; //current end is new begin
						//find new end
						if( n2 == edges[(j+1)%edges.size()]->getBeg() )
							n2 = edges[(j+1)%edges.size()]->getEnd();
						else
							n2 = edges[(j+1)%edges.size()]->getBeg();
					}
				} while(true);
				data.RemPrivateMarker(mrk);
				Storage::real fnrm[3], fcnt[3], ccnt[3] = {0,0,0}, nnodes = 0;
				Storage::real_array x0,a,b;
				//find cell centroid
				for(typename ElementArray<T>::size_type j = 0; j < data.size(); j++)
				{
					ElementArray<Node> nodes = data[j]->getAsFace()->getNodes(mrk,true);
					nodes.SetPrivateMarker(mrk);
					for(ElementArray<Node>::iterator qt = nodes.begin(); qt != nodes.end(); ++qt)
					{
						x0 = coords->Get(qt->self());
						ccnt[0] += x0[0];
						ccnt[1] += x0[1];
						ccnt[2] += x0[2];
						nnodes += 1;
					}
				}
				ccnt[0] /= nnodes;
				ccnt[1] /= nnodes;
				ccnt[2] /= nnodes;
				for(typename ElementArray<T>::size_type j = 0; j < data.size(); j++)
				{
					//compute normal to face
					ElementArray<Node> nodes = data[j]->getAsFace()->getNodes();
					nodes.RemPrivateMarker(mrk);
					fnrm[0] = fnrm[1] = fnrm[2] = 0;
					fcnt[0] = fcnt[1] = fcnt[2] = 0;
					nnodes = 0;
					x0 = coords->Get(nodes[0]);
					a = x0;
					for(unsigned i = 0; i < nodes.size(); i++)
					{
						b = coords->Get(nodes[(i+1)%nodes.size()]);
						fnrm[0] += (a[1]-x0[1])*(b[2]-x0[2]) - (a[2]-x0[2])*(b[1]-x0[1]);
						fnrm[1] += (a[2]-x0[2])*(b[0]-x0[0]) - (a[0]-x0[0])*(b[2]-x0[2]);
						fnrm[2] += (a[0]-x0[0])*(b[1]-x0[1]) - (a[1]-x0[1])*(b[0]-x0[0]);
						
						fcnt[0] += a[0];
						fcnt[1] += a[1];
						fcnt[2] += a[2];
						
						a.swap(b);
						
						nnodes += 1;
					}
					fnrm[0] *= 0.5;
					fnrm[1] *= 0.5;
					fnrm[2] *= 0.5;
					fcnt[0] /= nnodes;
					fcnt[1] /= nnodes;
					fcnt[2] /= nnodes;
					for(int r = 0; r < 3; ++r)
						fcnt[r] = fcnt[r]-ccnt[r];
					measure += (data[j]->GetPrivateMarker(rev) ? -1.0 : 1.0)*dot_prod(fcnt,fnrm);
				}
				mesh->ReleasePrivateMarker(mrk);
				data.RemPrivateMarker(rev);
				mesh->ReleasePrivateMarker(rev);
				measure /= 3.0;
				measure = fabs(measure);
			}
			return measure;
		}
		void recursive_find(unsigned node, unsigned length)
		{
			if( !min_loop.empty() && length > min_loop.size() ) return;
			bool success = false;
			if( do_show_row(node) )
			{
				success = test_success();
				
				if( success )
				{
					//if( min_loop.empty() || min_loop.size() >= length )
					{
						
						
						temp_loop.resize(length);
						for(unsigned j = 0; j < insert_order.size(); j++)
							temp_loop.at(j) = head_column[insert_order[j]];
						Storage::real measure = compute_measure(temp_loop);
						
						if( print )
						{
							std::cout << "found loop [" << temp_loop.size() <<"]: ";
							for(unsigned j = 0; j < temp_loop.size(); ++j)
983
								std::cout << ElementTypeName(GetHandleElementType(head_column[insert_order[j]])) << ":" << GetHandleID(head_column[insert_order[j]]) << " ";
984 985 986 987 988 989 990 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 1036 1037 1038 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 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 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 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
							std::cout << "measure " << measure << std::endl;
						}
						
						if( min_loop.empty() || min_loop_measure + 1.0e-6 >= measure )
						{
							if( !(fabs(min_loop_measure-measure) < 1.0e-6 && min_loop.size() < temp_loop.size()) )
							{
								min_loop.swap(temp_loop);
								min_loop_measure = measure;
								if( print ) std::cout << "selected as current loop" << std::endl;
							}
							//~ if( min_loop.size() == head_column.size() ) // all elements were visited
							//~ {
							//~ unsigned num = 0;
							//~ for(unsigned j = 0; j < head_row.size(); j++) //check that all bridge elements were visited - we don't have any other loop then
							//~ num += hide_row[j];
							//~ if( num == head_row.size() ) exit_recurse = true; //exit recursive loop
							//~ }
						}
					}
				}
				else
				{
					bool stub = false;
					for(dynarray<unsigned char,256>::size_type j = 0; j < head_row_count.size() && !exit_recurse; j++) //first try follow the order
					{
						if( stub_row[j] == 0 && matrix[node*head_row_count.size()+j] == 1 && head_row_count[j] == 1 )
						{
							for(dynarray<HandleType,256>::size_type q = 0; q < head_column.size() && !exit_recurse; q++)
							{
								if( visits[q] > 0 && matrix[q*head_row_count.size()+j] == 1 && hide_column[q] == 1 )
								{
									recursive_find(static_cast<unsigned>(q),length+1);
								}
							}
							if( head_row_count[j] == 1 )
							{
								stub_row[j] = 1;
								stub = true;
								break; //this is a stub path
							}
						}
					}
					
					if( !stub ) for(dynarray<unsigned char,256>::size_type j = 0; j < head_row_count.size() && !exit_recurse; j++)
					{
						if( stub_row[j] == 0 && matrix[node*head_row_count.size()+j] == 0 && head_row_count[j] == 1 )
						{
							for(dynarray<HandleType,256>::size_type q = 0; q < head_column.size() && !exit_recurse; q++)
							{
								if( visits[q] > 0 && matrix[q*head_row_count.size()+j] == 1 && hide_column[q] == 1 )
								{
									recursive_find(static_cast<unsigned>(q),length+1);
								}
							}
							if( head_row_count[j] == 1 )
							{
								stub_row[j] = 1;
								stub = true;
								break; //this is a stub path
							}
						}
					}
					
				}
				do_hide_row(node);
			}
			if( length == 1 )
			{
				for(dynarray<HandleType,256>::size_type j = 0; j < head_row.size(); j++)
					stub_row[j] = 0;
			}
		}
	public:
		bool all_visited()
		{
			for(dynarray<char,256>::size_type k = 0; k < visits.size(); k++)
				if( visits[k] != 0 ) return false;
			return true;
		}
		void print_matrix()
		{
			Storage::real cnt[3];
			for(dynarray<HandleType,256>::size_type k = 0; k < head_column.size(); k++)
			{
				for(dynarray<HandleType,256>::size_type j = 0; j < head_row.size(); j++)
					std::cout << static_cast<int>(matrix[k*head_row.size()+ j]);
				std::cout << " " << (int)visits[k] << " " << (int)visits0[k];
				Element(mesh,head_column[k])->Centroid(cnt);
				std::cout << " " << cnt[0] << " " << cnt[1] << " " << cnt[2];
				std::cout << std::endl;
			}
#if defined(RECORD_PATH)
			std::cout << "loops [" << remember.size() << "]:" << std::endl;
			for(size_t k = 0; k < remember.size(); ++k)
			{
				std::cout << k << " size " << remember[k].first.size() << ": ";
				for(size_t l = 0; l < remember[k].first.size()-1; ++l)
					std::cout << remember[k].first[l] << ", ";
				std::cout << remember[k].first.back() << " measure " << remember[k].second << std::endl;
			}
#endif
			
			if( GetHandleElementType(head_column[0]) == EDGE )
			{
				std::cout << "edges [" << head_column.size() << "]" << std::endl;
				for(int k = 0; k < (int)head_column.size(); ++k)
				{
					Edge e(mesh,head_column[k]);
					std::cout << "(" << e->getBeg()->Coords()[0] << "," << e->getBeg()->Coords()[1] << "," << e->getBeg()->Coords()[2] << ") <-> (" << e->getEnd()->Coords()[0] << "," << e->getEnd()->Coords()[1] << "," << e->getEnd()->Coords()[2] << ")" << std::endl;
				}
				std::cout << "edges [" << head_column.size() << "]" << std::endl;
				for(int k = 0; k < (int)head_column.size(); ++k)
				{
					Edge e(mesh,head_column[k]);
					std::cout << e->getBeg()->GetHandle() << " <-> " << e->getEnd()->GetHandle() << std::endl;
				}
			}
		}
		void MapData(const dynarray<HandleType,256> & set)
		{
			
		}
		template<typename InputIterator>
		incident_matrix(Mesh * mesh, InputIterator beg, InputIterator end, typename ElementArray<T>::size_type num_inner, const AbstractCoords & _coords = GridCoords(), bool print = false)
		: mesh(mesh), head_column(beg,end), min_loop(), print(print), coords(_coords.Copy())
		{
			min_loop.SetMeshLink(mesh);
			temp_loop.SetMeshLink(mesh);
			//isInputForwardIterators<T,InputIterator>();
			if( !head_column.empty() )
			{
				MarkerType hide_marker = mesh->CreatePrivateMarker();
				
				visits.resize(head_column.size());
				visits0.resize(head_column.size());
				/*
				 for(typename dynarray<HandleType, 256>::size_type it = 0; it < head_column.size(); ++it)
				 {
					Element::adj_type const & sub = mesh->LowConn(head_column[it]);
					for(Element::adj_type::size_type jt = 0; jt < sub.size(); ++jt)
				 if( mesh->GetPrivateMarker(sub[jt],hide_marker) )
				 printf("element %s:%d already have marker %d\n",ElementTypeName(GetHandleElementType(sub[jt])),GetHandleID(sub[jt]),hide_marker);
				 }
				 */
				for(typename dynarray<HandleType, 256>::size_type it = 0; it < head_column.size(); ++it)
				{
					visits[it] = it < num_inner ? 2 : 1;
					visits0[it] = visits[it];
					Element::adj_type const & sub = mesh->LowConn(head_column[it]);
					for(Element::adj_type::size_type jt = 0; jt < sub.size(); ++jt)
					{
						if( !mesh->GetPrivateMarker(sub[jt],hide_marker) )
						{
							head_row.push_back(sub[jt]);
							mesh->SetPrivateMarker(sub[jt],hide_marker);
						}
					}
				}
				tiny_map<HandleType,int,256> mat_num;
				for(dynarray<HandleType,256>::size_type it = 0; it < head_row.size(); ++it)
				{
					mesh->RemPrivateMarker(head_row[it],hide_marker);
					mat_num[head_row[it]] = static_cast<int>(it);
				}
				
				mesh->ReleasePrivateMarker(hide_marker);
				
				matrix.resize(head_row.size()*head_column.size(),0);
				
				
				
				for(typename dynarray<HandleType,256>::size_type it = 0; it < head_column.size(); ++it)
				{
					Element::adj_type const & sub = mesh->LowConn(head_column[it]);
					for(Element::adj_type::size_type jt = 0; jt < sub.size(); ++jt)
					{
						matrix[(it)*head_row.size()+mat_num[sub[jt]]] = 1;
					}
				}
				head_row_count.resize(head_row.size(),0);
				stub_row.resize(head_row.size(),0);
				hide_row.resize(head_row.size(),1);
				hide_column.resize(head_column.size(),1);
			}
		}
		incident_matrix(const incident_matrix & other)
		: mesh(other.mesh), matrix(other.matrix), head_column(other.head_column), head_row(other.head_row),
		head_row_count(other.head_row_count), min_loop(other.min_loop),
		hide_row(other.hide_row), hide_column(other.hide_column),
		stub_row(other.stub_row), coords(other.coords.Copy())
		{
		}
		incident_matrix & operator =(const incident_matrix & other)
		{
			mesh = other.mesh;
			matrix = other.matrix;
			head_column = other.head_column;
			head_row = other.head_row;
			head_row_count = other.head_row_count;
			min_loop = other.min_loop;
			hide_row = other.hide_row;
			hide_column = other.hide_column;
			stub_row = other.stub_row;
			coords = other.coords.Copy();
			return *this;
		}
		~incident_matrix()
		{
			delete coords;
		}
		bool find_shortest_loop(ElementArray<T> & ret)
		{
			ret.clear();
			exit_recurse = false;
			unsigned first = UINT_MAX;
			do
			{
				first = UINT_MAX;
				for(unsigned q = 0; q < head_column.size(); q++)
					if( visits[q] == 1 )
					{
						first = q;
						break;
					}
				if( first != UINT_MAX )
				{
					min_loop_measure = 1.0e+20;
					recursive_find(first,1);
					if( min_loop.empty() )
					{
						if( print ) std::cout << "abandon " << first << std::endl;
#if defined(RECORD_PATH)
						remember.push_back(std::make_pair(std::vector<int>(1,first),-1.0));
#endif
						visits[first]--; //don't start again from this element
					}
				}
			} while( min_loop.empty() && first != UINT_MAX );
			
			
			
			ret.insert(ret.end(),min_loop.begin(),min_loop.end());
			min_loop.clear();
			
			if( !ret.empty() )
			{
#if defined(RECORD_PATH)
				std::vector<int> add_remember;
				add_remember.reserve(min_loop.size());
#endif
				MarkerType hide_marker = mesh->CreatePrivateMarker();
				for(typename ElementArray<T>::size_type k = 0; k < ret.size(); k++) mesh->SetPrivateMarker(ret.at(k),hide_marker);
				if( print ) std::cout << "return loop [" << ret.size() << "]:";
				for(dynarray<HandleType,256>::size_type k = 0; k < head_column.size(); k++)
					if( mesh->GetPrivateMarker(head_column[k],hide_marker) )
					{
						visits[k]--;
#if defined(RECORD_PATH)
						add_remember.push_back((int)k);
#endif
						if( print ) std::cout << k << " ";
					}
				if( print ) std::cout << std::endl;
				for(typename ElementArray<T>::size_type k = 0; k < ret.size(); k++) mesh->RemPrivateMarker(ret.at(k),hide_marker);
				mesh->ReleasePrivateMarker(hide_marker);
#if defined(RECORD_PATH)
				remember.push_back(std::make_pair(add_remember,min_loop_measure));
#endif
				return true;
			}
			return false;
		}
		
		Element get_element(unsigned k) {return Element(mesh,head_column[k]);}
		void set_visit(unsigned k, char vis ) { visits[k] = vis; }
	};
	
	
#endif //NEW_ALGORITHM
Kirill Terekhov's avatar
Kirill Terekhov committed
1264 1265 1266 1267 1268 1269
}




#endif