-
Notifications
You must be signed in to change notification settings - Fork 107
/
Graph.hpp
3763 lines (3441 loc) · 126 KB
/
Graph.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
/***********************************************************/
/*** ______ ____ ______ _ ***/
/*** / ___\ \/ /\ \/ / ___|_ __ __ _ _ __ | |__ ***/
/*** | | \ / \ / | _| '__/ _` | '_ \| '_ \ ***/
/*** | |___ / \ / \ |_| | | | (_| | |_) | | | | ***/
/*** \____/_/\_\/_/\_\____|_| \__,_| .__/|_| |_| ***/
/*** |_| ***/
/***********************************************************/
/*** Header-Only C++ Library for Graph ***/
/*** Representation and Algorithms ***/
/***********************************************************/
/*** Author: ZigRazor ***/
/*** E-Mail: zigrazor@gmail.com ***/
/***********************************************************/
/*** Collaboration: ----------- ***/
/***********************************************************/
/*** License: AGPL v3.0 ***/
/***********************************************************/
#ifndef __CXXGRAPH_GRAPH_H__
#define __CXXGRAPH_GRAPH_H__
#include <cstdio>
#pragma once
#include <limits.h>
#include <atomic>
#include <cmath>
#include <condition_variable>
#include <cstring>
#include <deque>
#include <fstream>
#include <sstream>
#include <functional>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include "Edge/DirectedEdge.hpp"
#include "Edge/DirectedWeightedEdge.hpp"
#include "Edge/Edge.hpp"
#include "Edge/UndirectedEdge.hpp"
#include "Edge/UndirectedWeightedEdge.hpp"
#include "Edge/Weighted.hpp"
#include "Node/Node.hpp"
#include "Partitioning/Partition.hpp"
#include "Partitioning/PartitionAlgorithm.hpp"
#include "Partitioning/Partitioner.hpp"
#include "Partitioning/Utility/Globals.hpp"
#include "Utility/ConstString.hpp"
#include "Utility/ConstValue.hpp"
#include "Utility/PointerHash.hpp"
#include "Utility/Reader.hpp"
#include "Utility/ThreadSafe.hpp"
#include "Utility/Typedef.hpp"
#include "Utility/Writer.hpp"
#ifdef WITH_COMPRESSION
#include <zlib.h>
#endif
namespace CXXGraph {
// Smart pointers alias
template <typename T>
using unique = std::unique_ptr<T>;
template <typename T>
using shared = std::shared_ptr<T>;
using std::make_shared;
using std::make_unique;
template <typename T>
using T_EdgeSet = std::unordered_set<shared<const Edge<T>>, edgeHash<T>>;
namespace Partitioning {
template <typename T>
class Partition;
}
template <typename T>
std::ostream &operator<<(std::ostream &o, const Graph<T> &graph);
template <typename T>
std::ostream &operator<<(std::ostream &o, const AdjacencyMatrix<T> &adj);
/// Class that implement the Graph. ( This class is not Thread Safe )
template <typename T>
class Graph {
private:
T_EdgeSet<T> edgeSet = {};
// Private non-const getter for the set of nodes
std::unordered_set<shared<Node<T>>, nodeHash<T>> nodeSet();
std::optional<std::pair<std::string, char>> getExtenstionAndSeparator(
InputOutputFormat format) const;
void writeGraphToStream(std::ostream &oGraph, std::ostream &oNodeFeat,
std::ostream &oEdgeWeight, const char &sep,
bool writeNodeFeat, bool writeEdgeWeight) const;
void readGraphFromStream(std::istream &iGraph, std::istream &iNodeFeat,
std::istream &iEdgeWeight, bool readNodeFeat,
bool readEdgeWeight);
int writeToDot(const std::string &workingDir, const std::string &OFileName,
const std::string &graphName) const;
int readFromDot(const std::string &workingDir, const std::string &fileName);
void recreateGraph(
std::unordered_map<unsigned long long,
std::pair<std::string, std::string>> &edgeMap,
std::unordered_map<unsigned long long, bool> &edgeDirectedMap,
std::unordered_map<std::string, T> &nodeFeatMap,
std::unordered_map<unsigned long long, double> &edgeWeightMap);
#ifdef WITH_COMPRESSION
int compressFile(const std::string &inputFile,
const std::string &outputFile) const;
int decompressFile(const std::string &inputFile,
const std::string &outputFile) const;
#endif
public:
Graph() = default;
Graph(const T_EdgeSet<T> &edgeSet);
virtual ~Graph() = default;
/**
* \brief
* Function that return the Edge set of the Graph
* Note: No Thread Safe
*
* @returns a list of Edges of the graph
*
*/
virtual const T_EdgeSet<T> &getEdgeSet() const;
/**
* \brief
* Function set the Edge Set of the Graph
* Note: No Thread Safe
*
* @param edgeSet The Edge Set
*
*/
virtual void setEdgeSet(const T_EdgeSet<T> &edgeSet);
/**
* \brief
* Function add an Edge to the Graph Edge Set
* First check if a pointer to a node with the same userId has
* already been added, and if not add it
* Note: No Thread Safe
*
* @param edge The Edge to insert
*
*/
virtual void addEdge(const Edge<T> *edge);
/**
* \brief
* Function add an Edge to the Graph Edge Set
* First check if a pointer to a node with the same userId has
* already been added, and if not add it
* Note: No Thread Safe
*
* @param edge The Edge to insert
*
*/
virtual void addEdge(shared<const Edge<T>> edge);
/**
* \brief
* Function remove an Edge from the Graph Edge Set
* Note: No Thread Safe
*
* @param edgeId The Edge Id to remove
*
*/
virtual void removeEdge(const unsigned long long edgeId);
/**
* \brief
* Finds the given edge defined by v1 and v2 within the graph.
*
* @param v1 The first vertex.
* @param v2 The second vertex.
* @param id The edge id if the edge is found. Otherwise set to 0.
* @return True if the edge exists in the graph.
*/
virtual bool findEdge(const Node<T> *v1, const Node<T> *v2,
unsigned long long &id) const;
/**
* \brief
* Overload of findEdge which takes shared pointers as parameters
*
* @param v1 The first vertex.
* @param v2 The second vertex.
* @param id The edge id if the edge is found. Otherwise set to 0.
* @return True if the edge exists in the graph.
*/
virtual bool findEdge(shared<const Node<T>> v1, shared<const Node<T>> v2,
unsigned long long &id) const;
/**
* \brief
* Function that return the Node Set of the Graph
* Note: No Thread Safe
*
* @returns a list of Nodes of the graph
*
*/
virtual const std::unordered_set<shared<const Node<T>>, nodeHash<T>>
getNodeSet() const;
/**
* \brief
* Function that sets the data contained in a node
*
* @param nodeUserId The userId string of the node whose data is to be changes
* @param data The new value for the node data
*
*/
virtual void setNodeData(const std::string &nodeUserId, T data);
/**
* \brief
* Function that sets the data contained in every node of the graph
*
* @param dataMap Map of the userId of every node with its new data value
*
*/
virtual void setNodeData(std::map<std::string, T> &dataMap);
/**
* \brief
* Function that return an Edge with specific ID if Exist in the Graph
* Note: No Thread Safe
*
* @param edgeId The Edge Id to return
* @returns the Edge if exist
*
*/
virtual const std::optional<shared<const Edge<T>>> getEdge(
const unsigned long long edgeId) const;
/**
* @brief This function generate a list of adjacency matrix with every element
* of the matrix contain the node where is directed the link and the Edge
* corrispondent to the link
* Note: No Thread Safe
*/
virtual const std::shared_ptr<AdjacencyMatrix<T>> getAdjMatrix() const;
/**
* \brief This function generates a set of nodes linked to the provided node
* in a directed graph
*
* @param Pointer to the node
*
*/
virtual const std::unordered_set<shared<const Node<T>>, nodeHash<T>>
outNeighbors(const Node<T> *node) const;
/**
* \brief This function generates a set of nodes linked to the provided node
* in a directed graph
*
* @param Pointer to the node
*
*/
virtual const std::unordered_set<shared<const Node<T>>, nodeHash<T>>
outNeighbors(shared<const Node<T>> node) const;
/**
* \brief This function generates a set of nodes linked to the provided node
* in any graph
*
* @param Pointer to the node
*
*/
virtual const std::unordered_set<shared<const Node<T>>, nodeHash<T>>
inOutNeighbors(const Node<T> *node) const;
/**
* \brief
* \brief This function generates a set of nodes linked to the provided node
* in any graph
*
* @param Pointer to the node
*
*/
virtual const std::unordered_set<shared<const Node<T>>, nodeHash<T>>
inOutNeighbors(shared<const Node<T>> node) const;
/**
* @brief This function finds the subset of given a nodeId
* Subset is stored in a map where keys are the hash-id of the node & values
* is the subset.
* @param subset query subset, we want to find target in this subset
* @param elem elem that we wish to find in the subset
*
* @return parent node of elem
* Note: No Thread Safe
*/
virtual unsigned long long setFind(
std::unordered_map<unsigned long long, Subset> *,
const unsigned long long elem) const;
/**
* @brief This function finds the subset of given a nodeId
* Subset is stored in a map where keys are the hash-id of the node & values
* is the subset.
* @param shared pointer to subset query subset, we want to find target in
* this subset
* @param elem elem that we wish to find in the subset
*
* @return parent node of elem
* Note: No Thread Safe
*/
virtual unsigned long long setFind(
shared<std::unordered_map<unsigned long long, Subset>>,
const unsigned long long elem) const;
/**
* @brief This function modifies the original subset array
* such that it the union of two sets a and b
* @param subset original subset is modified to obtain union of a & b
* @param a parent id of set1
* @param b parent id of set2
* NOTE: Original subset is no longer available after union.
* Note: No Thread Safe
*/
virtual void setUnion(std::unordered_map<unsigned long long, Subset> *,
const unsigned long long set1,
const unsigned long long elem2) const;
/**
* @brief This function modifies the original subset array
* such that it the union of two sets a and b
* @param subset original subset is modified to obtain union of a & b
* @param a parent id of set1
* @param b parent id of set2
* NOTE: Original subset is no longer available after union.
* Note: No Thread Safe
*/
virtual void setUnion(shared<std::unordered_map<unsigned long long, Subset>>,
const unsigned long long set1,
const unsigned long long elem2) const;
/**
* @brief This function finds the eulerian path of a directed graph using
* hierholzers algorithm
*
* @return a vector containing nodes in eulerian path
* Note: No Thread Safe
*/
virtual std::shared_ptr<std::vector<Node<T>>> eulerianPath() const;
/**
* @brief Function runs the dijkstra algorithm for some source node and
* target node in the graph and returns the shortest distance of target
* from the source.
* Note: No Thread Safe
*
* @param source source vertex
* @param target target vertex
*
* @return shortest distance if target is reachable from source else ERROR in
* case if target is not reachable from source or there is error in the
* computation.
*/
virtual const DijkstraResult dijkstra(const Node<T> &source,
const Node<T> &target) const;
/**
* @brief This function runs the tarjan algorithm and returns different types
* of results depending on the input parameter typeMask.
*
* @param typeMask each bit of typeMask within valid range represents a kind
* of results should be returned.
*
* Note: No Thread Safe
*
* @return The types of return include strongly connected components
* (only for directed graphs) and cut vertices、 bridges、edge
* biconnected components and vertice biconnected components
* (only for undirected graphs).
*/
virtual const TarjanResult<T> tarjan(const unsigned int typeMask) const;
/**
* @brief Function runs the bellman-ford algorithm for some source node and
* target node in the graph and returns the shortest distance of target
* from the source. It can also detect if a negative cycle exists in the
* graph. Note: No Thread Safe
*
* @param source source vertex
* @param target target vertex
*
* @return shortest distance if target is reachable from source else ERROR in
* case if target is not reachable from source. If there is no error then also
* returns if the graph contains a negative cycle.
*/
virtual const BellmanFordResult bellmanford(const Node<T> &source,
const Node<T> &target) const;
/**
* @brief This function computes the transitive reduction of the graph,
* returning a graph with the property of transitive closure satisfied. It
* removes the "short-circuit" paths from a graph, leaving only the longest
* paths. Commonly used to remove duplicate edges among nodes that do not pass
* through the entire graph.
* @return A copy of the current graph with the transitive closure property
* satisfied.
*
*/
virtual const Graph<T> transitiveReduction() const;
/**
* @brief Function runs the floyd-warshall algorithm and returns the shortest
* distance of all pair of nodes. It can also detect if a negative cycle
* exists in the graph. Note: No Thread Safe
* @return a map whose keys are node ids and values are the shortest distance.
* If there is no error then also returns if the graph contains a negative
* cycle.
*/
virtual const FWResult floydWarshall() const;
/**
* @brief Function runs the prim algorithm and returns the minimum spanning
* tree if the graph is undirected. Note: No Thread Safe
* @return a vector containing id of nodes in minimum spanning tree & cost of
* MST
*/
virtual const MstResult prim() const;
/**
* @brief Function runs the boruvka algorithm and returns the minimum spanning
* tree & cost if the graph is undirected. Note: No Thread Safe
* @return struct of type MstResult with following fields
* success: true if algorithm completed successfully ELSE false
* mst: vector containing id of nodes in minimum spanning tree & cost of MST
* mstCost: Cost of MST
* errorMessage: "" if no error ELSE report the encountered error
*/
virtual const MstResult boruvka() const;
/**
* @brief Function runs the kruskal algorithm and returns the minimum spanning
* tree if the graph is undirected. Note: No Thread Safe
* @return struct of type MstResult with following fields
* success: true if algorithm completed successfully ELSE false
* mst: vector containing id of nodes in minimum spanning tree & cost of MST
* mstCost: Cost of MST
* errorMessage: "" if no error ELSE report the encountered error
*/
virtual const MstResult kruskal() const;
/**
* \brief
* Function runs the best first search algorithm over the graph
* using an evaluation function to decide which adjacent node is
* most promising to explore
* Note: No Thread Safe
*
* @param source source node
* @param target target node
* @returns a struct with a vector of Nodes if target is reachable else ERROR
* in case if target is not reachable or there is an error in the computation.
*
*/
virtual BestFirstSearchResult<T> best_first_search(
const Node<T> &source, const Node<T> &target) const;
/**
* \brief
* Function performs the breadth first search algorithm over the graph
* Note: No Thread Safe
*
* @param start Node from where traversing starts
* @returns a vector of Node indicating which Node were visited during the
* search.
*
*/
virtual const std::vector<Node<T>> breadth_first_search(
const Node<T> &start) const;
/**
* \brief
* The multithreaded version of breadth_first_search
* It turns out to be two indepentent functions because of implemntation
* differences
*
* @param start Node from where traversing starts
* @param num_threads number of threads
* @returns a vector of Node indicating which Node were visited during the
* search.
*
*/
virtual const std::vector<Node<T>> concurrency_breadth_first_search(
const Node<T> &start, size_t num_threads) const;
/**
* \brief
* Function performs the depth first search algorithm over the graph
* Note: No Thread Safe
*
* @param start Node from where traversing starts
* @returns a vector of Node indicating which Node were visited during the
* search.
*
*/
virtual const std::vector<Node<T>> depth_first_search(
const Node<T> &start) const;
/**
* \brief
* This function uses DFS to check for cycle in the graph.
* Pay Attention, this function work only with directed Graph
* Note: No Thread Safe
*
* @return true if a cycle is detected, else false. ( false is returned also
* if the graph in indirected)
*/
virtual bool isCyclicDirectedGraphDFS() const;
/**
* \brief
* This function uses BFS to check for cycle in the graph.
* Pay Attention, this function work only with directed Graph
* Note: No Thread Safe
*
* @return true if a cycle is detected, else false. ( false is returned also
* if the graph in indirected)
*/
virtual bool isCyclicDirectedGraphBFS() const;
/**
* @brief
* This function checks if the given set of edges
* forms a cycle or not using union-find method.
*
* @return true if a cycle is detected, else false
*/
virtual bool containsCycle(const T_EdgeSet<T> *) const;
/**
* @brief
* This function checks if the given set of edges
* forms a cycle or not using union-find method.
*
* @return true if a cycle is detected, else false
*/
virtual bool containsCycle(shared<const T_EdgeSet<T>>) const;
/**
* @brief
* This function checks if the given Subset
* forms a cycle or not using union-find method.
*
* @return true if a cycle is detected, else false
*/
virtual bool containsCycle(
shared<const T_EdgeSet<T>> edgeSet,
shared<std::unordered_map<unsigned long long, Subset>>) const;
/**
* \brief
* This function checks if a graph is directed
* Note: No Thread Safe
*
* @return true if the graph is directed, else false.
*/
virtual bool isDirectedGraph() const;
/**
* \brief
* This function checks if a graph is undirected
* Note: No Thread Safe
*
* @return true if the graph is undirected, else false.
*/
virtual bool isUndirectedGraph() const;
/**
* @brief This function reverse the direction of the edges in a directed graph
*/
virtual void reverseDirectedGraph();
/**
* @brief This function checks if the graph is connected or not
* Applicable for Undirected Graph, for Directed Graph use the
* isStronglyConnectedGraph() function
*
* @return true if the graph is connected
* @return false otherwise
*/
virtual bool isConnectedGraph() const;
/**
* @brief This function checks if the graph is strongly connected or not
* Applicable for Directed Graph, for Undirected Graph use the
* isConnectedGraph() function
*
* @return true if the graph is connected
* @return false otherwise
*/
virtual bool isStronglyConnectedGraph() const;
/**
* @brief This function sort nodes in topological order.
* Applicable for Directed Acyclic Graph
*
* @return a struct with a vector of Nodes ordered topologically else ERROR in
* case of undirected or cyclic graph
*/
virtual TopoSortResult<T> topologicalSort() const;
/**
* @brief This function sort nodes in topological order using kahn's algorithm
* Applicable for Directed Acyclic Graph
*
* @return a struct with a vector of Nodes ordered topologically else ERROR in
* case of undirected or cyclic graph
*/
virtual TopoSortResult<T> kahn() const;
/**
* \brief
* This function performs performs the kosaraju algorthm on the graph to find
the strongly connected components.
*
* Mathematical definition of the problem:
* A strongly connected component (SCC) of a directed graph is a maximal
strongly connected subgraph.
* Note: No Thread Safe
* @return a vector of vector of strongly connected components.
*/
virtual SCCResult<T> kosaraju() const;
/**
* \brief
* This function performs Graph Slicing based on connectivity
*
* Mathematical definition of the problem:
*
* Let G be the set of nodes in a graph and n be a given node in that set.
* Let C be the non-strict subset of G containing both n and all nodes
reachable
* from n, and let C' be its complement. There's a third set M, which is the
* non-strict subset of C containing all nodes that are reachable from any node
in C'.
* The problem consists of finding all nodes that belong to C but not to M.
* Note: No Thread Safe
* @param start Node from where traversing starts
* @return a vector of nodes that belong to C but not to M.
*/
virtual const std::vector<Node<T>> graph_slicing(const Node<T> &start) const;
/**
* @brief Function runs the Dial algorithm (Optimized Dijkstra for small
* range weights) for some source node and target node in the graph and
* returns the shortest distance of target from the source. Note: No Thread
* Safe
*
* @param source source vertex
* @param maxWeight maximum weight of the edge
*
* @return shortest distance for all nodes reachable from source else ERROR in
* case there is error in the computation.
*/
virtual const DialResult dial(const Node<T> &source, int maxWeight) const;
/**
* @brief Function runs the Ford-Fulkerson algorithm for some source node and
* target node in the graph and returns the maximum flow of the graph
*
* @param source source vertex
* @param target target vertex
* @return double Max-Flow value or -1 in case of error
*/
virtual double fordFulkersonMaxFlow(const Node<T> &source,
const Node<T> &target) const;
/**
* \brief
* This function writes the graph to an output file
* Note: Not threadsafe
*
* @param format The output format of the file
* @param workingDir The parent directory of the output file
* @param OFileName The output filename
* @param compress Enables compression (requires zlib)
* @param writeNodeFeat Indicates if export also Node Features
* @param writeEdgeWeight Indicates if export also Edge Weights
* @return 0 if OK, else return a negative value
*/
virtual int writeToFile(
InputOutputFormat format = InputOutputFormat::STANDARD_CSV,
const std::string &workingDir = ".",
const std::string &OFileName = "graph", bool compress = false,
bool writeNodeFeat = false, bool writeEdgeWeight = false) const;
virtual int writeToDotFile(const std::string &workingDir,
const std::string &OFileName,
const std::string &graphName) const;
virtual int writeToMTXFile(const std::string &workingDir,
const std::string &OFileName, char delimier) const;
/**
* \brief
* This function reads the graph from an input file
* Note: Not threadsafe
*
* @param format The input format of the file
* @param workingDir The parent directory of the input
* file
* @param OFileName The input filename
* @param compress Enables compression (requires zlib)
* @param readNodeFeat Indicates if import also Node Features
* @param readEdgeWeight Indicates if import also Edge Weights
* @return 0 if OK, else return a negative value
*/
virtual int readFromFile(
InputOutputFormat format = InputOutputFormat::STANDARD_CSV,
const std::string &workingDir = ".",
const std::string &OFileName = "graph", bool compress = false,
bool readNodeFeat = false, bool readEdgeWeight = false);
virtual int readFromDotFile(const std::string &workingDir,
const std::string &fileName);
virtual int readFromMTXFile(const std::string &workingDir,
const std::string &fileName);
/**
* \brief
* This function partition a graph in a set of partitions
* Note: No Thread Safe
*
* @param algorithm The partition algorithm
* @param numberOfPartition The number of partitions
* @return The partiton Map of the partitioned graph
*/
virtual PartitionMap<T> partitionGraph(
const Partitioning::PartitionAlgorithm algorithm,
const unsigned int numberOfPartitions, const double param1 = 0.0,
const double param2 = 0.0, const double param3 = 0.0,
const unsigned int numberOfthreads =
std::thread::hardware_concurrency()) const;
friend std::ostream &operator<< <>(std::ostream &os, const Graph<T> &graph);
friend std::ostream &operator<< <>(std::ostream &os,
const AdjacencyMatrix<T> &adj);
};
template <typename T>
Graph<T>::Graph(const T_EdgeSet<T> &edgeSet) {
for (auto edgeIt : edgeSet) {
this->edgeSet.insert(edgeIt);
}
}
template <typename T>
const T_EdgeSet<T> &Graph<T>::getEdgeSet() const {
return edgeSet;
}
template <typename T>
void Graph<T>::setEdgeSet(const T_EdgeSet<T> &edgeSet) {
this->edgeSet.clear();
for (auto edgeIt : edgeSet) {
this->edgeSet.insert(edgeIt);
}
}
template <typename T>
void Graph<T>::addEdge(const Edge<T> *edge) {
if (edge->isDirected().has_value() && edge->isDirected().value()) {
if (edge->isWeighted().has_value() && edge->isWeighted().value()) {
auto edge_shared = make_shared<DirectedWeightedEdge<T>>(*edge);
this->edgeSet.insert(edge_shared);
} else {
auto edge_shared = make_shared<DirectedEdge<T>>(*edge);
this->edgeSet.insert(edge_shared);
}
} else {
if (edge->isWeighted().has_value() && edge->isWeighted().value()) {
auto edge_shared = make_shared<UndirectedWeightedEdge<T>>(*edge);
this->edgeSet.insert(edge_shared);
} else {
auto edge_shared = make_shared<UndirectedEdge<T>>(*edge);
this->edgeSet.insert(edge_shared);
}
}
}
template <typename T>
void Graph<T>::addEdge(shared<const Edge<T>> edge) {
this->edgeSet.insert(edge);
}
template <typename T>
void Graph<T>::removeEdge(const unsigned long long edgeId) {
auto edgeOpt = Graph<T>::getEdge(edgeId);
if (edgeOpt.has_value()) {
/*
edgeSet.erase(std::find_if(this->edgeSet.begin(), this->edgeSet.end(),
[edgeOpt](const Edge<T> *edge) { return (*(edgeOpt.value()) == *edge); }));
*/
edgeSet.erase(edgeSet.find(edgeOpt.value()));
}
}
template <typename T>
bool Graph<T>::findEdge(const Node<T> *v1, const Node<T> *v2,
unsigned long long &id) const {
auto v1_shared = make_shared<const Node<T>>(*v1);
auto v2_shared = make_shared<const Node<T>>(*v2);
return findEdge(v1_shared, v2_shared, id);
}
template <typename T>
bool Graph<T>::findEdge(shared<const Node<T>> v1, shared<const Node<T>> v2,
unsigned long long &id) const {
// This could be made faster by looking for the edge hash, assuming we hash
// based on node data, instead of a unique integer
for (auto e : this->edgeSet) {
if ((e->getNodePair().first == v1) && (e->getNodePair().second == v2)) {
id = e->getId();
return true;
}
if (!e->isDirected() &&
((e->getNodePair().second == v1) && (e->getNodePair().first == v2))) {
id = e->getId();
return true;
}
}
id = 0;
return false;
}
template <typename T>
const std::unordered_set<shared<const Node<T>>, nodeHash<T>>
Graph<T>::getNodeSet() const {
std::unordered_set<shared<const Node<T>>, nodeHash<T>> nodeSet;
for (const auto &edgeSetIt : edgeSet) {
nodeSet.insert(edgeSetIt->getNodePair().first);
nodeSet.insert(edgeSetIt->getNodePair().second);
}
/*
std::deque<const Node<T> *> nodeSet;
for (const auto &edge : edgeSet)
{
if (std::find_if(nodeSet.begin(), nodeSet.end(), [edge](const Node<T>
*node) { return (*edge->getNodePair().first == *node); }) == nodeSet.end())
{
nodeSet.push_back(edge->getNodePair().first);
}
if (std::find_if(nodeSet.begin(), nodeSet.end(), [edge](const Node<T>
*node) { return (*edge->getNodePair().second == *node); }) == nodeSet.end())
{
nodeSet.push_back(edge->getNodePair().second);
}
}
*/
return nodeSet;
}
template <typename T>
void Graph<T>::setNodeData(const std::string &nodeUserId, T data) {
auto nodeset = this->nodeSet();
auto nodeIt = std::find_if(
nodeset.begin(), nodeset.end(),
[&nodeUserId](auto node) { return node->getUserId() == nodeUserId; });
(*nodeIt)->setData(std::move(data));
}
template <typename T>
void Graph<T>::setNodeData(std::map<std::string, T> &dataMap) {
// Construct the set of all the nodes in the graph
for (auto &nodeSetIt : this->nodeSet()) {
nodeSetIt->setData(std::move(dataMap[nodeSetIt->getUserId()]));
}
}
template <typename T>
const std::optional<shared<const Edge<T>>> Graph<T>::getEdge(
const unsigned long long edgeId) const {
for (const auto &it : edgeSet) {
if (it->getId() == edgeId) {
return it;
}
}
return std::nullopt;
}
template <typename T>
std::unordered_set<shared<Node<T>>, nodeHash<T>> Graph<T>::nodeSet() {
std::unordered_set<shared<Node<T>>, nodeHash<T>> nodeSet;
for (auto &edgeSetIt : edgeSet) {
nodeSet.insert(
std::const_pointer_cast<Node<T>>(edgeSetIt->getNodePair().first));
nodeSet.insert(
std::const_pointer_cast<Node<T>>(edgeSetIt->getNodePair().second));
}
return nodeSet;
}
template <typename T>
std::optional<std::pair<std::string, char>> Graph<T>::getExtenstionAndSeparator(
InputOutputFormat format) const {
if (format == InputOutputFormat::STANDARD_CSV) {
return std::pair<std::string, char>(".csv", ',');
} else if (format == InputOutputFormat::STANDARD_TSV) {
return std::pair<std::string, char>(".tsv", '\t');
} else {
return std::nullopt;
}
}
template <typename T>
int Graph<T>::writeToDot(const std::string &workingDir,
const std::string &OFileName,
const std::string &graphName) const {
const std::string linkSymbol = "--";
const std::string directedLinkSymbol = "->";
const std::string completePathToFileGraph =
workingDir + '/' + OFileName + ".dot";
std::ofstream ofileGraph;
ofileGraph.open(completePathToFileGraph);
if (!ofileGraph.is_open()) {
// ERROR File Not Open
return -1;
}
// Write the header of the DOT file
std::string headerLine;
if (this->isDirectedGraph()) {
headerLine = "digraph " + graphName + " {\n";
} else {
headerLine = "graph " + graphName + " {\n";
}
ofileGraph << headerLine;
for (auto const &edgePtr : edgeSet) {
std::string edgeLine = "";
if (edgePtr->isDirected().has_value() && edgePtr->isDirected().value()) {
auto directedPtr =
std::static_pointer_cast<const DirectedEdge<T>>(edgePtr);
edgeLine += '\t' + directedPtr->getFrom().getUserId() + ' ';
edgeLine += directedLinkSymbol + ' ';
edgeLine += directedPtr->getTo().getUserId();
} else {
edgeLine += '\t' + edgePtr->getNodePair().first->getUserId() + ' ';
edgeLine += linkSymbol + ' ';
edgeLine += edgePtr->getNodePair().second->getUserId();
}
if (edgePtr->isWeighted().has_value() && edgePtr->isWeighted().value()) {
// Weights in dot files must be integers
edgeLine += " [weight=" +
std::to_string(static_cast<int>(
std::dynamic_pointer_cast<const Weighted>(edgePtr)
->getWeight())) +
']';
}
edgeLine += ";\n";
ofileGraph << edgeLine;
}
ofileGraph << '}';
ofileGraph.close();
return 0;
}
// This ctype facet classifies ',' and '\t' as whitespace
struct csv_whitespace : std::ctype<char> {
static const mask *make_table() {
// make a copy of the "C" locale table
static std::vector<mask> v(classic_table(), classic_table() + table_size);
v[','] |= space; // comma will be classified as whitespace
v['\t'] |= space;
v[' '] &= ~space; // space will not be classified as whitespace
return &v[0];
}
csv_whitespace(std::size_t refs = 0) : ctype(make_table(), false, refs) {}
};
template <typename T>
void Graph<T>::writeGraphToStream(std::ostream &oGraph, std::ostream &oNodeFeat,
std::ostream &oEdgeWeight, const char &sep,
bool writeNodeFeat,
bool writeEdgeWeight) const {
for (const auto &edge : edgeSet) {
oGraph << edge->getId() << sep << edge->getNodePair().first->getUserId()
<< sep << edge->getNodePair().second->getUserId() << sep
<< ((edge->isDirected().has_value() && edge->isDirected().value())
? 1
: 0)
<< std::endl;
}
if (writeNodeFeat) {
auto nodeSet = getNodeSet();
for (const auto &node : nodeSet) {
oNodeFeat << node->getUserId() << sep << node->getData() << std::endl;
}
}
if (writeEdgeWeight) {
for (const auto &edge : edgeSet) {
oEdgeWeight
<< edge->getId() << sep
<< (edge->isWeighted().has_value() && edge->isWeighted().value()
? (std::dynamic_pointer_cast<const Weighted>(edge))
->getWeight()