/
logkdecomp.go
445 lines (360 loc) · 11.3 KB
/
logkdecomp.go
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
//Log-K-Decomp - A research prototype to compute Hypertree Decompositions of
// Conjunctive Queries and Constraint Satisfaction Problems, using a parallel algorithm
// with logarithmic recursion depth.
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"reflect"
"runtime"
"runtime/pprof"
"time"
algo "github.com/cem-okulmus/BalancedGo/algorithms"
"github.com/cem-okulmus/BalancedGo/lib"
)
// Decomp used to improve readability
type Decomp = lib.Decomp
// Edge used to improve readability
type Edge = lib.Edge
// Graph used to improve readability
type Graph = lib.Graph
func logActive(b bool) {
if b {
log.SetOutput(os.Stderr)
log.SetFlags(0)
} else {
log.SetOutput(ioutil.Discard)
}
}
func check(e error) {
if e != nil {
panic(e)
}
}
type labelTime struct {
time float64
label string
}
func (l labelTime) String() string {
return fmt.Sprintf("%s : %.5f ms", l.label, l.time)
}
func outputStanza(algorithm string, decomp Decomp, times []labelTime, graph Graph, gml string, K int, skipCheck bool) {
decomp.RestoreSubedges()
fmt.Println("Used algorithm: " + algorithm)
fmt.Println("Result ( ran with K =", K, ")\n", decomp)
// Print the times
var sumTotal float64
for _, time := range times {
sumTotal = sumTotal + time.time
}
fmt.Printf("Time: %.5f ms\n", sumTotal)
fmt.Println("Time Composition: ")
for _, time := range times {
fmt.Println(time)
}
fmt.Println("\nWidth: ", decomp.CheckWidth())
var correct bool
if !skipCheck {
correct = decomp.Correct(graph)
} else {
correct = true
}
fmt.Println("Correct: ", correct)
if correct && len(gml) > 0 {
f, err := os.Create(gml)
check(err)
defer f.Close()
f.WriteString(decomp.ToGML())
f.Sync()
}
}
func main() {
// ==============================================
// Command-Line Argument Parsing
flagSet := flag.NewFlagSet("", flag.ContinueOnError)
flagSet.SetOutput(ioutil.Discard)
// input flags
graphPath := flagSet.String("graph", "", "input (for format see hyperbench.dbai.tuwien.ac.at/downloads/manual.pdf)")
width := flagSet.Int("width", 0, "a positive, non-zero integer indicating the width of the HD to search for")
exact := flagSet.Bool("exact", false, "Compute exact width (width flag ignored)")
// approx := flagSet.Int("approx", 0, "Compute approximated width and set a timeout in seconds (width flag ignored)")
// algorithms flags
logK := flagSet.Bool("logk", false, "Use non-hybrid LogKDecomp algorithm (not recommended)")
// logKHybrid := flagSet.Bool("logkHybrid", false, "Use DetK - LogK Hybrid algorithm. Choose non-zero values to use specific forms of hybridisation, otherwise the default one is chosen.")
// heuristic flags
heur := "1 ... Vertex Degree Ordering\n\t2 ... Max. Separator Ordering\n\t3 ... MCSO\n\t4 ... Edge Degree Ordering"
useHeuristic := flagSet.Int("heuristic", 0, "turn on to activate edge ordering\n\t"+heur)
gyö := flagSet.Bool("g", false, "perform a GYÖ reduct")
typeC := flagSet.Bool("t", false, "perform a Type Collapse")
hingeFlag := flagSet.Bool("h", false, "use hingeTree Optimization")
//other optional flags
logKHybridCustom := flagSet.Int("logkHybridCustom", 0, "Use DetK - LogK Hybrid algorithm, but non-standard form of hybridisation.")
cpuprofile := flagSet.String("cpuprofile", "", "write cpu profile to file")
logging := flagSet.Bool("log", false, "turn on extensive logs")
balanceFactorFlag := flagSet.Int("balfactor", 2, "Changes the factor that balanced separator check uses, default 2")
numCPUs := flagSet.Int("cpu", -1, "Set number of CPUs to use")
bench := flagSet.Bool("bench", false, "Benchmark mode, reduces unneeded output (incompatible with -log flag)")
gml := flagSet.String("gml", "", "Output the produced decomposition into the specified gml file ")
pace := flagSet.Bool("pace", false, "Use PACE 2019 format for graphs (see pacechallenge.org/2019/htd/htd_format/)")
meta := flagSet.Int("meta", 0, "meta parameter for LogKHybrid, to be used when choosing non-zero values in the logKHybrid flag.")
parseError := flagSet.Parse(os.Args[1:])
if parseError != nil {
fmt.Print("Parse Error:\n", parseError.Error(), "\n\n")
}
// Output usage message if graph and width not specified
if parseError != nil || *graphPath == "" || (*width <= 0 && !*exact) {
out := fmt.Sprint("Usage of log-k-decomp:")
fmt.Fprintln(os.Stderr, out)
flagSet.VisitAll(func(f *flag.Flag) {
if f.Name != "width" && f.Name != "graph" && f.Name != "exact" {
return
}
s := fmt.Sprintf("%T", f.Value) // used to get type of flag
if s[6:len(s)-5] != "bool" {
fmt.Printf(" -%-10s \t<%s>\n", f.Name, s[6:len(s)-5])
} else {
fmt.Printf(" -%-10s \n", f.Name)
}
fmt.Println("\t" + f.Usage)
})
fmt.Println("\nAlgorithm Choice: ")
flagSet.VisitAll(func(f *flag.Flag) {
if f.Name != "logk" && f.Name != "logkHybrid" {
return
}
s := fmt.Sprintf("%T", f.Value) // used to get type of flag
if s[6:len(s)-5] != "bool" {
fmt.Printf(" -%-10s \t<%s>\n", f.Name, s[6:len(s)-5])
} else {
fmt.Printf(" -%-10s \n", f.Name)
}
fmt.Println("\t" + f.Usage)
})
fmt.Println("\nOptional Arguments: ")
flagSet.VisitAll(func(f *flag.Flag) {
if f.Name == "width" || f.Name == "graph" || f.Name == "exact" || f.Name == "logkHybrid" || f.Name == "logk" {
return
}
s := fmt.Sprintf("%T", f.Value) // used to get type of flag
if s[6:len(s)-5] != "bool" {
fmt.Printf(" -%-10s \t<%s>\n", f.Name, s[6:len(s)-5])
} else {
fmt.Printf(" -%-10s \n", f.Name)
}
fmt.Println("\t" + f.Usage)
})
return
}
// END Command-Line Argument Parsing
// ==============================================
// if *exact && (*approx > 0) {
// fmt.Println("Cannot have exact and approx flags set at the same time. Make up your mind.")
// return
// }
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
if *bench { // no logging output when running benchmarks
*logging = false
}
logActive(*logging)
BalFactor := *balanceFactorFlag
runtime.GOMAXPROCS(*numCPUs)
dat, err := ioutil.ReadFile(*graphPath)
check(err)
var parsedGraph Graph
if !*pace {
parsedGraph, _ = lib.GetGraph(string(dat))
} else {
parsedGraph = lib.GetGraphPACE(string(dat))
}
originalGraph := parsedGraph
if !*bench { // skip any output if bench flag is set
log.Println("BIP: ", parsedGraph.GetBIP())
}
var reducedGraph Graph
var times []labelTime
// Sorting Edges to find separators faster
if *useHeuristic > 0 {
var heuristicMessage string
start := time.Now()
switch *useHeuristic {
case 1:
parsedGraph.Edges = lib.GetDegreeOrder(parsedGraph.Edges)
heuristicMessage = "Using degree ordering as a heuristic"
break
case 2:
parsedGraph.Edges = lib.GetMaxSepOrder(parsedGraph.Edges)
heuristicMessage = "Using max separator ordering as a heuristic"
break
case 3:
parsedGraph.Edges = lib.GetMSCOrder(parsedGraph.Edges)
heuristicMessage = "Using MSC ordering as a heuristic"
break
case 4:
parsedGraph.Edges = lib.GetEdgeDegreeOrder(parsedGraph.Edges)
heuristicMessage = "Using edge degree ordering as a heuristic"
break
}
d := time.Now().Sub(start)
msec := d.Seconds() * float64(time.Second/time.Millisecond)
times = append(times, labelTime{time: msec, label: "Heuristic"})
if !*bench {
fmt.Println(heuristicMessage)
fmt.Printf("Time for heuristic: %.5f ms\n", msec)
fmt.Printf("Ordering: %v\n", parsedGraph.String())
}
}
var removalMap map[int][]int
// Performing Type Collapse
if *typeC {
count := 0
reducedGraph, removalMap, count = parsedGraph.TypeCollapse()
parsedGraph = reducedGraph
if !*bench { // be silent when benchmarking
fmt.Println("\n\n", *graphPath)
fmt.Println("Graph after Type Collapse:")
for _, e := range reducedGraph.Edges.Slice() {
fmt.Printf("%v %v\n", e, Edge{Vertices: e.Vertices})
}
fmt.Print("Removed ", count, " vertex/vertices\n\n")
}
}
var ops []lib.GYÖReduct
// Performing GYÖ reduction
if *gyö {
if *typeC {
reducedGraph, ops = reducedGraph.GYÖReduct()
} else {
reducedGraph, ops = parsedGraph.GYÖReduct()
}
parsedGraph = reducedGraph
if !*bench { // be silent when benchmarking
fmt.Println("Graph after GYÖ:")
fmt.Println(reducedGraph)
fmt.Println("Reductions:")
fmt.Print(ops, "\n\n")
}
}
var hinget lib.Hingetree
var msecHinge float64
if *hingeFlag {
startHinge := time.Now()
hinget = lib.GetHingeTree(parsedGraph)
dHinge := time.Now().Sub(startHinge)
msecHinge = dHinge.Seconds() * float64(time.Second/time.Millisecond)
times = append(times, labelTime{time: msecHinge, label: "Hingetree"})
if !*bench {
fmt.Println("Produced Hingetree: ")
fmt.Println(hinget)
}
}
var solver algo.Algorithm
// Check for multiple flags
chosen := 0
// LogkHybrid Default
if !*logK && *logKHybridCustom == 0 {
logKHyb := LogKHybrid{
Graph: parsedGraph,
K: *width,
BalFactor: BalFactor,
}
logKHyb.Size = 300 // use the default case
var pred HybridPredicate
pred = logKHyb.ETimesKDivAvgEdgePred // use the default method
logKHyb.Predicate = pred // set the predicate to use
solver = &logKHyb
chosen++
}
if *logK {
logK := LogKDecomp{
Graph: parsedGraph,
K: *width,
BalFactor: BalFactor,
}
solver = &logK
chosen++
}
// LogkHybrid Custom - To be used if you know what you are doing
if *logKHybridCustom > 0 {
logKHyb := LogKHybrid{
Graph: parsedGraph,
K: *width,
BalFactor: BalFactor,
}
logKHyb.Size = *meta
var pred HybridPredicate
switch *logKHybridCustom {
case 1:
pred = logKHyb.NumberEdgesPred
case 2:
pred = logKHyb.SumEdgesPred
case 3:
pred = logKHyb.ETimesKDivAvgEdgePred
case 4:
pred = logKHyb.OneRoundPred
}
logKHyb.Predicate = pred // set the predicate to use
solver = &logKHyb
chosen++
}
if chosen > 1 {
fmt.Println("Only one algorithm may be chosen at a time. Make up your mind.")
return
}
if solver != nil {
solver.SetGenerator(lib.ParallelSearchGen{})
var decomp Decomp
start := time.Now()
if *exact {
solved := false
k := 1
for ; !solved; k++ {
solver.SetWidth(k)
if *hingeFlag {
decomp = hinget.DecompHinge(solver, parsedGraph)
} else {
decomp = solver.FindDecomp()
}
solved = decomp.Correct(parsedGraph)
}
*width = k - 1 // for correct output
} else {
if *hingeFlag {
decomp = hinget.DecompHinge(solver, parsedGraph)
} else {
decomp = solver.FindDecomp()
}
}
d := time.Now().Sub(start)
msec := d.Seconds() * float64(time.Second/time.Millisecond)
times = append(times, labelTime{time: msec, label: "Decomposition"})
if !reflect.DeepEqual(decomp, Decomp{}) || (len(ops) > 0 && parsedGraph.Edges.Len() == 0) {
var result bool
decomp.Root, result = decomp.Root.RestoreGYÖ(ops)
if !result {
fmt.Println("Partial decomp:", decomp.Root)
log.Panicln("GYÖ reduction failed")
}
decomp.Root, result = decomp.Root.RestoreTypes(removalMap)
if !result {
fmt.Println("Partial decomp:", decomp.Root)
log.Panicln("Type Collapse reduction failed")
}
}
if !reflect.DeepEqual(decomp, Decomp{}) {
decomp.Graph = originalGraph
}
outputStanza(solver.Name(), decomp, times, originalGraph, *gml, *width, false)
return
}
fmt.Println("No algorithm or procedure selected.")
}