-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathudgcd.hpp
2434 lines (2131 loc) · 69.4 KB
/
udgcd.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
263
264
265
266
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Sebastien Kramm 2016-2020
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/**
\file udgcd.hpp
\brief UnDirected Graph Cycle Detection. Finds all the cycles inside an undirected graph.
Home page: https://github.com/skramm/udgcd
Inspired from http://www.boost.org/doc/libs/1_58_0/libs/graph/example/undirected_dfs.cpp
\todo Check memory usage with `$ valgrind --tool=massif`
See file README.md
*/
#ifndef HG_UDGCD_HPP
#define HG_UDGCD_HPP
#include <vector>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/undirected_dfs.hpp>
#include <boost/dynamic_bitset.hpp> // needed ! Allows bitwise operations on dynamic size boolean vectors
#include <boost/graph/graphviz.hpp>
/// TEMP
#include <boost/graph/graph_utility.hpp>
#ifdef UDGCD_USE_M4RI
#include "wrapper_m4ri.hpp"
#endif
#ifdef UDGCD_LOG_FUNC
#define PRINT_FUNCTION std::cout << "*** start function " << __FUNCTION__ << "()\n"
#define PRINT_FUNCTION_2 if(1) std::cout << "*** start function " << __FUNCTION__ << "()"
#else
#define PRINT_FUNCTION
#define PRINT_FUNCTION_2 if(0) std::cout
#endif
#ifdef UDGCD_DEV_MODE
#include <iostream>
#define UDGCD_COUT if(1) std::cout << std::setw(4) << __LINE__ << ": "
#define UDGCD_PRINT_STEPS
#define UDGCD_ASSERT_2(a,b,c) if(!(a)) std::cout << "ASSERT FAILURE, line " << __LINE__ << ", b=" << b << " c=" << c << '\n'
// #define PRINT_DIFF( step, v_after, v_before ) std::cout << step << ": REMOVAL OF " << v_before.size() - v_after.size() << " cycles\n"
#else
#define UDGCD_COUT if(0) std::cout
#define UDGCD_ASSERT_2(a,b,c) assert(a)
// #define PRINT_DIFF(a,b,c) ;
#endif
/// All the library code is in this namespace
namespace udgcd {
//-------------------------------------------------------------------------------------------
template<typename T>
void
printVector( std::ostream& f, const std::vector<T>& vec, const char* msg=nullptr )
{
f << "#=" << vec.size() << ": ";
if( msg )
f << "(" << msg << ") ";
for( const auto& elem : vec )
f << elem << "-";
f << "\n";
}
/// Additional helper function, can be used to print the cycles found
template<typename T>
void
printPaths( std::ostream& f, const std::vector<std::vector<T>>& v_paths, const char* msg=0 )
{
static int iter=0;
f << "Paths (" << iter++ << "): nb=" << v_paths.size();
if( msg )
f << ": " << msg;
f << "\n";
for( size_t i=0; i<v_paths.size(); i++ )
{
f << " - " << i << ": ";
printVector( f, v_paths[i] );
}
}
//-------------------------------------------------------------------------------------------
/// holds private types and functions, unneeded to use this library
namespace priv {
//-------------------------------------------------------------------------------------------
/// Print vector of bits
template<typename T>
void
printBitVector( std::ostream& f, const T& vec )
{
for( size_t i=0; i<vec.size(); i++ )
{
f << vec[i];
if( !((i+1)%4) && i != vec.size()-1 )
f << '.';
}
f << ": #=" << vec.count() << "\n"; // works with boost::dynamic_bitset << "\n";
}
template<typename T>
void
printBitMatrix( std::ostream& f, const T& mat, std::string msg )
{
f << "Matrix " << msg << ", nbLines=" << mat.size() << " nbCols=" << mat[0].size() << "\n";
for( auto line: mat )
{
f << " | ";
for( size_t i=0; i<line.size(); i++ )
{
f << line[i];
if( !((i+1)%4) && i != line.size()-1 )
f << '.';
}
f << " |\n";
}
}
/// Holds a path as a binary vector
/**
Based on https://www.boost.org/doc/libs/release/libs/dynamic_bitset/dynamic_bitset.html
For a graph of \f$n\f$ vertices, its size needs to be \f$ n.(n-1)/2 \f$
Example: for the path 1-3-4 on a graph of 5 vertices (0 - 4), the vector will have a size of 10 elements:
\verbatim
edge: 0 0 0 0 1 1 1 2 2 3
1 2 3 4 2 3 4 3 4 4
--------------------------------------
vector: 0 0 0 0 0 1 1 0 0 1
\endverbatim
Each edge part of the path has a '1' at the corresponding potential edge. In this case, edges 1-3, 1-4 and 3-4.
*/
typedef boost::dynamic_bitset<> BinaryVec;
//-------------------------------------------------------------------------------------------
struct BinaryMatInfo
{
size_t nbLines = 0;
size_t nbCols = 0;
size_t nbOnes = 0;
size_t nb0Cols = 0; ///< nb of columns with only 0 values
size_t nb0Lines = 0; ///< nb of lines with only 0 values
void print( std::ostream& f ) const
{
f << "BinaryMatInfo:"
<< "\n-nbLines =" << nbLines
<< "\n-nbCols =" << nbCols
<< "\n-nbOnes =" << nbOnes
// << "\n-nb0Lines =" << nb0Lines
<< "\n-nb0Cols =" << nb0Cols
<< '\n';
}
};
//-------------------------------------------------------------------------------------------
/// Holds two vertices
template <typename vertex_t>
struct VertexPair
{
vertex_t v1,v2;
VertexPair() {}
VertexPair( vertex_t va, vertex_t vb ): v1(va), v2(vb)
{
if( v2<v1 )
std::swap( v1, v2 );
}
// 2-3 is smaller than 2-4
friend bool operator < ( const VertexPair& vp_a, const VertexPair& vp_b )
{
if( vp_a.v1 < vp_b.v1 )
return true;
if( vp_a.v1 == vp_b.v1 )
return ( vp_a.v2 < vp_b.v2 );
return false;
}
bool operator == ( const VertexPair& p ) const
{
if( p.v1 != v1 )
return false;
if( p.v2 != v2 )
return false;
return true;
}
//#ifdef UDGCD_DEV_MODE
friend std::ostream& operator << ( std::ostream& s, const VertexPair& vp )
{
s << '(' << vp.v1 << '-' << vp.v2 << ')';
return s;
}
//#endif
};
//-------------------------------------------------------------------------------------------
/// A binary matrix, implemented as a vector of BinaryVec
/**
This type will allow to fetch some relevant information on what the matrix holds
*/
struct BinaryMatrix
{
friend bool operator == ( const BinaryMatrix&, const BinaryMatrix& );
std::vector<BinaryVec> _data;
BinaryMatrix( size_t nbLines, size_t nbCols )
{
assert( nbLines>0 );
assert( nbCols>0 );
_data.resize( nbLines );
std::for_each( _data.begin(), _data.end(), [nbCols](BinaryVec& bv){ bv.resize(nbCols); } ); // lambda
}
BinaryMatrix( size_t nbLines )
{
assert( nbLines>0 );
_data.resize( nbLines );
}
BinaryMatrix()
{}
size_t nbLines() const { return _data.size(); }
size_t nbCols() const
{
if( 0==nbLines() )
return 0;
return _data.at(0).size();
}
auto begin() -> decltype(_data.begin()) { return _data.begin(); }
auto end() -> decltype(_data.end()) { return _data.end(); }
auto begin() const -> decltype(_data.begin()) { return _data.begin(); }
auto end() const -> decltype(_data.end()) { return _data.end(); }
void addLine( const BinaryVec& bvec )
{
if( nbLines() ) // make sure that the added vector has the same
assert( bvec.size() == _data.back().size() ); // size as the one we are adding
_data.push_back(bvec);
}
void addCol( const BinaryVec& vin )
{
assert( vin.size() == nbLines() );
for( size_t i=0; i<vin.size(); i++ )
_data[i].push_back( vin[i] );
}
/// Creates a binary vector, fills it with the column content, and returns it
BinaryVec getCol( size_t col ) const
{
assert( col<nbCols() );
BinaryVec out( nbLines() );
for( size_t i=0; i<nbLines(); i++ )
out[i] = line(i)[col];
return out;
}
const BinaryVec& line( size_t idx ) const
{
assert( idx<nbLines() );
return _data[idx];
}
BinaryVec& line( size_t idx )
{
assert( idx<nbLines() );
return _data[idx];
}
void clear()
{
for( auto & li: _data )
li.clear();
}
void setDiag()
{
clear();
for( size_t i=0; i<nbLines(); i++ )
_data[i][i] = 1;
}
/// return number of ones
size_t count() const
{
size_t c = 0;
for( const auto& l: _data )
c += l.count();
return c;
}
BinaryMatInfo getInfo() const
{
BinaryMatInfo info;
info.nbLines = nbLines();
assert( _data.size() );
info.nbCols = nbCols();
std::for_each( _data.begin(), _data.end(), [&info](const BinaryVec& v){ info.nbOnes+= v.count();} ); // count 1
for( size_t i=0; i<nbCols(); i++ )
{
bool foundOne=false;
for( size_t j=0; j<nbLines(); j++ )
{
if( _data[j][i] == 1 )
{
foundOne = true;
break;
}
}
if( !foundOne )
info.nb0Cols++;
}
return info;
}
std::vector<size_t> getNonEmptyCols() const
{
std::vector<size_t> out;
for( size_t col=0; col<nbCols(); col++ )
{
bool foundOne=false;
for( size_t row=0; row<nbLines(); row++ )
{
if( _data[row][col] == 1 )
{
foundOne = true;
break;
}
}
if( foundOne )
out.push_back(col);
}
return out;
}
void printMat( std::ostream& f, std::string msg=std::string() ) const
{
size_t c=0, i=0;
f << "BinaryMatrix: " << msg << ", nbLines=" << nbLines() << " nbCols=" << nbCols() << "\n";
for( auto line: *this )
{
f << std::setw(4) << i++ << ": | ";
for( size_t i=0; i<line.size(); i++ )
{
f << line[i];
if( !((i+1)%4) && i != line.size()-1 )
f << '.';
}
f << " | #" << line.count() << "\n";
c += line.count();
}
f << "Total count=" << c << "\n";
}
/// Returns a vector having as size the number of columns and holding the number of "1" the column has
std::vector<size_t> getColumnCount() const
{
std::vector<size_t> out( nbCols(), 0 );
for( size_t col=0; col<nbCols(); col++ )
{
size_t n=0;
for( size_t row=0; row<nbLines(); row++ )
{
if( _data[row][col] == 1 )
n++;
}
out[col] = n;
}
return out;
}
};
inline
bool
operator == ( const BinaryMatrix& m1, const BinaryMatrix& m2 )
{
if( m1.nbLines() != m2.nbLines() )
return false;
if( m1.nbCols() != m2.nbCols() )
return false;
for( size_t i=0; i<m1.nbLines(); i++ )
if( m1.line(i) != m2.line(i) )
return false;
return true;
}
//######################
namespace deprec {
//######################
//-------------------------------------------------------------------------------------------
/// A binary matrix with an added data member so we know to which
/// edge a given column is about. Holds incidence matrix,
/**
that describes the whole graph
- rows: vertices
- cols: edges
See https://en.wikipedia.org/wiki/Incidence_matrix#Undirected_and_directed_graphs
*/
template<typename vertex_t>
struct IncidenceMatrix : public BinaryMatrix
{
std::vector<VertexPair<vertex_t>> _columnEdge;
IncidenceMatrix( size_t nbLines, size_t nbCols )
: BinaryMatrix( nbLines, nbCols )
, _columnEdge( nbCols )
{}
/// Set (=1) at lines v1 and v2, column \c col, and assigns comun edge
void setPair( vertex_t v1, vertex_t v2, size_t col )
{
assert( v1 < nbLines() );
assert( v2 < nbLines() );
assert( col < nbCols() );
_columnEdge[col] = VertexPair<vertex_t>( v1, v2 );
auto& row1 = _data[v1];
auto& row2 = _data[v2];
row1[col] = row2[col] = 1;
}
void printMat( std::ostream& f, std::string msg=std::string() ) const
{
f << "IncidenceMatrix:" << msg << "\n -columns:\n";
for( size_t i=0; i<nbCols(); i++ )
f << i << ": " << _columnEdge[i] << "\n";
BinaryMatrix::printMat( f, "IncidenceMatrix" );
}
};
//-------------------------------------------------------------------------------------------
//######################
} // namespace deprec
//######################
// TEMP
} // namespace priv
} // namespace udgcd
#ifdef UDGCD_USE_M4RI
#include "wrapper_m4ri_convert.hpp"
#endif
namespace udgcd {
//-------------------------------------------------------------------------------------------
/// holds runtime flags (replicated in UdgcdInfo to minimize number of parameters
struct RunTimeOptions
{
bool printTrees = false;
bool printCycles = false;
bool printHistogram = false;
bool doChecking = false;
};
//-------------------------------------------------------------------------------------------
/// Holds information on the cycle detection process
/// (nb of cycles at each step and timing information)
/**
Also holds some runtime options (\se RunTimeOptions)
*/
struct UdgcdInfo
{
size_t nbRawCycles = 0;
size_t nbStrippedCycles = 0;
size_t nbNonChordlessCycles = 0;
size_t nbFinalCycles = 0;
size_t nbSourceVertex = 0;
int maxDepth = 0; ///< post-DFS max explore depth
std::vector<
std::pair<
std::string,
std::chrono::time_point<std::chrono::high_resolution_clock>
>
> timePoints;
RunTimeOptions runTime;
public:
void setTimeStamp( const char* stepName=0 )
{
std::string s;
if( stepName )
s = stepName;
timePoints.push_back( std::make_pair( s, std::chrono::high_resolution_clock::now() ) );
}
void print( std::ostream& f ) const
{
f << "UdgcdInfo:"
<< "\n - nbRawCycles=" << nbRawCycles
<< "\n - nbSourceVertex=" << nbSourceVertex
<< "\n - nbStrippedCycles=" << nbStrippedCycles
<< "\n - nbNonChordlessCycles=" << nbNonChordlessCycles
<< "\n - nbFinalCycles=" << nbFinalCycles
<< "\n - maxDepth=" << maxDepth
<< "\n - Duration per step:\n";
for( size_t i=0; i<timePoints.size()-1; i++ )
{
auto dur = timePoints[i+1].second - timePoints[i].second;
f << "step " << i+1 << " ("
<< timePoints[i].first << "): "
<< std::chrono::duration_cast<std::chrono::milliseconds>(dur).count() << " ms\n";
}
}
void printCSV( std::ostream& f ) const
{
auto siz = timePoints.size();
char sep=';';
f << nbRawCycles << sep
<< nbStrippedCycles << sep
<< nbNonChordlessCycles << sep
<< nbFinalCycles << sep;
for( size_t i=0; i<siz-1; i++ )
{
auto d = timePoints[i+1].second - timePoints[i].second;
f << std::chrono::duration_cast<std::chrono::milliseconds>(d).count();
if( i != siz-2 )
f << sep;
}
f << "\n";
}
};
namespace priv {
//-------------------------------------------------------------------------------------------
/// Print vector of vectors of bits
#if 0
template<typename T>
void
printBitVectors( std::ostream& f, const T& vec )
{
f << "Binary vectors for each paths, #="<< vec.size() << '\n';
for( size_t i=0; i<vec.size(); i++ )
{
f << i << ": ";
printBitVector( f, vec[i] );
}
// f << "\n";
}
#endif
//-------------------------------------------------------------------------------------------
/// Recursive function, explores edges connected to \c v1 until we find a cycle
/**
\warning Have to be sure there \b is a cycle, else infinite recursion !
*/
template <class vertex_t, class graph_t>
bool
explore(
const vertex_t& v1, ///< the starting vertex we want to explore
const graph_t& gr,
std::vector<std::vector<vertex_t>>& vv_paths,
std::vector<std::vector<vertex_t>>& v_cycles, ///< this is where we store the paths that have cycles
int depth,
int& maxDepth
)
{
++depth;
maxDepth = std::max( depth, maxDepth );
assert( vv_paths.size()>0 );
std::vector<vertex_t> src_path = vv_paths.back();
bool found = false;
for( auto oei = boost::out_edges( v1, gr ); oei.first != oei.second; ++oei.first ) // iterating on all the output edges
{
bool b = false;
vertex_t v2a = boost::source( *oei.first, gr );
vertex_t v2b = boost::target( *oei.first, gr );
#ifdef UDGCD_DEV_MODE
// UDGCD_COUT << ++iter << '/' << nbedges << " - v1=" << v1 << ": connected edges v2a=" << v2a << " v2b=" << v2b << "\n";
#endif
if( v2b == v1 && v2a == src_path[0] ) // we just found the edge that we started on, so no need to finish the current iteration, just move on.
continue;
std::vector<vertex_t> newv(src_path); // create new path from source
bool AddNode = true;
if( newv.size() > 1 )
if( newv[ newv.size()-2 ] == v2b )
AddNode = false;
if( AddNode )
{
if( std::find( newv.cbegin(), newv.cend(), v2b ) != newv.cend() )
{
newv.push_back( v2b );
// UDGCD_COUT << "*** FOUND CYCLE: "; PrintVector( std::cout, newv );
v_cycles.push_back( newv );
return true;
}
else
{
newv.push_back( v2b ); // else add'em and continue
// UDGCD_COUT << " -adding vector "; for( const auto& vv:newv ) UDGCD_COUT << vv << "-"; UDGCD_COUT << "\n";
vv_paths.push_back( newv );
b = explore( v2b, gr, vv_paths, v_cycles, depth, maxDepth );
}
}
if( b )
found = true;
}
return found;
}
//-------------------------------------------------------------------------------------------
/// putSmallestElemFirst
template<typename T>
void
putSmallestElemFirst( std::vector<T>& vec )
{
auto it = std::min_element( vec.begin(), vec.end() ); // rotate so that smallest is first
std::rotate( vec.begin(), it, vec.end() );
}
//-------------------------------------------------------------------------------------------
/// Normalize the cycle: puts the smallest index in first position, and reverses it if needed
/// so that the second element if less than the last one.
template<typename T>
void
normalizeCycle( std::vector<T>& cycle )
{
assert( cycle.size() > 2 );
putSmallestElemFirst( cycle ); // turn 2-1-4-5 into 1-4-5-2
if( cycle.back() < cycle[1] ) // if we have 1-4-5-2, then
{
std::reverse( cycle.begin(), cycle.end() ); // we transform it into 2-5-4-1
putSmallestElemFirst( cycle ); // and put smallest first: 1-2-5-4
}
}
//-------------------------------------------------------------------------------------------
/// Normalizes the set of cycles, see normalizeCycle()
template<typename T>
void
normalizeCycles( std::vector<std::vector<T>>& cycles )
{
for( auto& cycle: cycles )
normalizeCycle( cycle );
}
//-------------------------------------------------------------------------------------------
/// Removes the parts that are not part of the cycle, and normalize the order
/**
Example:
- in: 1-2-3-4-5-3
- out: 3-4-5
\sa putSmallestElemFirst()
*/
template<typename T>
std::vector<T>
findTrueCycle( const std::vector<T>& cycle )
{
PRINT_FUNCTION;
assert( cycle.size() > 2 ); // 3 or more nodes
if( cycle.size() == 3 ) // if 3 nodes, just return the input path
return cycle;
std::vector<T> out;
out.reserve( cycle.size() );
bool done = false;
for( size_t i=0; i<cycle.size()-1 && !done; ++i )
{
const T& n1 = cycle[i];
for( size_t j=i+2; j<cycle.size() && !done; ++j )
{
const T& n2 = cycle[j];
if( n1 == n2 )
{
out.resize( j-i );
std::copy( std::begin(cycle) + i, std::begin(cycle) + j, std::begin(out) );
done = true;
}
}
}
putSmallestElemFirst( out ); // if we have 4-3-2-1, then transform into 1-4-3-2 (rotate)
if( out.back() < out[1] ) // if we have 1-4-3-2, then
{
std::reverse( out.begin(), out.end() ); // we transform it into 2-3-4-1
putSmallestElemFirst( out ); // and put smallest first: 1-2-3-4
}
// UDGCD_COUT << "out: "; printVector( std::cout, out );
return out;
}
//-------------------------------------------------------------------------------------------
/// Holds code related to using trees to sort unique cycles
namespace tree {
/// A tree node, that holds the idx of the node in the main graph
/**
Required, because in a tree, we can have several nodes with the same cycle index.
*/
struct TreeVertex
{
size_t idx;
};
/// A class dedicated to printing trees in DOT format
/**
from: https://www.boost.org/doc/libs/1_82_0/libs/graph/doc/write-graphviz.html
\sa make_label_writer_1()
\sa printTree()
*/
template <class Name>
class label_writer
{
public:
label_writer(Name _name) : name(_name) {}
template <class VertexOrEdge>
void operator()(std::ostream& out, const VertexOrEdge& v) const
{
out << "[label=\"" << name[v] << "\"";
if( v == 0 )
out << ",penwidth=\"2\"";
out << "]";
}
private:
Name name;
};
/// \sa printTree()
template < class Name >
inline
label_writer<Name>
make_label_writer_1(Name n)
{
return label_writer<Name>(n);
}
/// Saves tree in a DOT file, can be rendered with `$ make svg`
template<typename tree_t>
inline
void
printTree( const tree_t& tree, std::string name )
{
// std::cout << name << " #v=" << boost::num_vertices(tree) << ":\n";
/// boost::print_graph( tree, boost::get(&TreeVertex::idx, tree), std::cout );
std::ofstream f( "out/" + name + ".dot" );
assert( f.is_open() );
boost::write_graphviz(
f,
tree,
make_label_writer_1(
boost::get( &TreeVertex::idx, tree )
)
);
}
template<typename tree_t>
void
printTrees( const std::vector<tree_t>& vtrees )
{
PRINT_FUNCTION;
/* std::cout << "Trees: ";
if( msg )
std::cout << msg << "\n";*/
size_t i = 0;
for( const auto& tree: vtrees )
{
std::ostringstream oss;
oss << "tree_" << i++;
printTree( tree, oss.str() );
}
}
//-------------------------------------------------------------------------------------------
/// Adds the \c cycle to the \c tree.
template<typename T, typename tree_t>
void
addCycleToNewTree(
tree_t& tree,
const std::vector<T>& cycle
)
{
PRINT_FUNCTION;
#ifdef UDGCD_DEV_MODE
printVector( std::cout, cycle, "cycle to add" );
#endif
assert( boost::num_vertices(tree) == 0 );
auto u = boost::add_vertex( tree ); // create initial vertex
tree[u].idx = cycle.front();
for( size_t i=0; i<cycle.size()-1; i++ )
{
auto v = boost::add_vertex(tree);
tree[v].idx = cycle[i+1];
boost::add_edge( u, v, tree );
u = v;
}
#ifdef UDGCD_DEV_MODE
boost::print_graph( tree, boost::get(&TreeVertex::idx, tree), std::cout );
#endif
}
//-------------------------------------------------------------------------------------------
/// Recursive function, starts from \c currVertex
/**
\return false if cycle is not in the tree, true if cycle is already in the tree
Say we have the following tree, starting from vertex 1:
\verbatim
1
/ | \
3 4 2
/ | | | \
4 5 5 4 5
\endverbatim
- If we query this function with the cycle 1-3-5 or 1-2-4, it will return true
- If we query this function with the cycle 1-4-6, it will return false.
*/
template<typename T, typename tree_t>
bool
searchCycleInTree(
tree_t& tree, ///< current tree
typename boost::graph_traits<tree_t>::vertex_descriptor& currVertex, ///< current vertex in tree
const std::vector<T>& cycle, ///< the cycle we are investigating
size_t& cyIdx, ///< current index in the cycle (this is a recursive function, so we need to know where we are)
typename boost::graph_traits<tree_t>::vertex_descriptor& lastGoodVertex
)
{
static int depth;
depth++;
UDGCD_COUT << "start, depth=" << depth << " currVertex=" << currVertex << " idx=" << tree[currVertex].idx << " lastGoodVertex=" << lastGoodVertex << '\n';
if( cyIdx+1 == cycle.size() ) // if last element of cycle, no more exploration of the tree is needed
{
depth--;
return true;
}
// We iterate on each leaf and check if the cycle element is there
bool found = false;
lastGoodVertex = currVertex;
for( auto oei = boost::out_edges( currVertex, tree ); oei.first != oei.second; ++oei.first )
{
currVertex = boost::target( *oei.first, tree );
UDGCD_COUT << "loop: currVertex=" << currVertex << " idx=" << tree[currVertex].idx << '\n';
if( tree[currVertex].idx == cycle[cyIdx+1] ) // correspondance at this level, lets get further down
{
cyIdx = cyIdx+1;
UDGCD_COUT << "equal, search further\n";
found = searchCycleInTree( tree, currVertex, cycle, cyIdx, lastGoodVertex ); // explore further on
}
}
// UDGCD_COUT << "BEFORE currVertex=" << currVertex << " idx=" << tree[currVertex].idx << " found=" << found << '\n';
// if( !found ) // path not found in tree, we set the current vertex to the one we began with
// currVertex = current;
// UDGCD_COUT << "END currVertex=" << currVertex << " idx=" << tree[currVertex].idx << '\n';
UDGCD_COUT << "END, depth=" << depth << " currVertex=" << currVertex << ",idx=" << tree[currVertex].idx << " lastGoodVertex=" << lastGoodVertex << ",idx=" << tree[lastGoodVertex].idx << '\n';
depth--;
return found;
}
//-------------------------------------------------------------------------------------------
/// Selects the right tree, create it if needed, then search the tree for the cycle \c cycle,
/// and add it if not present
/**
- If not present, add it to the tree and return false
- If present, return true
*/
template<typename T, typename tree_t>
bool
addCycleToTrees(
const std::vector<T>& cycle,
std::vector<tree_t>& vtrees ///< array of trees
)
{
PRINT_FUNCTION;
#ifdef UDGCD_DEV_MODE
printVector( std::cout, cycle, "addCycleToTrees()" );
#endif
// if tree starting with initial node equal to first one in path does not exist, then build it
auto firstNode = cycle.front();
UDGCD_ASSERT_2( firstNode < vtrees.size(), firstNode, vtrees.size() );
auto& tree = vtrees[firstNode];
if( boost::num_vertices( tree ) == 0 )
{
addCycleToNewTree( tree, cycle );
#ifdef UDGCD_DEV_MODE
std::ostringstream oss;
oss << "tree_tmp_" << firstNode << "_0";
printTree( tree, oss.str() );
UDGCD_COUT << "tree saved to " << oss.str() << "\n";
#endif
return false;
}
else
{
typename boost::graph_traits<tree_t>::vertex_descriptor currVertex = 0;
typename boost::graph_traits<tree_t>::vertex_descriptor lastGoodVertex = 0;
size_t cyIdx = 0;
auto found = searchCycleInTree( tree, currVertex, cycle, cyIdx, lastGoodVertex );
if( !found ) // add remaining elements of cycle in the tree
{
UDGCD_COUT << "not found, adding remaining elements of cycle, lastGoodVertex= "<< lastGoodVertex << " idx=" << tree[lastGoodVertex].idx << "\n";
for( size_t i=cyIdx+1; i<cycle.size(); i++ )
{
UDGCD_COUT << "i=" << i << " adding elem " << cycle[i] << " edge: from " << tree[lastGoodVertex].idx << "\n";
auto newV = boost::add_vertex( tree );
tree[newV].idx = cycle[i];
boost::add_edge( lastGoodVertex, newV, tree );
lastGoodVertex = newV;
}
#ifdef UDGCD_DEV_MODE
if( cycle.size() > cyIdx+1 )
{
static int index=1;
std::ostringstream oss;
oss << "tree_tmp_" << firstNode << "_" << index++;
printTree( tree, oss.str() );
UDGCD_COUT << "tree saved to " << oss.str() << "\n";
}
#endif
}
return found;
}
}
} // namespace tree
#if 0
//-------------------------------------------------------------------------------------------
namespace tree {
template<typename T, typename graph_t>
std::vector<std::vector<T>>
strip(
const std::vector<std::vector<T>>& v_cycles,
const graph_t& gr
)
{
PRINT_FUNCTION;
std::vector<std::vector<T>> out;
out.reserve( v_cycles.size() );
for( const auto& cycle: v_cycles )
{
auto newcy = findTrueCycle( cycle );
assert( newcy.size()>2 );
out.push_back( newcy );
}
return out;
}
//-------------------------------------------------------------------------------------------
template<typename T, typename graph_t>
std::vector<std::vector<T>>
storeUnique(
const std::vector<std::vector<T>>& v_cycles,
const graph_t& gr,
const UdgcdInfo& info
)
{
PRINT_FUNCTION;
using tree_t = boost::adjacency_list<
boost::vecS,
boost::vecS,
boost::directedS,
TreeVertex
>;
std::vector<std::vector<T>> out;
out.reserve( v_cycles.size() );