Evolver is a Genetic Algorithm library for Swift🐧.
The main units of Evolver are Generable
protocol and Evolver
class.
- Create Model conformed to Generable
struct Player: Generable {
var direction = Array(
repeating: Gene.template(Direction.self, geneSize: Counter(Direction.self).count),
count: 20
)
var action = Array(
repeating: Gene.template(Action.self, geneSize: Counter(Action.self).count),
count: 10
)
}
- Prepare Enumeration conformed to
Int
&GeneBase
enum Direction: Int, GeneBase {
case left
case right
case up
case down
}
- Implement Evaluate function
func evaluate(model: Player) -> Int {
・・・
}
- Simulate Genetic Algorithm
let result = Evolver.run(template: Player.self,
generations: 20,
individuals: 10,
completion: { model, generation, individual in
// Implement Evaluate model function
let score = self.evaluate(model: model)
return score
})
switch result {
case .success(let model):
for direction in model.direction {
print(direction.value) // You can get enum case
}
case .failure(let error):
print(error)
}
Evolver
is simulating on main thread default.
Use DispatchQueue
if you want to running on sub thread.
DispatchQueue.global(qos: .userInitiated).async {
let result = Evolver.run(template: Player.self,
generations: 20,
individuals: 10,
completion: { model, generation, individual in
let score = self.evaluate(model: model)
return score
})
DispatchQueue.main.async {
switch result {
case .success(let model):
print(model)
case .failure(let error):
print(error)
}
}
}
Add the following to your Podfile
:
pod "Evolver"
Add the following to your Cartfile
:
github "natmark/Evolver"
Evolver is available under the MIT license. See the LICENSE file for more info.