-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathGeneAlgorithmTest.scala
54 lines (41 loc) · 1.48 KB
/
GeneAlgorithmTest.scala
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
// Wei Chen - Gene Algorithm Test
// 2017-07-22
import com.scalaml.general.MatrixFunc._
import com.scalaml.algorithm.GeneAlgorithm
import org.scalatest.funsuite.AnyFunSuite
class GeneAlgorithmSuite extends AnyFunSuite {
val ga = new GeneAlgorithm()
val initseeds = Array(Array(0.0), Array(1.0))
def evaluation(arr: Array[Double]): Double = - (arr.head - 0.7).abs
def breeding(pa: Array[Double], pb: Array[Double]): Array[Array[Double]] =
Array(pa.zip(pb).map { case (a, b) =>
if (scala.util.Random.nextDouble > 0.1) (a + b) / 2
else scala.util.Random.nextDouble
})
val generationsize: Int = 100
val elitesize: Int = 3
val generationcount: Int = 10
test("GeneAlgorithm Test : Initial") {
assert(ga.seeds == null)
ga.setSeeds(initseeds)
assert(matrixequal(ga.seeds, initseeds))
}
test("GeneAlgorithm Test : Evolve") {
for (i <- 0 until 10)
ga.evolve(evaluation, breeding, generationsize, elitesize)
assert(ga.seeds.size == generationsize)
val best = ga.evolve(evaluation, breeding, generationsize, elitesize)
assert((best.head - 0.7).abs < 0.05)
}
test("GeneAlgorithm Test : Search") {
val best = ga.search(
evaluation,
breeding,
generationsize,
elitesize,
generationcount
)
assert(ga.seeds.size == generationsize)
assert((best.head - 0.7).abs < 0.05)
}
}