diff options
-rw-r--r-- | src/Genome.hs | 21 | ||||
-rw-r--r-- | test/GenomeTest.hs | 29 |
2 files changed, 48 insertions, 2 deletions
diff --git a/src/Genome.hs b/src/Genome.hs index cb90ed1..efc79d5 100644 --- a/src/Genome.hs +++ b/src/Genome.hs @@ -12,12 +12,16 @@ module Genome , mutateGenomeRemoveGene , mutateGenome + + , parseGenome ) where -import Mind (NeuronIndex (..)) +import Mind (Edge (..), NeuronIndex (..)) +import qualified Mind as N (Network (..), createEmptyNetwork, connectNeurons) import System.Random import Data.Ix +import Data.Maybe data Gene = Gene { source :: NeuronIndex, sink :: NeuronIndex, weight :: Float } deriving (Eq, Show) @@ -199,3 +203,18 @@ mutateGenome g r = ] ) r in f g r' + + +-- parse a genome into a network +parseGenome :: Genome -> N.Network +parseGenome g = + foldl + (\net gene -> + let + m = N.connectNeurons net (source gene) (sink gene) (weight gene) + net' = if isJust m then fromJust m else error $ "bad gene: " ++ show gene + in + net' + ) + (N.createEmptyNetwork (numInput g) (numInternal g) (numOutput g)) + (genes g) diff --git a/test/GenomeTest.hs b/test/GenomeTest.hs index aa6d310..2222347 100644 --- a/test/GenomeTest.hs +++ b/test/GenomeTest.hs @@ -2,7 +2,8 @@ module GenomeTest (suite) where import Test.Tasty import Test.Tasty.HUnit -import Mind (NeuronIndex (..)) +import Mind (Edge (..), NeuronIndex (..)) +import qualified Mind as N (Network (..)) import Genome import System.Random import Data.Ix @@ -204,4 +205,30 @@ mutationTests = testGroup "mutations" $ [ Gene { source = Internal 0, sink = Internal 1, weight = 1.0 } , Gene { source = Internal 2, sink = Output 0, weight = 1.0 } ] + , testCase "parse genome into network" $ + let + genome = Genome + { numInput = 1 + , numInternal = 3 + , numOutput = 1 + , genes = + [ Gene { source = Input 0, sink = Internal 0, weight = 1.0 } + , Gene { source = Internal 0, sink = Internal 1, weight = 2.0 } + , Gene { source = Internal 1, sink = Internal 2, weight = 3.0 } + , Gene { source = Internal 2, sink = Output 0, weight = 4.0 } + ] + } + network = parseGenome genome + expected = N.Network + { N.numInput = 1 + , N.internalNeurons = + [ [ Edge (Input 0, 1.0) ] + , [ Edge (Internal 0, 2.0) ] + , [ Edge (Internal 1, 3.0) ] + ] + , N.outputNeurons = + [ [ Edge (Internal 2, 4.0) ] + ] + } + in network @?= expected ] |