-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
585 lines (495 loc) · 15.4 KB
/
main.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
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
package main
import (
"flag"
"fmt"
"math/rand"
"sort"
"time"
. "github.com/athorp96/graphs"
)
// if somehow I need to change how this is checked, this provides an interface
type fitnessEvaluator func(*Undirected, []int) int
// A rerecombination is a function that somehow constructs a child Hamiltonian
// from two other Hamiltonians.
type recombination func(*Hamiltonian, *Hamiltonian, *Undirected) *Hamiltonian
// Hamiltonian is a hamiltonian cycle.
// it consists of a cycle and a fitness grade
// the lower the fitness, the shorter the cycle
type Hamiltonian struct {
// the path
path []int
// The optimitality of the solution
// The lower the number the shorter the path
fitness float64
}
func main() {
// default values
defualtPopulation := 50
defualtGenerations := 100
defaultBias := 0.5
// declare input variables
var filepath string
var populationSize int
var generations int
var bias float64
var connected bool
var quiet bool
// declare flags
flag.StringVar(&filepath, "f", "data/sgb128/sgb128.dat", "Path to the .wdat graph file")
flag.IntVar(&populationSize, "p", defualtPopulation, "Population size")
flag.IntVar(&generations, "g", defualtGenerations, "Number of generations to run")
flag.Float64Var(&bias, "b", defaultBias, "Fitness bias for parent selection, a number between zero and one **Currently does nothing**")
flag.BoolVar(&connected, "c", true, "Whether or not the graph is connected: adds a linear speedup since children don't need to be checked that they are a cycle.")
flag.BoolVar(&quiet, "v", true, "Verbose mode: Outputs percent completion")
play := flag.Bool("cascade", false, "Sweep along many different population and genreatio sizes")
// parse flags
flag.Parse()
rand.Seed(time.Now().Unix())
if !*play {
if connected {
ConnectedGentior(filepath, populationSize, generations, bias, quiet)
} else {
Gentior(filepath, populationSize, generations, bias, quiet)
}
} else {
// population size
ConcurrentGentior(filepath, populationSize, generations, bias, quiet)
}
}
func Gentior(filepath string, populationSize, generations int, bias float64, quiet bool) {
// Create graph and population
graph := NewWeightedGraphFromFile(filepath)
population := generatepopulation(graph, populationSize)
// genetically develop good solutions (hopefully)
for i := 0; i < generations; i++ {
parents := selectParents(len(population), bias)
pop := population[parents[0]]
mom := population[parents[1]]
child := edgeRecombination(pop, mom, graph)
population = reconstructPopulation(population, child)
if !quiet {
printProgress(i, generations)
}
}
fmt.Println()
fmt.Println("-------------------- Results -------------------- ")
fmt.Printf("Shortest path:\t%d\n\n", population[0].fitness)
fmt.Printf("Solution: %v\n", population[0].path)
fmt.Println("------------------------------------------------- ")
}
func printProgress(i, n int) {
percent := float64(i) / float64(n)
percent *= 100
fmt.Println("\033[H\033[2J")
fmt.Printf("%d%% \n", int(percent))
}
func ConnectedGentior(filepath string, populationSize, generations int, bias float64, quiet bool) {
start := time.Now()
// Create graph and population
graph := NewWeightedGraphFromFile(filepath) //O(n)
population := generatepopulation(graph, populationSize) //O(p)
// genetically develop good solutions (hopefully)
for i := 0; i < generations; i++ { // O(n)
parents := selectParents(len(population), bias) // O(1)
pop := population[parents[0]] // O(1)
mom := population[parents[1]] // O(1)
child := connectedEdgeRecombination(pop, mom, graph) // O(n)
population = reconstructPopulation(population, child) // O(logn)
if !quiet {
printProgress(i, generations)
}
}
elapsed := time.Now().Sub(start)
fmt.Println()
fmt.Println("---------------------- Results ---------------------- ")
fmt.Printf("Population: \t%d\t\tGenerations: \t%d\n", populationSize, generations)
fmt.Printf("Shortest path:\t%.2f\tTime: %v\n\n", population[0].fitness, elapsed)
fmt.Printf("Solution: %v\n", population[0].path)
fmt.Println("----------------------------------------------------- ")
}
func ConcurrentGentior(filepath string, populationSize, generations int, bias float64, quiet bool) {
// Create graph and population
graph := NewWeightedGraphFromFile(filepath)
results := make(chan string)
numRoutines := 0
for i := 100; i < 1000; i += 100 {
// generations
for j := i; j < 1000000; j += 1000 {
go ConcurrentGentiorBeef(graph, i, j, bias, results)
numRoutines++
}
}
fmt.Println()
fmt.Println("---------------------- Results ---------------------- ")
for i := 0; i < numRoutines; i++ {
fmt.Println(<-results)
}
fmt.Println("----------------------------------------------------- ")
}
func ConcurrentGentiorBeef(graph *Undirected, populationSize, generations int, bias float64, report chan string) {
population := generatepopulation(graph, populationSize)
// genetically develop good solutions (hopefully)
for i := 0; i < generations; i++ {
parents := selectParents(len(population), bias)
pop := population[parents[0]]
mom := population[parents[1]]
child := connectedEdgeRecombination(pop, mom, graph)
population = reconstructPopulation(population, child)
}
results := fmt.Sprintf("Population: \t%d\t\tGenerations: \t%d\n", populationSize, generations)
results += fmt.Sprintf("Shortest path:\t%d\n\n", population[0].fitness)
results += fmt.Sprintf("Sholution: %v\n", population[0].path)
report <- results
}
func reconstructPopulation(population []Hamiltonian, offspring *Hamiltonian) []Hamiltonian {
return binaryInsert(*offspring, population)
}
// Insert inserts an element into the list, maintaining the size
func binaryInsert(el Hamiltonian, data []Hamiltonian) []Hamiltonian {
index := sort.Search(len(data), func(i int) bool { return data[i].fitness > el.fitness })
data = append(data, Hamiltonian{})
copy(data[index+1:], data[index:])
data[index] = el
return data[:len(data)-1]
}
// Add inserts an element into the list, increasing the size
func binaryAdd(el Hamiltonian, data []Hamiltonian) []Hamiltonian {
index := sort.Search(len(data), func(i int) bool { return data[i].fitness > el.fitness })
data = append(data, Hamiltonian{})
copy(data[index+1:], data[index:])
data[index] = el
return data
}
func edgeRecombination(pop Hamiltonian, mom Hamiltonian, g *Undirected) *Hamiltonian {
numVertices := g.Order()
edgeList := getEdgeList(pop, mom)
child := new(Hamiltonian)
attemptCount := 0
maxAttempts := 6000
for pathFound := false; !pathFound; attemptCount++ {
// if you've tried n times with no successful child, adopt a new child
if attemptCount == maxAttempts {
child = makeZeroPath(g)
return child
}
start := 0
// random Start
start = rand.Intn(numVertices)
child.path = []int{}
visited := make([]bool, numVertices)
for i, m := 0, start; i < numVertices && m >= 0; i++ {
rand.Seed(rand.Int63())
visited[m] = true
child.path = append(child.path, m)
// get next index
nextEdge := smallestAdjecency(m, edgeList, visited)
if nextEdge >= 0 {
m = nextEdge
} else {
m = getUnvisitedEdge(m, visited, g)
}
}
if len(child.path) == numVertices && isCycle(g, child.path) {
pathFound = true
child.fitness = fitness(g, child.path)
}
}
return child
}
func connectedEdgeRecombination(pop Hamiltonian, mom Hamiltonian, g *Undirected) *Hamiltonian {
numVertices := g.Order()
edgeList := getEdgeList(pop, mom)
child := new(Hamiltonian)
attemptCount := 0
maxAttempts := 6000
for pathFound := false; !pathFound; attemptCount++ {
// if you've tried n times with no successful child, adopt a new child
if attemptCount == maxAttempts {
child = makeZeroPath(g)
return child
}
start := 0
// random Start
start = rand.Intn(numVertices)
child.path = []int{}
visited := make([]bool, numVertices)
for i, m := 0, start; i < numVertices && m >= 0; i++ {
rand.Seed(rand.Int63())
visited[m] = true
child.path = append(child.path, m)
// get next index
nextEdge := smallestAdjecency(m, edgeList, visited)
if nextEdge >= 0 {
m = nextEdge
} else {
m = getUnvisitedEdge(m, visited, g)
}
}
if len(child.path) == numVertices {
pathFound = true
child.fitness = fitness(g, child.path)
}
}
return child
}
// getUnvisitedEdgeaccepts an edge, a list of visited edges, and a graph.
// it returns a random, unvisited, adjecent vertex. If no such edge exists
// the method returns -1
func getUnvisitedEdge(current int, visited []bool, g *Undirected) int {
adjecents := g.GetEdges(current)
unvisited := []int{}
for _, n := range adjecents {
if !visited[n] {
unvisited = append(unvisited, n)
}
}
if len(unvisited) > 0 {
return unvisited[rand.Intn(len(unvisited))]
} else {
return -1
}
}
// getEdgeList takes in two hamiltonian cycles. It builds a list of
// neighbors based on what vertices are neighbors in each cycle.
// if pop = (0 1 2 3 4 5) and mom = (1 2 3 5 0 4), the list will return
// 0 : (1 4 5)
// 1 : (0 2 4)
// 2 : (1 3)
// 3 : (2 4 5)
// 4 : (0 1 3 5)
// 5 : (0 3 4)
func getEdgeList(pop Hamiltonian, mom Hamiltonian) [][]int {
numEdges := len(pop.path)
edgeList := make([][]int, numEdges)
// build edge list
for i, n := range pop.path {
last := i - 1
if last < 0 {
last = numEdges - 1
}
next := (i + 1) % len(edgeList)
edgeList[n] = insert(pop.path[last], edgeList[n])
edgeList[n] = insert(pop.path[next], edgeList[n])
}
for i, n := range mom.path {
last := i - 1
if last < 0 {
last = numEdges - 1
}
next := (i + 1) % len(edgeList)
edgeList[n] = insert(mom.path[last], edgeList[n])
edgeList[n] = insert(mom.path[next], edgeList[n])
}
return edgeList
}
// insert will append an element into a list if that element
// does not currently exist in the list. Used to ensure there are no
// repeated numbers in adjecency lists (introducing edge bias)
func insert(n int, list []int) []int {
if len(list) == 0 {
list = []int{n}
} else {
for _, m := range list {
if m == n {
return list
}
}
list = append(list, n)
}
return list
}
// smallestAdjecency finds the lowest degree unvisited edge adjecent to the current edge
// if no adjecent edges are unvisited, the function returns -1
func smallestAdjecency(current int, edges [][]int, visited []bool) int {
// building list of unvisited
possibles := []int{}
for _, n := range edges[current] {
if !visited[n] {
possibles = append(possibles, n)
}
}
smallIndex := -1
smallVal := -1
// search for smallest unvisisted node
for i, n := range possibles {
// if we are starting the list or we've found a smaller vertex, replace it
if smallIndex < 0 || len(edges[n]) < len(edges[smallVal]) {
smallIndex = i
smallVal = n
// Or if we have found the same degree vertex, randomly replace it
} else if len(edges[n]) == len(edges[smallVal]) && (rand.Int()%2 == 0) {
smallIndex = i
smallVal = n
}
}
return smallVal
}
func showPopulation(population []Hamiltonian) {
fmt.Println("Population: ")
for _, h := range population {
fmt.Printf("%v\n", h)
}
}
func selectParents(populationSize int, bias float64) []int {
return betterParents(populationSize, bias)
}
func randomParents(populationSize int, bias float64) []int {
// Select at Random
// TODO implement bias
mom := rand.Intn(populationSize)
pop := rand.Intn(populationSize)
// ensure parents are different
for mom == pop {
pop = rand.Intn(populationSize)
}
parentList := []int{pop, mom}
return parentList
}
func betterParents(populationSize int, bias float64) []int {
// Select at Random
// TODO implement bias
mom := betterRand(populationSize, bias)
pop := betterRand(populationSize, bias)
// ensure parents are different
for mom == pop {
pop = betterRand(populationSize, bias)
}
parentList := []int{pop, mom}
return parentList
}
func betterRand(max int, bias float64) int {
// chose two indices
n1 := rand.Intn(max)
n2 := rand.Intn(max)
// return the lesser of the two
if n1 < n2 {
return n1
} else {
return n2
}
}
//TODO?
func applyBias(i int, max int, b float64) int {
//probabilities := make(
n := randomBias(i, b)
if n > max {
return max
} else {
return n
}
}
//TODO?
func randomBias(i int, b float64) int {
return -1
}
func makeRandomPath(g *Undirected) *Hamiltonian {
tour := new(Hamiltonian)
tour.path = rand.Perm(g.Order())
tour.fitness = fitness(g, tour.path)
return tour
}
func generatepopulation(g *Undirected, populationSize int) []Hamiltonian {
population := make([]Hamiltonian, 0, populationSize)
for i := 0; i < populationSize; i++ {
path := makeRandomPath(g)
population = binaryAdd(*path, population)
}
return population
}
// makeZeroPath makes a path that starts at zero.
// It finds goal using a depth first search.
// and returns a path object
func makeZeroPath(g *Undirected) *Hamiltonian {
p := new(Hamiltonian)
//v := rand.Intn(g.Order())
//edges := g.GetEdges(v)
// initialize random walk path
path := randomDFS(0, g)
p.path = path
p.fitness = fitness(g, path)
return p
}
// randomDFS uses dfs to randomly search a graph for a goal.
// it is the master function and should
func randomDFS(vertex int, g *Undirected) []int {
visited := make([]bool, g.Order())
path, found := dfs(vertex, vertex, visited, 0, []int{}, g)
if !found {
fmt.Println("No possible Hamiltonian Cycle")
panic(fmt.Sprint(""))
} else {
return path
}
}
// dfsa is the helper function to randomDFS and should not
// be called directly.
//
// dfs takes in a current vertex, the goal vertex,
// an array of visited vertices, the depth of the search,
// and a graph.
//
// dfs recursivley searches the graph for the goal.
//
// @return the path taken by the recursive calls
// @return whether or not the goal was found
func dfs(current int, goal int, visited []bool, depth int, soFar []int, g *Undirected) ([]int, bool) {
// base case
if current == goal && depth == g.Order() {
return []int{}, true
} else {
visited[current] = true
}
edges := g.GetEdges(current)
// starting at a random index, iterate over edges, looping over the end
firstIteration := true
for i, j := rand.Intn(len(edges)), -1; firstIteration || i != j; i = (i + 1) % len(edges) {
// ensure i can't get back to j
if firstIteration {
firstIteration = false
j = i
}
// if at correct depth and adjecent to the goal, return success
if len(visited)-1 == depth {
for _, n := range edges {
if n == goal {
return []int{current}, true
}
}
}
// if the the has not been visited OR the next edge is not the goal (unless it is at the coorect depth
if !visited[edges[i]] || (depth >= len(visited) && edges[i] == goal) {
// copy visited array
visitedCopy := make([]bool, len(visited))
copy(visitedCopy, visited)
// visit that edge
path, found := dfs(edges[i], goal, visitedCopy, depth+1, append(soFar, current), g)
if found {
return append([]int{current}, path...), found
}
}
}
return nil, false
}
// A fitness evaluator
// Returns the sum weight of the walk
func fitness(g *Undirected, walk []int) float64 {
length := 0.0
for i := 0; i < len(walk); i++ {
n := (i + 1) % len(walk)
length += g.Weight(walk[i], walk[n])
}
return length
}
// determines if a walk is a cycle
// by ensuring that every sequential vertex is
// connected.
func isCycle(g *Undirected, walk []int) bool {
cycle := true
length := len(walk)
for i := 0; i < length && cycle; i++ {
n := walk[(i+1)%length]
m := walk[i]
cycle = g.IsConnected(m, n)
}
return cycle
}