コード例 #1
0
ファイル: tsp_test.go プロジェクト: cbarrick/evo
func TestTSP(t *testing.T) {
	fmt.Println("Minimize tour of US capitals - optimal is", best)

	// Setup:
	// We create a random initial population
	// and evolve it using a generational model.
	seed := make([]evo.Genome, size)
	for i := range seed {
		seed[i] = &tsp{gene: pool.Get().([]int)}
	}
	pop = graph.Hypercube(size)
	pop.Evolve(seed, Evolve)

	// Continuously print statistics while the optimization runs.
	pop.Poll(0, func() bool {
		count.Lock()
		n := count.n
		count.Unlock()
		stats := pop.Stats()

		// "\x1b[2K" is the escape code to clear the line
		// The fitness of minimization problems is negative
		fmt.Printf("\x1b[2K\rCount: %7d | Max: %6.0f | Mean: %6.0f | Min: %6.0f | RSD: %7.2e",
			n,
			-stats.Min(),
			-stats.Mean(),
			-stats.Max(),
			-stats.RSD())

		return false
	})

	// Stop when we get close. Finding the true minimum could take a while.
	pop.Poll(0, func() bool {
		stats := pop.Stats()
		return -stats.Max() < best*1.1
	})

	// Terminate after 2,000,000 fitness evaluations.
	pop.Poll(0, func() bool {
		count.Lock()
		n := count.n
		count.Unlock()
		return n > 2e6
	})

	pop.Wait()
	best := seed[0]
	bestFit := seed[0].Fitness()
	for i := range seed {
		fit := seed[i].Fitness()
		if fit > bestFit {
			best = seed[i]
			bestFit = fit
		}
	}
	fmt.Println("\nTour:", best)
}
コード例 #2
0
ファイル: tsp_test.go プロジェクト: lucmichalski/evo
func TestTSP(t *testing.T) {
	fmt.Println("Minimize tour of US capitals - optimal is", best)

	// Setup:
	// We create a random initial population
	// and evolve it using a generational model.
	init := make([]evo.Genome, size)
	for i := range init {
		init[i] = &tsp{gene: pool.Get().([]int)}
	}
	pop = graph.Hypercube(init)
	pop.Start()

	// Tear-down:
	// Upon returning, we cleanup our resources and print the solution.
	defer func() {
		pop.Close()
		fmt.Println("\nTour:", evo.Max(pop))
	}()

	// Run:
	// We continuously poll the population for statistics used in the
	// termination conditions.
	for {
		count.Lock()
		n := count.n
		count.Unlock()
		stats := pop.Stats()

		// "\x1b[2K" is the escape code to clear the line
		// The fitness of minimization problems is negative
		fmt.Printf("\x1b[2K\rCount: %7d | Max: %6.0f | Mean: %6.0f | Min: %6.0f | RSD: %7.2e",
			n,
			-stats.Min(),
			-stats.Mean(),
			-stats.Max(),
			stats.RSD())

		// Stop when we get close. Finding the true minimum could take a while.
		if -stats.Max() < best*1.1 {
			return
		}

		// Force stop after some number fitness evaluations
		if n > stop {
			t.Fail()
			return
		}
	}
}