Esempio n. 1
0
func main() {
	startX := fieldWidth / 2
	startY := fieldHeight / 2

	calc := func(candidate string) int {
		field, program := evaluate(candidate, startX, startY)
		fitness := getFitness(field.numberOfSquaresMowed, program.numberOfInstructions())
		return fitness
	}
	start := time.Now()

	disp := func(candidate string) {
		field, program := evaluate(candidate, startX, startY)
		fitness := getFitness(field.numberOfSquaresMowed, program.numberOfInstructions())
		display(field, program, fitness, startX, startY, time.Since(start))
	}

	var solver = new(genetic.Solver)
	solver.MaxSecondsToRunWithoutImprovement = 1
	solver.MaxRoundsWithoutImprovement = 10

	var best = solver.GetBestUsingHillClimbing(calc, disp, geneSet, maxMowerActions, 1, maxFitness)

	fmt.Print("\nFinal: ")
	disp(best)
}
Esempio n. 2
0
func main() {
	resources := []resource{
		{name: "Bark", value: 3000, weight: 0.3, volume: .025},
		{name: "Herb", value: 1800, weight: 0.2, volume: .015},
		{name: "Root", value: 2500, weight: 2.0, volume: .002},
	}

	const maxWeight = 25.0
	const maxVolume = .25

	geneSet := "0123456789ABCDEFGH"

	calc := func(candidate string) int {
		decoded := decodeGenes(candidate, resources, geneSet)
		return getFitness(decoded, maxWeight, maxVolume)
	}
	start := time.Now()

	disp := func(candidate string) {
		decoded := decodeGenes(candidate, resources, geneSet)
		fitness := getFitness(decoded, maxWeight, maxVolume)
		display(decoded, fitness, time.Since(start))
	}

	var solver = new(genetic.Solver)
	solver.MaxSecondsToRunWithoutImprovement = .1
	solver.MaxRoundsWithoutImprovement = 2

	var best = solver.GetBestUsingHillClimbing(calc, disp, geneSet, 10, 2, math.MaxInt32)

	fmt.Println("\nFinal:")
	disp(best)
}
Esempio n. 3
0
func main() {
	const genes = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!."
	target := "Not all those who wander are lost."
	calc := func(candidate string) int {
		return calculate(target, candidate)
	}

	start := time.Now()

	disp := func(candidate string) {
		fmt.Print(candidate)
		fmt.Print("\t")
		fmt.Print(calc(candidate))
		fmt.Print("\t")
		fmt.Println(time.Since(start))
	}

	var solver = new(genetic.Solver)
	solver.MaxSecondsToRunWithoutImprovement = 1

	var best = solver.GetBest(calc, disp, genes, len(target), 1)
	fmt.Println()
	fmt.Println(best)

	fmt.Print("Total time: ")
	fmt.Println(time.Since(start))
}
Esempio n. 4
0
func main() {
	genes := ""
	for i := 0; i < boardWidthHeight; i++ {
		genes += strconv.Itoa(i)
	}

	start := time.Now()

	calc := func(candidate string) int {
		return getFitness(candidate, boardWidthHeight)
	}

	disp := func(candidate string) {
		display(candidate, boardWidthHeight)
		fmt.Print(candidate)
		fmt.Print("\t")
		fmt.Print(getFitness(candidate, boardWidthHeight))
		fmt.Print("\t")
		fmt.Println(time.Since(start))
	}

	var solver = new(genetic.Solver)
	solver.MaxSecondsToRunWithoutImprovement = 1

	var best = solver.GetBest(calc, disp, genes, boardWidthHeight, 2)
	disp(best)
	fmt.Print("Total time: ")
	fmt.Println(time.Since(start))
}
Esempio n. 5
0
func main() {
	flag.Parse()
	if flag.NArg() != 1 {
		fmt.Println("Usage: go run samples/tsp.go ROUTEFILEPATH")
		return
	}
	var routeFileName = flag.Arg(0)
	if !File.Exists(routeFileName) {
		fmt.Println("file " + routeFileName + " does not exist.")
		return
	}
	fmt.Println("using route file: " + routeFileName)

	idToPointLookup := readPoints(routeFileName)
	fmt.Println("read " + strconv.Itoa(len(idToPointLookup)) + " points...")

	calc := func(candidate string) int {
		return getFitness(candidate, idToPointLookup)
	}

	if File.Exists(routeFileName + ".opt.tour") {
		fmt.Println("found optimal solution file: " + routeFileName + ".opt")
		optimalRoute := readOptimalRoute(routeFileName+".opt.tour", len(idToPointLookup))
		fmt.Println("read " + strconv.Itoa(len(optimalRoute)) + " segments in the optimal route")
		points := getPointsInOptimalOrder(idToPointLookup, optimalRoute)
		genes := genericGeneSet[0:len(idToPointLookup)]
		idToPointLookup = make(map[string]Point, len(idToPointLookup))
		for i, v := range points {
			idToPointLookup[genericGeneSet[i:i+1]] = v
		}
		fmt.Print("optimal route: " + genes)
		fmt.Print("\t")
		fmt.Println(getFitness(genes, idToPointLookup))
	}

	geneSet := genericGeneSet[0:len(idToPointLookup)]

	start := time.Now()

	disp := func(candidate string) {
		fmt.Print(candidate)
		fmt.Print("\t")
		fmt.Print(getFitness(candidate, idToPointLookup))
		fmt.Print("\t")
		fmt.Println(time.Since(start))
	}

	var solver = new(genetic.Solver)
	solver.MaxSecondsToRunWithoutImprovement = 20
	solver.LowerFitnessesAreBetter = true

	var best = solver.GetBest(calc, disp, geneSet, len(idToPointLookup), 1)
	fmt.Println()
	fmt.Println(best, "\t", getFitness(best, idToPointLookup))
	fmt.Print("Total time: ")
	fmt.Println(time.Since(start))
}
Esempio n. 6
0
func main() {
	flag.Parse()
	if flag.NArg() != 1 {
		fmt.Println("Usage: go run standard.go RESOURCEFILEPATH")
		return
	}
	var resourceFileName = flag.Arg(0)
	if !File.Exists(resourceFileName) {
		fmt.Println("file " + resourceFileName + " does not exist.")
		return
	}
	fmt.Println("using resource file: " + resourceFileName)

	resources, maxWeight, solution := loadResources(resourceFileName)

	optimalFitness := 0
	for resource, count := range solution {
		optimalFitness += resource.value * count
	}

	calc := func(candidate string) int {
		decoded := decodeGenes(candidate, resources)
		return getFitness(decoded, maxWeight, optimalFitness)
	}

	start := time.Now()

	disp := func(candidate string) {
		decoded := decodeGenes(candidate, resources)
		fitness := getFitness(decoded, maxWeight, optimalFitness)
		display(decoded, fitness, time.Since(start), true)
	}

	var solver = new(genetic.Solver)
	solver.MaxSecondsToRunWithoutImprovement = 5
	solver.MaxRoundsWithoutImprovement = 3

	var best = solver.GetBestUsingHillClimbing(calc, disp, hexLookup, 10, numberOfGenesPerChromosome, optimalFitness)

	fmt.Print("\nFinal: ")
	decoded := decodeGenes(best, resources)
	fitness := getFitness(decoded, maxWeight, optimalFitness)
	display(decoded, fitness, time.Since(start), false)
	if fitness == optimalFitness {
		fmt.Println("-- that's the optimal solution!")
	} else {
		percentOptimal := float32(100) * float32(fitness) / float32(optimalFitness)
		fmt.Printf("-- that's %f%% optimal\n", percentOptimal)
	}
}
Esempio n. 7
0
func main() {
	wanted := []string{"AL", "AK", "AS", "AZ", "AR"}
	unwanted := []string{"AA"}

	geneSet := getUniqueCharacters(wanted) + regexSpecials

	calc := func(candidate string) int {
		return calculate(wanted, unwanted, geneSet, candidate)
	}
	start := time.Now()

	disp := func(candidate string) {
		fmt.Println(candidate,
			"\t",
			calc(candidate),
			"\t",
			time.Since(start))
	}

	var solver = new(genetic.Solver)
	solver.MaxSecondsToRunWithoutImprovement = .5
	solver.MaxRoundsWithoutImprovement = 3

	var best = solver.GetBestUsingHillClimbing(calc, disp, geneSet, 10, 1, math.MaxInt32)

	matches, misses := getMatchResults(wanted, unwanted, geneSet, best)
	if matches == len(wanted) && misses == 0 {
		fmt.Println("\nsolved with: " + best)
	} else {
		fmt.Println("\nfailed to find a solution")
		fmt.Println("consider increasing the following:")
		fmt.Println("\tsolver.MaxSecondsToRunWithoutImprovement")
		fmt.Println("\tsolver.MaxRoundsWithoutImprovement")
	}

	fmt.Print("Total time: ")
	fmt.Println(time.Since(start))
}
Esempio n. 8
0
func main() {
	clearImages()
	startX := fieldWidth / 2
	startY := fieldHeight / 2

	flowerPoints := createFlowerPoints()

	calc := func(candidate string) int {
		field := NewField(fieldWidth, fieldHeight, flowerPoints)
		bee := NewBee(startX, startY)
		program := evaluate(candidate, bee, field, startX, startY)
		fitness := getFitness(field.numberOfFlowersFound, program.numberOfInstructions())
		return fitness
	}
	start := time.Now()

	disp := func(candidate string) {
		field := NewField(fieldWidth, fieldHeight, flowerPoints)
		bee := NewBee(startX, startY)
		program := evaluate(candidate, bee, field, startX, startY)
		fitness := getFitness(field.numberOfFlowersFound, program.numberOfInstructions())
		display(bee, flowerPoints, program, fitness, startX, startY, time.Since(start))
	}

	var solver = new(genetic.Solver)
	solver.MaxSecondsToRunWithoutImprovement = 3
	solver.MaxRoundsWithoutImprovement = 3
	solver.PrintDiagnosticInfo = true
	solver.NumberOfConcurrentEvolvers = 1 // 3
	//	solver.MaxProcs = 12

	var best = solver.GetBestUsingHillClimbing(calc, disp, geneSet, maxBeeActions, 4, maxFitness)

	fmt.Print("\nFinal: ")
	disp(best)
}
Esempio n. 9
0
func main() {
	var lengthTable = flag.String("lengthTable", "", "Source length table (2 columns, name<TAB>length)")
	var targetLength = flag.Int("targetLength", 1000, "Target length for bins")
	var maxBins = flag.Int("maxBins", 10, "Try and have fewer bins than this")
	var batchSize = flag.Int("batchSize", 40, "Batch N items at a time. MUST be <90")
	var slop = flag.Int("slop", 100, "Allow a certain amount of slop.")
	var patience = flag.Int("patience", 0, "Integer 0-5, with the max being Dalai-Lama-level patience")

	flag.Parse()

	resources := []resource{}

	content, err := ioutil.ReadFile(*lengthTable)
	if err != nil {
		//Do something
		panic(err)
	}

	lines := strings.Split(string(content), "\n")
	for _, line := range lines {
		data := strings.Split(line, "\t")
		if len(data) == 2 {
			length, _ := strconv.Atoi(data[1])
			resources = append(
				resources,
				*&resource{
					name:   data[0],
					length: length,
				},
			)
		}
	}

	geneSet := "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890-=_+!@#$%^&*()<>?|{}[];:',./\\"[0:*batchSize]

	fmt.Printf("# Round IDX\tBin Idx\tSum\tFeature IDs\n")
	for i := 0; i <= len(resources) / *batchSize; i++ {

		min_bound := i * (*batchSize)
		max_bound := (i + 1) * (*batchSize)
		max_bound = int(math.Min(float64(max_bound), float64(len(resources))))

		localResources := resources[min_bound:max_bound]
		log.Info(fmt.Sprintf("Processing %d items", len(localResources)))
		calc := func(candidate string) int {
			decoded := decodeGenes(candidate, localResources, geneSet)
			return getFitness(localResources, decoded, *targetLength, *maxBins, *slop)
		}
		start := time.Now()
		disp := func(candidate string) {
			decoded := decodeGenes(candidate, localResources, geneSet)
			fitness := getFitness(localResources, decoded, *targetLength, *maxBins, *slop)
			display(localResources, decoded, fitness, time.Since(start), i, false)
		}

		var solver = new(genetic.Solver)
		solver.MaxSecondsToRunWithoutImprovement = 1 + float64(*patience)*20
		solver.MaxRoundsWithoutImprovement = 10 + (*patience)*50

		var best = solver.GetBest(calc, disp, geneSet, *maxBins, 32)
		log.Info("Final:")

		decoded := decodeGenes(best, localResources, geneSet)
		fitness := getFitness(localResources, decoded, *targetLength, *maxBins, *slop)
		display(localResources, decoded, fitness, time.Since(start), i, true)

	}

}