Skip to content

Commit

Permalink
mutation: pass mutation probability to the mutater (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
khezen committed Mar 15, 2021
1 parent 0610664 commit 50a5e57
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 19 deletions.
23 changes: 14 additions & 9 deletions examplegnetic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,20 @@ func (i *HIndividual) SetFitness(newFitness float64) {
type HMutater struct {
}

func (m HMutater) Mutate(indiv evoli.Individual) (evoli.Individual, error) {
x := rand.Float64()*20 - 10
y := rand.Float64()*20 - 10
vx := rand.Float64()*20 - 10
vy := rand.Float64()*20 - 10
return &HIndividual{
x: []float64{x, y},
v: []float64{vx, vy},
}, nil
func (m HMutater) Mutate(indiv evoli.Individual, p float64) (evoli.Individual, error) {
if rand.Float64() <= p {
x := rand.Float64()*20 - 10
y := rand.Float64()*20 - 10
vx := rand.Float64()*20 - 10
vy := rand.Float64()*20 - 10
return &HIndividual{
x: []float64{x, y},
v: []float64{vx, vy},
}, nil
} else {
return indiv, nil
}

}

type HCrosser struct {
Expand Down
14 changes: 6 additions & 8 deletions genetic.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,15 +137,13 @@ func (g *genetic) mutations(pop Population) (Population, error) {
wg.Add(1)
go func(i int) {
defer wg.Done()
if rand.Float64() <= g.MutationProbability {
indiv := pop.Get(i)
mutant, err := g.mutater.Mutate(indiv)
if err != nil {
bubbledErr = err
return
}
pop.Replace(i, mutant)
indiv := pop.Get(i)
mutant, err := g.mutater.Mutate(indiv, g.MutationProbability)
if err != nil {
bubbledErr = err
return
}
pop.Replace(i, mutant)
}(i)
}
wg.Wait()
Expand Down
2 changes: 1 addition & 1 deletion mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func (e evaluaterMock) Evaluate(individual Individual) (Fitness float64, err err
type mutaterMock struct {
}

func (m mutaterMock) Mutate(individual Individual) (Individual, error) {
func (m mutaterMock) Mutate(individual Individual, p float64) (Individual, error) {
return individual, nil
}

Expand Down
2 changes: 1 addition & 1 deletion mutater.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ package evoli

// Mutater randomly modify a individual. This operator maintain diversity in a population.
type Mutater interface {
Mutate(Individual) (Individual, error)
Mutate(indiv Individual, p float64) (Individual, error)
}

0 comments on commit 50a5e57

Please sign in to comment.