GCG 4.1.1 (dev)

Generic Column Generation

Loading...
Searching...
No Matches
graphalgorithms_def.h
Go to the documentation of this file.
1/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2/* */
3/* This file is part of the program and library */
4/* GCG --- Generic Column Generation */
5/* a Dantzig-Wolfe decomposition based extension */
6/* of the branch-cut-and-price framework */
7/* SCIP --- Solving Constraint Integer Programs */
8/* */
9/* Copyright (C) 2010-2026 Operations Research, RWTH Aachen University */
10/* Zuse Institute Berlin (ZIB) */
11/* */
12/* Licensed under the Apache License, Version 2.0 (the "License"); */
13/* you may not use this file except in compliance with the License. */
14/* You may obtain a copy of the License at */
15/* */
16/* http://www.apache.org/licenses/LICENSE-2.0 */
17/* */
18/* Unless required by applicable law or agreed to in writing, software */
19/* distributed under the License is distributed on an "AS IS" BASIS, */
20/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
21/* See the License for the specific language governing permissions and */
22/* limitations under the License. */
23/* */
24/* You should have received a copy of the Apache-2.0 license */
25/* along with GCG; see the file LICENSE. If not visit gcg.or.rwth-aachen.de.*/
26/* */
27/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
28
29/**@file graphalgorithms_def.h
30 * @brief several metrics for graphs
31 * @author Martin Bergner
32 */
33
34/*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/
35
36#ifndef GCG_GRAPHALGORITHMS_DEF_H_
37#define GCG_GRAPHALGORITHMS_DEF_H_
38
40#include <vector>
41#include <algorithm>
42#include <map>
43#include <iostream>
44#include <stdlib.h>
45#include "graph/graph_tclique.h"
46#include "graph/graph_gcg.h"
47
48
49using std::vector;
50
51
52namespace gcg {
53
54template <typename T>
56
57
58/** compute weighted sum of external degrees */
59template<class T>
61 Hypergraph<T>& graph /**< the hypergraph */
62)
63{
64 SCIP_Real soed = 0.0;
65 size_t nedges = graph.getNHyperedges();
66 vector<int> partition = vector<int>(graph.getPartition());
67
68 for( size_t i = 0; i < nedges; ++i )
69 {
70 vector<int> nodes = graph.getHyperedgeNodes((int)i);
71 for( auto &it : nodes)
72 {
73 it = partition[it];
74 }
75 auto end = std::unique(nodes.begin(), nodes.end());
76 if( end - nodes.begin() > 1)
77 soed += ( end - nodes.begin())*graph.getHyperedgeWeight((int)i);
78 }
79 return soed;
80}
81
82/** compute minimum hyperedge cut */
83template<class T>
85 Hypergraph<T>& graph /**< the hypergraph */
86)
87{
88 SCIP_Real mincut = 0.0;
89 size_t nedges = graph.getNHyperedges();
90 vector<int> partition = vector<int>(graph.getPartition());
91
92 for( size_t i = 0; i < nedges; ++i )
93 {
94 vector<int> nodes = graph.getHyperedgeNodes((int)i);
95 for( auto &it : nodes)
96 {
97 it = partition[it];
98 }
99 auto end = std::unique(nodes.begin(), nodes.end());
100
101 if( end - nodes.begin() > 1)
102 mincut += graph.getHyperedgeWeight((int)i);
103 }
104
105 return mincut;
106}
107
108/** compute k-1 metric */
109template<class T>
111 Hypergraph<T>& graph /**< the hypergraph */
112)
113{
114 SCIP_Real kmetric = 0.0;
115 size_t nedges = graph.getNHyperedges();
116 vector<int> partition = vector<int>(graph.getPartition());
117
118 for( size_t i = 0; i < nedges; ++i )
119 {
120 vector<int> nodes = graph.getHyperedgeNodes((int)i);
121 for( auto &it : nodes)
122 {
123 it = partition[it];
124 }
125 auto end = std::unique(nodes.begin(), nodes.end());
126
127 kmetric += ( end - nodes.begin() -1)*graph.getHyperedgeWeight((int)i);
128 }
129
130 return kmetric;
131}
132
133
134/** run DBSCAN on the distance graph */
135template<class T>
137 Graph<GraphGCG>& graph, /**< the graph with weighted edges */
138 double eps, /**< radius in which we search for the neighbors */
139 int minPts /**< minimum number of neighbors needed to define a core point (can be fixed to 4 as stated in the paper) */
140)
141{
142
143 int n_nodes = graph.getNNodes();
144 std::vector<bool> visited(n_nodes, false);
145 std::vector<bool> is_core(n_nodes, false);
146 std::vector<int> labels(n_nodes, -1);
147 int curr_cluster = -1;
148
149 // visit all the points and check for the core points
150 for(int i = 0; i < n_nodes; i++)
151 {
152 if(visited[i])
153 {
154 continue;
155 }
156 visited[i] = true;
157
158 // check if i is a core point
159 std::vector<std::pair<int, double> > NeighborPts_row = graph.getNeighborWeights(i); // gets ALL connected points
160 std::vector<int> NeighborPts; // holds ONLY the neighbors within the radius
161 for(int j = 0; j < (int)NeighborPts_row.size(); j++)
162 {
163 if(NeighborPts_row[j].second <= eps)
164 {
165 NeighborPts.push_back(NeighborPts_row[j].first);
166 }
167
168 }
169 if((int)NeighborPts.size() < minPts)
170 {
171 labels[i] = -1; // mark point as noise
172 }
173 else {
174 curr_cluster++;
175 expandCluster(graph, visited, is_core, labels, i, NeighborPts, curr_cluster, eps, minPts);
176 }
177 }
178
179 // Add border points also. We assign the border point the same label as the first core point. This is basically arbitrary, but not random.
180 for(int i = 0; i < n_nodes; i++)
181 {
182 if(is_core[i])
183 {
184 continue;
185 }
186 std::vector<std::pair<int, double> > NeighborPts_row = graph.getNeighborWeights(i); // gets ALL connected points // holds ONLY the neighbors within the radius
187 for(int j = 0; j < (int)NeighborPts_row.size(); j++)
188 {
189 if(NeighborPts_row[j].second <= eps && is_core[NeighborPts_row[j].first])
190 {
191 labels[i] = labels[NeighborPts_row[j].first];
192 break;
193 }
194 }
195 }
196
197 return labels;
198}
199
200/** help function for DBSCAN */
201template<class T>
203 Graph<T>& graph,
204 std::vector<bool>& visited,
205 std::vector<bool>& is_core,
206 std::vector<int>& labels,
207 int point,
208 std::vector<int>& NeighborPts,
209 int curr_cluster,
210 double eps,
211 int minPts
212)
213{
214 // add P to cluster C
215 labels[point] = curr_cluster;
216 is_core[point] = true;
217
218 // for each point P' in NeighborPts
219 for(int i = 0; i < (int)NeighborPts.size(); i++)
220 {
221 int neighbor = NeighborPts[i];
222 // if P' is not visited {
223 if(!visited[neighbor])
224 {
225 // mark P' as visited
226 visited[neighbor] = true;
227 // NeighborPts' = regionQuery(P', eps)
228 std::vector<std::pair<int, double> > NeighborPts_tmp_row = graph.getNeighborWeights(neighbor); // gets ALL connected points
229 std::vector<int> NeighborPts_tmp; // holds ONLY the neighbors within the radius
230 for(int j = 0; j < (int)NeighborPts_tmp_row.size(); j++)
231 {
232 if(NeighborPts_tmp_row[j].second <= eps)
233 {
234 NeighborPts_tmp.push_back(NeighborPts_tmp_row[j].first);
235 }
236
237 }
238 if((int)NeighborPts_tmp.size() >= minPts)
239 {
240 // NeighborPts = NeighborPts joined with NeighborPts'
241 NeighborPts.insert(NeighborPts.end(), NeighborPts_tmp.begin(), NeighborPts_tmp.end());
242 }
243
244 }
245
246 // if P' is not yet member of any cluster
247 // add P' to cluster C
248 if(labels[neighbor] < 0)
249 {
250 labels[neighbor] = curr_cluster;
251 is_core[neighbor] = true;
252 }
253 }
254}
255
256/*
257 * template<class T>
258 * std::vector<int> GraphAlgorithms<T>::mst(
259 */
260template<class T>
261std::vector<int> GraphAlgorithms<T>::mst(
262 Graph<GraphGCG>& graph, /**< the graph with weighted edges */
263 double _cutoff, /**< threshold below which we cut the edges */
264 int minPts /**< minimum number of points needed in a cluster */
265)
266{
267 cutoff = _cutoff;
268 // Step 1: find a minimum spanning tree using Kruskal's algorithm
269
270 int nnodes = graph.getNNodes();
271 std::vector<void*> edges(graph.getNEdges());
272 graph.getEdges(edges);
273
274 vector<EdgeGCG> resultMST(nnodes-1);
275 int e = 0; // An index variable, used for resultMST
276 unsigned int j = 0; // An index variable, used for sorted edges
277
278 // Step 1: Sort all the edges in non-decreasing order of their weight
279 // If we are not allowed to change the given graph, we can create a copy of
280 // array of edges
281 sort(edges.begin(), edges.end(), weightComp);
282
283 // Create V subsets (one for each node)
284 vector<subset> subsetsmst(nnodes);
285
286 // Create V subsets with single elements
287 for (int v = 0; v < nnodes; ++v)
288 {
289 subsetsmst[v].parent = v;
290 subsetsmst[v].rank = 0;
291 }
292
293 // Number of edges to be taken is equal to V-1
294 while (e < nnodes - 1)
295 {
296 // Step 2: Pick the smallest edge. And increment the index
297 // for next iteration
298 if(j == edges.size()) break;
299 EdgeGCG next_edge = *(EdgeGCG *)(edges[j++]);
300 assert(next_edge.src < graph.getNNodes());
301 assert(next_edge.dest < graph.getNNodes());
302
303 int x = mstfind(subsetsmst, next_edge.src); // O(tree height)
304 int y = mstfind(subsetsmst, next_edge.dest);
305
306 // If including this edge does't cause cycle, include it
307 // in result and increment the index of result for next edge
308 if (x != y)
309 {
310 resultMST[e++] = next_edge;
311 mstunion(subsetsmst, x, y);
312 }
313 // Else discard the next_edge
314 }
315
316 resultMST.resize(e);
317
318 // Step 2: remove all the edges from the MST that are greater or equal to cutoff
319
320 //std::vector<EdgeGCG> resultDBG = resultMST;
321 resultMST.erase(std::remove_if(resultMST.begin(), resultMST.end(), cutoffif), resultMST.end());
322 // Step 3: use find-union to find the graph components
323
324 // saves the component labels (i.e. cluster labels)
325 std::vector<int> labels(nnodes, -1);
326
327 // Create V subsets (one for each node)
328 std::vector<subset> subsetscomp(nnodes);
329
330 // Create V subsets with single elements
331 for (int v = 0; v < nnodes; ++v)
332 {
333 subsetscomp[v].parent = v;
334 subsetscomp[v].rank = 0;
335 }
336
337
338 // iterate all the edges and assign its nodes to the root node of the set
339 for(unsigned int edge_it = 0; edge_it < resultMST.size(); edge_it++)
340 {
341 auto edge = resultMST[edge_it];
342 /*if(!(edge.src < graph.getNNodes()) || !(edge.dest < graph.getNNodes())){
343 cout << "DEBUG ME!!!" << endl;
344 }*/
345 assert(edge.src < graph.getNNodes());
346 assert(edge.dest < graph.getNNodes());
347 // if the nodes are directly connected, put them in the same set
348 mstunion(subsetscomp, edge.src, edge.dest);
349 }
350
351 for(int i = 0; i < nnodes; i++)
352 {
353 labels[i] = mstfind(subsetscomp, i);
354 }
355
356
357 // remove the clusters that are smaller than minPts
358 std::map<int,int> labelcount;
359 for(int i = 0; i < nnodes; i++)
360 {
361 labelcount[labels[i]]++;
362 }
363
364 for(int i = 0; i < nnodes; i++)
365 {
366 if(labelcount[labels[i]] < minPts)
367 labels[i] = -1;
368 }
369
370
371 // reassign the labels so that they start from 0 (actually this is done in postProcess, so we can skip this part here)
372
373
374 return labels;
375}
376
377
378template<class T>
380{
381 return a.weight > cutoff;
382}
383
384
385// Compare two edges according to their weights.
386// Used in sort() for sorting an array of edges
387template<class T>
388int GraphAlgorithms<T>::weightComp(const void* a, const void* b)
389{
390 const EdgeGCG* a1 = static_cast<const EdgeGCG*>(a);
391 const EdgeGCG* b1 = static_cast<const EdgeGCG*>(b);
392 return a1->weight < b1->weight;
393}
394
395
396// A utility function to find set of an element i
397// (uses path compression technique)
398template<class T>
399int GraphAlgorithms<T>::mstfind(std::vector<subset>& subsets, int i)
400{
401 // find root and make root as parent of i (path compression)
402 if (subsets[i].parent != i)
403 subsets[i].parent = mstfind(subsets, subsets[i].parent);
404
405 return subsets[i].parent;
406}
407
408
409// A function that does union of two sets of x and y
410// (uses union by rank)
411template<class T>
412void GraphAlgorithms<T>::mstunion(std::vector<subset>& subsets, int x, int y)
413{
414 int xroot = mstfind(subsets, x);
415 int yroot = mstfind(subsets, y);
416
417 // Attach smaller rank tree under root of high rank tree
418 // (Union by Rank)
419 if (subsets[xroot].rank < subsets[yroot].rank)
420 subsets[xroot].parent = yroot;
421 else if (subsets[xroot].rank > subsets[yroot].rank)
422 subsets[yroot].parent = xroot;
423
424 // If ranks are same, then make one as root and increment
425 // its rank by one
426 else
427 {
428 subsets[yroot].parent = xroot;
429 subsets[xroot].rank++;
430 }
431}
432
433
434template<class T>
435std::vector<int> GraphAlgorithms<T>::mcl(
436 Graph<GraphGCG>& graph, /**< the graph with weighted edges */
437 int& stoppedAfter, /**< number of iterations after which the clustering terminated */
438 double inflatefac, /**< inflate factor */
439 int maxiters, /**< max number of iterations, set to 25 per default */
440 int expandfac /**< expand factor, should be always set to 2 */
441)
442{
443#ifdef WITH_GSL
444 graph.initMCL();
445 graph.colL1Norm();
446 graph.prune();
447
448 int i = 0;
449 for(; i < maxiters; i++)
450 {
451 graph.inflate(inflatefac);
452 graph.expand(expandfac);
453 graph.prune();
454
455 if(graph.stopMCL(i))
456 {
457 break;
458 }
459 }
460 assert(i > 6);
461 stoppedAfter = i;
462
463 std::vector<int> res = graph.getClustersMCL();
464 graph.clearMCL();
465 return res;
466#else
467 return vector<int>();
468#endif
469}
470
471
472
473
474} /* namespace gcg */
475#endif
SCIP_VAR * a
SCIP_VAR ** b
SCIP_VAR ** y
SCIP_VAR ** x
double weight
Definition graph_gcg.h:53
static SCIP_Real computeMincut(Hypergraph< T > &graph)
static std::vector< int > mst(Graph< GraphGCG > &graph, double cutoff, int minPts=4)
static bool cutoffif(EdgeGCG &a)
static int weightComp(const void *a, const void *b)
static std::vector< int > mcl(Graph< GraphGCG > &graph, int &stoppedAfter, double inflatefac, int maxiters=25, int expandfac=2)
static SCIP_Real computekMetric(Hypergraph< T > &graph)
static SCIP_Real computeSoed(Hypergraph< T > &graph)
static void mstunion(std::vector< subset > &subsets, int x, int y)
static int mstfind(std::vector< subset > &subsets, int i)
static std::vector< int > dbscan(Graph< GraphGCG > &graph, double eps, int minPts=4)
static void expandCluster(Graph< T > &graph, std::vector< bool > &visited, std::vector< bool > &is_core, std::vector< int > &labels, int point, std::vector< int > &NeighborPts, int curr_cluster, double eps, int minPts)
virtual std::vector< int > getPartition() const
SCIP_RETCODE getEdges(std::vector< void * > &edges)
Definition graph_def.h:85
int getNNodes()
Definition graph_def.h:75
int getNEdges()
Definition graph_def.h:80
std::vector< std::pair< int, double > > getNeighborWeights(int i)
Definition graph_def.h:273
std::vector< int > getHyperedgeNodes(int i)
int getHyperedgeWeight(int i)
#define SCIP_Real
Implementation of the graph which supports both node and edge weights.
interface to the SCIP tclique graph library
several metrics for graphs
static assert(heur !=NULL)
int j
int i
SCIP_Longint nnodes
real eps