charlie 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,13 @@
1
+ == 0.8.0 / 2008-02-12
2
+ * Added BlendingCrossover
3
+ * Benchmark setup/teardown blocks
4
+ * Made population inherit array
5
+ * Support for GP-style evolution (never apply both crossover and mutation)
6
+ * Co-evolution with small tournaments, iterated prisoner's dilemma example.
7
+ * Added evolve_multiple* methods
8
+ * Added support for matrix genotypes, 2-d arrays of floats or bits.
9
+ * Added a genotype for neural networks
10
+
1
11
  == 0.7.1 / 2008-01-12
2
12
  * Fixed a major bug in RouletteSelection and ScaledRouletteSelection.
3
13
 
@@ -13,7 +13,8 @@ examples/EXAMPLES_README.txt
13
13
  examples/bitstring.rb
14
14
  examples/coevolution.rb
15
15
  examples/function_optimization.rb
16
- examples/output/bitstring_royalroad.html
16
+ examples/matrix.rb
17
+ examples/neural.rb
17
18
  examples/output/function_optimization_sombrero.html
18
19
  examples/output/function_optimization_twopeak.csv
19
20
  examples/output/function_optimization_twopeak.html
@@ -33,6 +34,8 @@ lib/charlie/genotype.rb
33
34
  lib/charlie/list/list_crossover.rb
34
35
  lib/charlie/list/list_genotype.rb
35
36
  lib/charlie/list/list_mutate.rb
37
+ lib/charlie/list/matrix.rb
38
+ lib/charlie/list/neural.rb
36
39
  lib/charlie/mutate.rb
37
40
  lib/charlie/permutation/permutation.rb
38
41
  lib/charlie/population.rb
@@ -42,7 +45,9 @@ test/t_common.rb
42
45
  test/test_benchmark.rb
43
46
  test/test_cross.rb
44
47
  test/test_evolve.rb
48
+ test/test_matrix.rb
45
49
  test/test_mutator.rb
50
+ test/test_neural.rb
46
51
  test/test_permutation.rb
47
52
  test/test_sel.rb
48
53
  test/test_tree.rb
data/README.txt CHANGED
@@ -1,4 +1,4 @@
1
- == Charlie version 0.7.1
1
+ == Charlie version 0.8.0
2
2
  * http://rubyforge.org/projects/charlie/
3
3
  * http://charlie.rubyforge.org
4
4
  * mailto:sander.land+ruby@gmail.com
data/Rakefile CHANGED
@@ -19,7 +19,7 @@ h = Hoe.new('charlie', Charlie::VERSION) do |p|
19
19
  p.changes = p.paragraphs_of('History.txt', 0..1).join("\n\n")
20
20
 
21
21
  #p.test_globs ['test/test_all.rb'] # removed test_all, because rake now does that anyway
22
- p.clean_globs = ['test/output/*','./**/*~'] # Remove this on "rake clean" : test output and kate backups
22
+ p.clean_globs = ['test/output/*','./**/*~','./**/*.rbc'] # Remove this on "rake clean" : test output and kate backups, rubinius stuff
23
23
 
24
24
  p.rdoc_pattern = /^lib|\.txt$|^data\/[A-Z]+(\..+)?$/ # include data/* doc files
25
25
  p.remote_rdoc_dir = '' # Release to root
data/TODO.txt CHANGED
@@ -1,19 +1,14 @@
1
1
  This is my todo list. Contributions and suggestions don't have to be restricted to these things in any way.
2
2
 
3
3
  === Small stuff
4
- * Arithmetic crossovers, Brood crossover?
4
+ * Brood crossover?
5
5
  === Bigger stuff
6
6
  * More builtin genotypes:
7
7
  * Tree-based, extending into genetic programming. mostly done. add option for ADFs?
8
- * Graphs / adjacency matrix. Multidimensional arrays in general?
9
- * Neural networks.
10
- * Method for population to do several shorter runs until convergence (cf. gridwalk example).
11
- * Method for population to do several shorter runs, save some the best in each to generate a new population, and evolve this. Is this useful?
12
- * More selection algorithms. Multiple populations with migration? Niching? gladiatorial/tournaments (+Prisoner's dilemma example)?
8
+ * More selection algorithms: multiple populations with migration? Niching?
13
9
  * Extend benchmarking options:
14
10
  * Extend dsl to have options for manual test cases given by sel/cross/mut/etc options, or even free code blocks.
15
11
  * Option to compare several generation/population size settings. Especially both of them together while keeping the number of fitness evaluations roughly constant.
16
- * Instead of (2), constraint on time, or # of fitness evals instead of generations. (?)
17
12
  * Detailed stats for use in comparing a small number of strategies? Including population stats for every generation and run, graphs?
18
13
 
19
14
 
@@ -46,6 +46,10 @@ complete, but will improve the accuracy of the results.
46
46
  * Default is the fitness itself.
47
47
  * This can be an array, if you want to track multiple stats at once (for example: tracking both training and generalization error).
48
48
 
49
+ ==== <tt>setup{|population| ... }</tt> and <tt>teardown{|population| ... }</tt>
50
+ * Extra blocks called before and after the tests (before Population#evolve_silent, and after 'track_stats')
51
+ * setup can be used to reshuffle traning data, initialize the population to some specific state, etc.
52
+
49
53
  ==== Remarks
50
54
  * If you want to test the module that is already included without repeating it, just pass Module.new as one of the arguments (or Module.new{self.name='default'} for something more descriptive). This is also the default, so <tt>GABenchmark.benchmark(klass){}</tt> will simply test the strategies already included.
51
55
  * The methods <tt>selection, crossover, mutator, generations, population_size, repeat</tt> are defined using metaprogramming as <tt>attr_dsl</tt>. Passing no arguments to the function will return the current value, passing more will assign the value. This means you can do things like <tt>selection << TournamentSelection(3)</tt> in the block.
@@ -20,7 +20,7 @@ Using the Genotype.use keyword does this automatically.
20
20
  === NullCrossover
21
21
  Just returns copies of the two parents, i.e. performs no crossover at all.
22
22
 
23
- == List-based Crossovers
23
+ == List-based Crossovers <tt>->file</tt>[link:files/lib/charlie/list/list_crossover_rb.html]
24
24
  These crossovers can be used for all list- and string-based genotypes.
25
25
 
26
26
  === SinglePointCrossover
@@ -32,6 +32,9 @@ Standard uniform crossover.Returns two children.
32
32
  === NPointCrossover(n=2)
33
33
  N-point crossover. Returns two children.
34
34
 
35
+ === BlendingCrossover(exploration_alpha=0.1,type=:cube)
36
+ Blending crossover as used in ES
37
+
35
38
 
36
39
  == Specialized Crossovers
37
40
  === For PermutationGenotype
@@ -41,10 +44,15 @@ It is fairly destructive, which can lead to poor performance.
41
44
  EdgeRecombinationCrossover is a less destructive crossover for permutations.
42
45
  It's reasonably effective, but fairly slow and only works for permutations of 0...n, so you have to look up the actual elements in the fitness function.
43
46
 
47
+ === For FloatMatrixGenotype, BitMatrixGenotype
48
+ * MatrixUniformCrossover does a uniform crossover (per-element) on matrices.
49
+ * The normal SinglePointCrossover, UniformCrossover, NPointCrossover can also be used. They act on rows as single elements.
50
+
51
+
44
52
  === For TreeGenotype
45
53
  TreeCrossover does a standard subtree swapping crossover for trees. Returns two children.
46
54
 
47
- == Meta-crossovers
55
+ == Meta-crossovers <tt>->file</tt>[link:files/lib/charlie/crossover_rb.html]
48
56
  These functions take one or more crossover modules and generate a new crossover module.
49
57
 
50
58
  === SingleChild(crossover) (#SingleChild)
@@ -11,7 +11,7 @@ The base class includes NullCrossover, NullMutator and Elitism(ScaledRouletteSel
11
11
  All of the other genotypes described here inherit the base class, and its associated selection/crossover/mutation operators, unless
12
12
  otherwise indicated.
13
13
 
14
- === List-based genotypes (file)[link:files/lib/charlie/list/list_genotype_rb.html]
14
+ === List-based genotypes <tt>->file</tt>[link:files/lib/charlie/list/list_genotype_rb.html]
15
15
  All of these genotypes are based on arrays and can use the list-based crossover and mutation operators.
16
16
  They are all generated dynamically by functions, and should be used like:
17
17
 
@@ -37,13 +37,33 @@ Genotype of +n+ elements (not necessarily chars).
37
37
 
38
38
  Includes <tt>ListMutator(:expected_n[2],:replace[*elements]), SinglePointCrossover</tt> by default.
39
39
 
40
+ ==== NeuralNetworkGenotype(input_n,hidden_n,output_n=1,scaling=1.0,hidden_f=NN_TANH,output_f=NN_TANH)
41
+ Genotype for a neural network. <tt>->file</tt>[link:files/lib/charlie/list/neural_rb.html]
42
+
43
+ Inherits FloatListGenotype and includes <tt>UniformCrossover</tt> by default.
44
+
45
+
46
+ === Matrix-based genotypes <tt>->file</tt>[link:files/lib/charlie/list/matrix_rb.html]
47
+ These genotypes are based on arrays of arrays and can use the matrix-based crossover and mutation operators. Some of the crossovers for lists also work on these, by considering rows as single elements of a list (see the CROSSOVER file for details).
48
+
49
+ ==== FloatMatrixGenotype(rows,columns=rows,range=0..1)
50
+ Genotype of <tt>rows x columns</tt> floats initialized in the range +range+. Mutations can take the floats out of this range.
51
+
52
+ Includes <tt>MatrixMutator()</tt> (with default parameters :expected_n[3], :uniform[ 0.25 ]) and <tt>MatrixUniformCrossover</tt> by default.
53
+
54
+ ==== BitStringGenotype(n)
55
+ Genotype of <tt>rows x columns</tt> bits.
56
+
57
+ Includes <tt>MatrixMutator(:expected_n[3],:flip)</tt> and <tt>MatrixUniformCrossover</tt> by default.
58
+
59
+
40
60
  === Specialized genotypes
41
61
  These genotypes have their own crossover and mutation operators.
42
62
 
43
- ==== PermutationGenotype(n,elements=0...n) (file)[link:files/lib/charlie/permutation/permutation_rb.html]
63
+ ==== PermutationGenotype(n,elements=0...n) <tt>->file</tt>[link:files/lib/charlie/permutation/permutation_rb.html]
44
64
  Genotype for permutations. Includes TranspositionMutator and PermutationCrossover by default.
45
65
 
46
- ==== TreeGenotype(terminals, unary_ops, binary_ops) (file)[link:files/lib/charlie/tree/tree_rb.html]
66
+ ==== TreeGenotype(terminals, unary_ops, binary_ops) <tt>->file</tt>[link:files/lib/charlie/tree/tree_rb.html]
47
67
  * Genotype for trees. Useful for genetic programming. Includes PMutate(0.5,TreeReplaceMutator) and PCross(0.7,TreeCrossover) by default.
48
68
  * Functions included: eval_genes(terminal_values_hash), size, depth, module GPTreeHelper
49
69
  * Check examples/tree.rb for usage.
@@ -18,7 +18,7 @@ The non-destructive counterpart +mutate+ is defined automatically by Genotype#mu
18
18
  Just returns self
19
19
 
20
20
  == List-based Mutators
21
- These crossovers can be used for all list- and string-based genotypes.
21
+ These mutators can be used for all list- and string-based genotypes.
22
22
 
23
23
  === ListMutator(strategy=:expected_n ,point_mutator=:uniform)
24
24
  Generates a wide variety of mutators for lists, strings and bitstrings.
@@ -29,16 +29,28 @@ See the documentation of list_mutate.rb[link:files/lib/charlie/list/list_mutate_
29
29
 
30
30
  Both of these parameters use Symbol#[] in the examples. <tt>:replace['a','b']</tt> is simply equivalent to <tt>[:replace,'a','b']</tt>
31
31
 
32
+ == Matrix-based Mutators
33
+ These mutators can be used for all matrix genotypes.
34
+
35
+ === MatrixMutator(strategy=:expected_n ,point_mutator=:uniform)
36
+ Generates a wide variety of mutators for matrices of floats or bits.
37
+
38
+ * strategy can be a proc or one of the MatrixMutationStrategies : single point, multi-point and probabilistic. See the documentation of matrix.rb[link:files/lib/charlie/list/matrix_rb.html] for more info on these.
39
+ * point_mutator can be a proc or one of the PointMutators, as with ListMutator.
40
+
41
+
32
42
  == Specialized Mutators
43
+
44
+
33
45
  === For PermutationGenotype
34
- All of these will probably work on other array/string-based genotypes as well, but this is untested.
46
+ All of these will probably work on other array/string/matrix-based genotypes as well, but this is untested.
35
47
 
36
48
  * TranspositionMutator is a transposition mutator for permutations. It interchanges two elements and leaves the remaining elements in their original positions.
37
49
  * InversionMutator is another mutator for permutations. It inverses a part of the genes array.
38
50
  * InsertionMutator takes a random element of the permutation, and inserts it at a random position.
39
51
  * RotationMutator takes a random element, and rotates the permutation such that this is the first element, i.e. it effectively does nothing if the permutation represents a cycle.
40
52
 
41
- === For TreeGenotype (file)[link:files/lib/charlie/tree/tree_rb.html]
53
+ === For TreeGenotype <tt>->file</tt>[link:files/lib/charlie/tree/tree_rb.html]
42
54
  * TreeReplaceMutator(depth,type) replaces a randomly chosen subtree with a new, randomly generated, subtree.
43
55
  * TreePruneMutator replaces a randomly chosen subtree with a randomly generated terminal.
44
56
  * TreeRemoveNodeMutator replaces a random node by one of its children.
@@ -20,13 +20,13 @@ Using the Genotype.use keyword does this automatically.
20
20
  These strategies work with genotype classes which define a +fitness+ function. The +fitness+ function should return a number, higher fitness means better and more likely to be selected. All except RouletteSelection can handle negative fitness values.
21
21
 
22
22
  * RandomSelection
23
- * TruncationSelection(best=0.3)
24
- * BestOnlySelection
23
+ * TruncationSelection(best=0.3), TruncationSelection = TruncationSelection()
24
+ * BestOnlySelection = TruncationSelection(1)
25
25
  * RouletteSelection
26
- * ScaledRouletteSelection(&block)
27
- * TournamentSelection(group_size=4,n_times=nil)
26
+ * ScaledRouletteSelection(&block), ScaledRouletteSelection = RankSelection = ScaledRouletteSelection()
27
+ * TournamentSelection(group_size=4,n_times=nil), TournamentSelection = TournamentSelection()
28
28
 
29
- The documentation for selection_rb[link:files/lib/charlie/selection_rb.html] contains explanations for most of these.
29
+ The documentation for <tt>selection.rb</tt>[link:files/lib/charlie/selection_rb.html] contains explanations for most of these.
30
30
 
31
31
  === Meta-selection
32
32
  ==== Elitism(selection,n=1)
@@ -36,13 +36,20 @@ Generates a module which applies elitism to some selection strategy. This:
36
36
  * replaces the last +n+ individuals in the new population with the best +n+ of the old population (unless the newer individual has higher fitness).
37
37
  This ensures the maximum fitness can never decrease.
38
38
 
39
+ ==== GP(selection,crossover_probability=0.75)
40
+ Applies crossover OR mutation instead of both for generating children. Common in genetic programming. Only works for selection methods which use yield to generate children (currently all of the built-in selection methods do this).
39
41
 
40
42
  == Co-evolutionary selection strategies
41
- These strategies work with genotype classes which define a <tt>fight(other)</tt> function.
42
- This function should return true if the instance defeats +other+ in a 'fight'.
43
43
 
44
44
  * GladiatorialSelection
45
+ * This strategy works with genotype classes which define a <tt>fight(other)</tt> function. This function should return true if the instance defeats +other+ in a 'fight'.
46
+
47
+ * CoTournamentSelection(group_size=4,full_tournament=false,n_times=nil)
48
+ * This strategy works with genotype classes which define a <tt>fight_points(other)</tt> function. This function should return [points for self,points for other] as a result from a 'fight'. Points should always be >= 0.
49
+ * Selection is total-points-proportional (as in roulette selection) within tournaments of size <tt>group_size</tt>.
45
50
 
46
51
  Because there is no way to determine who is the actual best individual, using Population#benchmark
47
52
  for comparing strategies for convergence speed, etc.
48
- is not possible. Defining a fitness function as some statistic you want to track and then using benchmark should be possible, but is untested.
53
+ is not possible. Defining a fitness function as some statistic you want to track or using <tt>track_stats</tt> to override the default and then using benchmark should be possible, but is untested.
54
+
55
+
@@ -1,70 +1,91 @@
1
- In this directory are several examples of how to use the library.
1
+ In this directory (<tt>/examples</tt>) are several examples of how to use the library.
2
2
  This file serves as an index, which can be used to find an example for a specific function.
3
3
 
4
- ==== function_optimization.rb ====
4
+ === function_optimization.rb
5
5
  - ruby function_optimization.rb hill
6
- Description: Function optimization example in many dimensions, hill climbing.
7
- Uses: FloatListGenotype, TournamentSelection, UniformCrossover, ListMutator
6
+ * Description: Function optimization example in many dimensions, hill climbing.
7
+ * Uses: FloatListGenotype, TournamentSelection, UniformCrossover, ListMutator
8
8
 
9
9
  - ruby function_optimization.rb twopeak
10
- Description: Function optimization example in 1 dimension, avoiding a local maximum.
11
- Uses: FloatListGenotype (single float), NullCrossover, GABenchmark
10
+ * Description: Function optimization example in 1 dimension, avoiding a local maximum.
11
+ * Uses: FloatListGenotype (single float), NullCrossover, GABenchmark
12
12
 
13
13
  - ruby function_optimization.rb sombrero
14
- Description: Function optimization example in 2 dimensions, avoiding many maxima.
15
- Uses: FloatListGenotype, GABenchmark
14
+ * Description: Function optimization example in 2 dimensions, avoiding many maxima.
15
+ * Uses: FloatListGenotype, GABenchmark
16
16
 
17
- ==== bitstring.rb ====
17
+ === bitstring.rb
18
18
  - ruby bitstring.rb 512
19
- Description: Very simple example that finds the binary representation of 512.
20
- Uses: BitStringGenotype
19
+ * Description: Very simple example that finds the binary representation of 512.
20
+ * Uses: BitStringGenotype
21
21
 
22
22
  - ruby bitstring.rb royalroad
23
- Description: Example for convergence with limited feedback from the fitness function.
24
- Uses: BitStringGenotype, TruncationSelection, UniformCrossover, ListMutator, cache_fitness, GABenchmark
23
+ * Description: Example for convergence with limited feedback from the fitness function.
24
+ * Uses: BitStringGenotype, TruncationSelection, UniformCrossover, ListMutator, cache_fitness, GABenchmark
25
25
 
26
- ==== string.rb ====
26
+ === string.rb
27
27
  - ruby string.rb weasel
28
- Description: Simple target string evolver.
29
- Uses: StringGenotype, BestOnlySelection, UniformCrossover, ListMutator, GABenchmark
28
+ * Description: Simple target string evolver.
29
+ * Uses: StringGenotype, BestOnlySelection, UniformCrossover, ListMutator, GABenchmark
30
30
 
31
31
  - ruby string.rb gridwalk
32
- Description: Example of using strings of symbols other than chars to evolve a route through a grid.
33
- Uses: StringGenotype, TournamentSelection, evolve_until
32
+ * Description: Example of using strings of symbols other than chars to evolve a route through a grid.
33
+ * Uses: StringGenotype, TournamentSelection, evolve_until
34
34
 
35
- ==== tsp.rb ====
35
+ === tsp.rb
36
36
  - ruby tsp.rb
37
- Description: Travelling salesperson problem.
38
- Uses: PermutationGenotype, PCross, PMutateN, evolve_until, TournamentSelection,
39
- EdgeRecombinationCrossover, InversionMutator ,InsertionMutator, GABenchmark
37
+ * Description: Travelling salesperson problem.
38
+ * Uses: PermutationGenotype, PCross, PMutateN, evolve_until, TournamentSelection,
39
+ * EdgeRecombinationCrossover, InversionMutator ,InsertionMutator, GABenchmark
40
40
 
41
- ==== permutation.rb ====
41
+ === permutation.rb
42
42
  - ruby permutation.rb
43
- Description: send+more=money problem with PermutationGenotype.
44
- Uses: PermutationGenotype
43
+ * Description: send+more=money problem with PermutationGenotype.
44
+ * Uses: PermutationGenotype
45
45
 
46
- ==== coevolution.rb ====
46
+ === coevolution.rb
47
47
  - ruby coevolution.rb simple
48
- Description: Simple co-evolutionary example. Evolves a two-element array to be [large,small]
49
- Uses: GladiatorialSelection, FloatListGenotype, UniformCrossover, ListMutator
48
+ * Description: Simple co-evolutionary example. Evolves a two-element array to be [large,small]
49
+ * Uses: GladiatorialSelection, FloatListGenotype, UniformCrossover, ListMutator
50
50
 
51
51
  - ruby coevolution.rb sunburn
52
- Description: More elaborate example of co-evolution. Evolves weapon systems on space ships (like Ashlock (2004), ch.4).
53
- Uses: GladiatorialSelection, StringGenotype, custom mutation/crossover, UniformCrossover
52
+ * Description: More elaborate example of co-evolution. Evolves weapon systems on space ships (like Ashlock (2004), ch.4).
53
+ * Uses: GladiatorialSelection, StringGenotype, custom mutation/crossover, UniformCrossover
54
54
 
55
- ==== tree.rb ====
55
+ - ruby coevolution.rb prisoner
56
+ * Description: Iterated prisoner's dilemma.
57
+ * Uses: CoTournamentSelection
58
+
59
+ === tree.rb
56
60
  - ruby tree.rb cos
57
- Description: Example for TreeGenotype/GP. Evolves a polynomial that approximates cos(x).
58
- Uses: TreeGenotype, ...
61
+ * Description: Example for TreeGenotype/GP. Evolves a polynomial that approximates cos(x).
62
+ * Uses: TreeGenotype, ...
59
63
 
60
64
  - ruby tree.rb pors [n=31]
61
- Description: Plus One Recall Store example. Generate a number n using a minimal # of +,1,STO,RCL operations.
62
- Uses: TreeGenotype, passing proc{}'s to node values at evaluation, custom unary operators.
65
+ * Description: Plus One Recall Store example. Generate a number n using a minimal # of +,1,STO,RCL operations.
66
+ * Uses: TreeGenotype, passing proc{}'s to node values at evaluation, custom unary operators.
63
67
 
64
68
  - ruby tree.rb porsx [n=31]
65
- Description: Same idea as PORS, but generate a tree that evaluates to n*T where T can only be recalled once.
69
+ * Description: Same idea as PORS, but generate a tree that evaluates to n*T where T can only be recalled once.
70
+
71
+ - ruby tree.rb xor
72
+ * Description: Finds the smallest tree for A XOR B using |,&,!.
66
73
 
67
74
  - ruby tree.rb bloat
68
- Description: Just grows large trees.
75
+ * Description: Just grows large trees.
76
+
77
+ === matrix.rb
78
+ - ruby matrix.rb royalmatrix
79
+ * Description: Like bitstring.rb royalroad.
80
+ * Uses: BitMatrixGenotype
81
+
82
+ - ruby matrix.rb inverse
83
+ * Description: Finds the inverse of a matrix.
84
+ * Uses: FloatMatrixGenotype
85
+
86
+ === neural.rb
87
+ - ruby neural.rb
88
+ * Description: Finds a neural network for the XOR function.
89
+ * Uses: NeuralNetworkGenotype
69
90
 
70
91
 
@@ -7,7 +7,7 @@ end
7
7
 
8
8
  if ARGV[0].nil?
9
9
  puts "Several examples for Co-evolution."
10
- puts "Usage: ruby coevolution.rb simple|sunburn"
10
+ puts "Usage: ruby coevolution.rb simple|sunburn|prisoner"
11
11
 
12
12
 
13
13
 
@@ -144,4 +144,45 @@ puts "Results:",pop
144
144
 
145
145
 
146
146
 
147
+ elsif ARGV[0].downcase.gsub(/[^a-z]/,'') == 'prisoner'
148
+
149
+
150
+
151
+
152
+ puts "Runs a tournament-based co-evolutionary genetic algorithm of the Prisoner's Dilemma. "
153
+
154
+ class Prisoner < BitStringGenotype(5)
155
+ RESULT = {'00'=>1,'01'=>5,'10'=>0,'11'=>3}
156
+ #look at last ft, 00 01 10 11 -> ix in genes .. genes[4] = init
157
+ # rev for other! 3-x?
158
+ def fight_points(other) # fight_points(other) return [points for self,points for other]
159
+ strat, other_strat = genes, other.genes
160
+ move, other_move = strat[4], other_strat[4] # initial move
161
+ s, os = 0,0
162
+ 100.times{
163
+ my_res = "#{move}#{other_move}"
164
+ other_res = my_res.reverse
165
+ s += RESULT[my_res]
166
+ os += RESULT[other_res]
167
+ move, other_move = strat[my_res.to_i(2)], other_strat[other_res.to_i(2)]
168
+ }
169
+ [s,os]
170
+ end
171
+ BIT = ['D','C']
172
+ NAMES = { # name some strategies
173
+ "1111"=>"ALL-C","0000"=>"ALL-D","0101"=>"TIT-FOR-TAT","0001"=>"GRUDGE (ALL-D-AFTER-ANY-D)","1001"=>"PAVLOV",
174
+ "0011"=>"ALL-START","0100"=>"ALL-C-AFTER-ANY-C","0111"=>"ALL-C-IF-START-C"
175
+ }
176
+ def to_s
177
+ long_name = "DD => #{BIT[genes[0]]} CD => #{BIT[genes[2]]} | DC => #{BIT[genes[1]]} CC=>#{BIT[genes[3]]} | START #{BIT[genes[4]]}"
178
+ "#{long_name} \t #{NAMES[super[0..3]]}"
179
+ end
180
+ use CoTournamentSelection(5), UniformCrossover, ListMutator(:expected_n[0.25],:flip)
181
+ end
182
+
183
+ pop = Population.new(Prisoner,50).evolve_silent(200)
184
+ puts "PREVIOUS MOVE OF SELF/OTHER => ACTION \t\t\t NAME"
185
+ puts pop
186
+
187
+
147
188
  end
@@ -0,0 +1,49 @@
1
+ begin
2
+ require '../lib/charlie'
3
+ rescue LoadError
4
+ require 'rubygems'
5
+ require 'charlie'
6
+ end
7
+ require 'pp'
8
+
9
+ if ARGV[0]=='royalmatrix'
10
+
11
+ puts "Like bitstring.rb royalroad, but with a matrix."
12
+
13
+ class RRMatrix < BitMatrixGenotype(16,4)
14
+ def fitness
15
+ genes.count{|row| row.all?{|b| b==1 } }
16
+ end
17
+ def to_s ; genes.map{|row| row.all?{|b| b==1 } ? '*':'_' }.join ; end
18
+ use MatrixMutator(:expected_n_per_row[0.1],:flip), UniformCrossover # row-based uniform crossover
19
+ end
20
+ r = Population.new(RRMatrix).evolve_on_console(200)
21
+
22
+ elsif ARGV[0]=='inverse'
23
+
24
+ puts "Evolves the inverse of a matrix. Not very effective."
25
+
26
+ N = 3
27
+ M = Array.new(N){Array.new(N){rand}}
28
+ I = (0...N).map{|i| (0...N).map{|j| j==i ? 1 : 0 }}
29
+
30
+ class MInverse < FloatMatrixGenotype(N,N,-1..1)
31
+ def fitness
32
+ a = genes; b = M
33
+ diff = 0
34
+ (0...N).each{|i| (0...N).each{|j|
35
+ diff += (I[i][j] - (0...N).map{|k| a[i][k] * b[k][j] }.sum).abs
36
+ }}
37
+ -diff
38
+ end
39
+ def to_s
40
+ "\n" + genes.map{|r| r.map{|e| "%.2f" % e }.join("\t") }.join("\n")
41
+ end
42
+ use MatrixMutator(:expected_n[3],:gaussian[0.1])
43
+ end
44
+ r = Population.new(MInverse).evolve_on_console(200)
45
+
46
+ else
47
+ puts "Several examples for matrices."
48
+ puts "Usage: ruby matrix.rb royalmatrix|inverse"
49
+ end