diff --git a/.gitignore b/.gitignore index 854cb64..c1d429a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,9 @@ images output +data/ **/__pycache__/* /.idea **/.cache/* -*.ukp \ No newline at end of file +*.ukp +.vscode +*.egg-info* \ No newline at end of file diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/ch01/genetic.py b/ch01/genetic.py deleted file mode 100644 index efc59e3..0000000 --- a/ch01/genetic.py +++ /dev/null @@ -1,82 +0,0 @@ -# File: genetic.py -# from chapter 1 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time - - -def _generate_parent(length, geneSet, get_fitness): - genes = [] - while len(genes) < length: - sampleSize = min(length - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, sampleSize)) - genes = ''.join(genes) - fitness = get_fitness(genes) - return Chromosome(genes, fitness) - - -def _mutate(parent, geneSet, get_fitness): - index = random.randrange(0, len(parent.Genes)) - childGenes = list(parent.Genes) - newGene, alternate = random.sample(geneSet, 2) - childGenes[index] = alternate if newGene == childGenes[index] else newGene - genes = ''.join(childGenes) - fitness = get_fitness(genes) - return Chromosome(genes, fitness) - - -def get_best(get_fitness, targetLen, optimalFitness, geneSet, display): - random.seed() - bestParent = _generate_parent(targetLen, geneSet, get_fitness) - display(bestParent) - if bestParent.Fitness >= optimalFitness: - return bestParent - while True: - child = _mutate(bestParent, geneSet, get_fitness) - if bestParent.Fitness >= child.Fitness: - continue - display(child) - if child.Fitness >= optimalFitness: - return child - bestParent = child - - -class Chromosome: - def __init__(self, genes, fitness): - self.Genes = genes - self.Fitness = fitness - - -class Benchmark: - @staticmethod - def run(function): - timings = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - startTime = time.time() - function() - seconds = time.time() - startTime - sys.stdout = stdout - timings.append(seconds) - mean = statistics.mean(timings) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, mean, - statistics.stdev(timings, mean) if i > 1 else 0)) diff --git a/ch01/guessPasswordTests.py b/ch01/guessPasswordTests.py deleted file mode 100644 index 1317378..0000000 --- a/ch01/guessPasswordTests.py +++ /dev/null @@ -1,73 +0,0 @@ -# File: guessPasswordTests.py -# from chapter 1 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import unittest - -import genetic - - -def get_fitness(guess, target): - return sum(1 for expected, actual in zip(target, guess) - if expected == actual) - - -def display(candidate, startTime): - timeDiff = datetime.datetime.now() - startTime - print("{}\t{}\t{}".format( - candidate.Genes, candidate.Fitness, timeDiff)) - - -class GuessPasswordTests(unittest.TestCase): - geneset = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!.," - - def test_Hello_World(self): - target = "Hello World!" - self.guess_password(target) - - def test_For_I_am_fearfully_and_wonderfully_made(self): - target = "For I am fearfully and wonderfully made." - self.guess_password(target) - - def guess_password(self, target): - startTime = datetime.datetime.now() - - def fnGetFitness(genes): - return get_fitness(genes, target) - - def fnDisplay(candidate): - display(candidate, startTime) - - optimalFitness = len(target) - best = genetic.get_best(fnGetFitness, len(target), optimalFitness, - self.geneset, fnDisplay) - self.assertEqual(best.Genes, target) - - def test_Random(self): - length = 150 - target = ''.join(random.choice(self.geneset) - for _ in range(length)) - - self.guess_password(target) - - def test_benchmark(self): - genetic.Benchmark.run(self.test_Random) - - -if __name__ == '__main__': - unittest.main() diff --git a/ch02/genetic.py b/ch02/genetic.py deleted file mode 100644 index 11e5871..0000000 --- a/ch02/genetic.py +++ /dev/null @@ -1,80 +0,0 @@ -# File: genetic.py -# from chapter 2 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time - - -def _generate_parent(length, geneSet, get_fitness): - genes = [] - while len(genes) < length: - sampleSize = min(length - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, sampleSize)) - fitness = get_fitness(genes) - return Chromosome(genes, fitness) - - -def _mutate(parent, geneSet, get_fitness): - childGenes = parent.Genes[:] - index = random.randrange(0, len(parent.Genes)) - newGene, alternate = random.sample(geneSet, 2) - childGenes[index] = alternate if newGene == childGenes[index] else newGene - fitness = get_fitness(childGenes) - return Chromosome(childGenes, fitness) - - -def get_best(get_fitness, targetLen, optimalFitness, geneSet, display): - random.seed() - bestParent = _generate_parent(targetLen, geneSet, get_fitness) - display(bestParent) - if bestParent.Fitness >= optimalFitness: - return bestParent - while True: - child = _mutate(bestParent, geneSet, get_fitness) - if bestParent.Fitness >= child.Fitness: - continue - display(child) - if child.Fitness >= optimalFitness: - return child - bestParent = child - - -class Chromosome: - def __init__(self, genes, fitness): - self.Genes = genes - self.Fitness = fitness - - -class Benchmark: - @staticmethod - def run(function): - timings = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - startTime = time.time() - function() - seconds = time.time() - startTime - sys.stdout = stdout - timings.append(seconds) - mean = statistics.mean(timings) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, mean, - statistics.stdev(timings, mean) if i > 1 else 0)) diff --git a/ch02/guessPasswordTests.py b/ch02/guessPasswordTests.py deleted file mode 100644 index a42270b..0000000 --- a/ch02/guessPasswordTests.py +++ /dev/null @@ -1,75 +0,0 @@ -# File: guessPasswordTests.py -# from chapter 2 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import unittest - -import genetic - - -def get_fitness(guess, target): - return sum(1 for expected, actual in zip(target, guess) - if expected == actual) - - -def display(candidate, startTime): - timeDiff = datetime.datetime.now() - startTime - print("{}\t{}\t{}".format( - ''.join(candidate.Genes), - candidate.Fitness, - timeDiff)) - - -class GuessPasswordTests(unittest.TestCase): - geneset = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!.," - - def test_Hello_World(self): - target = "Hello World!" - self.guess_password(target) - - def test_For_I_am_fearfully_and_wonderfully_made(self): - target = "For I am fearfully and wonderfully made." - self.guess_password(target) - - def guess_password(self, target): - startTime = datetime.datetime.now() - - def fnGetFitness(genes): - return get_fitness(genes, target) - - def fnDisplay(candidate): - display(candidate, startTime) - - optimalFitness = len(target) - best = genetic.get_best(fnGetFitness, len(target), optimalFitness, - self.geneset, fnDisplay) - self.assertEqual(''.join(best.Genes), target) - - def test_Random(self): - length = 150 - target = ''.join(random.choice(self.geneset) - for _ in range(length)) - - self.guess_password(target) - - def test_benchmark(self): - genetic.Benchmark.run(self.test_Random) - - -if __name__ == '__main__': - unittest.main() diff --git a/ch02/oneMaxTests.py b/ch02/oneMaxTests.py deleted file mode 100644 index 930ce03..0000000 --- a/ch02/oneMaxTests.py +++ /dev/null @@ -1,58 +0,0 @@ -# File: oneMaxTests.py -# from chapter 2 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import unittest - -import genetic - - -def get_fitness(genes): - return genes.count(1) - - -def display(candidate, startTime): - timeDiff = datetime.datetime.now() - startTime - print("{}...{}\t{:3.2f}\t{}".format( - ''.join(map(str, candidate.Genes[:15])), - ''.join(map(str, candidate.Genes[-15:])), - candidate.Fitness, - timeDiff)) - - -class OneMaxTests(unittest.TestCase): - def test(self, length=100): - geneset = [0, 1] - startTime = datetime.datetime.now() - - def fnDisplay(candidate): - display(candidate, startTime) - - def fnGetFitness(genes): - return get_fitness(genes) - - optimalFitness = length - best = genetic.get_best(fnGetFitness, length, optimalFitness, - geneset, fnDisplay) - self.assertEqual(best.Fitness, optimalFitness) - - def test_benchmark(self): - genetic.Benchmark.run(lambda: self.test(4000)) - - -if __name__ == '__main__': - unittest.main() diff --git a/ch03/genetic.py b/ch03/genetic.py deleted file mode 100644 index 0a4e40d..0000000 --- a/ch03/genetic.py +++ /dev/null @@ -1,93 +0,0 @@ -# File: genetic.py -# from chapter 3 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time - - -def _generate_parent(length, geneSet, get_fitness): - genes = [] - while len(genes) < length: - sampleSize = min(length - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, sampleSize)) - fitness = get_fitness(genes) - return Chromosome(genes, fitness) - - -def _mutate(parent, geneSet, get_fitness): - childGenes = parent.Genes[:] - index = random.randrange(0, len(parent.Genes)) - newGene, alternate = random.sample(geneSet, 2) - childGenes[index] = alternate if newGene == childGenes[index] else newGene - fitness = get_fitness(childGenes) - return Chromosome(childGenes, fitness) - - -def get_best(get_fitness, targetLen, optimalFitness, geneSet, display): - random.seed() - - def fnMutate(parent): - return _mutate(parent, geneSet, get_fitness) - - def fnGenerateParent(): - return _generate_parent(targetLen, geneSet, get_fitness) - - for improvement in _get_improvement(fnMutate, fnGenerateParent): - display(improvement) - if not optimalFitness > improvement.Fitness: - return improvement - - -def _get_improvement(new_child, generate_parent): - bestParent = generate_parent() - yield bestParent - while True: - child = new_child(bestParent) - if bestParent.Fitness > child.Fitness: - continue - if not child.Fitness > bestParent.Fitness: - bestParent = child - continue - yield child - bestParent = child - - -class Chromosome: - def __init__(self, genes, fitness): - self.Genes = genes - self.Fitness = fitness - - -class Benchmark: - @staticmethod - def run(function): - timings = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - startTime = time.time() - function() - seconds = time.time() - startTime - sys.stdout = stdout - timings.append(seconds) - mean = statistics.mean(timings) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, mean, - statistics.stdev(timings, mean) if i > 1 else 0)) diff --git a/ch03/sortedNumbersTests.py b/ch03/sortedNumbersTests.py deleted file mode 100644 index 9d54e76..0000000 --- a/ch03/sortedNumbersTests.py +++ /dev/null @@ -1,85 +0,0 @@ -# File: sortedNumbersTests.py -# from chapter 3 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - - -import datetime -import unittest - -import genetic - - -def get_fitness(genes): - fitness = 1 - gap = 0 - - for i in range(1, len(genes)): - if genes[i] > genes[i - 1]: - fitness += 1 - else: - gap += genes[i - 1] - genes[i] - return Fitness(fitness, gap) - - -def display(candidate, startTime): - timeDiff = datetime.datetime.now() - startTime - print("{}\t=> {}\t{}".format( - ', '.join(map(str, candidate.Genes)), - candidate.Fitness, - timeDiff)) - - -class SortedNumbersTests(unittest.TestCase): - def test_sort_10_numbers(self): - self.sort_numbers(10) - - def sort_numbers(self, totalNumbers): - geneset = [i for i in range(100)] - startTime = datetime.datetime.now() - - def fnDisplay(candidate): - display(candidate, startTime) - - def fnGetFitness(genes): - return get_fitness(genes) - - optimalFitness = Fitness(totalNumbers, 0) - best = genetic.get_best(fnGetFitness, totalNumbers, optimalFitness, - geneset, fnDisplay) - self.assertTrue(not optimalFitness > best.Fitness) - - def test_benchmark(self): - genetic.Benchmark.run(lambda: self.sort_numbers(40)) - - -class Fitness: - def __init__(self, numbersInSequenceCount, totalGap): - self.NumbersInSequenceCount = numbersInSequenceCount - self.TotalGap = totalGap - - def __gt__(self, other): - if self.NumbersInSequenceCount != other.NumbersInSequenceCount: - return self.NumbersInSequenceCount > other.NumbersInSequenceCount - return self.TotalGap < other.TotalGap - - def __str__(self): - return "{} Sequential, {} Total Gap".format( - self.NumbersInSequenceCount, - self.TotalGap) - - -if __name__ == '__main__': - unittest.main() diff --git a/ch04/8queensTests.py b/ch04/8queensTests.py deleted file mode 100644 index 5e1ee11..0000000 --- a/ch04/8queensTests.py +++ /dev/null @@ -1,104 +0,0 @@ -# File: 8queensTests.py -# from chapter 4 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import unittest - -import genetic - - -def get_fitness(genes, size): - board = Board(genes, size) - rowsWithQueens = set() - colsWithQueens = set() - northEastDiagonalsWithQueens = set() - southEastDiagonalsWithQueens = set() - for row in range(size): - for col in range(size): - if board.get(row, col) == 'Q': - rowsWithQueens.add(row) - colsWithQueens.add(col) - northEastDiagonalsWithQueens.add(row + col) - southEastDiagonalsWithQueens.add(size - 1 - row + col) - total = size - len(rowsWithQueens) \ - + size - len(colsWithQueens) \ - + size - len(northEastDiagonalsWithQueens) \ - + size - len(southEastDiagonalsWithQueens) - return Fitness(total) - - -def display(candidate, startTime, size): - timeDiff = datetime.datetime.now() - startTime - board = Board(candidate.Genes, size) - board.print() - print("{}\t- {}\t{}".format( - ' '.join(map(str, candidate.Genes)), - candidate.Fitness, - timeDiff)) - - -class EightQueensTests(unittest.TestCase): - def test(self, size=8): - geneset = [i for i in range(size)] - startTime = datetime.datetime.now() - - def fnDisplay(candidate): - display(candidate, startTime, size) - - def fnGetFitness(genes): - return get_fitness(genes, size) - - optimalFitness = Fitness(0) - best = genetic.get_best(fnGetFitness, 2 * size, optimalFitness, - geneset, fnDisplay) - self.assertTrue(not optimalFitness > best.Fitness) - - def test_benchmark(self): - genetic.Benchmark.run(lambda: self.test(20)) - - -class Board: - def __init__(self, genes, size): - board = [['.'] * size for _ in range(size)] - for index in range(0, len(genes), 2): - row = genes[index] - column = genes[index + 1] - board[column][row] = 'Q' - self._board = board - - def get(self, row, column): - return self._board[column][row] - - def print(self): - # 0,0 prints in bottom left corner - for i in reversed(range(len(self._board))): - print(' '.join(self._board[i])) - - -class Fitness: - def __init__(self, total): - self.Total = total - - def __gt__(self, other): - return self.Total < other.Total - - def __str__(self): - return "{}".format(self.Total) - - -if __name__ == '__main__': - unittest.main() diff --git a/ch05/adjacent_states.csv b/ch05/adjacent_states.csv deleted file mode 100644 index 7f50837..0000000 --- a/ch05/adjacent_states.csv +++ /dev/null @@ -1,51 +0,0 @@ -AK, -AL,FL;GA;MS;TN -AR,LA;MO;MS;OK;TN;TX -AZ,CA;NM;NV;UT -CA,AZ;NV;OR -CO,KS;NE;NM;OK;UT;WY -CT,MA;NY;RI -DC,MD;VA -DE,MD;NJ;PA -FL,AL;GA -GA,AL;FL;NC;SC;TN -HI, -IA,IL;MN;MO;NE;SD;WI -ID,MT;NV;OR;UT;WA;WY -IL,IA;IN;KY;MO;WI -IN,IL;KY;MI;OH -KS,CO;MO;NE;OK -KY,IL;IN;MO;OH;TN;VA;WV -LA,AR;MS;TX -MA,CT;NH;NY;RI;VT -MD,DC;DE;PA;VA;WV -ME,NH -MI,IN;OH;WI -MN,IA;ND;SD;WI -MO,AR;IA;IL;KS;KY;NE;OK;TN -MS,AL;AR;LA;TN -MT,ID;ND;SD;WY -NC,GA;SC;TN;VA -ND,MN;MT;SD -NE,CO;IA;KS;MO;SD;WY -NH,MA;ME;VT -NJ,DE;NY;PA -NM,AZ;CO;OK;TX -NV,AZ;CA;ID;OR;UT -NY,CT;MA;NJ;PA;VT -OH,IN;KY;MI;PA;WV -OK,AR;CO;KS;MO;NM;TX -OR,CA;ID;NV;WA -PA,DE;MD;NJ;NY;OH;WV -RI,CT;MA -SC,GA;NC -SD,IA;MN;MT;ND;NE;WY -TN,AL;AR;GA;KY;MO;MS;NC;VA -TX,AR;LA;NM;OK -UT,AZ;CO;ID;NV;WY -VA,DC;KY;MD;NC;TN;WV -VT,MA;NH;NY -WA,ID;OR -WI,IA;IL;MI;MN -WV,KY;MD;OH;PA;VA -WY,CO;ID;MT;NE;SD;UT \ No newline at end of file diff --git a/ch05/graphColoringTests.py b/ch05/graphColoringTests.py deleted file mode 100644 index d25e27a..0000000 --- a/ch05/graphColoringTests.py +++ /dev/null @@ -1,137 +0,0 @@ -# File: graphColoringTests.py -# from chapter 5 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import unittest - -import genetic - - -def load_data(localFileName): - """ expects: T D1 [D2 ... DN] - where T is the record type - and D1 .. DN are record-type appropriate data elements - """ - rules = set() - nodes = set() - with open(localFileName, mode='r') as infile: - content = infile.read().splitlines() - for row in content: - if row[0] == 'e': # e aa bb, aa and bb are node ids - nodeIds = row.split(' ')[1:3] - rules.add(Rule(nodeIds[0], nodeIds[1])) - nodes.add(nodeIds[0]) - nodes.add(nodeIds[1]) - continue - if row[0] == 'n': # n aa ww, aa is a node id, ww is a weight - nodeIds = row.split(' ') - nodes.add(nodeIds[1]) - return rules, nodes - - -def build_rules(items): - rulesAdded = {} - for state, adjacent in items.items(): - for adjacentState in adjacent: - if adjacentState == '': - continue - rule = Rule(state, adjacentState) - if rule in rulesAdded: - rulesAdded[rule] += 1 - else: - rulesAdded[rule] = 1 - for k, v in rulesAdded.items(): - if v != 2: - print("rule {} is not bidirectional".format(k)) - return rulesAdded.keys() - - -def get_fitness(genes, rules, stateIndexLookup): - rulesThatPass = sum(1 for rule in rules - if rule.IsValid(genes, stateIndexLookup)) - return rulesThatPass - - -def display(candidate, startTime): - timeDiff = datetime.datetime.now() - startTime - print("{}\t{}\t{}".format( - ''.join(map(str, candidate.Genes)), - candidate.Fitness, - timeDiff)) - - -class GraphColoringTests(unittest.TestCase): - def test_states(self): - self.color("adjacent_states.col", - ["Orange", "Yellow", "Green", "Blue"]) - - def test_R100_1gb(self): - self.color("R100_1gb.col", - ["Red", "Orange", "Yellow", "Green", "Blue", "Indigo"]) - - def test_benchmark(self): - genetic.Benchmark.run(lambda: self.test_R100_1gb()) - - def color(self, file, colors): - rules, nodes = load_data(file) - optimalValue = len(rules) - colorLookup = {color[0]: color for color in colors} - geneset = list(colorLookup.keys()) - startTime = datetime.datetime.now() - nodeIndexLookup = {key: index - for index, key in enumerate(sorted(nodes))} - - def fnDisplay(candidate): - display(candidate, startTime) - - def fnGetFitness(genes): - return get_fitness(genes, rules, nodeIndexLookup) - - best = genetic.get_best(fnGetFitness, len(nodes), optimalValue, - geneset, fnDisplay) - self.assertTrue(not optimalValue > best.Fitness) - - keys = sorted(nodes) - for index in range(len(nodes)): - print(keys[index] + " is " + colorLookup[best.Genes[index]]) - - -class Rule: - def __init__(self, node, adjacent): - if node < adjacent: - node, adjacent = adjacent, node - self.Node = node - self.Adjacent = adjacent - - def __eq__(self, other): - return self.Node == other.Node and self.Adjacent == other.Adjacent - - def __hash__(self): - return hash(self.Node) * 397 ^ hash(self.Adjacent) - - def __str__(self): - return self.Node + " -> " + self.Adjacent - - def IsValid(self, genes, nodeIndexLookup): - index = nodeIndexLookup[self.Node] - adjacentNodeIndex = nodeIndexLookup[self.Adjacent] - - return genes[index] != genes[adjacentNodeIndex] - - -if __name__ == '__main__': - unittest.main() diff --git a/ch06/cardTests.py b/ch06/cardTests.py deleted file mode 100644 index f931c60..0000000 --- a/ch06/cardTests.py +++ /dev/null @@ -1,101 +0,0 @@ -# File: cardTests.py -# from chapter 6 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import functools -import operator -import random -import unittest - -import genetic - - -def get_fitness(genes): - group1Sum = sum(genes[0:5]) - group2Product = functools.reduce(operator.mul, genes[5:10]) - duplicateCount = (len(genes) - len(set(genes))) - return Fitness(group1Sum, group2Product, duplicateCount) - - -def display(candidate, startTime): - timeDiff = datetime.datetime.now() - startTime - print("{} - {}\t{}\t{}".format( - ', '.join(map(str, candidate.Genes[0:5])), - ', '.join(map(str, candidate.Genes[5:10])), - candidate.Fitness, - timeDiff)) - - -def mutate(genes, geneset): - if len(genes) == len(set(genes)): - count = random.randint(1, 4) - while count > 0: - count -= 1 - indexA, indexB = random.sample(range(len(genes)), 2) - genes[indexA], genes[indexB] = genes[indexB], genes[indexA] - else: - indexA = random.randrange(0, len(genes)) - indexB = random.randrange(0, len(geneset)) - genes[indexA] = geneset[indexB] - - -class CardTests(unittest.TestCase): - def test(self): - geneset = [i + 1 for i in range(10)] - startTime = datetime.datetime.now() - - def fnDisplay(candidate): - display(candidate, startTime) - - def fnGetFitness(genes): - return get_fitness(genes) - - def fnMutate(genes): - mutate(genes, geneset) - - optimalFitness = Fitness(36, 360, 0) - best = genetic.get_best(fnGetFitness, 10, optimalFitness, geneset, - fnDisplay, custom_mutate=fnMutate) - self.assertTrue(not optimalFitness > best.Fitness) - - def test_benchmark(self): - genetic.Benchmark.run(lambda: self.test()) - - -class Fitness: - def __init__(self, group1Sum, group2Product, duplicateCount): - self.Group1Sum = group1Sum - self.Group2Product = group2Product - sumDifference = abs(36 - group1Sum) - productDifference = abs(360 - group2Product) - self.TotalDifference = sumDifference + productDifference - self.DuplicateCount = duplicateCount - - def __gt__(self, other): - if self.DuplicateCount != other.DuplicateCount: - return self.DuplicateCount < other.DuplicateCount - return self.TotalDifference < other.TotalDifference - - def __str__(self): - return "sum: {} prod: {} dups: {}".format( - self.Group1Sum, - self.Group2Product, - self.DuplicateCount) - - -if __name__ == '__main__': - unittest.main() diff --git a/ch06/genetic.py b/ch06/genetic.py deleted file mode 100644 index 06cb28b..0000000 --- a/ch06/genetic.py +++ /dev/null @@ -1,103 +0,0 @@ -# File: genetic.py -# from chapter 6 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time - - -def _generate_parent(length, geneSet, get_fitness): - genes = [] - while len(genes) < length: - sampleSize = min(length - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, sampleSize)) - fitness = get_fitness(genes) - return Chromosome(genes, fitness) - - -def _mutate(parent, geneSet, get_fitness): - childGenes = parent.Genes[:] - index = random.randrange(0, len(parent.Genes)) - newGene, alternate = random.sample(geneSet, 2) - childGenes[index] = alternate if newGene == childGenes[index] else newGene - fitness = get_fitness(childGenes) - return Chromosome(childGenes, fitness) - - -def _mutate_custom(parent, custom_mutate, get_fitness): - childGenes = parent.Genes[:] - custom_mutate(childGenes) - fitness = get_fitness(childGenes) - return Chromosome(childGenes, fitness) - - -def get_best(get_fitness, targetLen, optimalFitness, geneSet, display, - custom_mutate=None): - if custom_mutate is None: - def fnMutate(parent): - return _mutate(parent, geneSet, get_fitness) - else: - def fnMutate(parent): - return _mutate_custom(parent, custom_mutate, get_fitness) - - def fnGenerateParent(): - return _generate_parent(targetLen, geneSet, get_fitness) - - for improvement in _get_improvement(fnMutate, fnGenerateParent): - display(improvement) - if not optimalFitness > improvement.Fitness: - return improvement - - -def _get_improvement(new_child, generate_parent): - bestParent = generate_parent() - yield bestParent - while True: - child = new_child(bestParent) - if bestParent.Fitness > child.Fitness: - continue - if not child.Fitness > bestParent.Fitness: - bestParent = child - continue - yield child - bestParent = child - - -class Chromosome: - def __init__(self, genes, fitness): - self.Genes = genes - self.Fitness = fitness - - -class Benchmark: - @staticmethod - def run(function): - timings = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - startTime = time.time() - function() - seconds = time.time() - startTime - sys.stdout = stdout - timings.append(seconds) - mean = statistics.mean(timings) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, mean, - statistics.stdev(timings, mean) if i > 1 else 0)) diff --git a/ch07/genetic.py b/ch07/genetic.py deleted file mode 100644 index 290906e..0000000 --- a/ch07/genetic.py +++ /dev/null @@ -1,108 +0,0 @@ -# File: genetic.py -# from chapter 7 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time - - -def _generate_parent(length, geneSet, get_fitness): - genes = [] - while len(genes) < length: - sampleSize = min(length - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, sampleSize)) - fitness = get_fitness(genes) - return Chromosome(genes, fitness) - - -def _mutate(parent, geneSet, get_fitness): - childGenes = parent.Genes[:] - index = random.randrange(0, len(parent.Genes)) - newGene, alternate = random.sample(geneSet, 2) - childGenes[index] = alternate if newGene == childGenes[index] else newGene - fitness = get_fitness(childGenes) - return Chromosome(childGenes, fitness) - - -def _mutate_custom(parent, custom_mutate, get_fitness): - childGenes = parent.Genes[:] - custom_mutate(childGenes) - fitness = get_fitness(childGenes) - return Chromosome(childGenes, fitness) - - -def get_best(get_fitness, targetLen, optimalFitness, geneSet, display, - custom_mutate=None, custom_create=None): - if custom_mutate is None: - def fnMutate(parent): - return _mutate(parent, geneSet, get_fitness) - else: - def fnMutate(parent): - return _mutate_custom(parent, custom_mutate, get_fitness) - - if custom_create is None: - def fnGenerateParent(): - return _generate_parent(targetLen, geneSet, get_fitness) - else: - def fnGenerateParent(): - genes = custom_create() - return Chromosome(genes, get_fitness(genes)) - - for improvement in _get_improvement(fnMutate, fnGenerateParent): - display(improvement) - if not optimalFitness > improvement.Fitness: - return improvement - - -def _get_improvement(new_child, generate_parent): - bestParent = generate_parent() - yield bestParent - while True: - child = new_child(bestParent) - if bestParent.Fitness > child.Fitness: - continue - if not child.Fitness > bestParent.Fitness: - bestParent = child - continue - yield child - bestParent = child - - -class Chromosome: - def __init__(self, genes, fitness): - self.Genes = genes - self.Fitness = fitness - - -class Benchmark: - @staticmethod - def run(function): - timings = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - startTime = time.time() - function() - seconds = time.time() - startTime - sys.stdout = stdout - timings.append(seconds) - mean = statistics.mean(timings) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, mean, - statistics.stdev(timings, mean) if i > 1 else 0)) diff --git a/ch07/knightsTests.py b/ch07/knightsTests.py deleted file mode 100644 index b232cc9..0000000 --- a/ch07/knightsTests.py +++ /dev/null @@ -1,196 +0,0 @@ -# File: knightsTests.py -# from chapter 7 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import unittest - -import genetic - - -def get_fitness(genes, boardWidth, boardHeight): - attacked = set(pos - for kn in genes - for pos in get_attacks(kn, boardWidth, boardHeight)) - return len(attacked) - - -def display(candidate, startTime, boardWidth, boardHeight): - timeDiff = datetime.datetime.now() - startTime - board = Board(candidate.Genes, boardWidth, boardHeight) - board.print() - - print("{}\n\t{}\t{}".format( - ' '.join(map(str, candidate.Genes)), - candidate.Fitness, - timeDiff)) - - -def mutate(genes, boardWidth, boardHeight, allPositions, nonEdgePositions): - count = 2 if random.randint(0, 10) == 0 else 1 - while count > 0: - count -= 1 - positionToKnightIndexes = dict((p, []) for p in allPositions) - for i, knight in enumerate(genes): - for position in get_attacks(knight, boardWidth, boardHeight): - positionToKnightIndexes[position].append(i) - knightIndexes = set(i for i in range(len(genes))) - unattacked = [] - for kvp in positionToKnightIndexes.items(): - if len(kvp[1]) > 1: - continue - if len(kvp[1]) == 0: - unattacked.append(kvp[0]) - continue - for p in kvp[1]: # len == 1 - if p in knightIndexes: - knightIndexes.remove(p) - - potentialKnightPositions = \ - [p for positions in - map(lambda x: get_attacks(x, boardWidth, boardHeight), - unattacked) - for p in positions if p in nonEdgePositions] \ - if len(unattacked) > 0 else nonEdgePositions - - geneIndex = random.randrange(0, len(genes)) \ - if len(knightIndexes) == 0 \ - else random.choice([i for i in knightIndexes]) - - position = random.choice(potentialKnightPositions) - genes[geneIndex] = position - - -def create(fnGetRandomPosition, expectedKnights): - genes = [fnGetRandomPosition() for _ in range(expectedKnights)] - return genes - - -def get_attacks(location, boardWidth, boardHeight): - return [i for i in set( - Position(x + location.X, y + location.Y) - for x in [-2, -1, 1, 2] if 0 <= x + location.X < boardWidth - for y in [-2, -1, 1, 2] if 0 <= y + location.Y < boardHeight - and abs(y) != abs(x))] - - -class KnightsTests(unittest.TestCase): - def test_3x4(self): - width = 4 - height = 3 - # 1,0 2,0 3,0 - # 0,2 1,2 2,2 - # 2 N N N . - # 1 . . . . - # 0 . N N N - # 0 1 2 3 - self.find_knight_positions(width, height, 6) - - def test_8x8(self): - width = 8 - height = 8 - self.find_knight_positions(width, height, 14) - - def test_10x10(self): - width = 10 - height = 10 - self.find_knight_positions(width, height, 22) - - def test_12x12(self): - width = 12 - height = 12 - self.find_knight_positions(width, height, 28) - - def test_13x13(self): - width = 13 - height = 13 - self.find_knight_positions(width, height, 32) - - def test_benchmark(self): - genetic.Benchmark.run(lambda: self.test_10x10()) - - def find_knight_positions(self, boardWidth, boardHeight, expectedKnights): - startTime = datetime.datetime.now() - - def fnDisplay(candidate): - display(candidate, startTime, boardWidth, boardHeight) - - def fnGetFitness(genes): - return get_fitness(genes, boardWidth, boardHeight) - - allPositions = [Position(x, y) - for y in range(boardHeight) - for x in range(boardWidth)] - - if boardWidth < 6 or boardHeight < 6: - nonEdgePositions = allPositions - else: - nonEdgePositions = [i for i in allPositions - if 0 < i.X < boardWidth - 1 and - 0 < i.Y < boardHeight - 1] - - def fnGetRandomPosition(): - return random.choice(nonEdgePositions) - - def fnMutate(genes): - mutate(genes, boardWidth, boardHeight, allPositions, - nonEdgePositions) - - def fnCreate(): - return create(fnGetRandomPosition, expectedKnights) - - optimalFitness = boardWidth * boardHeight - best = genetic.get_best(fnGetFitness, None, optimalFitness, None, - fnDisplay, fnMutate, fnCreate) - self.assertTrue(not optimalFitness > best.Fitness) - - -class Position: - def __init__(self, x, y): - self.X = x - self.Y = y - - def __str__(self): - return "{},{}".format(self.X, self.Y) - - def __eq__(self, other): - return self.X == other.X and self.Y == other.Y - - def __hash__(self): - return self.X * 1000 + self.Y - - -class Board: - def __init__(self, positions, width, height): - board = [['.'] * width for _ in range(height)] - - for index in range(len(positions)): - knightPosition = positions[index] - board[knightPosition.Y][knightPosition.X] = 'N' - self._board = board - self._width = width - self._height = height - - def print(self): - # 0,0 prints in bottom left corner - for i in reversed(range(self._height)): - print(i, "\t", ' '.join(self._board[i])) - print(" \t", ' '.join(map(str, range(self._width)))) - - -if __name__ == '__main__': - unittest.main() diff --git a/ch08/genetic.py b/ch08/genetic.py deleted file mode 100644 index 189107d..0000000 --- a/ch08/genetic.py +++ /dev/null @@ -1,131 +0,0 @@ -# File: genetic.py -# from chapter 8 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time -from bisect import bisect_left -from math import exp - - -def _generate_parent(length, geneSet, get_fitness): - genes = [] - while len(genes) < length: - sampleSize = min(length - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, sampleSize)) - fitness = get_fitness(genes) - return Chromosome(genes, fitness) - - -def _mutate(parent, geneSet, get_fitness): - childGenes = parent.Genes[:] - index = random.randrange(0, len(parent.Genes)) - newGene, alternate = random.sample(geneSet, 2) - childGenes[index] = alternate if newGene == childGenes[index] else newGene - fitness = get_fitness(childGenes) - return Chromosome(childGenes, fitness) - - -def _mutate_custom(parent, custom_mutate, get_fitness): - childGenes = parent.Genes[:] - custom_mutate(childGenes) - fitness = get_fitness(childGenes) - return Chromosome(childGenes, fitness) - - -def get_best(get_fitness, targetLen, optimalFitness, geneSet, display, - custom_mutate=None, custom_create=None, maxAge=None): - if custom_mutate is None: - def fnMutate(parent): - return _mutate(parent, geneSet, get_fitness) - else: - def fnMutate(parent): - return _mutate_custom(parent, custom_mutate, get_fitness) - - if custom_create is None: - def fnGenerateParent(): - return _generate_parent(targetLen, geneSet, get_fitness) - else: - def fnGenerateParent(): - genes = custom_create() - return Chromosome(genes, get_fitness(genes)) - - for improvement in _get_improvement(fnMutate, fnGenerateParent, maxAge): - display(improvement) - if not optimalFitness > improvement.Fitness: - return improvement - - -def _get_improvement(new_child, generate_parent, maxAge): - parent = bestParent = generate_parent() - yield bestParent - historicalFitnesses = [bestParent.Fitness] - while True: - child = new_child(parent) - if parent.Fitness > child.Fitness: - if maxAge is None: - continue - parent.Age += 1 - if maxAge > parent.Age: - continue - index = bisect_left(historicalFitnesses, child.Fitness, 0, - len(historicalFitnesses)) - proportionSimilar = index / len(historicalFitnesses) - if random.random() < exp(-proportionSimilar): - parent = child - continue - bestParent.Age = 0 - parent = bestParent - continue - if not child.Fitness > parent.Fitness: - # same fitness - child.Age = parent.Age + 1 - parent = child - continue - child.Age = 0 - parent = child - if child.Fitness > bestParent.Fitness: - bestParent = child - yield bestParent - historicalFitnesses.append(bestParent.Fitness) - - -class Chromosome: - def __init__(self, genes, fitness): - self.Genes = genes - self.Fitness = fitness - self.Age = 0 - - -class Benchmark: - @staticmethod - def run(function): - timings = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - startTime = time.time() - function() - seconds = time.time() - startTime - sys.stdout = stdout - timings.append(seconds) - mean = statistics.mean(timings) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, mean, - statistics.stdev(timings, mean) if i > 1 else 0)) diff --git a/ch08/magicSquareTests.py b/ch08/magicSquareTests.py deleted file mode 100644 index bb86110..0000000 --- a/ch08/magicSquareTests.py +++ /dev/null @@ -1,127 +0,0 @@ -# File: magicSquareTests.py -# from chapter 8 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import unittest - -import genetic - - -def get_fitness(genes, diagonalSize, expectedSum): - rows, columns, northeastDiagonalSum, southeastDiagonalSum = \ - get_sums(genes, diagonalSize) - - sumOfDifferences = sum(int(abs(s - expectedSum)) - for s in rows + columns + - [southeastDiagonalSum, northeastDiagonalSum] - if s != expectedSum) - - return Fitness(sumOfDifferences) - - -def display(candidate, diagonalSize, startTime): - timeDiff = datetime.datetime.now() - startTime - - rows, columns, northeastDiagonalSum, southeastDiagonalSum = \ - get_sums(candidate.Genes, diagonalSize) - - for rowNumber in range(diagonalSize): - row = candidate.Genes[ - rowNumber * diagonalSize:(rowNumber + 1) * diagonalSize] - print("\t ", row, "=", rows[rowNumber]) - print(northeastDiagonalSum, "\t", columns, "\t", southeastDiagonalSum) - print(" - - - - - - - - - - -", candidate.Fitness, timeDiff) - - -def get_sums(genes, diagonalSize): - rows = [0 for _ in range(diagonalSize)] - columns = [0 for _ in range(diagonalSize)] - southeastDiagonalSum = 0 - northeastDiagonalSum = 0 - for row in range(diagonalSize): - for column in range(diagonalSize): - value = genes[row * diagonalSize + column] - rows[row] += value - columns[column] += value - southeastDiagonalSum += genes[row * diagonalSize + row] - northeastDiagonalSum += genes[row * diagonalSize + - (diagonalSize - 1 - row)] - return rows, columns, northeastDiagonalSum, southeastDiagonalSum - - -def mutate(genes, indexes): - indexA, indexB = random.sample(indexes, 2) - genes[indexA], genes[indexB] = genes[indexB], genes[indexA] - - -class MagicSquareTests(unittest.TestCase): - def test_size_3(self): - self.generate(3, 50) - - def test_size_4(self): - self.generate(4, 50) - - def test_size_5(self): - self.generate(5, 500) - - def test_size_10(self): - self.generate(10, 5000) - - def test_benchmark(self): - genetic.Benchmark.run(self.test_size_4) - - def generate(self, diagonalSize, maxAge): - nSquared = diagonalSize * diagonalSize - geneset = [i for i in range(1, nSquared + 1)] - expectedSum = diagonalSize * (nSquared + 1) / 2 - - def fnGetFitness(genes): - return get_fitness(genes, diagonalSize, expectedSum) - - def fnDisplay(candidate): - display(candidate, diagonalSize, startTime) - - geneIndexes = [i for i in range(0, len(geneset))] - - def fnMutate(genes): - mutate(genes, geneIndexes) - - def fnCustomCreate(): - return random.sample(geneset, len(geneset)) - - optimalValue = Fitness(0) - startTime = datetime.datetime.now() - best = genetic.get_best(fnGetFitness, nSquared, optimalValue, - geneset, fnDisplay, fnMutate, fnCustomCreate, - maxAge) - self.assertTrue(not optimalValue > best.Fitness) - - -class Fitness: - def __init__(self, sumOfDifferences): - self.SumOfDifferences = sumOfDifferences - - def __gt__(self, other): - return self.SumOfDifferences < other.SumOfDifferences - - def __str__(self): - return "{}".format(self.SumOfDifferences) - - -if __name__ == '__main__': - unittest.main() diff --git a/ch09/knapsackTests.py b/ch09/knapsackTests.py deleted file mode 100644 index 2f7ac5f..0000000 --- a/ch09/knapsackTests.py +++ /dev/null @@ -1,287 +0,0 @@ -# File: knapsackTests.py -# from chapter 9 of _Genetic Algorithms with Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2016 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import sys -import unittest - -import genetic - - -def get_fitness(genes): - totalWeight = 0 - totalVolume = 0 - totalValue = 0 - for iq in genes: - count = iq.Quantity - totalWeight += iq.Item.Weight * count - totalVolume += iq.Item.Volume * count - totalValue += iq.Item.Value * count - - return Fitness(totalWeight, totalVolume, totalValue) - - -def display(candidate, startTime): - timeDiff = datetime.datetime.now() - startTime - genes = candidate.Genes[:] - genes.sort(key=lambda iq: iq.Quantity, reverse=True) - - descriptions = [str(iq.Quantity) + "x" + iq.Item.Name for iq in genes] - if len(descriptions) == 0: - descriptions.append("Empty") - print("{}\t{}\t{}".format( - ', '.join(descriptions), - candidate.Fitness, - timeDiff)) - - -def max_quantity(item, maxWeight, maxVolume): - return min(int(maxWeight / item.Weight) - if item.Weight > 0 else sys.maxsize, - int(maxVolume / item.Volume) - if item.Volume > 0 else sys.maxsize) - - -def create(items, maxWeight, maxVolume): - genes = [] - remainingWeight, remainingVolume = maxWeight, maxVolume - for i in range(random.randrange(1, len(items))): - newGene = add(genes, items, remainingWeight, remainingVolume) - if newGene is not None: - genes.append(newGene) - remainingWeight -= newGene.Quantity * newGene.Item.Weight - remainingVolume -= newGene.Quantity * newGene.Item.Volume - return genes - - -def add(genes, items, maxWeight, maxVolume): - usedItems = {iq.Item for iq in genes} - item = random.choice(items) - while item in usedItems: - item = random.choice(items) - - maxQuantity = max_quantity(item, maxWeight, maxVolume) - return ItemQuantity(item, maxQuantity) if maxQuantity > 0 else None - - -def mutate(genes, items, maxWeight, maxVolume, window): - window.slide() - fitness = get_fitness(genes) - remainingWeight = maxWeight - fitness.TotalWeight - remainingVolume = maxVolume - fitness.TotalVolume - - removing = len(genes) > 1 and random.randint(0, 10) == 0 - if removing: - index = random.randrange(0, len(genes)) - iq = genes[index] - item = iq.Item - remainingWeight += item.Weight * iq.Quantity - remainingVolume += item.Volume * iq.Quantity - del genes[index] - - adding = (remainingWeight > 0 or remainingVolume > 0) and \ - (len(genes) == 0 or - (len(genes) < len(items) and random.randint(0, 100) == 0)) - - if adding: - newGene = add(genes, items, remainingWeight, remainingVolume) - if newGene is not None: - genes.append(newGene) - return - - index = random.randrange(0, len(genes)) - iq = genes[index] - item = iq.Item - remainingWeight += item.Weight * iq.Quantity - remainingVolume += item.Volume * iq.Quantity - - changeItem = len(genes) < len(items) and random.randint(0, 4) == 0 - if changeItem: - itemIndex = items.index(iq.Item) - start = max(1, itemIndex - window.Size) - stop = min(len(items) - 1, itemIndex + window.Size) - item = items[random.randint(start, stop)] - maxQuantity = max_quantity(item, remainingWeight, remainingVolume) - if maxQuantity > 0: - genes[index] = ItemQuantity(item, maxQuantity - if window.Size > 1 else random.randint(1, maxQuantity)) - else: - del genes[index] - - -class KnapsackTests(unittest.TestCase): - def test_cookies(self): - items = [ - Resource("Flour", 1680, 0.265, .41), - Resource("Butter", 1440, 0.5, .13), - Resource("Sugar", 1840, 0.441, .29) - ] - maxWeight = 10 - maxVolume = 4 - optimal = get_fitness( - [ItemQuantity(items[0], 1), - ItemQuantity(items[1], 14), - ItemQuantity(items[2], 6)]) - self.fill_knapsack(items, maxWeight, maxVolume, optimal) - - def test_exnsd16(self): - problemInfo = load_data("exnsd16.ukp") - items = problemInfo.Resources - maxWeight = problemInfo.MaxWeight - maxVolume = 0 - optimal = get_fitness(problemInfo.Solution) - self.fill_knapsack(items, maxWeight, maxVolume, optimal) - - def test_benchmark(self): - genetic.Benchmark.run(lambda: self.test_exnsd16()) - - def fill_knapsack(self, items, maxWeight, maxVolume, optimalFitness): - startTime = datetime.datetime.now() - window = Window(1, - max(1, int(len(items) / 3)), - int(len(items) / 2)) - - sortedItems = sorted(items, key=lambda item: item.Value) - - def fnDisplay(candidate): - display(candidate, startTime) - - def fnGetFitness(genes): - return get_fitness(genes) - - def fnCreate(): - return create(items, maxWeight, maxVolume) - - def fnMutate(genes): - mutate(genes, sortedItems, maxWeight, maxVolume, window) - - best = genetic.get_best(fnGetFitness, None, optimalFitness, None, - fnDisplay, fnMutate, fnCreate, maxAge=50) - self.assertTrue(not optimalFitness > best.Fitness) - - -def load_data(localFileName): - with open(localFileName, mode='r') as infile: - lines = infile.read().splitlines() - data = KnapsackProblemData() - f = find_constraint - - for line in lines: - f = f(line.strip(), data) - if f is None: - break - return data - - -def find_constraint(line, data): - parts = line.split(' ') - if parts[0] != "c:": - return find_constraint - data.MaxWeight = int(parts[1]) - return find_data_start - - -def find_data_start(line, data): - if line != "begin data": - return find_data_start - return read_resource_or_find_data_end - - -def read_resource_or_find_data_end(line, data): - if line == "end data": - return find_solution_start - parts = line.split('\t') - resource = Resource("R" + str(1 + len(data.Resources)), int(parts[1]), - int(parts[0]), 0) - data.Resources.append(resource) - return read_resource_or_find_data_end - - -def find_solution_start(line, data): - if line == "sol:": - return read_solution_resource_or_find_solution_end - return find_solution_start - - -def read_solution_resource_or_find_solution_end(line, data): - if line == "": - return None - parts = [p for p in line.split('\t') if p != ""] - resourceIndex = int(parts[0]) - 1 # make it 0 based - resourceQuantity = int(parts[1]) - data.Solution.append( - ItemQuantity(data.Resources[resourceIndex], resourceQuantity)) - return read_solution_resource_or_find_solution_end - - -class Resource: - def __init__(self, name, value, weight, volume): - self.Name = name - self.Value = value - self.Weight = weight - self.Volume = volume - - -class ItemQuantity: - def __init__(self, item, quantity): - self.Item = item - self.Quantity = quantity - - def __eq__(self, other): - return self.Item == other.Item and self.Quantity == other.Quantity - - -class Fitness: - def __init__(self, totalWeight, totalVolume, totalValue): - self.TotalWeight = totalWeight - self.TotalVolume = totalVolume - self.TotalValue = totalValue - - def __gt__(self, other): - if self.TotalValue != other.TotalValue: - return self.TotalValue > other.TotalValue - if self.TotalWeight != other.TotalWeight: - return self.TotalWeight < other.TotalWeight - return self.TotalVolume < other.TotalVolume - - def __str__(self): - return "wt: {:0.2f} vol: {:0.2f} value: {}".format( - self.TotalWeight, - self.TotalVolume, - self.TotalValue) - - -class KnapsackProblemData: - def __init__(self): - self.Resources = [] - self.MaxWeight = 0 - self.Solution = [] - - -class Window: - def __init__(self, minimum, maximum, size): - self.Min = minimum - self.Max = maximum - self.Size = size - - def slide(self): - self.Size = self.Size - 1 if self.Size > self.Min else self.Max - - -if __name__ == '__main__': - unittest.main() diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..8d8784a --- /dev/null +++ b/conftest.py @@ -0,0 +1,26 @@ +import shutil +from pathlib import Path +from typing import Generator + +import pytest + + +@pytest.fixture +def data_fixtures_folder(): + return Path(__file__).parent.absolute() / "data_fixtures" + + +@pytest.fixture(name="temp_folder") +def fixture_temp_folder() -> Generator[Path, None, None]: + """Create a temporary folder, and yield the path to it. The folder is + deleted after + Yields + ------ + Path + Path to the temporary folder + """ + test_folder = Path(__file__).parent.absolute() + temporary_test_folder = test_folder / "temp" + temporary_test_folder.mkdir(exist_ok=True) + yield temporary_test_folder + shutil.rmtree(temporary_test_folder) diff --git a/data_fixtures/raw/cricket_fixtures/cricket_clubs.csv b/data_fixtures/raw/cricket_fixtures/cricket_clubs.csv new file mode 100644 index 0000000..1467f42 --- /dev/null +++ b/data_fixtures/raw/cricket_fixtures/cricket_clubs.csv @@ -0,0 +1,169 @@ +team_num,name,ground,ground_num,division,division_num +1,BRE1,BRE_ground_1,1,1st XI Premier,0 +2,WAN1,WAN_ground_1,2,1st XI Premier,0 +3,CHE1,CHE_ground_1,3,1st XI Premier,0 +4,HAD1,HAD_ground_1,4,1st XI Premier,0 +5,HOR1,HOR_ground_1,5,1st XI Premier,0 +6,BIL1,BIL_ground_1,6,1st XI Premier,0 +7,CHI1,CHI_ground_1,7,1st XI Premier,0 +8,BEL1,BEL_ground_1,8,1st XI Premier,0 +9,COL1,COL_ground_1,9,1st XI Premier,0 +10,HAW1,HAW_ground_1,10,1st XI Premier,0 +11,BUC1,BUC_ground_1,11,1st XI Div 1,1 +12,ILF1,ILF_ground_1,12,1st XI Div 1,1 +13,SHE1,SHE_ground_1,13,1st XI Div 1,1 +14,WWE1,WWE_ground_1,14,1st XI Div 1,1 +15,FIV1,FIV_ground_1,15,1st XI Div 1,1 +16,HUT1,HUT_ground_1,16,1st XI Div 1,1 +17,LOU1,LOU_ground_1,17,1st XI Div 1,1 +18,UPM1,UPM_ground_1,18,1st XI Div 1,1 +19,OSS1,OSS_ground_1,19,1st XI Div 1,1 +20,HOH1,HOH_ground_1,20,1st XI Div 1,1 +21,GPR1,GPR_ground_1,21,1st XI Div 2,2 +22,SOS1,SOS_ground_1,22,1st XI Div 2,2 +23,OPA1,OPA_ground_1,23,1st XI Div 2,2 +24,ORS1,ORS_ground_1,24,1st XI Div 2,2 +25,HAT1,HAT_ground_1,25,1st XI Div 2,2 +26,BEN1,BEN_ground_1,26,1st XI Div 2,2 +27,WIC1,WIC_ground_1,27,1st XI Div 2,2 +28,FRE1,FRE_ground_1,28,1st XI Div 2,2 +29,LOS1,LOS_ground_1,29,1st XI Div 2,2 +30,WOS1,WOS_ground_1,30,1st XI Div 2,2 +31,OLB1,OLB_ground_1,31,1st XI Div 3,3 +32,SWD1,SWD_ground_1,32,1st XI Div 3,3 +33,HAR1,HAR_ground_1,33,1st XI Div 3,3 +34,WAL1,WAL_ground_1,34,1st XI Div 3,3 +35,ARD1,ARD_ground_1,35,1st XI Div 3,3 +36,EPP1,EPP_ground_1,36,1st XI Div 3,3 +37,GOR1,GOR_ground_1,37,1st XI Div 3,3 +38,SLH1,SLH_ground_1,38,1st XI Div 3,3 +39,WFG1,WFG_ground_1,39,1st XI Div 3,3 +40,WES1,WES_ground_1,40,1st XI Div 3,3 +41,RAI1,RAI_ground_1,41,1st XI Div 3,3 +42,BAR1,BAR_ground_1,42,1st XI Div 3,3 +43,NEW1,NEW_ground_1,43,1st XI Div 3,3 +44,SPR1,SPR_ground_1,44,1st XI Div 3,3 +45,HOR2,HOR_ground_1,5,2nd XI Premier,4 +46,CHE2,CHE_ground_1,3,2nd XI Premier,4 +47,BRE2,BRE_ground_1,1,2nd XI Premier,4 +48,WAN2,WAN_ground_1,2,2nd XI Premier,4 +49,ILF2,ILF_ground_1,12,2nd XI Premier,4 +50,SHE2,SHE_ground_1,13,2nd XI Premier,4 +51,WWE2,WWE_ground_1,14,2nd XI Premier,4 +52,OPA2,OPA_ground_1,23,2nd XI Premier,4 +53,CHI2,CHI_ground_1,7,2nd XI Premier,4 +54,BUC2,BUC_ground_1,11,2nd XI Premier,4 +55,UPM2,UPM_ground_1,18,2nd XI Div 1,5 +56,WIC2,WIC_ground_1,27,2nd XI Div 1,5 +57,HAW2,HAW_ground_1,10,2nd XI Div 1,5 +58,LOU2,LOU_ground_1,17,2nd XI Div 1,5 +59,HUT2,HUT_ground_1,16,2nd XI Div 1,5 +60,COL2,COL_ground_1,9,2nd XI Div 1,5 +61,BIL2,BIL_ground_1,6,2nd XI Div 1,5 +62,FRE2,FRE_ground_1,28,2nd XI Div 1,5 +63,SWD2,SWD_ground_1,32,2nd XI Div 1,5 +64,GPR2,GPR_ground_1,21,2nd XI Div 1,5 +65,BEL2,BEL_ground_1,4,2nd XI Div 2,6 +66,SOS2,SOS_ground_1,22,2nd XI Div 2,6 +67,HAR2,HAR_ground_1,33,2nd XI Div 2,6 +68,WOS2,WOS_ground_1,30,2nd XI Div 2,6 +69,OLB2,OLB_ground_1,31,2nd XI Div 2,6 +70,OSS2,OSS_ground_1,19,2nd XI Div 2,6 +71,ARD2,ARD_ground_1,35,2nd XI Div 2,6 +72,HAD2,HAD_ground_1,8,2nd XI Div 2,6 +73,LOS2,LOS_ground_1,29,2nd XI Div 2,6 +74,EPP2,EPP_ground_1,36,2nd XI Div 2,6 +75,WES2,WES_ground_1,40,2nd XI Div 3,7 +76,ORS2,ORS_ground_1,24,2nd XI Div 3,7 +77,BEN2,BEN_ground_1,26,2nd XI Div 3,7 +78,FIV2,FIV_ground_1,15,2nd XI Div 3,7 +79,SLH2,SLH_ground_1,38,2nd XI Div 3,7 +80,WFG2,WFG_ground_1,39,2nd XI Div 3,7 +81,GOR2,GOR_ground_1,37,2nd XI Div 3,7 +82,WAL2,WAL_ground_1,34,2nd XI Div 3,7 +83,HOH2,HOH_ground_1,25,2nd XI Div 3,7 +84,HAT2,HAT_ground_1,20,2nd XI Div 3,7 +85,UPM3,UPM_ground_2,45,3rd XI Premier,8 +86,BRE3,BRE_ground_2,46,3rd XI Premier,8 +87,SHE3,SHE_ground_2,47,3rd XI Premier,8 +88,HOR3,HOR_ground_2,48,3rd XI Premier,8 +89,HAW3,HAW_ground_2,49,3rd XI Premier,8 +90,HAR3,HAR_ground_2,50,3rd XI Premier,8 +91,WWE3,WWE_ground_2,51,3rd XI Premier,8 +92,WAN3,WAN_ground_2,52,3rd XI Premier,8 +93,ORS3,ORS_ground_2,53,3rd XI Premier,8 +94,HUT3,HUT_ground_2,54,3rd XI Premier,8 +95,LOU3,LOU_ground_2,55,3rd XI Div 1,9 +96,CHE3,CHE_ground_2,56,3rd XI Div 1,9 +97,UPM4,UPM_ground_2,45,3rd XI Div 1,9 +98,FRE3,FRE_ground_2,57,3rd XI Div 1,9 +99,BIL3,BIL_ground_2,58,3rd XI Div 1,9 +100,WAN4,WAN_ground_2,52,3rd XI Div 1,9 +101,BUH3,BUH_ground_2,59,3rd XI Div 1,9 +102,CHE4,CHE_ground_2,56,3rd XI Div 1,9 +103,ILF3,ILF_ground_2,60,3rd XI Div 1,9 +104,OPA3,OPA_ground_2,61,3rd XI Div 1,9 +105,BEL3,BEL_ground_2,62,3rd XI Div 2,10 +106,OSS3,OSS_ground_2,63,3rd XI Div 2,10 +107,WIC3,WIC_ground_2,64,3rd XI Div 2,10 +108,CHI3,CHI_ground_2,65,3rd XI Div 2,10 +109,FIV3,FIV_ground_2,66,3rd XI Div 2,10 +110,LOU4,LOU_ground_2,55,3rd XI Div 2,10 +111,SWD3,SWD_ground_2,67,3rd XI Div 2,10 +112,HOR4,HOR_ground_2,48,3rd XI Div 2,10 +113,BRE4,BRE_ground_2,46,3rd XI Div 2,10 +114,HAR4,HAR_ground_2,50,3rd XI Div 2,10 +115,WAN5,WAN_ground_3,68,3rd XI Div 3,11 +116,SOS3,SOS_ground_2,69,3rd XI Div 3,11 +117,HAW4,HAW_ground_2,49,3rd XI Div 3,11 +118,WAL3,WAL_ground_2,70,3rd XI Div 3,11 +119,FRE4,FRE_ground_2,57,3rd XI Div 3,11 +120,SLH3,SLH_ground_2,71,3rd XI Div 3,11 +121,GPR3,GPR_ground_2,72,3rd XI Div 3,11 +122,WFG3,WFG_ground_2,73,3rd XI Div 3,11 +123,WOS3,WOS_ground_2,74,3rd XI Div 3,11 +124,WES3,WES_ground_2,75,3rd XI Div 3,11 +125,HAT3,HAT_ground_2,76,4th XI Prem East,12 +126,ORS4,ORS_ground_2,53,4th XI Prem East,12 +127,LOS3,LOS_ground_2,77,4th XI Prem East,12 +128,HUT4,HUT_ground_2,54,4th XI Prem East,12 +129,BEL4,BEL_ground_2,62,4th XI Prem East,12 +130,BEN3,BEN_ground_2,78,4th XI Prem East,12 +131,BIL4,BIL_ground_2,58,4th XI Prem East,12 +132,ARD3,ARD_ground_2,79,4th XI Prem East,12 +133,CHE5,CHE_ground_3,80,4th XI Prem East,12 +134,BYE1,BYE_ground_1,81,4th XI Prem East,12 +135,HOH3,HOH_ground_2,82,4th XI Prem West,13 +136,OAP4,OAP_ground_2,83,4th XI Prem West,13 +137,BUH4,BUH_ground_2,59,4th XI Prem West,13 +138,UPM5,UPM_ground_3,84,4th XI Prem West,13 +139,BRE5,BRE_ground_3,85,4th XI Prem West,13 +140,LOU5,LOU_ground_3,86,4th XI Prem West,13 +141,SHE4,SHE_ground_2,47,4th XI Prem West,13 +142,EPP3,EPP_ground_2,87,4th XI Prem West,13 +143,WAL4,WAL_ground_2,70,4th XI Prem West,13 +144,BYE2,BYE_ground_1,81,4th XI Prem West,13 +145,ORS5,ORS_ground_3,88,4th XI Div 1 East,14 +146,SOS4,SOS_ground_2,69,4th XI Div 1 East,14 +147,HOH4,HOH_ground_2,82,4th XI Div 1 East,14 +148,SLH4,SLH_ground_2,71,4th XI Div 1 East,14 +149,LOS4,LOS_ground_2,77,4th XI Div 1 East,14 +150,BEL5,BEL_ground_3,89,4th XI Div 1 East,14 +151,BEN4,BEN_ground_2,78,4th XI Div 1 East,14 +152,HAT4,HAT_ground_2,76,4th XI Div 1 East,14 +153,OSS4,OSS_ground_2,63,4th XI Div 1 East,14 +154,BRE6,BRE_ground_3,85,4th XI Div 1 East,14 +155,OSS5,OSS_ground_3,90,4th XI Div 1 East,14 +156,WIC5,WIC_ground_3,91,4th XI Div 1 East,14 +157,GPR4,GPR_ground_2,72,4th XI Div 1 West,15 +158,SWD4,SWD_ground_2,67,4th XI Div 1 West,15 +159,GOR3,GOR_ground_2,92,4th XI Div 1 West,15 +160,HOR5,HOR_ground_3,93,4th XI Div 1 West,15 +161,OAP5,OAP_ground_3,94,4th XI Div 1 West,15 +162,ILF4,ILF_ground_2,60,4th XI Div 1 West,15 +163,WAN6,WAN_ground_3,68,4th XI Div 1 West,15 +164,CHI4,CHI_ground_2,65,4th XI Div 1 West,15 +165,HAW5,HAW_ground_3,95,4th XI Div 1 West,15 +166,ARD4,ARD_ground_2,79,4th XI Div 1 West,15 +167,HUT5,HUT_ground_3,96,4th XI Div 1 West,15 +168,FIV4,FIV_ground_2,66,4th XI Div 1 West,15 diff --git a/data_fixtures/raw/cricket_fixtures/single_division_unique_grounds.csv b/data_fixtures/raw/cricket_fixtures/single_division_unique_grounds.csv new file mode 100644 index 0000000..a848cd6 --- /dev/null +++ b/data_fixtures/raw/cricket_fixtures/single_division_unique_grounds.csv @@ -0,0 +1,9 @@ +team_num,name,ground,ground_num,division,division_num +1,manchester united,old trafford,1,premier league,0 +2,manchester city,etihad,2,premier league,0 +3,liverpool,anfield,3,premier league,0 +4,chelsea,stamford bridge,4,premier league,0 +5,arsenal,emirates,5,premier league,0 +6,tottenham,white hart lane,6,premier league,0 +7,everton,goodison park,7,premier league,0 +8,newcastle united,st james park,8,premier league,0 diff --git a/data_fixtures/raw/cricket_fixtures/three_divisions_shared_grounds.csv b/data_fixtures/raw/cricket_fixtures/three_divisions_shared_grounds.csv new file mode 100644 index 0000000..efacfa4 --- /dev/null +++ b/data_fixtures/raw/cricket_fixtures/three_divisions_shared_grounds.csv @@ -0,0 +1,32 @@ +team_num,name,ground,division,division_num,ground_num +1,manchester united,old trafford,premier league,0,1 +2,manchester city,etihad,premier league,0,2 +3,liverpool,anfield,premier league,0,3 +4,chelsea,stamford bridge,premier league,0,4 +5,arsenal,emirates,premier league,0,5 +6,tottenham,white hart lane,premier league,0,6 +7,everton,goodison park,premier league,0,7 +8,newcastle united,st james park,premier league,0,8 +9,Ipswich town,portman road,championship,1,9 +10,Norwich city,carrow road,championship,1,10 +11,Leeds united,etihad,championship,1,2 +12,Birmingham city,st andrews,championship,1,11 +13,Bristol city,ashton gate,championship,1,12 +14,Bristol rovers,memorial stadium,championship,1,13 +15,Burnley,turf moor,championship,1,14 +16,Cardiff city,cardiff city stadium,championship,1,15 +17,Charlton athletic,old trafford,championship,1,1 +18,Derby county,goodison park,championship,1,7 +19,Doncaster rovers,anfield,championship,1,3 +20,Fulham,emirates,championship,1,5 +21,Leyton orient,white hart lane,division 2,2,6 +22,Middlesbrough,riverside stadium,division 2,2,16 +23,Millwall,the den,division 2,2,17 +24,Nottingham forest,city ground,division 2,2,18 +25,Preston north end,etihad,division 2,2,2 +26,Queens park rangers,emirates,division 2,2,5 +27,Reading,madejski stadium,division 2,2,19 +28,Sheffield wednesday,anfield,division 2,2,3 +29,Watford,vicarage road,division 2,2,20 +30,Wigan athletic,old trafford,division 2,2,1 +31,Wolverhampton wanderers,st andrews,division 2,2,11 \ No newline at end of file diff --git a/data_fixtures/raw/cricket_fixtures/three_divisions_unique_grounds.csv b/data_fixtures/raw/cricket_fixtures/three_divisions_unique_grounds.csv new file mode 100644 index 0000000..0d56260 --- /dev/null +++ b/data_fixtures/raw/cricket_fixtures/three_divisions_unique_grounds.csv @@ -0,0 +1,32 @@ +team_num,name,ground,division,division_num,ground_num +1,manchester united,old trafford,premier league,0,1 +2,manchester city,etihad,premier league,0,2 +3,liverpool,anfield,premier league,0,3 +4,chelsea,stamford bridge,premier league,0,4 +5,arsenal,emirates,premier league,0,5 +6,tottenham,white hart lane,premier league,0,6 +7,everton,goodison park,premier league,0,7 +8,newcastle united,st james park,premier league,0,8 +9,Ipswich town,portman road,championship,1,9 +10,Norwich city,carrow road,championship,1,10 +11,Leeds united,elland road,championship,1,11 +12,Birmingham city,st andrews,championship,1,12 +13,Bristol city,ashton gate,championship,1,13 +14,Bristol rovers,memorial stadium,championship,1,14 +15,Burnley,turf moor,championship,1,15 +16,Cardiff city,cardiff city stadium,championship,1,16 +17,Charlton athletic,the valley,championship,1,17 +18,Derby county,pride park,championship,1,18 +19,Doncaster rovers,keepmoat stadium,championship,1,19 +20,Fulham,craven cottage,championship,1,20 +21,Leyton orient,barking,division 2,2,21 +22,Middlesbrough,riverside stadium,division 2,2,22 +23,Millwall,the den,division 2,2,23 +24,Nottingham forest,city ground,division 2,2,24 +25,Preston north end,deepdale,division 2,2,25 +26,Queens park rangers,loftus road,division 2,2,26 +27,Reading,madejski stadium,division 2,2,27 +28,Sheffield wednesday,hillsborough,division 2,2,28 +29,Watford,vicarage road,division 2,2,29 +30,Wigan athletic,DW stadium,division 2,2,30 +31,Wolverhampton wanderers,molineux,division 2,2,31 \ No newline at end of file diff --git a/ch05/adjacent_states.col b/data_fixtures/raw/graph_colouring/adjacent_states.col similarity index 99% rename from ch05/adjacent_states.col rename to data_fixtures/raw/graph_colouring/adjacent_states.col index 13c372b..cab8d7b 100644 --- a/ch05/adjacent_states.col +++ b/data_fixtures/raw/graph_colouring/adjacent_states.col @@ -1,4 +1,4 @@ -p edge 51 214 +p edge 51 107 e AL FL e AL GA e AL MS diff --git a/data_fixtures/raw/graph_colouring/simple.col b/data_fixtures/raw/graph_colouring/simple.col new file mode 100644 index 0000000..1cc7ef0 --- /dev/null +++ b/data_fixtures/raw/graph_colouring/simple.col @@ -0,0 +1,11 @@ +c FILE: simple.col +p edge 5 9 +e 1 2 +e 1 3 +e 1 4 +e 1 5 +e 2 3 +e 2 4 +e 2 5 +e 3 4 +e 3 5 diff --git a/es/README.md b/es/README.md deleted file mode 100644 index a1325bb..0000000 --- a/es/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# Algoritmos Genéticos con Python -El código del libro Algoritmos Genéticos con Python por Clinton Sheppard - -Descripción -=== - -[English edition](https://github.com/handcraftsman/GeneticAlgorithmsWithPython#description) - -tapa del libro Algoritmos Genéticos con Python -Obtén una introducción práctica al aprendizaje automático con los algoritmos genéticos usando Python. Los tutoriales paso a paso desarrollan tus habilidades desde el ¡Hola Mundo! hasta optimizar un algoritmo genético con otro y, finalmente, la programación genética; preparándote así para aplicar los algoritmos genéticos a problemas de tu propio campo de especialización. - -Los algoritmos genéticos son una de las herramientas que puedes usar para aplicar el aprendizaje automático al hallazgo de soluciones buenas (a veces incluso óptimas) a problemas que tienen miles de millones de soluciones posibles. Este libro te ofrece experiencia en hacer que los algoritmos genéticos funcionen, usando proyectos de ejemplo fáciles de seguir a los que puedes recurrir cuando aprendas a usar otras herramientas y técnicas de aprendizaje automático. Cada capítulo es un tutorial paso a paso que te ayuda a desarrollar tus habilidades en el uso de los algoritmos genéticos para resolver problemas usando Python. - -- https://www.amazon.com/dp/1548125180/ ISBN-13: 978-1-548125-18-9 (Edición en tapa blanda) -- https://www.amazon.com/dp/B072NDMJ4L (Versión Kindle) - -Tabla de contenido -=== - -Una breve introducción a los algoritmos genéticos - -Capítulo 1: ¡Hola Mundo! -- Adivina una contraseña dado el número de letras correctas en la conjetura. Construye un motor de mutación. - -Capítulo 2: El Problema One-max -- Produce un arreglo de bits donde todos son unos. Expande el motor para funcionar con cualquier tipo de gen. - -Capítulo 3: Números ordenados -- Produce un arreglo de enteros ordenados. Demuestra el manejo de múltiples objetivos y restricciones de aptitud entre genes. - -Capítulo 4: El problema de las ocho reinas -- Encuentra posiciones seguras para las reinas en un tablero de 8x8 y luego expande a NxN. Demuestra la diferencia entre fenotipo y genotipo. Ver el código de muestra. - -Capítulo 5: Coloración de grafos -- Colorea un mapa de países donde el español es el idioma nacional usando sólo 4 colores. Introduce conjuntos de datos estándar y trabajo con archivos. También introduce el uso de reglas para trabajar con las restricciones de los genes. - -Capítulo 6: El problema de las cartas -- Más restricciones genéticas. Introduce la mutación personalizada, los algoritmos meméticos y la técnica de la suma por diferencia. También muestra un cromosoma en el que la manera de usar un gen depende de su posición en el arreglo de genes. - -Capítulo 7: El problema de los caballos -- Encuentra el número mínimo de caballos que hacen falta para atacar todas las posiciones en un tablero. Introduce los genes personalizados y la creación de arreglos de genes. También demuestra los mínimos y máximos locales. - -Capítulo 8: Cuadrados mágicos -- Encuentra cuadrados en los que todas las filas, columnas y ambas diagonales de una matriz de NxN tengan la misma suma. Introduce el recocido simulado. - -Capítulo 9: El problema de la mochila -- Optimiza el contenido de un recipiente para una o más variables. Introduce la ramificación y poda, así como los cromosomas de longitud variable. - -Capítulo 10: Resolver ecuaciones lineales -- Encuentra las soluciones de las ecuaciones lineales con 2, 3 y 4 incógnitas. Variación de ramificación y poda. Refuerza la flexibilidad del genotipo. - -Capítulo 11: Generación de Sudoku -- Un ejercicio guiado para generar rompecabezas sudoku. - -Capítulo 12: El problema del viajante -- Encuentra la ruta óptima para visitar ciudades. Introduce la recombinación y una reserva de padres. - -Capítulo 13: Aproximarse a Pi -- Encuentra los dos números de 10 bits cuyo dividendo está más cerca de Pi. Introduce el uso de un algoritmo genético para optimizar otro. - -Capítulo 14: Generación de ecuaciones -- Encuentra la ecuación más corta que produce un resultado específico usando la suma, la resta, la multiplicación, etc. Introduce la programación genética simbólica. - -Capítulo 15: El problema de la cortadora de césped -- Genera una serie de instrucciones que hacen que una cortadora de césped corte un campo de césped. Programación genética con estructuras de control, objetos y funciones definidas automáticamente (FDAs). - -Capítulo 16: Circuitos lógicos -- Genera circuitos que se comportan como puertas básicas, combinaciones de puertas y finalmente un sumador de 2 bits. Introduce los nodos de árboles y los algoritmos de escalada. - -Capítulo 17: Expresiones regulares -- Encuentra expresiones regulares que coincidan con las cadenas buscadas. Introduce la reparación de cromosomas y el control de crecimiento. - -Capítulo 18: Tres en raya -- Crea reglas para jugar al juego sin perder. Introduce la selección por torneos. diff --git "a/es/ch01/contrase\303\261a.py" "b/es/ch01/contrase\303\261a.py" deleted file mode 100644 index c3aa03d..0000000 --- "a/es/ch01/contrase\303\261a.py" +++ /dev/null @@ -1,77 +0,0 @@ -# File: contraseña.py -# Del capítulo 1 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import unittest - -import genetic - - -def obtener_aptitud(conjetura, objetivo): - return sum(1 for esperado, real in zip(objetivo, conjetura) - if esperado == real) - - -def mostrar(candidato, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - print("{}\t{}\t{}".format( - candidato.Genes, candidato.Aptitud, diferencia)) - - -# `nosetests` no admite caracteres como ñ en el nombre de la clase -class PruebasDeContrasena(unittest.TestCase): - geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!¡.," - - def test_Hola_Mundo(self): - objetivo = "¡Hola Mundo!" - self.adivine_contraseña(objetivo) - - def test_Porque_me_formaste_de_una_manera_formidable_y_maravillosa( - self): - objetivo = "Porque me formaste de una manera formidable y " \ - "maravillosa." - self.adivine_contraseña(objetivo) - - def adivine_contraseña(self, objetivo): - horaInicio = datetime.datetime.now() - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, objetivo) - - def fnMostrar(candidato): - mostrar(candidato, horaInicio) - - aptitudÓptima = len(objetivo) - mejor = genetic.obtener_mejor(fnObtenerAptitud, len(objetivo), - aptitudÓptima, self.geneSet, - fnMostrar) - self.assertEqual(mejor.Genes, objetivo) - - def test_aleatorio(self): - longitud = 150 - objetivo = ''.join(random.choice(self.geneSet) - for _ in range(longitud)) - - self.adivine_contraseña(objetivo) - - def test_comparativa(self): - genetic.Comparar.ejecutar(self.test_aleatorio) - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch01/genetic.py b/es/ch01/genetic.py deleted file mode 100644 index 2b7417f..0000000 --- a/es/ch01/genetic.py +++ /dev/null @@ -1,86 +0,0 @@ -# File: genetic.py -# Del capítulo 1 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time - - -def _generar_padre(longitud, geneSet, obtener_aptitud): - genes = [] - while len(genes) < longitud: - tamañoMuestral = min(longitud - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, tamañoMuestral)) - genes = ''.join(genes) - aptitud = obtener_aptitud(genes) - return Cromosoma(genes, aptitud) - - -def _mutar(padre, geneSet, obtener_aptitud): - índice = random.randrange(0, len(padre.Genes)) - genesDelNiño = list(padre.Genes) - nuevoGen, alterno = random.sample(geneSet, 2) - genesDelNiño[índice] = alterno if nuevoGen == genesDelNiño[ - índice] else nuevoGen - genes = ''.join(genesDelNiño) - aptitud = obtener_aptitud(genes) - return Cromosoma(genes, aptitud) - - -def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, - mostrar): - random.seed() - mejorPadre = _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - mostrar(mejorPadre) - if mejorPadre.Aptitud >= aptitudÓptima: - return mejorPadre - while True: - niño = _mutar(mejorPadre, geneSet, obtener_aptitud) - if mejorPadre.Aptitud >= niño.Aptitud: - continue - mostrar(niño) - if niño.Aptitud >= aptitudÓptima: - return niño - mejorPadre = niño - - -class Cromosoma: - def __init__(self, genes, aptitud): - self.Genes = genes - self.Aptitud = aptitud - - -class Comparar: - @staticmethod - def ejecutar(función): - print(función) - cronometrajes = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - horaInicio = time.time() - función() - segundos = time.time() - horaInicio - sys.stdout = stdout - cronometrajes.append(segundos) - promedio = statistics.mean(cronometrajes) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, promedio, - statistics.stdev(cronometrajes, - promedio) if i > 1 else 0)) diff --git "a/es/ch02/contrase\303\261a.py" "b/es/ch02/contrase\303\261a.py" deleted file mode 100644 index 19f9ff8..0000000 --- "a/es/ch02/contrase\303\261a.py" +++ /dev/null @@ -1,76 +0,0 @@ -# File: contraseña.py -# Del capítulo 2 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import unittest - -import genetic - - -def obtener_aptitud(conjetura, objetivo): - return sum(1 for esperado, real in zip(objetivo, conjetura) - if esperado == real) - - -def mostrar(candidato, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - print("{}\t{}\t{}".format( - ''.join(candidato.Genes), - candidato.Aptitud, - diferencia)) - - -# `nosetests` no admite caracteres como ñ en el nombre de la clase -class PruebasDeContrasena(unittest.TestCase): - geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!¡.," - - def test_Hola_Mundo(self): - objetivo = "¡Hola Mundo!" - self.adivine_contraseña(objetivo) - - def test_Porque_me_formaste_de_una_manera_formidable_y_maravillosa(self): - objetivo = "Porque me formaste de una manera formidable y maravillosa." - self.adivine_contraseña(objetivo) - - def adivine_contraseña(self, objetivo): - horaInicio = datetime.datetime.now() - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, objetivo) - - def fnMostrar(candidato): - mostrar(candidato, horaInicio) - - aptitudÓptima = len(objetivo) - mejor = genetic.obtener_mejor(fnObtenerAptitud, len(objetivo), - aptitudÓptima, self.geneSet, fnMostrar) - self.assertEqual(''.join(mejor.Genes), objetivo) - - def test_aleatorio(self): - longitud = 150 - objetivo = ''.join(random.choice(self.geneSet) - for _ in range(longitud)) - - self.adivine_contraseña(objetivo) - - def test_comparativa(self): - genetic.Comparar.ejecutar(self.test_aleatorio) - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch02/genetic.py b/es/ch02/genetic.py deleted file mode 100644 index 803b841..0000000 --- a/es/ch02/genetic.py +++ /dev/null @@ -1,82 +0,0 @@ -# File: genetic.py -# Del capítulo 2 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time - - -def _generar_padre(longitud, geneSet, obtener_aptitud): - genes = [] - while len(genes) < longitud: - tamañoMuestral = min(longitud - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, tamañoMuestral)) - aptitud = obtener_aptitud(genes) - return Cromosoma(genes, aptitud) - - -def _mutar(padre, geneSet, obtener_aptitud): - genesDelNiño = padre.Genes[:] - índice = random.randrange(0, len(padre.Genes)) - nuevoGen, alterno = random.sample(geneSet, 2) - genesDelNiño[índice] = alterno if nuevoGen == genesDelNiño[ - índice] else nuevoGen - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud) - - -def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, - mostrar): - random.seed() - mejorPadre = _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - mostrar(mejorPadre) - if mejorPadre.Aptitud >= aptitudÓptima: - return mejorPadre - while True: - niño = _mutar(mejorPadre, geneSet, obtener_aptitud) - if mejorPadre.Aptitud >= niño.Aptitud: - continue - mostrar(niño) - if niño.Aptitud >= aptitudÓptima: - return niño - mejorPadre = niño - - -class Cromosoma: - def __init__(self, genes, aptitud): - self.Genes = genes - self.Aptitud = aptitud - - -class Comparar: - @staticmethod - def ejecutar(función): - cronometrajes = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - horaInicio = time.time() - función() - segundos = time.time() - horaInicio - sys.stdout = stdout - cronometrajes.append(segundos) - promedio = statistics.mean(cronometrajes) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, promedio, - statistics.stdev(cronometrajes, promedio) if i > 1 else 0)) diff --git a/es/ch02/oneMax.py b/es/ch02/oneMax.py deleted file mode 100644 index 5ff10d2..0000000 --- a/es/ch02/oneMax.py +++ /dev/null @@ -1,58 +0,0 @@ -# File: oneMax.py -# Del capítulo 2 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import unittest - -import genetic - - -def obtener_aptitud(genes): - return genes.count(1) - - -def mostrar(candidato, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - print("{}...{}\t{:3.2f}\t{}".format( - ''.join(map(str, candidato.Genes[:15])), - ''.join(map(str, candidato.Genes[-15:])), - candidato.Aptitud, - diferencia)) - - -class PruebasDeOneMax(unittest.TestCase): - def test(self, longitud=100): - geneSet = [0, 1] - horaInicio = datetime.datetime.now() - - def fnMostrar(candidato): - mostrar(candidato, horaInicio) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes) - - aptitudÓptima = longitud - mejor = genetic.obtener_mejor(fnObtenerAptitud, longitud, - aptitudÓptima, geneSet, fnMostrar) - self.assertEqual(mejor.Aptitud, aptitudÓptima) - - def test_comparativa(self): - genetic.Comparar.ejecutar(lambda: self.test(4000)) - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch03/genetic.py b/es/ch03/genetic.py deleted file mode 100644 index f4cd5dc..0000000 --- a/es/ch03/genetic.py +++ /dev/null @@ -1,95 +0,0 @@ -# File: genetic.py -# Del capítulo 3 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time - - -def _generar_padre(longitud, geneSet, obtener_aptitud): - genes = [] - while len(genes) < longitud: - tamañoMuestral = min(longitud - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, tamañoMuestral)) - aptitud = obtener_aptitud(genes) - return Cromosoma(genes, aptitud) - - -def _mutar(padre, geneSet, obtener_aptitud): - genesDelNiño = padre.Genes[:] - índice = random.randrange(0, len(padre.Genes)) - nuevoGen, alterno = random.sample(geneSet, 2) - genesDelNiño[índice] = alterno if nuevoGen == genesDelNiño[ - índice] else nuevoGen - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud) - - -def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, - mostrar): - random.seed() - - def fnMutar(padre): - return _mutar(padre, geneSet, obtener_aptitud) - - def fnGenerarPadre(): - return _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - - for mejora in _obtener_mejoras(fnMutar, fnGenerarPadre): - mostrar(mejora) - if not aptitudÓptima > mejora.Aptitud: - return mejora - - -def _obtener_mejoras(nuevo_niño, generar_padre): - mejorPadre = generar_padre() - yield mejorPadre - while True: - niño = nuevo_niño(mejorPadre) - if mejorPadre.Aptitud > niño.Aptitud: - continue - if not niño.Aptitud > mejorPadre.Aptitud: - mejorPadre = niño - continue - yield niño - mejorPadre = niño - - -class Cromosoma: - def __init__(self, genes, aptitud): - self.Genes = genes - self.Aptitud = aptitud - - -class Comparar: - @staticmethod - def ejecutar(función): - cronometrajes = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - horaInicio = time.time() - función() - segundos = time.time() - horaInicio - sys.stdout = stdout - cronometrajes.append(segundos) - promedio = statistics.mean(cronometrajes) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, promedio, - statistics.stdev(cronometrajes, promedio) if i > 1 else 0)) diff --git "a/es/ch03/n\303\272merosOrdenados.py" "b/es/ch03/n\303\272merosOrdenados.py" deleted file mode 100644 index 2689d28..0000000 --- "a/es/ch03/n\303\272merosOrdenados.py" +++ /dev/null @@ -1,86 +0,0 @@ -# File: númerosOrdenados.py -# Del capítulo 3 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - - -import datetime -import unittest - -import genetic - - -def obtener_aptitud(genes): - aptitud = 1 - brecha = 0 - - for i in range(1, len(genes)): - if genes[i] > genes[i - 1]: - aptitud += 1 - else: - brecha += genes[i - 1] - genes[i] - return Aptitud(aptitud, brecha) - - -def mostrar(candidato, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - print("{}\t=> {}\t{}".format( - ', '.join(map(str, candidato.Genes)), - candidato.Aptitud, - diferencia)) - - -# `nosetests` no admite caracteres como ú en el nombre de la clase -class PruebasDeNumerosOrdenados(unittest.TestCase): - def test_ordenar_10_números(self): - self.ordenar_números(10) - - def ordenar_números(self, númerosTotales): - geneSet = [i for i in range(100)] - horaInicio = datetime.datetime.now() - - def fnMostrar(candidato): - mostrar(candidato, horaInicio) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes) - - aptitudÓptima = Aptitud(númerosTotales, 0) - mejor = genetic.obtener_mejor(fnObtenerAptitud, númerosTotales, - aptitudÓptima, geneSet, fnMostrar) - self.assertTrue(not aptitudÓptima > mejor.Aptitud) - - def test_comparativa(self): - genetic.Comparar.ejecutar(lambda: self.ordenar_números(40)) - - -class Aptitud: - def __init__(self, númerosEnSecuencia, brechaTotal): - self.NúmerosEnSecuencia = númerosEnSecuencia - self.BrechaTotal = brechaTotal - - def __gt__(self, otro): - if self.NúmerosEnSecuencia != otro.NúmerosEnSecuencia: - return self.NúmerosEnSecuencia > otro.NúmerosEnSecuencia - return self.BrechaTotal < otro.BrechaTotal - - def __str__(self): - return "{} secuencial, distancia {}".format( - self.NúmerosEnSecuencia, - self.BrechaTotal) - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch04/reinas.py b/es/ch04/reinas.py deleted file mode 100644 index a05d99d..0000000 --- a/es/ch04/reinas.py +++ /dev/null @@ -1,104 +0,0 @@ -# File: reinas.py -# Del capítulo 4 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import unittest - -import genetic - - -def obtener_aptitud(genes, tamaño): - tablero = Tablero(genes, tamaño) - filasConReinas = set() - columnasConReinas = set() - diagonalesNoresteConReinas = set() - diagonalesSudoesteConReinas = set() - for fila in range(tamaño): - for columna in range(tamaño): - if tablero.get(fila, columna) == 'R': - filasConReinas.add(fila) - columnasConReinas.add(columna) - diagonalesNoresteConReinas.add(fila + columna) - diagonalesSudoesteConReinas.add(tamaño - 1 - fila + columna) - total = (tamaño - len(filasConReinas) - + tamaño - len(columnasConReinas) - + tamaño - len(diagonalesNoresteConReinas) - + tamaño - len(diagonalesSudoesteConReinas)) - return Aptitud(total) - - -def mostrar(candidato, horaInicio, tamaño): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - tablero = Tablero(candidato.Genes, tamaño) - tablero.print() - print("{}\t- {}\t{}".format( - ' '.join(map(str, candidato.Genes)), - candidato.Aptitud, - diferencia)) - - -class PruebasDeReinas(unittest.TestCase): - def test(self, tamaño=8): - geneSet = [i for i in range(tamaño)] - horaInicio = datetime.datetime.now() - - def fnMostrar(candidato): - mostrar(candidato, horaInicio, tamaño) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, tamaño) - - aptitudÓptima = Aptitud(0) - mejor = genetic.obtener_mejor(fnObtenerAptitud, 2 * tamaño, - aptitudÓptima, geneSet, fnMostrar) - self.assertTrue(not aptitudÓptima > mejor.Aptitud) - - def test_comparativa(self): - genetic.Comparar.ejecutar(lambda: self.test(20)) - - -class Tablero: - def __init__(self, genes, tamaño): - tablero = [['.'] * tamaño for _ in range(tamaño)] - for índice in range(0, len(genes), 2): - fila = genes[índice] - columna = genes[índice + 1] - tablero[columna][fila] = 'R' - self._tablero = tablero - - def get(self, fila, columna): - return self._tablero[columna][fila] - - def print(self): - # 0,0 muestra en la esquina inferior izquierda - for i in reversed(range(len(self._tablero))): - print(' '.join(self._tablero[i])) - - -class Aptitud: - def __init__(self, total): - self.Total = total - - def __gt__(self, otro): - return self.Total < otro.Total - - def __str__(self): - return "{}".format(self.Total) - - -if __name__ == '__main__': - unittest.main() diff --git "a/es/ch05/coloraci\303\263n.py" "b/es/ch05/coloraci\303\263n.py" deleted file mode 100644 index b077e1c..0000000 --- "a/es/ch05/coloraci\303\263n.py" +++ /dev/null @@ -1,140 +0,0 @@ -# File: coloración.py -# Del capítulo 5 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import unittest - -import genetic - - -def cargar_datos(archivoLocal): - """ espera: T D1 [D2 ... DN] - donde T es el tipo de registro - y D1 .. DN son elementos de datos apropiados del tipo de registro - """ - reglas = set() - nodos = set() - with open(archivoLocal, mode='r') as fuente: - contenido = fuente.read().splitlines() - for fila in contenido: - if fila[0] == 'e': # e aa bb, aa y bb son identificadores de nodo - nodoIds = fila.split(' ')[1:3] - reglas.add(Regla(nodoIds[0], nodoIds[1])) - nodos.add(nodoIds[0]) - nodos.add(nodoIds[1]) - continue - if fila[0] == 'n': - # n aa ww, aa es un identificador de nodo, ww es un peso - nodoIds = fila.split(' ') - nodos.add(nodoIds[1]) - return reglas, nodos - - -def construir_reglas(artículos): - reglasAñadidas = {} - for país, adyacente in artículos.items(): - for paísAdyacente in adyacente: - if paísAdyacente == '': - continue - regla = Regla(país, paísAdyacente) - if regla in reglasAñadidas: - reglasAñadidas[regla] += 1 - else: - reglasAñadidas[regla] = 1 - for k, v in reglasAñadidas.items(): - if v != 2: - print("regla {} no es bidireccional".format(k)) - return reglasAñadidas.keys() - - -def obtener_aptitud(genes, reglas, búsquedaÍndicePaís): - reglasQuePasan = sum(1 for regla in reglas - if regla.EsVálida(genes, búsquedaÍndicePaís)) - return reglasQuePasan - - -def mostrar(candidato, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - print("{}\t{}\t{}".format( - ''.join(map(str, candidato.Genes)), - candidato.Aptitud, - diferencia)) - - -# `nosetests` no admite caracteres como ó y á en el nombre de la clase -class PruebasDeColoracionGrafica(unittest.TestCase): - def test_países(self): - self.color("países_españoles.col", - ["Naranja", "Amarillo", "Verde", "Rojo"]) - - def test_R100_1gb(self): - self.color("R100_1gb.col", - ["Dorado", "Naranja", "Amarillo", "Verde", "Rojo", "Morado"]) - - def test_comparativa(self): - genetic.Comparar.ejecutar(lambda: self.test_R100_1gb()) - - def color(self, file, colores): - reglas, nodos = cargar_datos(file) - valorÓptimo = len(reglas) - búsquedaDeColor = {color[0]: color for color in colores} - geneSet = list(búsquedaDeColor.keys()) - horaInicio = datetime.datetime.now() - búsquedaDeÍndiceDeNodo = {key: índice - for índice, key in enumerate(sorted(nodos))} - - def fnMostrar(candidato): - mostrar(candidato, horaInicio) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, reglas, búsquedaDeÍndiceDeNodo) - - mejor = genetic.obtener_mejor(fnObtenerAptitud, len(nodos), - valorÓptimo, geneSet, fnMostrar) - self.assertTrue(not valorÓptimo > mejor.Aptitud) - - llaves = sorted(nodos) - for índice in range(len(nodos)): - print( - llaves[índice] + " es " + búsquedaDeColor[mejor.Genes[índice]]) - - -class Regla: - def __init__(self, nodo, adyacente): - if nodo < adyacente: - nodo, adyacente = adyacente, nodo - self.Nodo = nodo - self.Adyacente = adyacente - - def __eq__(self, otro): - return self.Nodo == otro.Nodo and self.Adyacente == otro.Adyacente - - def __hash__(self): - return hash(self.Nodo) * 397 ^ hash(self.Adyacente) - - def __str__(self): - return self.Nodo + " -> " + self.Adyacente - - def EsVálida(self, genes, búsquedaDeÍndiceDeNodo): - índice = búsquedaDeÍndiceDeNodo[self.Nodo] - índiceDeNodosAdyacentes = búsquedaDeÍndiceDeNodo[self.Adyacente] - - return genes[índice] != genes[índiceDeNodosAdyacentes] - - -if __name__ == '__main__': - unittest.main() diff --git "a/es/ch05/pa\303\255ses_espa\303\261oles.col" "b/es/ch05/pa\303\255ses_espa\303\261oles.col" deleted file mode 100644 index c252d04..0000000 --- "a/es/ch05/pa\303\255ses_espa\303\261oles.col" +++ /dev/null @@ -1,46 +0,0 @@ -p edge 21 40 -e AR BO -e AR CL -e AR PY -e AR UY -e BO AR -e BO CL -e BO PE -e BO PY -e CL AR -e CL BO -e CL PE -e CO EC -e CO PA -e CO PE -e CO VE -e CR NI -e CR PA -e EC CO -e EC PE -e GT HN -e GT MX -e GT SV -e HN GT -e HN NI -e HN SV -e MX GT -e NI CR -e NI HN -e PA CO -e PA CR -e PE BO -e PE CL -e PE CO -e PE EC -e PY AR -e PY BO -e SV GT -e SV HN -e UY AR -e VE CO -n CU 0 -n DO 0 -n ES 0 -n GQ 0 -n PR 0 diff --git "a/es/ch05/pa\303\255ses_espa\303\261oles.csv" "b/es/ch05/pa\303\255ses_espa\303\261oles.csv" deleted file mode 100644 index 0364df3..0000000 --- "a/es/ch05/pa\303\255ses_espa\303\261oles.csv" +++ /dev/null @@ -1,21 +0,0 @@ -AR,BO;CL;PY;UY -BO,AR;PY;CL;PE -CL,AR;BO;PE -CO,EC;PA;PE;VE -CR,NI;PA -CU, -DO, -EC,CO;PE -ES, -GQ, -GT,MX;HN;SV -HN,GT;NI;SV -MX,GT -NI,CR;HN -PA,CO;CR -PE,BO;CL;CO;EC -PR, -PY,AR;BO -SV,GT;HN -UY,AR -VE,CO \ No newline at end of file diff --git a/es/ch06/cartas.py b/es/ch06/cartas.py deleted file mode 100644 index a90b8b1..0000000 --- a/es/ch06/cartas.py +++ /dev/null @@ -1,102 +0,0 @@ -# File: cartas.py -# Del capítulo 6 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import functools -import operator -import random -import unittest - -import genetic - - -def obtener_aptitud(genes): - sumaDelGrupo1 = sum(genes[0:5]) - productoDelGrupo2 = functools.reduce(operator.mul, genes[5:10]) - duplicados = (len(genes) - len(set(genes))) - return Aptitud(sumaDelGrupo1, productoDelGrupo2, duplicados) - - -def mostrar(candidato, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - print("{} - {}\t{}\t{}".format( - ', '.join(map(str, candidato.Genes[0:5])), - ', '.join(map(str, candidato.Genes[5:10])), - candidato.Aptitud, - diferencia)) - - -def mutar(genes, geneSet): - if len(genes) == len(set(genes)): - cuenta = random.randint(1, 4) - while cuenta > 0: - cuenta -= 1 - índiceA, índiceB = random.sample(range(len(genes)), 2) - genes[índiceA], genes[índiceB] = genes[índiceB], genes[índiceA] - else: - índiceA = random.randrange(0, len(genes)) - índiceB = random.randrange(0, len(geneSet)) - genes[índiceA] = geneSet[índiceB] - - -class PruebasDeCartas(unittest.TestCase): - def test(self): - geneSet = [i + 1 for i in range(10)] - horaInicio = datetime.datetime.now() - - def fnMostrar(candidato): - mostrar(candidato, horaInicio) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes) - - def fnMutar(genes): - mutar(genes, geneSet) - - aptitudÓptima = Aptitud(36, 360, 0) - mejor = genetic.obtener_mejor(fnObtenerAptitud, 10, aptitudÓptima, - geneSet, fnMostrar, - mutación_personalizada=fnMutar) - self.assertTrue(not aptitudÓptima > mejor.Aptitud) - - def test_comparativa(self): - genetic.Comparar.ejecutar(lambda: self.test()) - - -class Aptitud: - def __init__(self, sumaDelGrupo1, productoDelGrupo2, duplicados): - self.SumaDelGrupo1 = sumaDelGrupo1 - self.ProductoDelGrupo2 = productoDelGrupo2 - diferenciaSuma = abs(36 - sumaDelGrupo1) - diferenciaProducto = abs(360 - productoDelGrupo2) - self.DiferenciaTotal = diferenciaSuma + diferenciaProducto - self.Duplicados = duplicados - - def __gt__(self, otro): - if self.Duplicados != otro.Duplicados: - return self.Duplicados < otro.Duplicados - return self.DiferenciaTotal < otro.DiferenciaTotal - - def __str__(self): - return "sum: {} prod: {} dups: {}".format( - self.SumaDelGrupo1, - self.ProductoDelGrupo2, - self.Duplicados) - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch06/genetic.py b/es/ch06/genetic.py deleted file mode 100644 index 89e92e3..0000000 --- a/es/ch06/genetic.py +++ /dev/null @@ -1,105 +0,0 @@ -# File: genetic.py -# Del capítulo 6 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time - - -def _generar_padre(longitud, geneSet, obtener_aptitud): - genes = [] - while len(genes) < longitud: - tamañoMuestral = min(longitud - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, tamañoMuestral)) - aptitud = obtener_aptitud(genes) - return Cromosoma(genes, aptitud) - - -def _mutar(padre, geneSet, obtener_aptitud): - genesDelNiño = padre.Genes[:] - índice = random.randrange(0, len(padre.Genes)) - nuevoGen, alterno = random.sample(geneSet, 2) - genesDelNiño[índice] = alterno if nuevoGen == genesDelNiño[ - índice] else nuevoGen - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud) - - -def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): - genesDelNiño = padre.Genes[:] - mutación_personalizada(genesDelNiño) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud) - - -def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, - mostrar, mutación_personalizada=None): - if mutación_personalizada is None: - def fnMutar(padre): - return _mutar(padre, geneSet, obtener_aptitud) - else: - def fnMutar(padre): - return _mutar_personalizada(padre, mutación_personalizada, - obtener_aptitud) - - def fnGenerarPadre(): - return _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - - for mejora in _obtener_mejoras(fnMutar, fnGenerarPadre): - mostrar(mejora) - if not aptitudÓptima > mejora.Aptitud: - return mejora - - -def _obtener_mejoras(nuevo_niño, generar_padre): - mejorPadre = generar_padre() - yield mejorPadre - while True: - niño = nuevo_niño(mejorPadre) - if mejorPadre.Aptitud > niño.Aptitud: - continue - if not niño.Aptitud > mejorPadre.Aptitud: - mejorPadre = niño - continue - yield niño - mejorPadre = niño - - -class Cromosoma: - def __init__(self, genes, aptitud): - self.Genes = genes - self.Aptitud = aptitud - - -class Comparar: - @staticmethod - def ejecutar(función): - cronometrajes = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - horaInicio = time.time() - función() - segundos = time.time() - horaInicio - sys.stdout = stdout - cronometrajes.append(segundos) - promedio = statistics.mean(cronometrajes) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, promedio, - statistics.stdev(cronometrajes, promedio) if i > 1 else 0)) diff --git a/es/ch07/caballos.py b/es/ch07/caballos.py deleted file mode 100644 index b7ee5ee..0000000 --- a/es/ch07/caballos.py +++ /dev/null @@ -1,200 +0,0 @@ -# File: caballos.py -# Del capítulo 7 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import unittest - -import genetic - - -def obtener_aptitud(genes, tableroAncho, tableroAltura): - atacado = set(pos - for kn in genes - for pos in obtener_ataques(kn, tableroAncho, - tableroAltura)) - return len(atacado) - - -def mostrar(candidato, horaInicio, tableroAncho, tableroAltura): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - tablero = Tablero(candidato.Genes, tableroAncho, tableroAltura) - tablero.print() - - print("{}\n\t{}\t{}".format( - ' '.join(map(str, candidato.Genes)), - candidato.Aptitud, - diferencia)) - - -def mutar(genes, tableroAncho, tableroAltura, todasPosiciones, - posicionesNoBordeadas): - cuenta = 2 if random.randint(0, 10) == 0 else 1 - while cuenta > 0: - cuenta -= 1 - posiciónACaballoÍndices = dict((p, []) for p in todasPosiciones) - for i, caballo in enumerate(genes): - for posición in obtener_ataques(caballo, tableroAncho, - tableroAltura): - posiciónACaballoÍndices[posición].append(i) - caballoÍndices = set(i for i in range(len(genes))) - noAtacados = [] - for kvp in posiciónACaballoÍndices.items(): - if len(kvp[1]) > 1: - continue - if len(kvp[1]) == 0: - noAtacados.append(kvp[0]) - continue - for p in kvp[1]: # longitud == 1 - if p in caballoÍndices: - caballoÍndices.remove(p) - - posicionesPotenciales = \ - [p for posiciones in - map(lambda x: obtener_ataques(x, tableroAncho, tableroAltura), - noAtacados) - for p in posiciones if p in posicionesNoBordeadas] \ - if len(noAtacados) > 0 else posicionesNoBordeadas - - índiceDeGen = random.randrange(0, len(genes)) \ - if len(caballoÍndices) == 0 \ - else random.choice([i for i in caballoÍndices]) - - posición = random.choice(posicionesPotenciales) - genes[índiceDeGen] = posición - - -def crear(fnObtenerPosiciónAleatoria, caballosEsperados): - genes = [fnObtenerPosiciónAleatoria() for _ in range(caballosEsperados)] - return genes - - -def obtener_ataques(ubicación, tableroAncho, tableroAltura): - return [i for i in set( - Posición(x + ubicación.X, y + ubicación.Y) - for x in [-2, -1, 1, 2] if 0 <= x + ubicación.X < tableroAncho - for y in [-2, -1, 1, 2] if 0 <= y + ubicación.Y < tableroAltura - and abs(y) != abs(x))] - - -class PruebasDeCaballos(unittest.TestCase): - def test_3x4(self): - anchura = 4 - altura = 3 - # 1,0 2,0 3,0 - # 0,2 1,2 2,2 - # 2 C C C . - # 1 . . . . - # 0 . C C C - # 0 1 2 3 - self.encontrarCaballoPosiciones(anchura, altura, 6) - - def test_8x8(self): - anchura = 8 - altura = 8 - self.encontrarCaballoPosiciones(anchura, altura, 14) - - def test_10x10(self): - anchura = 10 - altura = 10 - self.encontrarCaballoPosiciones(anchura, altura, 22) - - def test_12x12(self): - anchura = 12 - altura = 12 - self.encontrarCaballoPosiciones(anchura, altura, 28) - - def test_13x13(self): - anchura = 13 - altura = 13 - self.encontrarCaballoPosiciones(anchura, altura, 32) - - def test_comparativa(self): - genetic.Comparar.ejecutar(lambda: self.test_10x10()) - - def encontrarCaballoPosiciones(self, tableroAncho, tableroAltura, - caballosEsperados): - horaInicio = datetime.datetime.now() - - def fnMostrar(candidato): - mostrar(candidato, horaInicio, tableroAncho, tableroAltura) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, tableroAncho, tableroAltura) - - todasPosiciones = [Posición(x, y) - for y in range(tableroAltura) - for x in range(tableroAncho)] - - if tableroAncho < 6 or tableroAltura < 6: - posicionesNoBordeadas = todasPosiciones - else: - posicionesNoBordeadas = [i for i in todasPosiciones - if 0 < i.X < tableroAncho - 1 and - 0 < i.Y < tableroAltura - 1] - - def fnObtenerPosiciónAleatoria(): - return random.choice(posicionesNoBordeadas) - - def fnMutar(genes): - mutar(genes, tableroAncho, tableroAltura, todasPosiciones, - posicionesNoBordeadas) - - def fnCrear(): - return crear(fnObtenerPosiciónAleatoria, caballosEsperados) - - aptitudÓptima = tableroAncho * tableroAltura - mejor = genetic.obtener_mejor(fnObtenerAptitud, None, aptitudÓptima, - None, fnMostrar, fnMutar, fnCrear) - self.assertTrue(not aptitudÓptima > mejor.Aptitud) - - -class Posición: - def __init__(self, x, y): - self.X = x - self.Y = y - - def __str__(self): - return "{},{}".format(self.X, self.Y) - - def __eq__(self, otro): - return self.X == otro.X and self.Y == otro.Y - - def __hash__(self): - return self.X * 1000 + self.Y - - -class Tablero: - def __init__(self, posiciones, anchura, altura): - tablero = [['.'] * anchura for _ in range(altura)] - - for índice in range(len(posiciones)): - posiciónDeCaballo = posiciones[índice] - tablero[posiciónDeCaballo.Y][posiciónDeCaballo.X] = 'C' - self._tablero = tablero - self._anchura = anchura - self._altura = altura - - def print(self): - # 0,0 muestra en la esquina inferior izquierda - for i in reversed(range(self._altura)): - print(i, "\t", ' '.join(self._tablero[i])) - print(" \t", ' '.join(map(str, range(self._anchura)))) - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch07/genetic.py b/es/ch07/genetic.py deleted file mode 100644 index 4d334b1..0000000 --- a/es/ch07/genetic.py +++ /dev/null @@ -1,111 +0,0 @@ -# File: genetic.py -# Del capítulo 7 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time - - -def _generar_padre(longitud, geneSet, obtener_aptitud): - genes = [] - while len(genes) < longitud: - tamañoMuestral = min(longitud - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, tamañoMuestral)) - aptitud = obtener_aptitud(genes) - return Cromosoma(genes, aptitud) - - -def _mutar(padre, geneSet, obtener_aptitud): - genesDelNiño = padre.Genes[:] - índice = random.randrange(0, len(padre.Genes)) - nuevoGen, alterno = random.sample(geneSet, 2) - genesDelNiño[índice] = alterno if nuevoGen == genesDelNiño[ - índice] else nuevoGen - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud) - - -def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): - genesDelNiño = padre.Genes[:] - mutación_personalizada(genesDelNiño) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud) - - -def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, - mostrar, mutación_personalizada=None, - creación_personalizada=None): - if mutación_personalizada is None: - def fnMutar(padre): - return _mutar(padre, geneSet, obtener_aptitud) - else: - def fnMutar(padre): - return _mutar_personalizada(padre, mutación_personalizada, - obtener_aptitud) - - if creación_personalizada is None: - def fnGenerarPadre(): - return _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - else: - def fnGenerarPadre(): - genes = creación_personalizada() - return Cromosoma(genes, obtener_aptitud(genes)) - - for mejora in _obtener_mejoras(fnMutar, fnGenerarPadre): - mostrar(mejora) - if not aptitudÓptima > mejora.Aptitud: - return mejora - - -def _obtener_mejoras(nuevo_niño, generar_padre): - mejorPadre = generar_padre() - yield mejorPadre - while True: - niño = nuevo_niño(mejorPadre) - if mejorPadre.Aptitud > niño.Aptitud: - continue - if not niño.Aptitud > mejorPadre.Aptitud: - mejorPadre = niño - continue - yield niño - mejorPadre = niño - - -class Cromosoma: - def __init__(self, genes, aptitud): - self.Genes = genes - self.Aptitud = aptitud - - -class Comparar: - @staticmethod - def ejecutar(función): - cronometrajes = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - horaInicio = time.time() - función() - segundos = time.time() - horaInicio - sys.stdout = stdout - cronometrajes.append(segundos) - promedio = statistics.mean(cronometrajes) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, promedio, - statistics.stdev(cronometrajes, promedio) if i > 1 else 0)) diff --git "a/es/ch08/cuadradosM\303\241gicos.py" "b/es/ch08/cuadradosM\303\241gicos.py" deleted file mode 100644 index 4e5d7c7..0000000 --- "a/es/ch08/cuadradosM\303\241gicos.py" +++ /dev/null @@ -1,129 +0,0 @@ -# File: cuadradosMágicos.py -# Del capítulo 8 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import unittest - -import genetic - - -def obtener_aptitud(genes, tamañoDiagonal, sumaEsperada): - filas, columnas, sumaDiagonalNoreste, sumaDiagonalSureste = \ - obtener_sums(genes, tamañoDiagonal) - - sumaDeDiferencias = sum(int(abs(s - sumaEsperada)) - for s in filas + columnas + - [sumaDiagonalSureste, sumaDiagonalNoreste] - if s != sumaEsperada) - - return Aptitud(sumaDeDiferencias) - - -def mostrar(candidato, tamañoDiagonal, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - - filas, columnas, sumaDiagonalNoreste, sumaDiagonalSureste = \ - obtener_sums(candidato.Genes, tamañoDiagonal) - - for númeroDeFila in range(tamañoDiagonal): - fila = candidato.Genes[ - númeroDeFila * tamañoDiagonal:(númeroDeFila + 1) * - tamañoDiagonal] - print("\t ", fila, "=", filas[númeroDeFila]) - print(sumaDiagonalNoreste, "\t", columnas, "\t", sumaDiagonalSureste) - print(" - - - - - - - - - - -", candidato.Aptitud, diferencia) - - -def obtener_sums(genes, tamañoDiagonal): - filas = [0 for _ in range(tamañoDiagonal)] - columnas = [0 for _ in range(tamañoDiagonal)] - sumaDiagonalSureste = 0 - sumaDiagonalNoreste = 0 - for fila in range(tamañoDiagonal): - for columna in range(tamañoDiagonal): - valor = genes[fila * tamañoDiagonal + columna] - filas[fila] += valor - columnas[columna] += valor - sumaDiagonalSureste += genes[fila * tamañoDiagonal + fila] - sumaDiagonalNoreste += genes[fila * tamañoDiagonal + - (tamañoDiagonal - 1 - fila)] - return filas, columnas, sumaDiagonalNoreste, sumaDiagonalSureste - - -def mutar(genes, índices): - índiceA, índiceB = random.sample(índices, 2) - genes[índiceA], genes[índiceB] = genes[índiceB], genes[índiceA] - - -# `nosetests` no admite caracteres como á en el nombre de la clase -class PruebasDeCuadradosMagicos(unittest.TestCase): - def test_tamaño_3(self): - self.generar(3, 50) - - def test_tamaño_4(self): - self.generar(4, 50) - - def test_tamaño_5(self): - self.generar(5, 500) - - def test_tamaño_10(self): - self.generar(10, 5000) - - def test_comparativa(self): - genetic.Comparar.ejecutar(self.test_tamaño_4) - - def generar(self, tamañoDiagonal, edadMáxima): - nCuadrado = tamañoDiagonal * tamañoDiagonal - geneSet = [i for i in range(1, nCuadrado + 1)] - sumaEsperada = tamañoDiagonal * (nCuadrado + 1) / 2 - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, tamañoDiagonal, sumaEsperada) - - def fnMostrar(candidato): - mostrar(candidato, tamañoDiagonal, horaInicio) - - geneÍndices = [i for i in range(0, len(geneSet))] - - def fnMutar(genes): - mutar(genes, geneÍndices) - - def fnCreaciónPersonalizada(): - return random.sample(geneSet, len(geneSet)) - - valorÓptimo = Aptitud(0) - horaInicio = datetime.datetime.now() - mejor = genetic.obtener_mejor(fnObtenerAptitud, nCuadrado, valorÓptimo, - geneSet, fnMostrar, fnMutar, - fnCreaciónPersonalizada, edadMáxima) - self.assertTrue(not valorÓptimo > mejor.Aptitud) - - -class Aptitud: - def __init__(self, sumaDeDiferencias): - self.SumaDeDiferencias = sumaDeDiferencias - - def __gt__(self, otro): - return self.SumaDeDiferencias < otro.SumaDeDiferencias - - def __str__(self): - return "{}".format(self.SumaDeDiferencias) - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch08/genetic.py b/es/ch08/genetic.py deleted file mode 100644 index 059d452..0000000 --- a/es/ch08/genetic.py +++ /dev/null @@ -1,134 +0,0 @@ -# File: genetic.py -# Del capítulo 8 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time -from bisect import bisect_left -from math import exp - - -def _generar_padre(longitud, geneSet, obtener_aptitud): - genes = [] - while len(genes) < longitud: - tamañoMuestral = min(longitud - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, tamañoMuestral)) - aptitud = obtener_aptitud(genes) - return Cromosoma(genes, aptitud) - - -def _mutar(padre, geneSet, obtener_aptitud): - genesDelNiño = padre.Genes[:] - índice = random.randrange(0, len(padre.Genes)) - nuevoGen, alterno = random.sample(geneSet, 2) - genesDelNiño[índice] = alterno if nuevoGen == genesDelNiño[ - índice] else nuevoGen - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud) - - -def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): - genesDelNiño = padre.Genes[:] - mutación_personalizada(genesDelNiño) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud) - - -def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, - mostrar, mutación_personalizada=None, - creación_personalizada=None, edadMáxima=None): - if mutación_personalizada is None: - def fnMutar(padre): - return _mutar(padre, geneSet, obtener_aptitud) - else: - def fnMutar(padre): - return _mutar_personalizada(padre, mutación_personalizada, - obtener_aptitud) - - if creación_personalizada is None: - def fnGenerarPadre(): - return _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - else: - def fnGenerarPadre(): - genes = creación_personalizada() - return Cromosoma(genes, obtener_aptitud(genes)) - - for mejora in _obtener_mejoras(fnMutar, fnGenerarPadre, edadMáxima): - mostrar(mejora) - if not aptitudÓptima > mejora.Aptitud: - return mejora - - -def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima): - padre = mejorPadre = generar_padre() - yield mejorPadre - aptitudesHistóricas = [mejorPadre.Aptitud] - while True: - niño = nuevo_niño(padre) - if padre.Aptitud > niño.Aptitud: - if edadMáxima is None: - continue - padre.Edad += 1 - if edadMáxima > padre.Edad: - continue - índice = bisect_left(aptitudesHistóricas, niño.Aptitud, 0, - len(aptitudesHistóricas)) - proporciónSimilar = índice / len(aptitudesHistóricas) - if random.random() < exp(-proporciónSimilar): - padre = niño - continue - mejorPadre.Edad = 0 - padre = mejorPadre - continue - if not niño.Aptitud > padre.Aptitud: - # mismo aptitud - niño.Edad = padre.Edad + 1 - padre = niño - continue - niño.Edad = 0 - padre = niño - if niño.Aptitud > mejorPadre.Aptitud: - mejorPadre = niño - yield mejorPadre - aptitudesHistóricas.append(mejorPadre.Aptitud) - - -class Cromosoma: - def __init__(self, genes, aptitud): - self.Genes = genes - self.Aptitud = aptitud - self.Edad = 0 - - -class Comparar: - @staticmethod - def ejecutar(función): - cronometrajes = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - horaInicio = time.time() - función() - segundos = time.time() - horaInicio - sys.stdout = stdout - cronometrajes.append(segundos) - promedio = statistics.mean(cronometrajes) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, promedio, - statistics.stdev(cronometrajes, promedio) if i > 1 else 0)) diff --git a/es/ch09/mochila.py b/es/ch09/mochila.py deleted file mode 100644 index e575a5d..0000000 --- a/es/ch09/mochila.py +++ /dev/null @@ -1,295 +0,0 @@ -# File: mochila.py -# Del capítulo 9 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import sys -import unittest - -import genetic - - -def obtener_aptitud(genes): - pesoTotal = 0 - volumenTotal = 0 - valorTotal = 0 - for ac in genes: - cuenta = ac.Cantidad - pesoTotal += ac.Artículo.Peso * cuenta - volumenTotal += ac.Artículo.Volumen * cuenta - valorTotal += ac.Artículo.Valor * cuenta - - return Aptitud(pesoTotal, volumenTotal, valorTotal) - - -def mostrar(candidato, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - genes = candidato.Genes[:] - genes.sort(key=lambda ac: ac.Cantidad, reverse=True) - - descripciones = [str(ac.Cantidad) + "x" + ac.Artículo.Nombre for ac in - genes] - if len(descripciones) == 0: - descripciones.append("Vacío") - print("{}\t{}\t{}".format( - ', '.join(descripciones), - candidato.Aptitud, - diferencia)) - - -def cantidad_máxima(artículo, pesoMáximo, volumenMáximo): - return min(int(pesoMáximo / artículo.Peso) - if artículo.Peso > 0 else sys.maxsize, - int(volumenMáximo / artículo.Volumen) - if artículo.Volumen > 0 else sys.maxsize) - - -def crear(artículos, pesoMáximo, volumenMáximo): - genes = [] - pesoRestante, volumenRestante = pesoMáximo, volumenMáximo - for i in range(random.randrange(1, len(artículos))): - nuevoGen = añadir(genes, artículos, pesoRestante, volumenRestante) - if nuevoGen is not None: - genes.append(nuevoGen) - pesoRestante -= nuevoGen.Cantidad * nuevoGen.Artículo.Peso - volumenRestante -= nuevoGen.Cantidad * nuevoGen.Artículo.Volumen - return genes - - -def añadir(genes, artículos, pesoMáximo, volumenMáximo): - artículosUsados = {ac.Artículo for ac in genes} - artículo = random.choice(artículos) - while artículo in artículosUsados: - artículo = random.choice(artículos) - - cantidadMáxima = cantidad_máxima(artículo, pesoMáximo, volumenMáximo) - return ArtículoCantidad(artículo, - cantidadMáxima) if cantidadMáxima > 0 else None - - -def mutar(genes, artículos, pesoMáximo, volumenMáximo, ventana): - ventana.deslizar() - aptitud = obtener_aptitud(genes) - pesoRestante = pesoMáximo - aptitud.PesoTotal - volumenRestante = volumenMáximo - aptitud.VolumenTotal - - eliminando = len(genes) > 1 and random.randint(0, 10) == 0 - if eliminando: - índice = random.randrange(0, len(genes)) - ac = genes[índice] - artículo = ac.Artículo - pesoRestante += artículo.Peso * ac.Cantidad - volumenRestante += artículo.Volumen * ac.Cantidad - del genes[índice] - - añadiendo = (pesoRestante > 0 or volumenRestante > 0) and \ - (len(genes) == 0 or (len(genes) < len(artículos) and - random.randint(0, 100) == 0)) - - if añadiendo: - nuevoGen = añadir(genes, artículos, pesoRestante, volumenRestante) - if nuevoGen is not None: - genes.append(nuevoGen) - return - - índice = random.randrange(0, len(genes)) - ac = genes[índice] - artículo = ac.Artículo - pesoRestante += artículo.Peso * ac.Cantidad - volumenRestante += artículo.Volumen * ac.Cantidad - - artículoACambiar = len(genes) < len(artículos) and \ - random.randint(0, 4) == 0 - if artículoACambiar: - artículoÍndice = artículos.index(ac.Artículo) - principio = max(1, artículoÍndice - ventana.Tamaño) - fin = min(len(artículos) - 1, artículoÍndice + ventana.Tamaño) - artículo = artículos[random.randint(principio, fin)] - cantidadMáxima = cantidad_máxima(artículo, pesoRestante, volumenRestante) - if cantidadMáxima > 0: - genes[índice] = ArtículoCantidad(artículo, cantidadMáxima - if ventana.Tamaño > 1 else random.randint(1, cantidadMáxima)) - else: - del genes[índice] - - -class PruebasDeMochila(unittest.TestCase): - def test_galletas(self): - artículos = [ - Recurso("Harina", 1680, 0.265, .41), - Recurso("Mantequilla", 1440, 0.5, .13), - Recurso("Azúcar", 1840, 0.441, .29) - ] - pesoMáximo = 10 - volumenMáximo = 4 - óptimo = obtener_aptitud( - [ArtículoCantidad(artículos[0], 1), - ArtículoCantidad(artículos[1], 14), - ArtículoCantidad(artículos[2], 6)]) - self.rellenar_mochila(artículos, pesoMáximo, volumenMáximo, óptimo) - - def test_exnsd16(self): - informaciónDelProblema = cargar_datos("exnsd16.ukp") - artículos = informaciónDelProblema.Recursos - pesoMáximo = informaciónDelProblema.PesoMáximo - volumenMáximo = 0 - óptimo = obtener_aptitud(informaciónDelProblema.Solución) - self.rellenar_mochila(artículos, pesoMáximo, volumenMáximo, óptimo) - - def test_comparativa(self): - genetic.Comparar.ejecutar(lambda: self.test_exnsd16()) - - def rellenar_mochila(self, artículos, pesoMáximo, volumenMáximo, - aptitudÓptima): - horaInicio = datetime.datetime.now() - ventana = Ventana(1, - max(1, int(len(artículos) / 3)), - int(len(artículos) / 2)) - - artículosOrdenados = sorted(artículos, - key=lambda artículo: artículo.Valor) - - def fnMostrar(candidato): - mostrar(candidato, horaInicio) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes) - - def fnCrear(): - return crear(artículos, pesoMáximo, volumenMáximo) - - def fnMutar(genes): - mutar(genes, artículosOrdenados, pesoMáximo, volumenMáximo, - ventana) - - mejor = genetic.obtener_mejor(fnObtenerAptitud, None, aptitudÓptima, - None, fnMostrar, fnMutar, fnCrear, - edadMáxima=50) - self.assertTrue(not aptitudÓptima > mejor.Aptitud) - - -def cargar_datos(archivoLocal): - with open(archivoLocal, mode='r') as fuente: - filas = fuente.read().splitlines() - datos = DatosDelProblema() - f = encontrar_restricción - - for fila in filas: - f = f(fila.strip(), datos) - if f is None: - break - return datos - - -def encontrar_restricción(fila, datos): - partes = fila.split(' ') - if partes[0] != "c:": - return encontrar_restricción - datos.PesoMáximo = int(partes[1]) - return buscar_inicio_de_datos - - -def buscar_inicio_de_datos(fila, datos): - if fila != "begin data": - return buscar_inicio_de_datos - return leer_recurso_o_encontrar_final_de_datos - - -def leer_recurso_o_encontrar_final_de_datos(fila, datos): - if fila == "end data": - return encontrar_inicio_de_la_solución - partes = fila.split('\t') - recurso = Recurso("R" + str(1 + len(datos.Recursos)), int(partes[1]), - int(partes[0]), 0) - datos.Recursos.append(recurso) - return leer_recurso_o_encontrar_final_de_datos - - -def encontrar_inicio_de_la_solución(fila, datos): - if fila == "sol:": - return leer_solución_recurso_o_encontrar_final_de_solución - return encontrar_inicio_de_la_solución - - -def leer_solución_recurso_o_encontrar_final_de_solución(fila, datos): - if fila == "": - return None - partes = [p for p in fila.split('\t') if p != ""] - recursoÍndice = int(partes[0]) - 1 # hacer que sea basado en 0 - recursoCantidad = int(partes[1]) - datos.Solución.append( - ArtículoCantidad(datos.Recursos[recursoÍndice], recursoCantidad)) - return leer_solución_recurso_o_encontrar_final_de_solución - - -class Recurso: - def __init__(self, nombre, valor, peso, volumen): - self.Nombre = nombre - self.Valor = valor - self.Peso = peso - self.Volumen = volumen - - -class ArtículoCantidad: - def __init__(self, artículo, cantidad): - self.Artículo = artículo - self.Cantidad = cantidad - - def __eq__(self, otro): - return self.Artículo == otro.Artículo and \ - self.Cantidad == otro.Cantidad - - -class Aptitud: - def __init__(self, pesoTotal, volumenTotal, valorTotal): - self.PesoTotal = pesoTotal - self.VolumenTotal = volumenTotal - self.ValorTotal = valorTotal - - def __gt__(self, otro): - if self.ValorTotal != otro.ValorTotal: - return self.ValorTotal > otro.ValorTotal - if self.PesoTotal != otro.PesoTotal: - return self.PesoTotal < otro.PesoTotal - return self.VolumenTotal < otro.VolumenTotal - - def __str__(self): - return "peso: {:0.2f} vol: {:0.2f} valor: {}".format( - self.PesoTotal, - self.VolumenTotal, - self.ValorTotal) - - -class DatosDelProblema: - def __init__(self): - self.Recursos = [] - self.PesoMáximo = 0 - self.Solución = [] - - -class Ventana: - def __init__(self, mínimo, máximo, tamaño): - self.Min = mínimo - self.Max = máximo - self.Tamaño = tamaño - - def deslizar(self): - self.Tamaño = self.Tamaño - 1 if self.Tamaño > self.Min else self.Max - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch10/ecuacionesLineales.py b/es/ch10/ecuacionesLineales.py deleted file mode 100644 index 497fcb9..0000000 --- a/es/ch10/ecuacionesLineales.py +++ /dev/null @@ -1,196 +0,0 @@ -# File: ecuacionesLineales.py -# Del capítulo 10 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -from fractions import Fraction -import random -import unittest - -import genetic - - -def obtener_aptitud(genes, ecuaciones): - aptitud = Aptitud(sum(abs(e(genes)) for e in ecuaciones)) - return aptitud - - -def mostrar(candidato, horaInicio, fnGenesAEntradas): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - símbolos = "xyza" - resultado = ', '.join("{} = {}".format(s, v) - for s, v in - zip(símbolos, fnGenesAEntradas(candidato.Genes))) - print("{}\t{}\t{}".format( - resultado, - candidato.Aptitud, - diferencia)) - - -def mutar(genes, geneSetOrdenado, ventana, geneÍndices): - índices = random.sample(geneÍndices, random.randint(1, len(genes))) \ - if random.randint(0, 10) == 0 else [random.choice(geneÍndices)] - ventana.deslizar() - while len(índices) > 0: - índice = índices.pop() - geneSetÍndice = geneSetOrdenado.index(genes[índice]) - principio = max(0, geneSetÍndice - ventana.Tamaño) - fin = min(len(geneSetOrdenado) - 1, geneSetÍndice + ventana.Tamaño) - geneSetÍndice = random.randint(principio, fin) - genes[índice] = geneSetOrdenado[geneSetÍndice] - - -class PruebasDeEcuacionesLineales(unittest.TestCase): - def test_2_desconocidos(self): - geneSet = [i for i in range(-5, 5) if i != 0] - - def fnGenesAEntradas(genes): - return genes[0], genes[1] - - def e1(genes): - x, y = fnGenesAEntradas(genes) - return x + 2 * y - 4 - - def e2(genes): - x, y = fnGenesAEntradas(genes) - return 4 * x + 4 * y - 12 - - ecuaciones = [e1, e2] - self.resolver_desconocidos(2, geneSet, ecuaciones, fnGenesAEntradas) - - def test_3_desconocidos(self): - valores = [i for i in range(-5, 5) if i != 0] - geneSet = [i for i in set( - Fraction(d, e) - for d in valores - for e in valores if e != 0)] - - def fnGenesAEntradas(genes): - return genes - - def e1(genes): - x, y, z = genes - return 6 * x - 2 * y + 8 * z - 20 - - def e2(genes): - x, y, z = genes - return y + 8 * x * z + 1 - - def e3(genes): - x, y, z = genes - return 2 * z * Fraction(6, x) \ - + 3 * Fraction(y, 2) - 6 - - ecuaciones = [e1, e2, e3] - self.resolver_desconocidos(3, geneSet, ecuaciones, fnGenesAEntradas) - - def test_4_desconocidos(self): - valores = [i for i in range(-13, 13) if i != 0] - geneSet = [i for i in set( - Fraction(d, e) - for d in valores - for e in valores if e != 0)] - - def fnGenesAEntradas(genes): - return genes - - def e1(genes): - x, y, z, a = genes - return Fraction(1, 15) * x \ - - 2 * y \ - - 15 * z \ - - Fraction(4, 5) * a \ - - 3 - - def e2(genes): - x, y, z, a = genes - return -Fraction(5, 2) * x \ - - Fraction(9, 4) * y \ - + 12 * z \ - - a \ - - 17 - - def e3(genes): - x, y, z, a = genes - return -13 * x \ - + Fraction(3, 10) * y \ - - 6 * z \ - - Fraction(2, 5) * a \ - - 17 - - def e4(genes): - x, y, z, a = genes - return Fraction(1, 2) * x \ - + 2 * y \ - + Fraction(7, 4) * z \ - + Fraction(4, 3) * a \ - + 9 - - ecuaciones = [e1, e2, e3, e4] - self.resolver_desconocidos(4, geneSet, ecuaciones, fnGenesAEntradas) - - def test_comparativa(self): - genetic.Comparar.ejecutar(lambda: self.test_4_desconocidos()) - - def resolver_desconocidos(self, numUnknowns, geneSet, ecuaciones, - fnGenesAEntradas): - horaInicio = datetime.datetime.now() - edadMáxima = 50 - ventana = Ventana(max(1, int(len(geneSet) / (2 * edadMáxima))), - max(1, int(len(geneSet) / 3)), - int(len(geneSet) / 2)) - geneÍndices = [i for i in range(numUnknowns)] - geneSetOrdenado = sorted(geneSet) - - def fnMostrar(candidato): - mostrar(candidato, horaInicio, fnGenesAEntradas) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, ecuaciones) - - def fnMutar(genes): - mutar(genes, geneSetOrdenado, ventana, geneÍndices) - - aptitudÓptima = Aptitud(0) - mejor = genetic.obtener_mejor(fnObtenerAptitud, numUnknowns, - aptitudÓptima, geneSet, fnMostrar, - fnMutar, edadMáxima=edadMáxima) - self.assertTrue(not aptitudÓptima > mejor.Aptitud) - - -class Aptitud: - def __init__(self, diferenciaTotal): - self.DiferenciaTotal = diferenciaTotal - - def __gt__(self, otro): - return self.DiferenciaTotal < otro.DiferenciaTotal - - def __str__(self): - return "dif: {:0.2f}".format(float(self.DiferenciaTotal)) - - -class Ventana: - def __init__(self, mínimo, máximo, tamaño): - self.Min = mínimo - self.Max = máximo - self.Tamaño = tamaño - - def deslizar(self): - self.Tamaño = self.Tamaño - 1 if self.Tamaño > self.Min else self.Max - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch11/sudoku.py b/es/ch11/sudoku.py deleted file mode 100644 index 1758f68..0000000 --- a/es/ch11/sudoku.py +++ /dev/null @@ -1,171 +0,0 @@ -# File: sudoku.py -# Del capítulo 11 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - - -import datetime -import random -import unittest - -import genetic - - -def obtener_aptitud(genes, reglasDeValidación): - try: - primeraReglaQueFalla = next(regla for regla in reglasDeValidación - if genes[regla.Índice] == genes[ - regla.OtroÍndice]) - except StopIteration: - aptitud = 100 - else: - aptitud = (1 + índice_fila(primeraReglaQueFalla.OtroÍndice)) * 10 \ - + (1 + índice_columna(primeraReglaQueFalla.OtroÍndice)) - return aptitud - - -def mostrar(candidato, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - - for filaId in range(9): - fila = ' | '.join( - ' '.join(str(i) - for i in - candidato.Genes[filaId * 9 + i:filaId * 9 + i + 3]) - for i in [0, 3, 6]) - print("", fila) - if filaId < 8 and filaId % 3 == 2: - print(" ----- + ----- + -----") - print(" - = - - = - - = - {}\t{}\n" - .format(candidato.Aptitud, diferencia)) - - -def mutar(genes, reglasDeValidación): - reglaSeleccionada = next(regla for regla in reglasDeValidación - if genes[regla.Índice] == genes[regla.OtroÍndice]) - if reglaSeleccionada is None: - return - - if índice_fila(reglaSeleccionada.OtroÍndice) % 3 == 2 \ - and random.randint(0, 10) == 0: - secciónPrincipio = sección_principio(reglaSeleccionada.Índice) - actual = reglaSeleccionada.OtroÍndice - while reglaSeleccionada.OtroÍndice == actual: - barajar_en_su_lugar(genes, secciónPrincipio, 80) - reglaSeleccionada = next(regla for regla in reglasDeValidación - if genes[regla.Índice] == genes[ - regla.OtroÍndice]) - return - fila = índice_fila(reglaSeleccionada.OtroÍndice) - principio = fila * 9 - índiceA = reglaSeleccionada.OtroÍndice - índiceB = random.randrange(principio, len(genes)) - genes[índiceA], genes[índiceB] = genes[índiceB], genes[índiceA] - - -def barajar_en_su_lugar(genes, primero, último): - while primero < último: - índice = random.randint(primero, último) - genes[primero], genes[índice] = genes[índice], genes[primero] - primero += 1 - - -class PruebasDeSudoku(unittest.TestCase): - def test(self): - geneSet = [i for i in range(1, 9 + 1)] - horaInicio = datetime.datetime.now() - valorÓptimo = 100 - - def fnMostrar(candidato): - mostrar(candidato, horaInicio) - - reglasDeValidación = construir_las_reglas_de_validación() - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, reglasDeValidación) - - def fnCrear(): - return random.sample(geneSet * 9, 81) - - def fnMutar(genes): - mutar(genes, reglasDeValidación) - - mejor = genetic.obtener_mejor(fnObtenerAptitud, None, valorÓptimo, - None, fnMostrar, fnMutar, fnCrear, - edadMáxima=50) - self.assertEqual(mejor.Aptitud, valorÓptimo) - - def test_comparativa(self): - genetic.Comparar.ejecutar(lambda: self.test()) - - -def construir_las_reglas_de_validación(): - reglas = [] - for índice in range(80): - suFila = índice_fila(índice) - suColumna = índice_columna(índice) - suSección = fila_columna_sección(suFila, suColumna) - - for índice2 in range(índice + 1, 81): - otroFila = índice_fila(índice2) - otroColumna = índice_columna(índice2) - otroSección = fila_columna_sección(otroFila, otroColumna) - if suFila == otroFila or \ - suColumna == otroColumna or \ - suSección == otroSección: - reglas.append(Regla(índice, índice2)) - - reglas.sort(key=lambda x: x.OtroÍndice * 100 + x.Índice) - return reglas - - -def índice_fila(índice): - return int(índice / 9) - - -def índice_columna(índice): - return int(índice % 9) - - -def fila_columna_sección(fila, columna): - return int(fila / 3) * 3 + int(columna / 3) - - -def índice_sección(índice): - return fila_columna_sección(índice_fila(índice), índice_columna(índice)) - - -def sección_principio(índice): - return int((índice_fila(índice) % 9) / 3) * 27 + int( - índice_columna(índice) / 3) * 3 - - -class Regla: - def __init__(self, eso, otro): - if eso > otro: - eso, otro = otro, eso - self.Índice = eso - self.OtroÍndice = otro - - def __eq__(self, otro): - return self.Índice == otro.Índice and \ - self.OtroÍndice == otro.OtroÍndice - - def __hash__(self): - return self.Índice * 100 + self.OtroÍndice - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch12/genetic.py b/es/ch12/genetic.py deleted file mode 100644 index d564f8b..0000000 --- a/es/ch12/genetic.py +++ /dev/null @@ -1,191 +0,0 @@ -# File: genetic.py -# Del capítulo 12 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time -from bisect import bisect_left -from enum import Enum -from math import exp - - -def _generar_padre(longitud, geneSet, obtener_aptitud): - genes = [] - while len(genes) < longitud: - tamañoMuestral = min(longitud - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, tamañoMuestral)) - aptitud = obtener_aptitud(genes) - return Cromosoma(genes, aptitud, Estrategias.Creación) - - -def _mutar(padre, geneSet, obtener_aptitud): - genesDelNiño = padre.Genes[:] - índice = random.randrange(0, len(padre.Genes)) - nuevoGen, alterno = random.sample(geneSet, 2) - genesDelNiño[índice] = alterno if nuevoGen == genesDelNiño[ - índice] else nuevoGen - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) - - -def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): - genesDelNiño = padre.Genes[:] - mutación_personalizada(genesDelNiño) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) - - -def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, - mutar, generar_padre): - índiceDeDonante = random.randrange(0, len(padres)) - if índiceDeDonante == índice: - índiceDeDonante = (índiceDeDonante + 1) % len(padres) - genesDelNiño = intercambiar(genesDePadre, padres[índiceDeDonante].Genes) - if genesDelNiño is None: - # padre y donante son indistinguibles - padres[índiceDeDonante] = generar_padre() - return mutar(padres[índice]) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Intercambio) - - -def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, - mostrar, mutación_personalizada=None, - creación_personalizada=None, edadMáxima=None, - tamañoDePiscina=1, intercambiar=None): - if mutación_personalizada is None: - def fnMutar(padre): - return _mutar(padre, geneSet, obtener_aptitud) - else: - def fnMutar(padre): - return _mutar_personalizada(padre, mutación_personalizada, - obtener_aptitud) - - if creación_personalizada is None: - def fnGenerarPadre(): - return _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - else: - def fnGenerarPadre(): - genes = creación_personalizada() - return Cromosoma(genes, obtener_aptitud(genes), - Estrategias.Creación) - - búsquedaDeEstrategia = { - Estrategias.Creación: lambda p, i, o: fnGenerarPadre(), - Estrategias.Mutación: lambda p, i, o: fnMutar(p), - Estrategias.Intercambio: lambda p, i, o: - _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMutar, - fnGenerarPadre) - } - - estrategiasUsadas = [búsquedaDeEstrategia[Estrategias.Mutación]] - if intercambiar is not None: - estrategiasUsadas.append(búsquedaDeEstrategia[Estrategias.Intercambio]) - - def fnNuevoNiño(padre, índice, padres): - return random.choice(estrategiasUsadas)(padre, índice, padres) - else: - def fnNuevoNiño(padre, índice, padres): - return fnMutar(padre) - - for mejora in _obtener_mejoras(fnNuevoNiño, fnGenerarPadre, edadMáxima, - tamañoDePiscina): - mostrar(mejora) - f = búsquedaDeEstrategia[mejora.Estrategia] - estrategiasUsadas.append(f) - if not aptitudÓptima > mejora.Aptitud: - return mejora - - -def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina): - mejorPadre = generar_padre() - yield mejorPadre - padres = [mejorPadre] - aptitudesHistóricas = [mejorPadre.Aptitud] - for _ in range(tamañoDePiscina - 1): - padre = generar_padre() - if padre.Aptitud > mejorPadre.Aptitud: - yield padre - mejorPadre = padre - aptitudesHistóricas.append(padre.Aptitud) - padres.append(padre) - índiceDelÚltimoPadre = tamañoDePiscina - 1 - pÍndice = 1 - while True: - pÍndice = pÍndice - 1 if pÍndice > 0 else índiceDelÚltimoPadre - padre = padres[pÍndice] - niño = nuevo_niño(padre, pÍndice, padres) - if padre.Aptitud > niño.Aptitud: - if edadMáxima is None: - continue - padre.Edad += 1 - if edadMáxima > padre.Edad: - continue - índice = bisect_left(aptitudesHistóricas, niño.Aptitud, 0, - len(aptitudesHistóricas)) - proporciónSimilar = índice / len(aptitudesHistóricas) - if random.random() < exp(-proporciónSimilar): - padres[pÍndice] = niño - continue - mejorPadre.Edad = 0 - padres[pÍndice] = mejorPadre - continue - if not niño.Aptitud > padre.Aptitud: - # mismo aptitud - niño.Edad = padre.Edad + 1 - padres[pÍndice] = niño - continue - niño.Edad = 0 - padres[pÍndice] = niño - if niño.Aptitud > mejorPadre.Aptitud: - mejorPadre = niño - yield mejorPadre - aptitudesHistóricas.append(mejorPadre.Aptitud) - - -class Cromosoma: - def __init__(self, genes, aptitud, estrategia): - self.Genes = genes - self.Aptitud = aptitud - self.Estrategia = estrategia - self.Edad = 0 - - -class Estrategias(Enum): - Creación = 0, - Mutación = 1, - Intercambio = 2 - - -class Comparar: - @staticmethod - def ejecutar(función): - cronometrajes = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - horaInicio = time.time() - función() - segundos = time.time() - horaInicio - sys.stdout = stdout - cronometrajes.append(segundos) - promedio = statistics.mean(cronometrajes) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, promedio, - statistics.stdev(cronometrajes, promedio) if i > 1 else 0)) diff --git a/es/ch12/vendedor.py b/es/ch12/vendedor.py deleted file mode 100644 index 138b8b5..0000000 --- a/es/ch12/vendedor.py +++ /dev/null @@ -1,211 +0,0 @@ -# File: vendedor.py -# Del capítulo 12 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import math -import random -import unittest -from itertools import chain - -import genetic - - -def obtener_aptitud(genes, búsquedaDeUbicación): - aptitud = obtener_distancia(búsquedaDeUbicación[genes[0]], - búsquedaDeUbicación[genes[-1]]) - - for i in range(len(genes) - 1): - principio = búsquedaDeUbicación[genes[i]] - end = búsquedaDeUbicación[genes[i + 1]] - aptitud += obtener_distancia(principio, end) - - return Aptitud(round(aptitud, 2)) - - -def mostrar(candidato, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - print("{}\t{}\t{}\t{}".format( - ' '.join(map(str, candidato.Genes)), - candidato.Aptitud, - candidato.Estrategia.name, - diferencia)) - - -def obtener_distancia(ubicaciónA, ubicaciónB): - ladoA = ubicaciónA[0] - ubicaciónB[0] - ladoB = ubicaciónA[1] - ubicaciónB[1] - ladoC = math.sqrt(ladoA * ladoA + ladoB * ladoB) - return ladoC - - -def mutar(genes, fnObtenerAptitud): - cuenta = random.randint(2, len(genes)) - aptitudInicial = fnObtenerAptitud(genes) - while cuenta > 0: - cuenta -= 1 - índiceA, índiceB = random.sample(range(len(genes)), 2) - genes[índiceA], genes[índiceB] = genes[índiceB], genes[índiceA] - aptitud = fnObtenerAptitud(genes) - if aptitud > aptitudInicial: - return - - -def intercambiar(genesDePadre, donanteGenes, fnObtenerAptitud): - pares = {Par(donanteGenes[0], donanteGenes[-1]): 0} - - for i in range(len(donanteGenes) - 1): - pares[Par(donanteGenes[i], donanteGenes[i + 1])] = 0 - - genesTemporales = genesDePadre[:] - if Par(genesDePadre[0], genesDePadre[-1]) in pares: - # encontrar una discontinuidad - encontró = False - for i in range(len(genesDePadre) - 1): - if Par(genesDePadre[i], genesDePadre[i + 1]) in pares: - continue - genesTemporales = genesDePadre[i + 1:] + genesDePadre[:i + 1] - encontró = True - break - if not encontró: - return None - - series = [[genesTemporales[0]]] - for i in range(len(genesTemporales) - 1): - if Par(genesTemporales[i], genesTemporales[i + 1]) in pares: - series[-1].append(genesTemporales[i + 1]) - continue - series.append([genesTemporales[i + 1]]) - - aptitudInicial = fnObtenerAptitud(genesDePadre) - cuenta = random.randint(2, 20) - índicesDeSerie = range(len(series)) - while cuenta > 0: - cuenta -= 1 - for i in índicesDeSerie: - if len(series[i]) == 1: - continue - if random.randint(0, len(series)) == 0: - series[i] = [n for n in reversed(series[i])] - - índiceA, índiceB = random.sample(índicesDeSerie, 2) - series[índiceA], series[índiceB] = series[índiceB], series[índiceA] - genesDelNiño = list(chain.from_iterable(series)) - if fnObtenerAptitud(genesDelNiño) > aptitudInicial: - return genesDelNiño - return genesDelNiño - - -class PruebasDeVendedorAmbulante(unittest.TestCase): - def test_8_reinas(self): - búsquedaDeUbicación = { - 'A': [4, 7], - 'B': [2, 6], - 'C': [0, 5], - 'D': [1, 3], - 'E': [3, 0], - 'F': [5, 1], - 'G': [7, 2], - 'H': [6, 4] - } - secuenciaÓptima = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] - self.resolver(búsquedaDeUbicación, secuenciaÓptima) - - def test_ulysses16(self): - búsquedaDeUbicación = cargar_datos("ulysses16.tsp") - secuenciaÓptima = [14, 13, 12, 16, 1, 3, 2, 4, - 8, 15, 5, 11, 9, 10, 7, 6] - self.resolver(búsquedaDeUbicación, secuenciaÓptima) - - def test_comparativa(self): - genetic.Comparar.ejecutar(lambda: self.test_ulysses16()) - - def resolver(self, búsquedaDeUbicación, secuenciaÓptima): - geneSet = [i for i in búsquedaDeUbicación.keys()] - - def fnCrear(): - return random.sample(geneSet, len(geneSet)) - - def fnMostrar(candidato): - mostrar(candidato, horaInicio) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, búsquedaDeUbicación) - - def fnMutar(genes): - mutar(genes, fnObtenerAptitud) - - def fnIntercambio(padre, donante): - return intercambiar(padre, donante, fnObtenerAptitud) - - aptitudÓptima = fnObtenerAptitud(secuenciaÓptima) - horaInicio = datetime.datetime.now() - mejor = genetic.obtener_mejor(fnObtenerAptitud, None, aptitudÓptima, - None, fnMostrar, fnMutar, fnCrear, - edadMáxima=500, tamañoDePiscina=25, - intercambiar=fnIntercambio) - self.assertTrue(not aptitudÓptima > mejor.Aptitud) - - -def cargar_datos(archivoLocal): - """ espera que: - Sección de HEADER antes de la sección de DATA, todos los filas - comienzan en columna 0 - Los elementos de la sección de DATA tienen un espacio en columna 0 - 1 23.45 67.89 - último fila de archivo es: " EOF" - """ - with open(archivoLocal, mode='r') as fuente: - contenido = fuente.read().splitlines() - búsquedaDeUbicación = {} - for fila in contenido: - if fila[0] != ' ': # HEADER - continue - if fila == " EOF": - break - - id, x, y = fila.split(' ')[1:4] - búsquedaDeUbicación[int(id)] = [float(x), float(y)] - return búsquedaDeUbicación - - -class Aptitud: - def __init__(self, distanciaTotal): - self.DistanciaTotal = distanciaTotal - - def __gt__(self, otro): - return self.DistanciaTotal < otro.DistanciaTotal - - def __str__(self): - return "{:0.2f}".format(self.DistanciaTotal) - - -class Par: - def __init__(self, nodo, adyacente): - if nodo < adyacente: - nodo, adyacente = adyacente, nodo - self.Nodo = nodo - self.Adyacente = adyacente - - def __eq__(self, otro): - return self.Nodo == otro.Nodo and self.Adyacente == otro.Adyacente - - def __hash__(self): - return hash(self.Nodo) * 397 ^ hash(self.Adyacente) - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch13/genetic.py b/es/ch13/genetic.py deleted file mode 100644 index 3591c1c..0000000 --- a/es/ch13/genetic.py +++ /dev/null @@ -1,203 +0,0 @@ -# File: genetic.py -# Del capítulo 13 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time -from bisect import bisect_left -from enum import Enum -from math import exp - - -def _generar_padre(longitud, geneSet, obtener_aptitud): - genes = [] - while len(genes) < longitud: - tamañoMuestral = min(longitud - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, tamañoMuestral)) - aptitud = obtener_aptitud(genes) - return Cromosoma(genes, aptitud, Estrategias.Creación) - - -def _mutar(padre, geneSet, obtener_aptitud): - genesDelNiño = padre.Genes[:] - índice = random.randrange(0, len(padre.Genes)) - nuevoGen, alterno = random.sample(geneSet, 2) - genesDelNiño[índice] = alterno if nuevoGen == genesDelNiño[ - índice] else nuevoGen - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) - - -def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): - genesDelNiño = padre.Genes[:] - mutación_personalizada(genesDelNiño) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) - - -def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, - mutar, generar_padre): - índiceDeDonante = random.randrange(0, len(padres)) - if índiceDeDonante == índice: - índiceDeDonante = (índiceDeDonante + 1) % len(padres) - genesDelNiño = intercambiar(genesDePadre, padres[índiceDeDonante].Genes) - if genesDelNiño is None: - # padre y donante son indistinguibles - padres[índiceDeDonante] = generar_padre() - return mutar(padres[índice]) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Intercambio) - - -def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, - mostrar, mutación_personalizada=None, - creación_personalizada=None, edadMáxima=None, - tamañoDePiscina=1, intercambiar=None, segundosMáximos=None): - if mutación_personalizada is None: - def fnMutar(padre): - return _mutar(padre, geneSet, obtener_aptitud) - else: - def fnMutar(padre): - return _mutar_personalizada(padre, mutación_personalizada, - obtener_aptitud) - - if creación_personalizada is None: - def fnGenerarPadre(): - return _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - else: - def fnGenerarPadre(): - genes = creación_personalizada() - return Cromosoma(genes, obtener_aptitud(genes), - Estrategias.Creación) - - búsquedaDeEstrategia = { - Estrategias.Creación: lambda p, i, o: fnGenerarPadre(), - Estrategias.Mutación: lambda p, i, o: fnMutar(p), - Estrategias.Intercambio: lambda p, i, o: - _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMutar, - fnGenerarPadre) - } - - estrategiasUsadas = [búsquedaDeEstrategia[Estrategias.Mutación]] - if intercambiar is not None: - estrategiasUsadas.append(búsquedaDeEstrategia[Estrategias.Intercambio]) - - def fnNuevoNiño(padre, índice, padres): - return random.choice(estrategiasUsadas)(padre, índice, padres) - else: - def fnNuevoNiño(padre, índice, padres): - return fnMutar(padre) - - for caducado, mejora in \ - _obtener_mejoras(fnNuevoNiño, fnGenerarPadre, edadMáxima, - tamañoDePiscina, segundosMáximos): - if caducado: - return mejora - mostrar(mejora) - f = búsquedaDeEstrategia[mejora.Estrategia] - estrategiasUsadas.append(f) - if not aptitudÓptima > mejora.Aptitud: - return mejora - - -def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina, - segundosMáximos): - horaInicio = time.time() - mejorPadre = generar_padre() - yield segundosMáximos is not None and time.time() \ - - horaInicio > segundosMáximos, mejorPadre - padres = [mejorPadre] - aptitudesHistóricas = [mejorPadre.Aptitud] - for _ in range(tamañoDePiscina - 1): - padre = generar_padre() - if segundosMáximos is not None and time.time() - horaInicio > \ - segundosMáximos: - yield True, padre - if padre.Aptitud > mejorPadre.Aptitud: - yield False, padre - mejorPadre = padre - aptitudesHistóricas.append(padre.Aptitud) - padres.append(padre) - índiceDelÚltimoPadre = tamañoDePiscina - 1 - pÍndice = 1 - while True: - if segundosMáximos is not None and time.time() - horaInicio > \ - segundosMáximos: - yield True, mejorPadre - pÍndice = pÍndice - 1 if pÍndice > 0 else índiceDelÚltimoPadre - padre = padres[pÍndice] - niño = nuevo_niño(padre, pÍndice, padres) - if padre.Aptitud > niño.Aptitud: - if edadMáxima is None: - continue - padre.Edad += 1 - if edadMáxima > padre.Edad: - continue - índice = bisect_left(aptitudesHistóricas, niño.Aptitud, 0, - len(aptitudesHistóricas)) - proporciónSimilar = índice / len(aptitudesHistóricas) - if random.random() < exp(-proporciónSimilar): - padres[pÍndice] = niño - continue - mejorPadre.Edad = 0 - padres[pÍndice] = mejorPadre - continue - if not niño.Aptitud > padre.Aptitud: - # mismo aptitud - niño.Edad = padre.Edad + 1 - padres[pÍndice] = niño - continue - niño.Edad = 0 - padres[pÍndice] = niño - if niño.Aptitud > mejorPadre.Aptitud: - mejorPadre = niño - yield False, mejorPadre - aptitudesHistóricas.append(mejorPadre.Aptitud) - - -class Cromosoma: - def __init__(self, genes, aptitud, estrategia): - self.Genes = genes - self.Aptitud = aptitud - self.Estrategia = estrategia - self.Edad = 0 - - -class Estrategias(Enum): - Creación = 0, - Mutación = 1, - Intercambio = 2 - - -class Comparar: - @staticmethod - def ejecutar(función): - cronometrajes = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - horaInicio = time.time() - función() - segundos = time.time() - horaInicio - sys.stdout = stdout - cronometrajes.append(segundos) - promedio = statistics.mean(cronometrajes) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, promedio, - statistics.stdev(cronometrajes, promedio) if i > 1 else 0)) diff --git a/es/ch13/pi.py b/es/ch13/pi.py deleted file mode 100644 index b15cbb0..0000000 --- a/es/ch13/pi.py +++ /dev/null @@ -1,147 +0,0 @@ -# File: pi.py -# Del capítulo 13 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import math -import random -import sys -import time -import unittest - -import genetic - - -def obtener_aptitud(genes, valoresDeBits): - denominator = obtener_denominador(genes, valoresDeBits) - if denominator == 0: - return 0 - - relación = obtener_numerador(genes, valoresDeBits) / denominator - return math.pi - math.fabs(math.pi - relación) - - -def mostrar(candidato, horaInicio, valoresDeBits): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - numerador = obtener_numerador(candidato.Genes, valoresDeBits) - denominator = obtener_denominador(candidato.Genes, valoresDeBits) - print("{}/{}\t{}\t{}".format( - numerador, - denominator, - candidato.Aptitud, diferencia)) - - -def bits_a_entero(bits, valoresDeBits): - resultado = 0 - for i, bit in enumerate(bits): - if bit == 0: - continue - resultado += valoresDeBits[i] - return resultado - - -def obtener_numerador(genes, valoresDeBits): - return 1 + bits_a_entero(genes[:len(valoresDeBits)], valoresDeBits) - - -def obtener_denominador(genes, valoresDeBits): - return bits_a_entero(genes[len(valoresDeBits):], valoresDeBits) - - -def mutar(genes, numBits): - índiceDelNumerador, índiceDelDenominador \ - = random.randrange(0, numBits), random.randrange(numBits, - len(genes)) - genes[índiceDelNumerador] = 1 - genes[índiceDelNumerador] - genes[índiceDelDenominador] = 1 - genes[índiceDelDenominador] - - -class PruebasDePi(unittest.TestCase): - def test(self, valoresDeBits=[512, 256, 128, 64, 32, 16, 8, 4, 2, 1], - segundosMáximos=None): - geneSet = [i for i in range(2)] - horaInicio = datetime.datetime.now() - - def fnMostrar(candidato): - mostrar(candidato, horaInicio, valoresDeBits) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, valoresDeBits) - - aptitudÓptima = 3.14159 - - def fnMutar(genes): - mutar(genes, len(valoresDeBits)) - - longitud = 2 * len(valoresDeBits) - mejor = genetic.obtener_mejor(fnObtenerAptitud, longitud, - aptitudÓptima, geneSet, fnMostrar, - fnMutar, edadMáxima=250, - segundosMáximos=segundosMáximos) - return aptitudÓptima <= mejor.Aptitud - - def test_optimize(self): - geneSet = [i for i in range(1, 512 + 1)] - longitud = 10 - segundosMáximos = 2 - - def fnObtenerAptitud(genes): - horaInicio = time.time() - cuenta = 0 - stdout = sys.stdout - sys.stdout = None - while time.time() - horaInicio < segundosMáximos: - if self.test(genes, segundosMáximos): - cuenta += 1 - sys.stdout = stdout - distancia = abs(sum(genes) - 1023) - fracción = 1 / distancia if distancia > 0 else distancia - cuenta += round(fracción, 4) - return cuenta - - def fnMostrar(cromosoma): - print("{}\t{}".format(cromosoma.Genes, cromosoma.Aptitud)) - - initial = [512, 256, 128, 64, 32, 16, 8, 4, 2, 1] - print("initial:", initial, fnObtenerAptitud(initial)) - - aptitudÓptima = 10 * segundosMáximos - genetic.obtener_mejor(fnObtenerAptitud, longitud, aptitudÓptima, - geneSet, fnMostrar, segundosMáximos=600) - - def test_comparativa(self): - genetic.Comparar.ejecutar( - lambda: self.test([98, 334, 38, 339, 117, - 39, 145, 123, 40, 129])) - - def test_encontrar_10_mejores_aproximaciones(self): - mejor = {} - for numerador in range(1, 1024): - for denominator in range(1, 1024): - relación = numerador / denominator - piDist = math.pi - abs(math.pi - relación) - if piDist not in mejor or mejor[piDist][0] > numerador: - mejor[piDist] = [numerador, denominator] - - mejoresAproximaciones = list(reversed(sorted(mejor.keys()))) - for i in range(10): - relación = mejoresAproximaciones[i] - nd = mejor[relación] - print("%i / %i\t%f" % (nd[0], nd[1], relación)) - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch14/ecuaciones.py b/es/ch14/ecuaciones.py deleted file mode 100644 index ffc76ca..0000000 --- a/es/ch14/ecuaciones.py +++ /dev/null @@ -1,177 +0,0 @@ -# File: ecuaciones.py -# Del capítulo 14 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import unittest - -import genetic - - -def evaluar(genes, operacionesPriorizadas): - ecuación = genes[:] - for operationSet in operacionesPriorizadas: - iOffset = 0 - for i in range(1, len(ecuación), 2): - i += iOffset - opSímbolo = ecuación[i] - if opSímbolo in operationSet: - operandoIzquierdo = ecuación[i - 1] - operandoDerecho = ecuación[i + 1] - ecuación[i - 1] = operationSet[opSímbolo](operandoIzquierdo, - operandoDerecho) - del ecuación[i + 1] - del ecuación[i] - iOffset += -2 - return ecuación[0] - - -def añadir(a, b): - return a + b - - -def sustraer(a, b): - return a - b - - -def multiplicar(a, b): - return a * b - - -def obtener_aptitud(genes, totalEsperado, fnEvaluar): - resultado = fnEvaluar(genes) - - if resultado != totalEsperado: - aptitud = totalEsperado - abs(resultado - totalEsperado) - else: - aptitud = 1000 - len(genes) - - return aptitud - - -def mostrar(candidato, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - print("{}\t{}\t{}".format( - (' '.join(map(str, [i for i in candidato.Genes]))), - candidato.Aptitud, - diferencia)) - - -def crear(números, operaciones, númerosMin, númerosMax): - genes = [random.choice(números)] - cuenta = random.randint(númerosMin, 1 + númerosMax) - while cuenta > 1: - cuenta -= 1 - genes.append(random.choice(operaciones)) - genes.append(random.choice(números)) - return genes - - -def mutar(genes, números, operaciones, númerosMin, númerosMax, - fnObtenerAptitud): - cuenta = random.randint(1, 10) - aptitudInicial = fnObtenerAptitud(genes) - while cuenta > 0: - cuenta -= 1 - if fnObtenerAptitud(genes) > aptitudInicial: - return - cuentaDeNúmeros = (1 + len(genes)) / 2 - añadiendo = cuentaDeNúmeros < númerosMax and \ - random.randint(0, 100) == 0 - if añadiendo: - genes.append(random.choice(operaciones)) - genes.append(random.choice(números)) - continue - - eliminando = cuentaDeNúmeros > númerosMin and \ - random.randint(0, 20) == 0 - if eliminando: - índice = random.randrange(0, len(genes) - 1) - del genes[índice] - del genes[índice] - continue - - índice = random.randrange(0, len(genes)) - genes[índice] = random.choice(operaciones) \ - if (índice & 1) == 1 else random.choice(números) - - -class PruebasDeEcuaciones(unittest.TestCase): - def test_adición(self): - operaciones = ['+', '-'] - operacionesPriorizadas = [{'+': añadir, - '-': sustraer}] - soluciónDeLongitudÓptima = [7, '+', 7, '+', 7, '+', 7, '+', 7, '-', 6] - self.resolver(operaciones, operacionesPriorizadas, - soluciónDeLongitudÓptima) - - def test_multiplicación(self): - operaciones = ['+', '-', '*'] - operacionesPriorizadas = [{'*': multiplicar}, - {'+': añadir, - '-': sustraer}] - soluciónDeLongitudÓptima = [6, '*', 3, '*', 3, '*', 6, '-', 7] - self.resolver(operaciones, operacionesPriorizadas, - soluciónDeLongitudÓptima) - - def test_exponente(self): - operaciones = ['^', '+', '-', '*'] - operacionesPriorizadas = [{'^': lambda a, b: a ** b}, - {'*': multiplicar}, - {'+': añadir, - '-': sustraer}] - soluciónDeLongitudÓptima = [6, '^', 3, '*', 2, '-', 5] - self.resolver(operaciones, operacionesPriorizadas, - soluciónDeLongitudÓptima) - - def resolver(self, operaciones, operacionesPriorizadas, - soluciónDeLongitudÓptima): - números = [1, 2, 3, 4, 5, 6, 7] - totalEsperado = evaluar(soluciónDeLongitudÓptima, - operacionesPriorizadas) - númerosMin = (1 + len(soluciónDeLongitudÓptima)) / 2 - númerosMax = 6 * númerosMin - horaInicio = datetime.datetime.now() - - def fnMostrar(candidato): - mostrar(candidato, horaInicio) - - def fnEvaluar(genes): - return evaluar(genes, operacionesPriorizadas) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, totalEsperado, fnEvaluar) - - def fnCrear(): - return crear(números, operaciones, númerosMin, númerosMax) - - def fnMutar(niño): - mutar(niño, números, operaciones, númerosMin, númerosMax, - fnObtenerAptitud) - - aptitudÓptima = fnObtenerAptitud(soluciónDeLongitudÓptima) - mejor = genetic.obtener_mejor(fnObtenerAptitud, None, aptitudÓptima, - None, fnMostrar, fnMutar, fnCrear, - edadMáxima=50) - self.assertTrue(not aptitudÓptima > mejor.Aptitud) - - def test_comparativa(self): - genetic.Comparar.ejecutar(self.test_exponente) - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch15/cortadora.py b/es/ch15/cortadora.py deleted file mode 100644 index 1c8070b..0000000 --- a/es/ch15/cortadora.py +++ /dev/null @@ -1,167 +0,0 @@ -# File: cortadora.py -# Del capítulo 15 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -from enum import Enum - - -class ContenidoDelCampo(Enum): - Hierba = ' #' - Cortado = ' .' - Cortador = 'C' - - def __str__(self): - return self.value - - -class Dirección: - def __init__(self, índice, xOffset, yOffset, símbolo): - self.Índice = índice - self.XOffset = xOffset - self.YOffset = yOffset - self.Símbolo = símbolo - - def mover_de(self, ubicación, distancia=1): - return Ubicación(ubicación.X + distancia * self.XOffset, - ubicación.Y + distancia * self.YOffset) - - -class Direcciones(Enum): - Norte = Dirección(0, 0, -1, '^') - Este = Dirección(1, 1, 0, '>') - Sur = Dirección(2, 0, 1, 'v') - Oeste = Dirección(3, -1, 0, '<') - - @staticmethod - def obtener_dirección_después_de_girar_a_la_izquierda_90_grados(dirección): - nuevoÍndice = dirección.Índice - 1 \ - if dirección.Índice > 0 \ - else len(Direcciones) - 1 - nuevaDirección = next(i for i in Direcciones - if i.value.Índice == nuevoÍndice) - return nuevaDirección.value - - @staticmethod - def obtener_dirección_después_de_girar_a_la_derecha_90_grados(dirección): - nuevoÍndice = dirección.Índice + 1 \ - if dirección.Índice < len(Direcciones) - 1 \ - else 0 - nuevaDirección = next(i for i in Direcciones - if i.value.Índice == nuevoÍndice) - return nuevaDirección.value - - -class Ubicación: - def __init__(self, x, y): - self.X, self.Y = x, y - - def mover(self, xOffset, yOffset): - return Ubicación(self.X + xOffset, self.Y + yOffset) - - -class Cortadora: - def __init__(self, ubicación, dirección): - self.Ubicación = ubicación - self.Dirección = dirección - self.CuentaDePasos = 0 - - def girar_a_la_izquierda(self): - self.CuentaDePasos += 1 - self.Dirección = Direcciones \ - .obtener_dirección_después_de_girar_a_la_izquierda_90_grados( - self.Dirección) - - def corta(self, campo): - nuevaUbicación = self.Dirección.mover_de(self.Ubicación) - nuevaUbicación, esVálida = campo.arreglar_ubicación(nuevaUbicación) - if esVálida: - self.Ubicación = nuevaUbicación - self.CuentaDePasos += 1 - campo.ajuste(self.Ubicación, - self.CuentaDePasos if self.CuentaDePasos > 9 - else " {}".format(self.CuentaDePasos)) - - def salta(self, campo, adelante, derecha): - nuevaUbicación = self.Dirección.mover_de(self.Ubicación, adelante) - derechaDirección = Direcciones \ - .obtener_dirección_después_de_girar_a_la_derecha_90_grados( - self.Dirección) - nuevaUbicación = derechaDirección.mover_de(nuevaUbicación, derecha) - nuevaUbicación, esVálida = campo.arreglar_ubicación(nuevaUbicación) - if esVálida: - self.Ubicación = nuevaUbicación - self.CuentaDePasos += 1 - campo.ajuste(self.Ubicación, self.CuentaDePasos - if self.CuentaDePasos > 9 - else " {}".format(self.CuentaDePasos)) - - -class Campo: - def __init__(self, anchura, altura, contenidoInicial): - self.Campo = [[contenidoInicial] * anchura for _ in range(altura)] - self.Anchura = anchura - self.Altura = altura - - def ajuste(self, ubicación, símbolo): - self.Campo[ubicación.Y][ubicación.X] = símbolo - - def cuente_cortada(self): - return sum(1 for fila in range(self.Altura) - for columna in range(self.Anchura) - if self.Campo[fila][columna] != ContenidoDelCampo.Hierba) - - def mostrar(self, cortadora): - for índiceDeFilas in range(self.Altura): - if índiceDeFilas != cortadora.Ubicación.Y: - fila = ' '.join(map(str, self.Campo[índiceDeFilas])) - else: - r = self.Campo[índiceDeFilas][:] - r[cortadora.Ubicación.X] = "{}{}".format( - ContenidoDelCampo.Cortador, cortadora.Dirección.Símbolo) - fila = ' '.join(map(str, r)) - print(fila) - - -class CampoValidando(Campo): - def __init__(self, anchura, altura, contenidoInicial): - super().__init__(anchura, altura, contenidoInicial) - - def arreglar_ubicación(self, ubicación): - if ubicación.X >= self.Anchura or \ - ubicación.X < 0 or \ - ubicación.Y >= self.Altura or \ - ubicación.Y < 0: - return None, False - return ubicación, True - - -class CampoToroidal(Campo): - def __init__(self, anchura, altura, contenidoInicial): - super().__init__(anchura, altura, contenidoInicial) - - def arreglar_ubicación(self, ubicación): - nuevaUbicación = Ubicación(ubicación.X, ubicación.Y) - if nuevaUbicación.X < 0: - nuevaUbicación.X += self.Anchura - elif nuevaUbicación.X >= self.Anchura: - nuevaUbicación.X %= self.Anchura - - if nuevaUbicación.Y < 0: - nuevaUbicación.Y += self.Altura - elif nuevaUbicación.Y >= self.Altura: - nuevaUbicación.Y %= self.Altura - - return nuevaUbicación, True diff --git a/es/ch15/genetic.py b/es/ch15/genetic.py deleted file mode 100644 index 9659892..0000000 --- a/es/ch15/genetic.py +++ /dev/null @@ -1,203 +0,0 @@ -# File: genetic.py -# Del capítulo 13 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time -from bisect import bisect_left -from enum import Enum -from math import exp - - -def _generar_padre(longitud, geneSet, obtener_aptitud): - genes = [] - while len(genes) < longitud: - tamañoMuestral = min(longitud - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, tamañoMuestral)) - aptitud = obtener_aptitud(genes) - return Cromosoma(genes, aptitud, Estrategias.Creación) - - -def _mudar(padre, geneSet, obtener_aptitud): - genesDelNiño = padre.Genes[:] - índice = random.randrange(0, len(padre.Genes)) - nuevoGen, alterno = random.sample(geneSet, 2) - genesDelNiño[índice] = alterno if nuevoGen == genesDelNiño[ - índice] else nuevoGen - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) - - -def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): - genesDelNiño = padre.Genes[:] - mutación_personalizada(genesDelNiño) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) - - -def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, - mudar, generar_padre): - índiceDeDonante = random.randrange(0, len(padres)) - if índiceDeDonante == índice: - índiceDeDonante = (índiceDeDonante + 1) % len(padres) - genesDelNiño = intercambiar(genesDePadre, padres[índiceDeDonante].Genes) - if genesDelNiño is None: - # padre y donante son indistinguibles - padres[índiceDeDonante] = generar_padre() - return mudar(padres[índice]) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Intercambio) - - -def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, - mostrar, mutación_personalizada=None, - creación_personalizada=None, edadMáxima=None, - tamañoDePiscina=1, intercambiar=None, segundosMáximos=None): - if mutación_personalizada is None: - def fnMudar(padre): - return _mudar(padre, geneSet, obtener_aptitud) - else: - def fnMudar(padre): - return _mudar_personalizada(padre, mutación_personalizada, - obtener_aptitud) - - if creación_personalizada is None: - def fnGenerarPadre(): - return _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - else: - def fnGenerarPadre(): - genes = creación_personalizada() - return Cromosoma(genes, obtener_aptitud(genes), - Estrategias.Creación) - - búsquedaDeEstrategia = { - Estrategias.Creación: lambda p, i, o: fnGenerarPadre(), - Estrategias.Mutación: lambda p, i, o: fnMudar(p), - Estrategias.Intercambio: lambda p, i, o: - _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMudar, - fnGenerarPadre) - } - - estrategiasUsadas = [búsquedaDeEstrategia[Estrategias.Mutación]] - if intercambiar is not None: - estrategiasUsadas.append(búsquedaDeEstrategia[Estrategias.Intercambio]) - - def fnNuevoNiño(padre, índice, padres): - return random.choice(estrategiasUsadas)(padre, índice, padres) - else: - def fnNuevoNiño(padre, índice, padres): - return fnMudar(padre) - - for caducado, mejora in _obtener_mejoras(fnNuevoNiño, fnGenerarPadre, - edadMáxima, tamañoDePiscina, - segundosMáximos): - if caducado: - return mejora - mostrar(mejora) - f = búsquedaDeEstrategia[mejora.Estrategia] - estrategiasUsadas.append(f) - if not aptitudÓptima > mejora.Aptitud: - return mejora - - -def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina, - segundosMáximos): - horaInicio = time.time() - mejorPadre = generar_padre() - yield segundosMáximos is not None and time.time() \ - - horaInicio > segundosMáximos, mejorPadre - padres = [mejorPadre] - aptitudesHistóricas = [mejorPadre.Aptitud] - for _ in range(tamañoDePiscina - 1): - padre = generar_padre() - if segundosMáximos is not None and time.time() - horaInicio > \ - segundosMáximos: - yield True, padre - if padre.Aptitud > mejorPadre.Aptitud: - yield False, padre - mejorPadre = padre - aptitudesHistóricas.append(padre.Aptitud) - padres.append(padre) - índiceDelÚltimoPadre = tamañoDePiscina - 1 - pÍndice = 1 - while True: - if segundosMáximos is not None and time.time() - horaInicio > \ - segundosMáximos: - yield True, mejorPadre - pÍndice = pÍndice - 1 if pÍndice > 0 else índiceDelÚltimoPadre - padre = padres[pÍndice] - niño = nuevo_niño(padre, pÍndice, padres) - if padre.Aptitud > niño.Aptitud: - if edadMáxima is None: - continue - padre.Edad += 1 - if edadMáxima > padre.Edad: - continue - índice = bisect_left(aptitudesHistóricas, niño.Aptitud, 0, - len(aptitudesHistóricas)) - proporciónSimilar = índice / len(aptitudesHistóricas) - if random.random() < exp(-proporciónSimilar): - padres[pÍndice] = niño - continue - padres[pÍndice] = mejorPadre - padre.Edad = 0 - continue - if not niño.Aptitud > padre.Aptitud: - # mismo aptitud - niño.Edad = padre.Edad + 1 - padres[pÍndice] = niño - continue - padres[pÍndice] = niño - padre.Edad = 0 - if niño.Aptitud > mejorPadre.Aptitud: - yield False, niño - mejorPadre = niño - aptitudesHistóricas.append(niño.Aptitud) - - -class Cromosoma: - def __init__(self, genes, aptitud, estrategia): - self.Genes = genes - self.Aptitud = aptitud - self.Estrategia = estrategia - self.Edad = 0 - - -class Estrategias(Enum): - Creación = 0, - Mutación = 1, - Intercambio = 2 - - -class Comparar: - @staticmethod - def ejecutar(función): - cronometrajes = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - horaInicio = time.time() - función() - segundos = time.time() - horaInicio - sys.stdout = stdout - cronometrajes.append(segundos) - promedio = statistics.mean(cronometrajes) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, promedio, - statistics.stdev(cronometrajes, promedio) if i > 1 else 0)) diff --git a/es/ch15/pruebas.py b/es/ch15/pruebas.py deleted file mode 100644 index 81e931a..0000000 --- a/es/ch15/pruebas.py +++ /dev/null @@ -1,425 +0,0 @@ -# File: pruebas.py -# Del capítulo 15 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import unittest - -import genetic -from cortadora import * - - -def obtener_aptitud(genes, fnEvaluar): - campo, cortadora, _ = fnEvaluar(genes) - return Aptitud(campo.cuente_cortada(), len(genes), cortadora.CuentaDePasos) - - -def mostrar(candidato, horaInicio, fnEvaluar): - campo, cortadora, programa = fnEvaluar(candidato.Genes) - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - campo.mostrar(cortadora) - print("{}\t{}".format( - candidato.Aptitud, - diferencia)) - programa.print() - - -def mutar(genes, geneSet, mínGenes, máxGenes, fnObtenerAptitud, rondasMáximas): - cuenta = random.randint(1, rondasMáximas) - aptitudInicial = fnObtenerAptitud(genes) - while cuenta > 0: - cuenta -= 1 - if fnObtenerAptitud(genes) > aptitudInicial: - return - añadiendo = len(genes) == 0 or \ - (len(genes) < máxGenes and random.randint(0, 5) == 0) - if añadiendo: - genes.append(random.choice(geneSet)()) - continue - - eliminando = len(genes) > mínGenes and random.randint(0, 50) == 0 - if eliminando: - índice = random.randrange(0, len(genes)) - del genes[índice] - continue - - índice = random.randrange(0, len(genes)) - genes[índice] = random.choice(geneSet)() - - -def crear(geneSet, mínGenes, máxGenes): - cantidad = random.randint(mínGenes, máxGenes) - genes = [random.choice(geneSet)() for _ in range(1, cantidad)] - return genes - - -def intercambiar(padre, otroPadre): - genesDelNiño = padre[:] - if len(padre) <= 2 or len(otroPadre) < 2: - return genesDelNiño - longitud = random.randint(1, len(padre) - 2) - principio = random.randrange(0, len(padre) - longitud) - genesDelNiño[principio:principio + longitud] = \ - otroPadre[principio:principio + longitud] - return genesDelNiño - - -class PruebasDeCortadora(unittest.TestCase): - def test_corta_gira(self): - anchura = altura = 8 - geneSet = [lambda: Corta(), - lambda: Gira()] - mínGenes = anchura * altura - máxGenes = int(1.5 * mínGenes) - rondasMáximasDeMutación = 3 - númeroEsperadoDeInstrucciones = 78 - - def fnCrearCampo(): - return CampoToroidal(anchura, altura, - ContenidoDelCampo.Hierba) - - self.ejecutar_con(geneSet, anchura, altura, mínGenes, máxGenes, - númeroEsperadoDeInstrucciones, - rondasMáximasDeMutación, fnCrearCampo, - númeroEsperadoDeInstrucciones) - - def test_corta_gira_salta(self): - anchura = altura = 8 - geneSet = [lambda: Corta(), - lambda: Gira(), - lambda: Salta(random.randint(0, min(anchura, altura)), - random.randint(0, min(anchura, altura)))] - mínGenes = anchura * altura - máxGenes = int(1.5 * mínGenes) - rondasMáximasDeMutación = 1 - númeroEsperadoDeInstrucciones = 64 - - def fnCrearCampo(): - return CampoToroidal(anchura, altura, - ContenidoDelCampo.Hierba) - - self.ejecutar_con(geneSet, anchura, altura, mínGenes, máxGenes, - númeroEsperadoDeInstrucciones, - rondasMáximasDeMutación, fnCrearCampo, - númeroEsperadoDeInstrucciones) - - def test_corta_gira_salta_validando(self): - anchura = altura = 8 - geneSet = [lambda: Corta(), - lambda: Gira(), - lambda: Salta(random.randint(0, min(anchura, altura)), - random.randint(0, min(anchura, altura)))] - mínGenes = anchura * altura - máxGenes = int(1.5 * mínGenes) - rondasMáximasDeMutación = 3 - númeroEsperadoDeInstrucciones = 79 - - def fnCrearCampo(): - return CampoValidando(anchura, altura, - ContenidoDelCampo.Hierba) - - self.ejecutar_con(geneSet, anchura, altura, mínGenes, máxGenes, - númeroEsperadoDeInstrucciones, - rondasMáximasDeMutación, fnCrearCampo, - númeroEsperadoDeInstrucciones) - - def test_corta_gira_repite(self): - anchura = altura = 8 - geneSet = [lambda: Corta(), - lambda: Gira(), - lambda: Repite(random.randint(0, 8), - random.randint(0, 8))] - mínGenes = 3 - máxGenes = 20 - rondasMáximasDeMutación = 3 - númeroEsperadoDeInstrucciones = 9 - númeroEsperadoDePasos = 88 - - def fnCrearCampo(): - return CampoToroidal(anchura, altura, - ContenidoDelCampo.Hierba) - - self.ejecutar_con(geneSet, anchura, altura, mínGenes, máxGenes, - númeroEsperadoDeInstrucciones, - rondasMáximasDeMutación, fnCrearCampo, - númeroEsperadoDePasos) - - def test_corta_gira_salta_func(self): - anchura = altura = 8 - geneSet = [lambda: Corta(), - lambda: Gira(), - lambda: Salta(random.randint(0, min(anchura, altura)), - random.randint(0, min(anchura, altura))), - lambda: Func()] - mínGenes = 3 - máxGenes = 20 - rondasMáximasDeMutación = 3 - númeroEsperadoDeInstrucciones = 17 - númeroEsperadoDePasos = 64 - - def fnCrearCampo(): - return CampoToroidal(anchura, altura, - ContenidoDelCampo.Hierba) - - self.ejecutar_con(geneSet, anchura, altura, mínGenes, máxGenes, - númeroEsperadoDeInstrucciones, - rondasMáximasDeMutación, fnCrearCampo, - númeroEsperadoDePasos) - - def test_corta_gira_salta_llama(self): - anchura = altura = 8 - geneSet = [lambda: Corta(), - lambda: Gira(), - lambda: Salta(random.randint(0, min(anchura, altura)), - random.randint(0, min(anchura, altura))), - lambda: Func(expectLlama=True), - lambda: Llama(random.randint(0, 5))] - mínGenes = 3 - máxGenes = 20 - rondasMáximasDeMutación = 3 - númeroEsperadoDeInstrucciones = 18 - númeroEsperadoDePasos = 65 - - def fnCrearCampo(): - return CampoToroidal(anchura, altura, - ContenidoDelCampo.Hierba) - - self.ejecutar_con(geneSet, anchura, altura, mínGenes, máxGenes, - númeroEsperadoDeInstrucciones, - rondasMáximasDeMutación, fnCrearCampo, - númeroEsperadoDePasos) - - def ejecutar_con(self, geneSet, anchura, altura, mínGenes, máxGenes, - númeroEsperadoDeInstrucciones, rondasMáximasDeMutación, - fnCrearCampo, númeroEsperadoDePasos): - ubicaciónInicialDelCortador = Ubicación(int(anchura / 2), - int(altura / 2)) - direcciónInicialDelCortador = Direcciones.Sur.value - - def fnCrear(): - return crear(geneSet, 1, altura) - - def fnEvaluar(instrucciones): - programa = Programa(instrucciones) - cortadora = Cortadora(ubicaciónInicialDelCortador, - direcciónInicialDelCortador) - campo = fnCrearCampo() - try: - programa.evaluar(cortadora, campo) - except RecursionError: - pass - return campo, cortadora, programa - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, fnEvaluar) - - horaInicio = datetime.datetime.now() - - def fnMostrar(candidato): - mostrar(candidato, horaInicio, fnEvaluar) - - def fnMutar(niño): - mutar(niño, geneSet, mínGenes, máxGenes, fnObtenerAptitud, - rondasMáximasDeMutación) - - aptitudÓptima = Aptitud(anchura * altura, - númeroEsperadoDeInstrucciones, - númeroEsperadoDePasos) - - mejor = genetic.obtener_mejor(fnObtenerAptitud, None, aptitudÓptima, - None, fnMostrar, fnMutar, fnCrear, - edadMáxima=None, tamañoDePiscina=10, - intercambiar=intercambiar) - - self.assertTrue(not aptitudÓptima > mejor.Aptitud) - - -class Corta: - def __init__(self): - pass - - @staticmethod - def ejecutar(cortadora, campo): - cortadora.corta(campo) - - def __str__(self): - return "corta" - - -class Gira: - def __init__(self): - pass - - @staticmethod - def ejecutar(cortadora, campo): - cortadora.girar_a_la_izquierda() - - def __str__(self): - return "gira" - - -class Salta: - def __init__(self, adelante, derecha): - self.Adelante = adelante - self.Derecha = derecha - - def ejecutar(self, cortadora, campo): - cortadora.salta(campo, self.Adelante, self.Derecha) - - def __str__(self): - return "salta({},{})".format(self.Adelante, self.Derecha) - - -class Repite: - def __init__(self, númeroDeOperaciones, veces): - self.NúmeroDeOperaciones = númeroDeOperaciones - self.Veces = veces - self.Instrucciones = [] - - def ejecutar(self, cortadora, campo): - for i in range(self.Veces): - for instrucción in self.Instrucciones: - instrucción.ejecutar(cortadora, campo) - - def __str__(self): - return "repite({},{})".format( - ' '.join(map(str, self.Instrucciones)) - if len(self.Instrucciones) > 0 - else self.NúmeroDeOperaciones, - self.Veces) - - -class Func: - def __init__(self, expectLlama=False): - self.Instrucciones = [] - self.ExpectLlama = expectLlama - self.Id = None - - def ejecutar(self, cortadora, campo): - for instrucción in self.Instrucciones: - instrucción.ejecutar(cortadora, campo) - - def __str__(self): - return "func{1}: {0}".format( - ' '.join(map(str, self.Instrucciones)), - self.Id if self.Id is not None else '') - - -class Llama: - def __init__(self, funcId=None): - self.FuncId = funcId - self.Funcs = None - - def ejecutar(self, cortadora, campo): - funcId = 0 if self.FuncId is None else self.FuncId - if len(self.Funcs) > funcId: - self.Funcs[funcId].ejecutar(cortadora, campo) - - def __str__(self): - return "llama-{}".format( - self.FuncId - if self.FuncId is not None - else 'func') - - -class Programa: - def __init__(self, genes): - temp = genes[:] - funcs = [] - - for índice in reversed(range(len(temp))): - if type(temp[índice]) is Repite: - principio = índice + 1 - fin = min(índice + temp[índice].NúmeroDeOperaciones + 1, - len(temp)) - temp[índice].Instrucciones = temp[principio:fin] - del temp[principio:fin] - continue - - if type(temp[índice]) is Llama: - temp[índice].Funcs = funcs - if type(temp[índice]) is Func: - if len(funcs) > 0 and not temp[índice].ExpectLlama: - temp[índice] = Llama() - temp[índice].Funcs = funcs - continue - principio = índice + 1 - fin = len(temp) - func = Func() - if temp[índice].ExpectLlama: - func.Id = len(funcs) - func.Instrucciones = [i for i in temp[principio:fin] - if type(i) is not Repite or - type(i) is Repite and len( - i.Instrucciones) > 0] - funcs.append(func) - del temp[índice:fin] - - for func in funcs: - for índice in reversed(range(len(func.Instrucciones))): - if type(func.Instrucciones[índice]) is Llama: - func_id = func.Instrucciones[índice].FuncId - if func_id is None: - continue - if func_id >= len(funcs) or \ - len(funcs[func_id].Instrucciones) == 0: - del func.Instrucciones[índice] - - for índice in reversed(range(len(temp))): - if type(temp[índice]) is Llama: - func_id = temp[índice].FuncId - if func_id is None: - continue - if func_id >= len(funcs) or \ - len(funcs[func_id].Instrucciones) == 0: - del temp[índice] - self.Principal = temp - self.Funcs = funcs - - def evaluar(self, cortadora, campo): - for i, instrucción in enumerate(self.Principal): - instrucción.ejecutar(cortadora, campo) - - def print(self): - if self.Funcs is not None: - for func in self.Funcs: - if func.Id is not None and len(func.Instrucciones) == 0: - continue - print(func) - print(' '.join(map(str, self.Principal))) - - -class Aptitud: - def __init__(self, totalCortada, instruccionesTotales, cuentaDePasos): - self.TotalCortada = totalCortada - self.InstruccionesTotales = instruccionesTotales - self.CuentaDePasos = cuentaDePasos - - def __gt__(self, otro): - if self.TotalCortada != otro.TotalCortada: - return self.TotalCortada > otro.TotalCortada - if self.CuentaDePasos != otro.CuentaDePasos: - return self.CuentaDePasos < otro.CuentaDePasos - return self.InstruccionesTotales < otro.InstruccionesTotales - - def __str__(self): - return "{} segados con {} instrucciones y {} pasos".format( - self.TotalCortada, self.InstruccionesTotales, self.CuentaDePasos) - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch16/circuitos.py b/es/ch16/circuitos.py deleted file mode 100644 index de105b0..0000000 --- a/es/ch16/circuitos.py +++ /dev/null @@ -1,100 +0,0 @@ -# File: circuitos.py -# Del capítulo 16 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -class Not: - def __init__(self, entrada): - self._entrada = entrada - - def obtener_salida(self): - if self._entrada is None: - return None - valor = self._entrada.obtener_salida() - if valor is None: - return None - return not valor - - def __str__(self): - if self._entrada is None: - return "Not(?)" - return "Not({})".format(self._entrada) - - @staticmethod - def recuento_de_entradas(): - return 1 - - -class PuertaCon2Entradas: - def __init__(self, entradaA, entradaB, etiqueta, fnPrueba): - self._entradaA = entradaA - self._entradaB = entradaB - self._etiqueta = etiqueta - self._fnPrueba = fnPrueba - - def obtener_salida(self): - if self._entradaA is None or self._entradaB is None: - return None - aValor = self._entradaA.obtener_salida() - if aValor is None: - return None - bValor = self._entradaB.obtener_salida() - if bValor is None: - return None - return self._fnPrueba(aValor, bValor) - - def __str__(self): - if self._entradaA is None or self._entradaB is None: - return "{}(?)".format(self._etiqueta) - return "{}({} {})".format(self._etiqueta, self._entradaA, - self._entradaB) - - @staticmethod - def recuento_de_entradas(): - return 2 - - -class And(PuertaCon2Entradas): - def __init__(self, entradaA, entradaB): - super().__init__(entradaA, entradaB, type(self).__name__, - lambda a, b: a and b) - - -class Or(PuertaCon2Entradas): - def __init__(self, entradaA, entradaB): - super().__init__(entradaA, entradaB, type(self).__name__, - lambda a, b: a or b) - - -class Xor(PuertaCon2Entradas): - def __init__(self, entradaA, entradaB): - super().__init__(entradaA, entradaB, type(self).__name__, - lambda a, b: a != b) - - -class Fuente: - def __init__(self, fuenteId, contenedorDeFuentes): - self._fuenteId = fuenteId - self._contenedorDeFuentes = contenedorDeFuentes - - def obtener_salida(self): - return self._contenedorDeFuentes[self._fuenteId] - - def __str__(self): - return self._fuenteId - - @staticmethod - def recuento_de_entradas(): - return 0 diff --git a/es/ch16/genetic.py b/es/ch16/genetic.py deleted file mode 100644 index e912871..0000000 --- a/es/ch16/genetic.py +++ /dev/null @@ -1,222 +0,0 @@ -# File: genetic.py -# Del capítulo 16 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time -from bisect import bisect_left -from enum import Enum -from math import exp - - -def _generar_padre(longitud, geneSet, obtener_aptitud): - genes = [] - while len(genes) < longitud: - tamañoMuestral = min(longitud - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, tamañoMuestral)) - aptitud = obtener_aptitud(genes) - return Cromosoma(genes, aptitud, Estrategias.Creación) - - -def _mutar(padre, geneSet, obtener_aptitud): - genesDelNiño = padre.Genes[:] - índice = random.randrange(0, len(padre.Genes)) - nuevoGen, alterno = random.sample(geneSet, 2) - genesDelNiño[índice] = alterno if nuevoGen == genesDelNiño[ - índice] else nuevoGen - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) - - -def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): - genesDelNiño = padre.Genes[:] - mutación_personalizada(genesDelNiño) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) - - -def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, - mutar, generar_padre): - índiceDeDonante = random.randrange(0, len(padres)) - if índiceDeDonante == índice: - índiceDeDonante = (índiceDeDonante + 1) % len(padres) - genesDelNiño = intercambiar(genesDePadre, padres[índiceDeDonante].Genes) - if genesDelNiño is None: - # padre y donante son indistinguibles - padres[índiceDeDonante] = generar_padre() - return mutar(padres[índice]) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Intercambio) - - -def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, - mostrar, mutación_personalizada=None, - creación_personalizada=None, edadMáxima=None, - tamañoDePiscina=1, intercambiar=None, segundosMáximos=None): - if mutación_personalizada is None: - def fnMutar(padre): - return _mutar(padre, geneSet, obtener_aptitud) - else: - def fnMutar(padre): - return _mutar_personalizada(padre, mutación_personalizada, - obtener_aptitud) - - if creación_personalizada is None: - def fnGenerarPadre(): - return _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - else: - def fnGenerarPadre(): - genes = creación_personalizada() - return Cromosoma(genes, obtener_aptitud(genes), - Estrategias.Creación) - - búsquedaDeEstrategia = { - Estrategias.Creación: lambda p, i, o: fnGenerarPadre(), - Estrategias.Mutación: lambda p, i, o: fnMutar(p), - Estrategias.Intercambio: lambda p, i, o: - _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMutar, - fnGenerarPadre) - } - - estrategiasUsadas = [búsquedaDeEstrategia[Estrategias.Mutación]] - if intercambiar is not None: - estrategiasUsadas.append(búsquedaDeEstrategia[Estrategias.Intercambio]) - - def fnNuevoNiño(padre, índice, padres): - return random.choice(estrategiasUsadas)(padre, índice, padres) - else: - def fnNuevoNiño(padre, índice, padres): - return fnMutar(padre) - - for caducado, mejora in _obtener_mejoras(fnNuevoNiño, fnGenerarPadre, - edadMáxima, tamañoDePiscina, - segundosMáximos): - if caducado: - return mejora - mostrar(mejora) - f = búsquedaDeEstrategia[mejora.Estrategia] - estrategiasUsadas.append(f) - if not aptitudÓptima > mejora.Aptitud: - return mejora - - -def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina, - segundosMáximos): - horaInicio = time.time() - mejorPadre = generar_padre() - yield segundosMáximos is not None and time.time() \ - - horaInicio > segundosMáximos, mejorPadre - padres = [mejorPadre] - aptitudesHistóricas = [mejorPadre.Aptitud] - for _ in range(tamañoDePiscina - 1): - padre = generar_padre() - if segundosMáximos is not None and time.time() - horaInicio > \ - segundosMáximos: - yield True, padre - if padre.Aptitud > mejorPadre.Aptitud: - yield False, padre - mejorPadre = padre - aptitudesHistóricas.append(padre.Aptitud) - padres.append(padre) - índiceDelÚltimoPadre = tamañoDePiscina - 1 - pÍndice = 1 - while True: - if segundosMáximos is not None and time.time() - horaInicio > \ - segundosMáximos: - yield True, mejorPadre - pÍndice = pÍndice - 1 if pÍndice > 0 else índiceDelÚltimoPadre - padre = padres[pÍndice] - niño = nuevo_niño(padre, pÍndice, padres) - if padre.Aptitud > niño.Aptitud: - if edadMáxima is None: - continue - padre.Edad += 1 - if edadMáxima > padre.Edad: - continue - índice = bisect_left(aptitudesHistóricas, niño.Aptitud, 0, - len(aptitudesHistóricas)) - proporciónSimilar = índice / len(aptitudesHistóricas) - if random.random() < exp(-proporciónSimilar): - padres[pÍndice] = niño - continue - mejorPadre.Edad = 0 - padres[pÍndice] = mejorPadre - continue - if not niño.Aptitud > padre.Aptitud: - # mismo aptitud - niño.Edad = padre.Edad + 1 - padres[pÍndice] = niño - continue - niño.Edad = 0 - padres[pÍndice] = niño - if niño.Aptitud > mejorPadre.Aptitud: - mejorPadre = niño - yield False, mejorPadre - aptitudesHistóricas.append(mejorPadre.Aptitud) - - -def ascenso_de_la_colina(funciónDeOptimización, es_mejora, es_óptimo, - obtener_valor_de_característica_siguiente, mostrar, - valorInicialDeCaracterística): - mejor = funciónDeOptimización(valorInicialDeCaracterística) - stdout = sys.stdout - sys.stdout = None - while not es_óptimo(mejor): - valorDeCaracterística = obtener_valor_de_característica_siguiente( - mejor) - niño = funciónDeOptimización(valorDeCaracterística) - if es_mejora(mejor, niño): - mejor = niño - sys.stdout = stdout - mostrar(mejor, valorDeCaracterística) - sys.stdout = None - sys.stdout = stdout - return mejor - - -class Cromosoma: - def __init__(self, genes, aptitud, estrategia): - self.Genes = genes - self.Aptitud = aptitud - self.Estrategia = estrategia - self.Edad = 0 - - -class Estrategias(Enum): - Creación = 0, - Mutación = 1, - Intercambio = 2 - - -class Comparar: - @staticmethod - def ejecutar(función): - cronometrajes = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - horaInicio = time.time() - función() - segundos = time.time() - horaInicio - sys.stdout = stdout - cronometrajes.append(segundos) - promedio = statistics.mean(cronometrajes) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, promedio, - statistics.stdev(cronometrajes, promedio) if i > 1 else 0)) diff --git a/es/ch16/pruebas.py b/es/ch16/pruebas.py deleted file mode 100644 index 03a1a8d..0000000 --- a/es/ch16/pruebas.py +++ /dev/null @@ -1,236 +0,0 @@ -# File: pruebas.py -# Del capítulo 16 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import unittest - -import circuitos -import genetic - - -def obtener_aptitud(genes, reglas, entradas): - circuito = nodos_a_circuito(genes)[0] - etiquetasDeFuente = "ABCD" - reglasExitosas = 0 - for regla in reglas: - entradas.clear() - entradas.update(zip(etiquetasDeFuente, regla[0])) - if circuito.obtener_salida() == regla[1]: - reglasExitosas += 1 - return reglasExitosas - - -def mostrar(candidato, horaInicio): - circuito = nodos_a_circuito(candidato.Genes)[0] - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - print("{}\t{}\t{}".format( - circuito, - candidato.Aptitud, - diferencia)) - - -def crear_gen(índice, puertas, fuentes): - if índice < len(fuentes): - tipoDePuerta = fuentes[índice] - else: - tipoDePuerta = random.choice(puertas) - índiceA = índiceB = None - if tipoDePuerta[1].recuento_de_entradas() > 0: - índiceA = random.randint(0, índice) - if tipoDePuerta[1].recuento_de_entradas() > 1: - índiceB = random.randint(0, índice) - if índiceB == índiceA: - índiceB = random.randint(0, índice) - return Nodo(tipoDePuerta[0], índiceA, índiceB) - - -def mutar(genesDelNiño, fnCrearGen, fnObtenerAptitud, fuenteCount): - cuenta = random.randint(1, 5) - aptitudInicial = fnObtenerAptitud(genesDelNiño) - while cuenta > 0: - cuenta -= 1 - índicesUsados = [i for i in nodos_a_circuito(genesDelNiño)[1] - if i >= fuenteCount] - if len(índicesUsados) == 0: - return - índice = random.choice(índicesUsados) - genesDelNiño[índice] = fnCrearGen(índice) - if fnObtenerAptitud(genesDelNiño) > aptitudInicial: - return - - -class PruebasDeCircuitos(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.entradas = dict() - cls.puertas = [[circuitos.And, circuitos.And], - [lambda i1, i2: circuitos.Not(i1), circuitos.Not]] - cls.fuentes = [ - [lambda i1, i2: circuitos.Fuente('A', cls.entradas), - circuitos.Fuente], - [lambda i1, i2: circuitos.Fuente('B', cls.entradas), - circuitos.Fuente]] - - def test_generar_OR(self): - reglas = [[[False, False], False], - [[False, True], True], - [[True, False], True], - [[True, True], True]] - - longitudÓptima = 6 - self.encontrar_circuito(reglas, longitudÓptima) - - def test_generar_XOR(self): - reglas = [[[False, False], False], - [[False, True], True], - [[True, False], True], - [[True, True], False]] - self.encontrar_circuito(reglas, 9) - - def test_generar_AxBxC(self): - reglas = [[[False, False, False], False], - [[False, False, True], True], - [[False, True, False], True], - [[False, True, True], False], - [[True, False, False], True], - [[True, False, True], False], - [[True, True, False], False], - [[True, True, True], True]] - self.fuentes.append( - [lambda l, r: circuitos.Fuente('C', self.entradas), - circuitos.Fuente]) - self.puertas.append([circuitos.Or, circuitos.Or]) - self.encontrar_circuito(reglas, 12) - - def obtener_reglas_para_sumador_de_2_bits_bit(self, bit): - reglas = [[[0, 0, 0, 0], [0, 0, 0]], # 0 + 0 = 0 - [[0, 0, 0, 1], [0, 0, 1]], # 0 + 1 = 1 - [[0, 0, 1, 0], [0, 1, 0]], # 0 + 2 = 2 - [[0, 0, 1, 1], [0, 1, 1]], # 0 + 3 = 3 - [[0, 1, 0, 0], [0, 0, 1]], # 1 + 0 = 1 - [[0, 1, 0, 1], [0, 1, 0]], # 1 + 1 = 2 - [[0, 1, 1, 0], [0, 1, 1]], # 1 + 2 = 3 - [[0, 1, 1, 1], [1, 0, 0]], # 1 + 3 = 4 - [[1, 0, 0, 0], [0, 1, 0]], # 2 + 0 = 2 - [[1, 0, 0, 1], [0, 1, 1]], # 2 + 1 = 3 - [[1, 0, 1, 0], [1, 0, 0]], # 2 + 2 = 4 - [[1, 0, 1, 1], [1, 0, 1]], # 2 + 3 = 5 - [[1, 1, 0, 0], [0, 1, 1]], # 3 + 0 = 3 - [[1, 1, 0, 1], [1, 0, 0]], # 3 + 1 = 4 - [[1, 1, 1, 0], [1, 0, 1]], # 3 + 2 = 5 - [[1, 1, 1, 1], [1, 1, 0]]] # 3 + 3 = 6 - reglasDeBitN = [[regla[0], regla[1][2 - bit]] for regla in reglas] - self.puertas.append([circuitos.Or, circuitos.Or]) - self.puertas.append([circuitos.Xor, circuitos.Xor]) - self.fuentes.append( - [lambda l, r: circuitos.Fuente('C', self.entradas), - circuitos.Fuente]) - self.fuentes.append( - [lambda l, r: circuitos.Fuente('D', self.entradas), - circuitos.Fuente]) - return reglasDeBitN - - def test_sumador_de_2_bits_bit_1(self): - reglas = self.obtener_reglas_para_sumador_de_2_bits_bit(0) - self.encontrar_circuito(reglas, 3) - - def test_sumador_de_2_bits_bit_2(self): - reglas = self.obtener_reglas_para_sumador_de_2_bits_bit(1) - self.encontrar_circuito(reglas, 7) - - def test_sumador_de_2_bits_bit_4s(self): - reglas = self.obtener_reglas_para_sumador_de_2_bits_bit(2) - self.encontrar_circuito(reglas, 9) - - def encontrar_circuito(self, reglas, longitudEsperada): - horaInicio = datetime.datetime.now() - - def fnMostrar(candidato, longitud=None): - if longitud is not None: - print("-- nodos distintos en el circuito:", - len(nodos_a_circuito(candidato.Genes)[1])) - mostrar(candidato, horaInicio) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, reglas, self.entradas) - - def fnCrearGen(índice): - return crear_gen(índice, self.puertas, self.fuentes) - - def fnMutar(genes): - mutar(genes, fnCrearGen, fnObtenerAptitud, len(self.fuentes)) - - longitudMáxima = 50 - - def fnCrear(): - return [fnCrearGen(i) for i in range(longitudMáxima)] - - def fnFunciónDeOptimización(longitudVariable): - nonlocal longitudMáxima - longitudMáxima = longitudVariable - return genetic.obtener_mejor( - fnObtenerAptitud, None, len(reglas), None, fnMostrar, - fnMutar, fnCrear, tamañoDePiscina=3, segundosMáximos=30) - - def fnEsUnaMejora(mejorActual, niño): - return niño.Aptitud == len(reglas) and \ - len(nodos_a_circuito(niño.Genes)[1]) < \ - len(nodos_a_circuito(mejorActual.Genes)[1]) - - def fnEsÓptimo(niño): - return niño.Aptitud == len(reglas) and \ - len(nodos_a_circuito(niño.Genes)[1]) <= longitudEsperada - - def fnObtenerValorDeCaracterísticaSiguiente(mejorActual): - return len(nodos_a_circuito(mejorActual.Genes)[1]) - - mejor = genetic.ascenso_de_la_colina( - fnFunciónDeOptimización, fnEsUnaMejora, fnEsÓptimo, - fnObtenerValorDeCaracterísticaSiguiente, fnMostrar, - longitudMáxima) - self.assertTrue(mejor.Aptitud == len(reglas)) - self.assertFalse(len(nodos_a_circuito(mejor.Genes)[1]) - > longitudEsperada) - - -def nodos_a_circuito(genes): - circuito = [] - índicesUsados = [] - for i, nodo in enumerate(genes): - usados = {i} - entradaA = entradaB = None - if nodo.ÍndiceA is not None and i > nodo.ÍndiceA: - entradaA = circuito[nodo.ÍndiceA] - usados.update(índicesUsados[nodo.ÍndiceA]) - if nodo.ÍndiceB is not None and i > nodo.ÍndiceB: - entradaB = circuito[nodo.ÍndiceB] - usados.update(índicesUsados[nodo.ÍndiceB]) - circuito.append(nodo.CrearPuerta(entradaA, entradaB)) - índicesUsados.append(usados) - return circuito[-1], índicesUsados[-1] - - -class Nodo: - def __init__(self, crearPuerta, índiceA=None, índiceB=None): - self.CrearPuerta = crearPuerta - self.ÍndiceA = índiceA - self.ÍndiceB = índiceB - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch17/regex.py b/es/ch17/regex.py deleted file mode 100644 index 8e5cd61..0000000 --- a/es/ch17/regex.py +++ /dev/null @@ -1,395 +0,0 @@ -# File: regex.py -# Del capítulo 17 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import re -import unittest -from functools import partial - -import genetic - -metasDeRepetición = {'?', '*', '+', '{2}', '{2,}'} -metasDeInicio = {'|', '(', '['} -metasFinales = {')', ']'} -todosMetacaracteres = metasDeRepetición | metasDeInicio | metasFinales - -erroresEnRegexes = {} - - -def reparar_regex(genes): - resultado = [] - finales = [] - f = reparar_o_ignorar_metas_de_repetición - for símbolo in genes: - f = f(símbolo, resultado, finales) - if ']' in finales and resultado[-1] == '[': - del resultado[-1] - resultado.extend(reversed(finales)) - return ''.join(resultado) - - -def reparar_o_ignorar_metas_de_repetición(símbolo, resultado, finales): - if símbolo in metasDeRepetición or símbolo in metasFinales: - return reparar_o_ignorar_metas_de_repetición - if símbolo == '(': - finales.append(')') - resultado.append(símbolo) - if símbolo == '[': - finales.append(']') - return reparar_in_character_set - return manejar_metas_de_repetición_que_siguen_metas_de_repetición_o_inicio - - -def manejar_metas_de_repetición_que_siguen_metas_de_repetición_o_inicio( - símbolo, resultado, finales): - último = resultado[-1] - if símbolo not in metasDeRepetición: - if símbolo == '[': - resultado.append(símbolo) - finales.append(']') - return reparar_in_character_set - if símbolo == '(': - finales.append(')') - elif símbolo == ')': - coincidencia = ''.join(finales).rfind(')') - if coincidencia != -1: - del finales[coincidencia] - else: - resultado[0:0] = ['('] - resultado.append(símbolo) - elif último in metasDeInicio: - pass - elif símbolo == '?' and último == '?' and len(resultado) > 2 \ - and resultado[-2] in metasDeRepetición: - pass - elif último in metasDeRepetición: - pass - else: - resultado.append(símbolo) - return manejar_metas_de_repetición_que_siguen_metas_de_repetición_o_inicio - - -def reparar_in_character_set(símbolo, resultado, finales): - if símbolo == ']': - if resultado[-1] == '[': - del resultado[-1] - resultado.append(símbolo) - coincidencia = ''.join(finales).rfind(']') - if coincidencia != -1: - del finales[coincidencia] - return manejar_metas_de_repetición_que_siguen_metas_de_repetición_o_inicio - elif símbolo == '[': - pass - elif símbolo == '|' and resultado[-1] == '|': - pass # suprimir FutureWarning sobre || - else: - resultado.append(símbolo) - return reparar_in_character_set - - -def obtener_aptitud(genes, deseadas, noDeseadas): - patrón = reparar_regex(genes) - longitud = len(patrón) - - try: - re.compile(patrón) - except re.error as e: - llave = str(e) - llave = llave[:llave.index("at position")] - info = [str(e), - "genes = ['{}']".format("', '".join(genes)), - "regex: " + patrón] - if llave not in erroresEnRegexes or len(info[1]) < len( - erroresEnRegexes[llave][1]): - erroresEnRegexes[llave] = info - return Aptitud(0, len(deseadas), len(noDeseadas), longitud) - - númeroDeDeseadosQueCoincidieron = sum( - 1 for i in deseadas if re.fullmatch(patrón, i)) - númeroDeNoDeseadosQueCoincidieron = sum( - 1 for i in noDeseadas if re.fullmatch(patrón, i)) - return Aptitud(númeroDeDeseadosQueCoincidieron, len(deseadas), - númeroDeNoDeseadosQueCoincidieron, longitud) - - -def mostrar(candidato, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - print("{}\t{}\t{}".format( - reparar_regex(candidato.Genes), candidato.Aptitud, diferencia)) - - -def mutar_añadir(genes, geneSet): - índice = random.randrange(0, len(genes) + 1) if len(genes) > 0 else 0 - genes[índice:índice] = [random.choice(geneSet)] - return True - - -def mutar_remover(genes): - if len(genes) < 1: - return False - del genes[random.randrange(0, len(genes))] - if len(genes) > 1 and random.randint(0, 1) == 1: - del genes[random.randrange(0, len(genes))] - return True - - -def mutar_reemplazar(genes, geneSet): - if len(genes) < 1: - return False - índice = random.randrange(0, len(genes)) - genes[índice] = random.choice(geneSet) - return True - - -def mutar_intercambiar(genes): - if len(genes) < 2: - return False - índiceA, índiceB = random.sample(range(len(genes)), 2) - genes[índiceA], genes[índiceB] = genes[índiceB], genes[índiceA] - return True - - -def mutar_mover(genes): - if len(genes) < 3: - return False - principio = random.choice(range(len(genes))) - fin = principio + random.randint(1, 2) - aMover = genes[principio:fin] - genes[principio:fin] = [] - índice = random.choice(range(len(genes))) - if índice >= principio: - índice += 1 - genes[índice:índice] = aMover - return True - - -def mutar_a_conjunto_de_caracteres(genes): - if len(genes) < 3: - return False - o = [i for i in range(1, len(genes) - 1) - if genes[i] == '|' and - genes[i - 1] not in todosMetacaracteres and - genes[i + 1] not in todosMetacaracteres] - if len(o) == 0: - return False - corta = [i for i in o - if sum(len(w) for w in genes[i - 1:i + 2:2]) > - len(set(c for w in genes[i - 1:i + 2:2] for c in w))] - if len(corta) == 0: - return False - índice = random.choice(o) - distinto = set(c for w in genes[índice - 1:índice + 2:2] for c in w) - secuencia = ['['] + [i for i in distinto] + [']'] - genes[índice - 1:índice + 2] = secuencia - return True - - -def mutar_a_conjunto_de_caracteres_izquierda(genes, deseadas): - if len(genes) < 4: - return False - o = [i for i in range(-1, len(genes) - 3) - if (i == -1 or genes[i] in metasDeInicio) and - len(genes[i + 1]) == 2 and - genes[i + 1] in deseadas and - (len(genes) == i + 1 or genes[i + 2] == '|' or - genes[i + 2] in metasFinales)] - if len(o) == 0: - return False - búsqueda = {} - for i in o: - búsqueda.setdefault(genes[i + 1][0], []).append(i) - mín2 = [i for i in búsqueda.values() if len(i) > 1] - if len(mín2) == 0: - return False - choice = random.choice(mín2) - caracteres = ['|', genes[choice[0] + 1][0], '['] - caracteres.extend([genes[i + 1][1] for i in choice]) - caracteres.append(']') - for i in reversed(choice): - if i >= 0: - genes[i:i + 2] = [] - genes.extend(caracteres) - return True - - -def mutar_add_deseadas(genes, deseadas): - índice = random.randrange(0, len(genes) + 1) if len(genes) > 0 else 0 - genes[índice:índice] = ['|'] + [random.choice(deseadas)] - return True - - -def mutar(genes, fnObtenerAptitud, operadoresDeMutación, recuentoDeMutaciones): - aptitudInicial = fnObtenerAptitud(genes) - cuenta = random.choice(recuentoDeMutaciones) - for i in range(1, cuenta + 2): - duplo = operadoresDeMutación[:] - func = random.choice(duplo) - while not func(genes): - duplo.remove(func) - func = random.choice(duplo) - if fnObtenerAptitud(genes) > aptitudInicial: - recuentoDeMutaciones.append(i) - return - - -class PruebasDeRegex(unittest.TestCase): - def test_dos_dígitos(self): - deseadas = {"01", "11", "10"} - noDeseadas = {"00", ""} - self.encontrar_regex(deseadas, noDeseadas, 7) - - def test_grupos(self): - deseadas = {"01", "0101", "010101"} - noDeseadas = {"0011", ""} - self.encontrar_regex(deseadas, noDeseadas, 5) - - def test_códigos_de_estado(self): - Aptitud.UseRegexLongitud = True - deseadas = {"NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND"} - noDeseadas = {"N" + l for l in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - if "N" + l not in deseadas} - operadoresPersonalizados = [ - partial(mutar_a_conjunto_de_caracteres_izquierda, - deseadas=deseadas), - ] - self.encontrar_regex(deseadas, noDeseadas, 11, - operadoresPersonalizados) - - def test_longitud_par(self): - deseadas = {"00", "01", "10", "11", "0000", "0001", "0010", "0011", - "0100", "0101", "0110", "0111", "1000", "1001", "1010", - "1011", "1100", "1101", "1110", "1111"} - noDeseadas = {"0", "1", "000", "001", "010", "011", "100", "101", - "110", "111", ""} - operadoresPersonalizados = [ - mutar_a_conjunto_de_caracteres, - ] - self.encontrar_regex(deseadas, noDeseadas, 10, - operadoresPersonalizados) - - def test_50_códigos_de_estado(self): - Aptitud.UseRegexLongitud = True - deseadas = {"AL", "AK", "AZ", "AR", "CA", - "CO", "CT", "DE", "FL", "GA", - "HI", "ID", "IL", "IN", "IA", - "KS", "KY", "LA", "ME", "MD", - "MA", "MI", "MN", "MS", "MO", - "MT", "NE", "NV", "NH", "NJ", - "NM", "NY", "NC", "ND", "OH", - "OK", "OR", "PA", "RI", "SC", - "SD", "TN", "TX", "UT", "VT", - "VA", "WA", "WV", "WI", "WY"} - noDeseadas = {a + b for a in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - for b in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - if a + b not in deseadas} | \ - set(i for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ") - operadoresPersonalizados = [ - partial(mutar_a_conjunto_de_caracteres_izquierda, - deseadas=deseadas), - mutar_a_conjunto_de_caracteres, - partial(mutar_add_deseadas, deseadas=[i for i in deseadas]), - ] - self.encontrar_regex(deseadas, noDeseadas, 120, - operadoresPersonalizados) - - def encontrar_regex(self, deseadas, noDeseadas, longitudEsperada, - operadoresPersonalizados=None): - horaInicio = datetime.datetime.now() - genesDeTexto = deseadas | set(c for w in deseadas for c in w) - geneSet = [i for i in todosMetacaracteres | genesDeTexto] - - def fnMostrar(candidato): - mostrar(candidato, horaInicio) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes, deseadas, noDeseadas) - - recuentoDeMutaciones = [1] - - operadoresDeMutación = [ - partial(mutar_añadir, geneSet=geneSet), - partial(mutar_reemplazar, geneSet=geneSet), - mutar_remover, - mutar_intercambiar, - mutar_mover, - ] - if operadoresPersonalizados is not None: - operadoresDeMutación.extend(operadoresPersonalizados) - - def fnMutar(genes): - mutar(genes, fnObtenerAptitud, operadoresDeMutación, - recuentoDeMutaciones) - - aptitudÓptima = Aptitud(len(deseadas), len(deseadas), 0, - longitudEsperada) - - mejor = genetic.obtener_mejor( - fnObtenerAptitud, max(len(i) for i in genesDeTexto), - aptitudÓptima, geneSet, fnMostrar, fnMutar, tamañoDePiscina=10) - self.assertTrue(not aptitudÓptima > mejor.Aptitud) - - for info in erroresEnRegexes.values(): - print("") - print(info[0]) - print(info[1]) - print(info[2]) - - def test_comparativa(self): - genetic.Comparar.ejecutar(self.test_dos_dígitos) - - -class Aptitud: - UseRegexLongitud = False - - def __init__(self, númeroDeDeseadosQueCoincidieron, totalDeseado, - númeroDeNoDeseadosQueCoincidieron, longitud): - self.NúmeroDeDeseadosQueCoincidieron = númeroDeDeseadosQueCoincidieron - self._totalDeseado = totalDeseado - self.NúmeroDeNoDeseadosQueCoincidieron = \ - númeroDeNoDeseadosQueCoincidieron - self.Longitud = longitud - - def __gt__(self, otro): - conjunto = (self._totalDeseado - - self.NúmeroDeDeseadosQueCoincidieron) + \ - self.NúmeroDeNoDeseadosQueCoincidieron - otroConjunto = (otro._totalDeseado - - otro.NúmeroDeDeseadosQueCoincidieron) + \ - otro.NúmeroDeNoDeseadosQueCoincidieron - if conjunto != otroConjunto: - return conjunto < otroConjunto - éxito = conjunto == 0 - otroÉxito = otroConjunto == 0 - if éxito != otroÉxito: - return éxito - if not éxito: - return self.Longitud <= otro.Longitud if \ - Aptitud.UseRegexLongitud else False - return self.Longitud < otro.Longitud - - def __str__(self): - return "coincide con: {} deseadas, y {} no deseadas, lon {}".format( - "todas" if self._totalDeseado == - self.NúmeroDeDeseadosQueCoincidieron else - self.NúmeroDeDeseadosQueCoincidieron, - self.NúmeroDeNoDeseadosQueCoincidieron, - self.Longitud) - - -if __name__ == '__main__': - unittest.main() diff --git a/es/ch18/genetic.py b/es/ch18/genetic.py deleted file mode 100644 index 4d7506b..0000000 --- a/es/ch18/genetic.py +++ /dev/null @@ -1,272 +0,0 @@ -# File: genetic.py -# Del capítulo 18 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import random -import statistics -import sys -import time -from bisect import bisect_left -from enum import Enum -from enum import IntEnum -from math import exp - - -def _generar_padre(longitud, geneSet, obtener_aptitud): - genes = [] - while len(genes) < longitud: - tamañoMuestral = min(longitud - len(genes), len(geneSet)) - genes.extend(random.sample(geneSet, tamañoMuestral)) - aptitud = obtener_aptitud(genes) - return Cromosoma(genes, aptitud, Estrategias.Creación) - - -def _mutar(padre, geneSet, obtener_aptitud): - genesDelNiño = padre.Genes[:] - índice = random.randrange(0, len(padre.Genes)) - nuevoGen, alterno = random.sample(geneSet, 2) - genesDelNiño[índice] = alterno if nuevoGen == genesDelNiño[ - índice] else nuevoGen - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) - - -def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): - genesDelNiño = padre.Genes[:] - mutación_personalizada(genesDelNiño) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) - - -def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, - mutar, generar_padre): - índiceDeDonante = random.randrange(0, len(padres)) - if índiceDeDonante == índice: - índiceDeDonante = (índiceDeDonante + 1) % len(padres) - genesDelNiño = intercambiar(genesDePadre, padres[índiceDeDonante].Genes) - if genesDelNiño is None: - # padre y donante son indistinguibles - padres[índiceDeDonante] = generar_padre() - return mutar(padres[índice]) - aptitud = obtener_aptitud(genesDelNiño) - return Cromosoma(genesDelNiño, aptitud, Estrategias.Intercambio) - - -def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, - mostrar, mutación_personalizada=None, - creación_personalizada=None, edadMáxima=None, - tamañoDePiscina=1, intercambiar=None, segundosMáximos=None): - if mutación_personalizada is None: - def fnMutar(padre): - return _mutar(padre, geneSet, obtener_aptitud) - else: - def fnMutar(padre): - return _mutar_personalizada(padre, mutación_personalizada, - obtener_aptitud) - - if creación_personalizada is None: - def fnGenerarPadre(): - return _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - else: - def fnGenerarPadre(): - genes = creación_personalizada() - return Cromosoma(genes, obtener_aptitud(genes), - Estrategias.Creación) - - búsquedaDeEstrategia = { - Estrategias.Creación: lambda p, i, o: fnGenerarPadre(), - Estrategias.Mutación: lambda p, i, o: fnMutar(p), - Estrategias.Intercambio: lambda p, i, o: - _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMutar, - fnGenerarPadre) - } - - estrategiasUsadas = [búsquedaDeEstrategia[Estrategias.Mutación]] - if intercambiar is not None: - estrategiasUsadas.append(búsquedaDeEstrategia[Estrategias.Intercambio]) - - def fnNuevoNiño(padre, índice, padres): - return random.choice(estrategiasUsadas)(padre, índice, padres) - else: - def fnNuevoNiño(padre, índice, padres): - return fnMutar(padre) - - for caducado, mejora in _obtener_mejoras( - fnNuevoNiño, fnGenerarPadre, edadMáxima, tamañoDePiscina, - segundosMáximos): - if caducado: - return mejora - mostrar(mejora) - f = búsquedaDeEstrategia[mejora.Estrategia] - estrategiasUsadas.append(f) - if not aptitudÓptima > mejora.Aptitud: - return mejora - - -def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina, - segundosMáximos): - horaInicio = time.time() - mejorPadre = generar_padre() - yield segundosMáximos is not None and time.time() - \ - horaInicio > segundosMáximos, mejorPadre - padres = [mejorPadre] - aptitudesHistóricas = [mejorPadre.Aptitud] - for _ in range(tamañoDePiscina - 1): - padre = generar_padre() - if segundosMáximos is not None and time.time() - horaInicio > \ - segundosMáximos: - yield True, padre - if padre.Aptitud > mejorPadre.Aptitud: - yield False, padre - mejorPadre = padre - aptitudesHistóricas.append(padre.Aptitud) - padres.append(padre) - índiceDelÚltimoPadre = tamañoDePiscina - 1 - pÍndice = 1 - while True: - if segundosMáximos is not None and time.time() - horaInicio > \ - segundosMáximos: - yield True, mejorPadre - pÍndice = pÍndice - 1 if pÍndice > 0 else índiceDelÚltimoPadre - padre = padres[pÍndice] - niño = nuevo_niño(padre, pÍndice, padres) - if padre.Aptitud > niño.Aptitud: - if edadMáxima is None: - continue - padre.Edad += 1 - if edadMáxima > padre.Edad: - continue - índice = bisect_left(aptitudesHistóricas, niño.Aptitud, 0, - len(aptitudesHistóricas)) - proporciónSimilar = índice / len(aptitudesHistóricas) - if random.random() < exp(-proporciónSimilar): - padres[pÍndice] = niño - continue - mejorPadre.Edad = 0 - padres[pÍndice] = mejorPadre - continue - if not niño.Aptitud > padre.Aptitud: - # mismo aptitud - niño.Edad = padre.Edad + 1 - padres[pÍndice] = niño - continue - niño.Edad = 0 - padres[pÍndice] = niño - if niño.Aptitud > mejorPadre.Aptitud: - mejorPadre = niño - yield False, mejorPadre - aptitudesHistóricas.append(mejorPadre.Aptitud) - - -def ascenso_de_la_colina(funciónDeOptimización, es_mejora, es_óptimo, - obtener_valor_de_característica_siguiente, mostrar, - valorInicialDeCaracterística): - mejor = funciónDeOptimización(valorInicialDeCaracterística) - stdout = sys.stdout - sys.stdout = None - while not es_óptimo(mejor): - valorDeCaracterística = obtener_valor_de_característica_siguiente( - mejor) - niño = funciónDeOptimización(valorDeCaracterística) - if es_mejora(mejor, niño): - mejor = niño - sys.stdout = stdout - mostrar(mejor, valorDeCaracterística) - sys.stdout = None - sys.stdout = stdout - return mejor - - -def torneo(generar_padre, intercambiar, competir, mostrar, clave_de_orden, - númeroDePadres=10, generaciones_máximas=100): - piscina = [[generar_padre(), [0, 0, 0]] for _ in - range(1 + númeroDePadres * númeroDePadres)] - mejor, mejorPuntuación = piscina[0] - - def obtenerClaveDeOrden(x): - return clave_de_orden(x[0], x[1][ResultadoDeCompetición.Ganado], - x[1][ResultadoDeCompetición.Empatado], - x[1][ResultadoDeCompetición.Perdido]) - - generación = 0 - while generación < generaciones_máximas: - generación += 1 - for i in range(0, len(piscina)): - for j in range(0, len(piscina)): - if i == j: - continue - jugadorA, puntuaciónA = piscina[i] - jugadorB, puntuaciónB = piscina[j] - resultado = competir(jugadorA, jugadorB) - puntuaciónA[resultado] += 1 - puntuaciónB[2 - resultado] += 1 - - piscina.sort(key=obtenerClaveDeOrden, reverse=True) - if obtenerClaveDeOrden(piscina[0]) > obtenerClaveDeOrden( - [mejor, mejorPuntuación]): - mejor, mejorPuntuación = piscina[0] - mostrar(mejor, mejorPuntuación[ResultadoDeCompetición.Ganado], - mejorPuntuación[ResultadoDeCompetición.Empatado], - mejorPuntuación[ResultadoDeCompetición.Perdido], - generación) - - padres = [piscina[i][0] for i in range(númeroDePadres)] - piscina = [[intercambiar(padres[i], padres[j]), [0, 0, 0]] - for i in range(len(padres)) - for j in range(len(padres)) - if i != j] - piscina.extend([padre, [0, 0, 0]] for padre in padres) - piscina.append([generar_padre(), [0, 0, 0]]) - return mejor - - -class ResultadoDeCompetición(IntEnum): - Perdido = 0, - Empatado = 1, - Ganado = 2, - - -class Cromosoma: - def __init__(self, genes, aptitud, estrategia): - self.Genes = genes - self.Aptitud = aptitud - self.Estrategia = estrategia - self.Edad = 0 - - -class Estrategias(Enum): - Creación = 0, - Mutación = 1, - Intercambio = 2 - - -class Comparar: - @staticmethod - def ejecutar(función): - cronometrajes = [] - stdout = sys.stdout - for i in range(100): - sys.stdout = None - horaInicio = time.time() - función() - segundos = time.time() - horaInicio - sys.stdout = stdout - cronometrajes.append(segundos) - promedio = statistics.mean(cronometrajes) - if i < 10 or i % 10 == 9: - print("{} {:3.2f} {:3.2f}".format( - 1 + i, promedio, - statistics.stdev(cronometrajes, promedio) if i > 1 else 0)) diff --git a/es/ch18/ticTacToe.py b/es/ch18/ticTacToe.py deleted file mode 100644 index eb8ea4a..0000000 --- a/es/ch18/ticTacToe.py +++ /dev/null @@ -1,738 +0,0 @@ -# File: ticTacToe.py -# Del capítulo 18 de _Algoritmos Genéticos con Python_ -# -# Author: Clinton Sheppard -# Copyright (c) 2017 Clinton Sheppard -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. - -import datetime -import random -import unittest -from functools import partial - -import genetic - - -def obtener_aptitud(genes): - copiaLocal = genes[:] - aptitud = obtener_aptitud_para_juegos(copiaLocal) - aptitud.ConteoDeGenes = len(genes) - return aptitud - - -índicesDeCuadrados = [1, 2, 3, 4, 5, 6, 7, 8, 9] - - -def jugar1en1(xGenes, oGenes): - tablero = dict((i, Cuadrado(i, TipoDeContenido.Vacío)) for i in range(1, 9 + 1)) - vacíos = [v for v in tablero.values() if v.Contenido == TipoDeContenido.Vacío] - datosDeRonda = [[xGenes, TipoDeContenido.Mia, genetic.ResultadoDeCompetición.Perdido, - genetic.ResultadoDeCompetición.Ganado], - [oGenes, TipoDeContenido.Oponente, genetic.ResultadoDeCompetición.Ganado, - genetic.ResultadoDeCompetición.Perdido]] - índiceDelJugador = 0 - - while len(vacíos) > 0: - datosDelJugador = datosDeRonda[índiceDelJugador] - índiceDelJugador = 1 - índiceDelJugador - genes, pieza, perdió, ganó = datosDelJugador - - índiceDeReglaYMovimiento = obtener_mover(genes, tablero, vacíos) - if índiceDeReglaYMovimiento is None: # no pudo encontrar un movimiento - return perdió - - índice = índiceDeReglaYMovimiento[0] - tablero[índice] = Cuadrado(índice, pieza) - - sóloElMovimientoMásReciente = [tablero[índice]] - if len(FiltroDeContenidoDeFila(pieza, 3).obtener_coincidencias(tablero, sóloElMovimientoMásReciente)) > 0 or \ - len(FiltroDeContenidoDeColumna(pieza, 3).obtener_coincidencias(tablero, sóloElMovimientoMásReciente)) > 0 or \ - len(DiagonalContenidoFilter(pieza, 3).obtener_coincidencias(tablero, sóloElMovimientoMásReciente)) > 0: - return ganó - vacíos = [v for v in tablero.values() if v.Contenido == TipoDeContenido.Vacío] - return genetic.ResultadoDeCompetición.Empatado - - -def obtener_aptitud_para_juegos(genes): - def obtenerCadenaDelTablero(b): - return ''.join(map(lambda i: - '.' if b[i].Contenido == TipoDeContenido.Vacío - else 'x' if b[i].Contenido == TipoDeContenido.Mia - else 'o', índicesDeCuadrados)) - - tablero = dict((i, Cuadrado(i, TipoDeContenido.Vacío)) for i in range(1, 9 + 1)) - - cola = [tablero] - for cuadrado in tablero.values(): - copiaDelCandidato = tablero.copy() - copiaDelCandidato[cuadrado.Índice] = Cuadrado(cuadrado.Índice, TipoDeContenido.Oponente) - cola.append(copiaDelCandidato) - - reglasGanadoras = {} - ganados = empates = perdidos = 0 - - while len(cola) > 0: - tablero = cola.pop() - cadenaDelTablero = obtenerCadenaDelTablero(tablero) - vacíos = [v for v in tablero.values() if v.Contenido == TipoDeContenido.Vacío] - - if len(vacíos) == 0: - empates += 1 - continue - - candidatoÍndiceAndReglaÍndice = obtener_mover(genes, tablero, vacíos) - - if candidatoÍndiceAndReglaÍndice is None: # no pudo encontrar un movimiento - # hay vacíos pero no encontró un movimiento - perdidos += 1 - # ir al siguiente tablero - continue - - # encontró al menos un movimiento - índice = candidatoÍndiceAndReglaÍndice[0] - tablero[índice] = Cuadrado(índice, TipoDeContenido.Mia) - # newTableroString = obtenerCadenaDelTablero(tablero) - - # Si ahora tenemos tres de mis piezas en cualquier fila, columna o diagonal, ganamos - sóloElMovimientoMásReciente = [tablero[índice]] - if len(tengoTresEnUnaFila.obtener_coincidencias(tablero, sóloElMovimientoMásReciente)) > 0 or \ - len(tengoTresEnUnaColumna.obtener_coincidencias(tablero, sóloElMovimientoMásReciente)) > 0 or \ - len(tengoTresEnDiagonal.obtener_coincidencias(tablero, sóloElMovimientoMásReciente)) > 0: - reglaId = candidatoÍndiceAndReglaÍndice[1] - if reglaId not in reglasGanadoras: - reglasGanadoras[reglaId] = list() - reglasGanadoras[reglaId].append(cadenaDelTablero) - ganados += 1 - # ir al siguiente tablero - continue - - # perdemos si vacíos tienen dos piezas opositoras en una fila, columna o diagonal - vacíos = [v for v in tablero.values() if v.Contenido == TipoDeContenido.Vacío] - if len(oponenteTieneDosEnUnaFila.obtener_coincidencias(tablero, vacíos)) > 0: - perdidos += 1 - # ir al siguiente tablero - continue - - # poner en cola todas las posibles respuestas de los oponentes - for cuadrado in vacíos: - copiaDelCandidato = tablero.copy() - copiaDelCandidato[cuadrado.Índice] = Cuadrado(cuadrado.Índice, - TipoDeContenido.Oponente) - cola.append(copiaDelCandidato) - - return Aptitud(ganados, empates, perdidos, len(genes)) - - -def obtener_mover(reglaSet, tablero, vacíos, índiceDePrimeraRegla=0): - copiaDeReglas = reglaSet[:] - - for reglaÍndice in range(índiceDePrimeraRegla, len(copiaDeReglas)): - gene = copiaDeReglas[reglaÍndice] - coincidencias = gene.obtener_coincidencias(tablero, vacíos) - if len(coincidencias) == 0: - continue - if len(coincidencias) == 1: - return [list(coincidencias)[0], reglaÍndice] - if len(vacíos) > len(coincidencias): - vacíos = [e for e in vacíos if e.Índice in coincidencias] - - return None - - -def mostrar(candidato, horaInicio): - diferencia = (datetime.datetime.now() - horaInicio).total_seconds() - copiaLocal = candidato.Genes[:] - for i in reversed(range(len(copiaLocal))): - copiaLocal[i] = str(copiaLocal[i]) - - print("\t{}\n{}\n{}".format( - '\n\t'.join([d for d in copiaLocal]), - candidato.Aptitud, - diferencia)) - - -def mutar_añadir(genes, geneSet): - índice = random.randrange(0, len(genes) + 1) if len(genes) > 0 else 0 - genes[índice:índice] = [random.choice(geneSet)] - return True - - -def mutar_remover(genes): - if len(genes) < 1: - return False - del genes[random.randrange(0, len(genes))] - if len(genes) > 1 and random.randint(0, 1) == 1: - del genes[random.randrange(0, len(genes))] - return True - - -def mutar_reemplazar(genes, geneSet): - if len(genes) < 1: - return False - índice = random.randrange(0, len(genes)) - genes[índice] = random.choice(geneSet) - return True - - -def mutar_intercambiar_adyacente(genes): - if len(genes) < 2: - return False - índice = random.choice(range(len(genes) - 1)) - genes[índice], genes[índice + 1] = genes[índice + 1], genes[índice] - return True - - -def mutar_mover(genes): - if len(genes) < 3: - return False - principio = random.choice(range(len(genes))) - fin = principio + random.randint(1, 2) - aMover = genes[principio:fin] - genes[principio:fin] = [] - índice = random.choice(range(len(genes))) - if índice >= principio: - índice += 1 - genes[índice:índice] = aMover - return True - - -def mutar(genes, fnObtenerAptitud, operadoresDeMutación, recuentoDeMutaciones): - aptitudInicial = fnObtenerAptitud(genes) - cuenta = random.choice(recuentoDeMutaciones) - for i in range(1, cuenta + 2): - duplo = operadoresDeMutación[:] - func = random.choice(duplo) - while not func(genes): - duplo.remove(func) - func = random.choice(duplo) - if fnObtenerAptitud(genes) > aptitudInicial: - recuentoDeMutaciones.append(i) - return - - -def crear_geneSet(): - opciones = [[TipoDeContenido.Oponente, [0, 1, 2]], - [TipoDeContenido.Mia, [0, 1, 2]]] - geneSet = [ - ReglaMetadatos(FiltroDeContenidoDeFila, opciones), - ReglaMetadatos(lambda contenidoEsperado, cuenta: FiltroDeFilaSuperior(), opciones), - ReglaMetadatos(lambda contenidoEsperado, cuenta: FiltroDeFilaDelMedio(), - opciones), - ReglaMetadatos(lambda contenidoEsperado, cuenta: FiltroDeFilaInferior(), - opciones), - ReglaMetadatos(FiltroDeContenidoDeColumna, opciones), - ReglaMetadatos(lambda contenidoEsperado, cuenta: FiltroDeColumnaIzquierda(), - opciones), - ReglaMetadatos(lambda contenidoEsperado, cuenta: FiltroDeColumnaMedia(), - opciones), - ReglaMetadatos(lambda contenidoEsperado, cuenta: FiltroDeColumnaDerecha(), - opciones), - ReglaMetadatos(DiagonalContenidoFilter, opciones), - ReglaMetadatos(lambda contenidoEsperado, cuenta: FiltroDeUbicaciónDiagonal(), - opciones), - ReglaMetadatos(lambda contenidoEsperado, cuenta: FiltroDeEsquina()), - ReglaMetadatos(lambda contenidoEsperado, cuenta: FiltroDeLado()), - ReglaMetadatos(lambda contenidoEsperado, cuenta: FiltroCentral()), - ReglaMetadatos(lambda contenidoEsperado, cuenta: - FiltroDeOpuestosDeFila(contenidoEsperado), opciones, - necesitaContenidoEspecífico=True), - ReglaMetadatos(lambda contenidoEsperado, cuenta: FiltroDeOpuestosDeColumna( - contenidoEsperado), opciones, necesitaContenidoEspecífico=True), - ReglaMetadatos(lambda contenidoEsperado, cuenta: FiltroDeOpuestosDeDiagonal( - contenidoEsperado), opciones, necesitaContenidoEspecífico=True), - ] - - genes = list() - for gene in geneSet: - genes.extend(gene.crear_reglas()) - - print("creado " + str(len(genes)) + " genes") - return genes - - -class TicTacToeTests(unittest.TestCase): - def test_conocimiento_perfecto(self): - mínGenes = 10 - máxGenes = 20 - geneSet = crear_geneSet() - horaInicio = datetime.datetime.now() - - def fnMostrar(candidato): - mostrar(candidato, horaInicio) - - def fnObtenerAptitud(genes): - return obtener_aptitud(genes) - - recuentoDeMutaciones = [1] - - operadoresDeMutación = [ - partial(mutar_añadir, geneSet=geneSet), - partial(mutar_reemplazar, geneSet=geneSet), - mutar_remover, - mutar_intercambiar_adyacente, - mutar_mover, - ] - - def fnMutar(genes): - mutar(genes, fnObtenerAptitud, operadoresDeMutación, recuentoDeMutaciones) - - def fnIntercambio(padre, donante): - niño = padre[0:int(len(padre) / 2)] + \ - donante[int(len(donante) / 2):] - fnMutar(niño) - return niño - - def fnCrear(): - return random.sample(geneSet, random.randrange(mínGenes, máxGenes)) - - aptitudÓptima = Aptitud(620, 120, 0, 11) - mejor = genetic.obtener_mejor(fnObtenerAptitud, mínGenes, aptitudÓptima, None, - fnMostrar, fnMutar, fnCrear, edadMáxima=500, - tamañoDePiscina=20, intercambiar=fnIntercambio) - self.assertTrue(not aptitudÓptima > mejor.Aptitud) - - def test_tornament(self): - mínGenes = 10 - máxGenes = 20 - geneSet = crear_geneSet() - horaInicio = datetime.datetime.now() - - def fnMostrar(genes, ganados, empates, perdidos, generación): - print("-- generación {} --".format(generación)) - mostrar(genetic.Cromosoma(genes, - Aptitud(ganados, empates, perdidos, len(genes)), - None), horaInicio) - - recuentoDeMutaciones = [1] - - operadoresDeMutación = [ - partial(mutar_añadir, geneSet=geneSet), - partial(mutar_reemplazar, geneSet=geneSet), - mutar_remover, - mutar_intercambiar_adyacente, - mutar_mover, - ] - - def fnMutar(genes): - mutar(genes, lambda x: 0, operadoresDeMutación, recuentoDeMutaciones) - - def fnIntercambio(padre, donante): - niño = padre[0:int(len(padre) / 2)] + \ - donante[int(len(donante) / 2):] - fnMutar(niño) - return niño - - def fnCrear(): - return random.sample(geneSet, random.randrange(mínGenes, máxGenes)) - - def fnClaveDeOrden(genes, ganados, empates, perdidos): - return -1000 * perdidos - empates + 1 / len(genes) - - genetic.torneo(fnCrear, fnIntercambio, jugar1en1, fnMostrar, - fnClaveDeOrden, 13) - - -class TipoDeContenido: - Vacío = 'VACÍO' - Mia = 'MIA' - Oponente = 'OPONENTE' - - -class Cuadrado: - def __init__(self, índice, contenido=TipoDeContenido.Vacío): - self.Contenido = contenido - self.Índice = índice - self.Diagonales = [] - # diseño del tablero es - # 1 2 3 - # 4 5 6 - # 7 8 9 - self.EsCentro = False - self.EsEsquina = False - self.EsLado = False - self.EsFilaSuperior = False - self.EsFilaDelMedio = False - self.EsFilaInferior = False - self.EsColumnaIzquierda = False - self.EsColumnaEnMedio = False - self.EsColumnaDerecha = False - self.Fila = None - self.Columna = None - self.OpuestoDeDiagonal = None - self.OpuestoDeFila = None - self.OpuestoDeColumna = None - - if índice == 1 or índice == 2 or índice == 3: - self.EsFilaSuperior = True - self.Fila = [1, 2, 3] - elif índice == 4 or índice == 5 or índice == 6: - self.EsFilaDelMedio = True - self.Fila = [4, 5, 6] - elif índice == 7 or índice == 8 or índice == 9: - self.EsFilaInferior = True - self.Fila = [7, 8, 9] - - if índice % 3 == 1: - self.Columna = [1, 4, 7] - self.EsColumnaIzquierda = True - elif índice % 3 == 2: - self.Columna = [2, 5, 8] - self.EsColumnaEnMedio = True - elif índice % 3 == 0: - self.Columna = [3, 6, 9] - self.EsColumnaDerecha = True - - if índice == 5: - self.EsCentro = True - else: - if índice == 1 or índice == 3 or índice == 7 or índice == 9: - self.EsEsquina = True - elif índice == 2 or índice == 4 or índice == 6 or índice == 8: - self.EsLado = True - - if índice == 1: - self.OpuestoDeFila = 3 - self.OpuestoDeColumna = 7 - self.OpuestoDeDiagonal = 9 - elif índice == 2: - self.OpuestoDeColumna = 8 - elif índice == 3: - self.OpuestoDeFila = 1 - self.OpuestoDeColumna = 9 - self.OpuestoDeDiagonal = 7 - elif índice == 4: - self.OpuestoDeFila = 6 - elif índice == 6: - self.OpuestoDeFila = 4 - elif índice == 7: - self.OpuestoDeFila = 9 - self.OpuestoDeColumna = 1 - self.OpuestoDeDiagonal = 3 - elif índice == 8: - self.OpuestoDeColumna = 2 - else: # índice == 9 - self.OpuestoDeFila = 7 - self.OpuestoDeColumna = 3 - self.OpuestoDeDiagonal = 1 - - if índice == 1 or self.OpuestoDeDiagonal == 1 or self.EsCentro: - self.Diagonales.append([1, 5, 9]) - if índice == 3 or self.OpuestoDeDiagonal == 3 or self.EsCentro: - self.Diagonales.append([7, 5, 3]) - - -class Regla: - def __init__(self, prefijoDeDescripción, contenidoEsperado=None, cuenta=None): - self.PrefijoDeDescripción = prefijoDeDescripción - self.ContenidoEsperado = contenidoEsperado - self.Cuenta = cuenta - - def __str__(self): - resultado = self.PrefijoDeDescripción + " " - if self.Cuenta is not None: - resultado += str(self.Cuenta) + " " - if self.ContenidoEsperado is not None: - resultado += self.ContenidoEsperado + " " - return resultado - - -class ReglaMetadatos: - def __init__(self, crear, opciones=None, necesitaContenidoEspecífico=True, - necesitaCuentaEspecífica=True): - if opciones is None: - necesitaContenidoEspecífico = False - necesitaCuentaEspecífica = False - if necesitaCuentaEspecífica and not necesitaContenidoEspecífico: - raise ValueError('necesitaCuentaEspecífica solo es válida si necesitaContenidoEspecífico es verdadera') - self.crear = crear - self.opciones = opciones - self.necesitaContenidoEspecífico = necesitaContenidoEspecífico - self.necesitaCuentaEspecífica = necesitaCuentaEspecífica - - def crear_reglas(self): - opción = None - cuenta = None - - visto = set() - if self.necesitaContenidoEspecífico: - reglas = list() - - for opciónInfo in self.opciones: - opción = opciónInfo[0] - if self.necesitaCuentaEspecífica: - cuentaDeOpciones = opciónInfo[1] - - for cuenta in cuentaDeOpciones: - gene = self.crear(opción, cuenta) - if str(gene) not in visto: - visto.add(str(gene)) - reglas.append(gene) - else: - gene = self.crear(opción, None) - if str(gene) not in visto: - visto.add(str(gene)) - reglas.append(gene) - return reglas - else: - return [self.crear(opción, cuenta)] - - -class ContenidoFilter(Regla): - def __init__(self, descripción, contenidoEsperado, cuentaEsperada, - obtenerValorDelCuadrado): - super().__init__(descripción, contenidoEsperado, cuentaEsperada) - self.obtenerValorDelCuadrado = obtenerValorDelCuadrado - - def obtener_coincidencias(self, tablero, cuadrados): - resultado = set() - for cuadrado in cuadrados: - m = list(map(lambda i: tablero[i].Contenido, - self.obtenerValorDelCuadrado(cuadrado))) - if m.count(self.ContenidoEsperado) == self.Cuenta: - resultado.add(cuadrado.Índice) - return resultado - - -class FiltroDeContenidoDeFila(ContenidoFilter): - def __init__(self, contenidoEsperado, cuentaEsperada): - super().__init__("su FILA tiene", contenidoEsperado, cuentaEsperada, - lambda s: s.Fila) - - -class FiltroDeContenidoDeColumna(ContenidoFilter): - def __init__(self, contenidoEsperado, cuentaEsperada): - super().__init__("su COLUMNA tiene", contenidoEsperado, cuentaEsperada, - lambda s: s.Columna) - - -class FiltroDeUbicación(Regla): - def __init__(self, ubicaciónEsperada, descripciónDelContenedor, func): - super().__init__( - "es en " + descripciónDelContenedor + (" " if len(descripciónDelContenedor) > 0 else "") + ubicaciónEsperada) - self.func = func - - def obtener_coincidencias(self, tablero, cuadrados): - resultado = set() - for cuadrado in cuadrados: - if self.func(cuadrado): - resultado.add(cuadrado.Índice) - return resultado - - -class RowFiltroDeUbicación(FiltroDeUbicación): - def __init__(self, ubicaciónEsperada, func): - super().__init__(ubicaciónEsperada, "FILA", func) - - -class ColumnFiltroDeUbicación(FiltroDeUbicación): - def __init__(self, ubicaciónEsperada, func): - super().__init__(ubicaciónEsperada, "COLUMNA", func) - - -class FiltroDeFilaSuperior(RowFiltroDeUbicación): - def __init__(self): - super().__init__("SUPERIOR", lambda cuadrado: cuadrado.EsFilaSuperior) - - -class FiltroDeFilaDelMedio(RowFiltroDeUbicación): - def __init__(self): - super().__init__("MEDIO", lambda cuadrado: cuadrado.EsFilaDelMedio) - - -class FiltroDeFilaInferior(RowFiltroDeUbicación): - def __init__(self): - super().__init__("INFERIOR", lambda cuadrado: cuadrado.EsFilaInferior) - - -class FiltroDeColumnaIzquierda(ColumnFiltroDeUbicación): - def __init__(self): - super().__init__("IZQUIERDA", lambda cuadrado: cuadrado.EsColumnaIzquierda) - - -class FiltroDeColumnaMedia(ColumnFiltroDeUbicación): - def __init__(self): - super().__init__("MEDIO", lambda cuadrado: cuadrado.EsColumnaEnMedio) - - -class FiltroDeColumnaDerecha(ColumnFiltroDeUbicación): - def __init__(self): - super().__init__("DERECHO", lambda cuadrado: cuadrado.EsColumnaDerecha) - - -class FiltroDeUbicaciónDiagonal(FiltroDeUbicación): - def __init__(self): - super().__init__("DIAGONAL", "", - lambda cuadrado: not (cuadrado.EsFilaDelMedio or - cuadrado.EsColumnaEnMedio) or - cuadrado.EsCentro) - - -class DiagonalContenidoFilter(Regla): - def __init__(self, contenidoEsperado, cuenta): - super().__init__("su DIAGONAL tiene", contenidoEsperado, cuenta) - - def obtener_coincidencias(self, tablero, cuadrados): - resultado = set() - for cuadrado in cuadrados: - for diagonal in cuadrado.Diagonales: - m = list(map(lambda i: tablero[i].Contenido, diagonal)) - if m.count(self.ContenidoEsperado) == self.Cuenta: - resultado.add(cuadrado.Índice) - break - return resultado - - -class FiltroDeVictorias(Regla): - def __init__(self, contenido): - super().__init__("GANAR" if contenido == TipoDeContenido - .Mia else "bloquear OPONENTE de GANAR") - self.reglaDeFila = FiltroDeContenidoDeFila(contenido, 2) - self.reglaDeColumna = FiltroDeContenidoDeColumna(contenido, 2) - self.reglaDeDiagonal = DiagonalContenidoFilter(contenido, 2) - - def obtener_coincidencias(self, tablero, cuadrados): - enDiagonal = self.reglaDeDiagonal.obtener_coincidencias(tablero, cuadrados) - if len(enDiagonal) > 0: - return enDiagonal - enFila = self.reglaDeFila.obtener_coincidencias(tablero, cuadrados) - if len(enFila) > 0: - return enFila - enColumna = self.reglaDeColumna.obtener_coincidencias(tablero, cuadrados) - return enColumna - - -class FiltroDeOpuestosDeDiagonal(Regla): - def __init__(self, contenidoEsperado): - super().__init__("OPUESTO en DIAGONAL es", contenidoEsperado) - - def obtener_coincidencias(self, tablero, cuadrados): - resultado = set() - for cuadrado in cuadrados: - if cuadrado.OpuestoDeDiagonal is None: - continue - if tablero[cuadrado.OpuestoDeDiagonal].Contenido == self.ContenidoEsperado: - resultado.add(cuadrado.Índice) - return resultado - - -class FiltroDeOpuestosDeFila(Regla): - def __init__(self, contenidoEsperado): - super().__init__("OPUESTO en FILA es", contenidoEsperado) - - def obtener_coincidencias(self, tablero, cuadrados): - resultado = set() - for cuadrado in cuadrados: - if cuadrado.OpuestoDeFila is None: - continue - if tablero[cuadrado.OpuestoDeFila].Contenido == self.ContenidoEsperado: - resultado.add(cuadrado.Índice) - return resultado - - -class FiltroDeOpuestosDeColumna(Regla): - def __init__(self, contenidoEsperado): - super().__init__("OPUESTO en COLUMNA es", contenidoEsperado) - - def obtener_coincidencias(self, tablero, cuadrados): - resultado = set() - for cuadrado in cuadrados: - if cuadrado.OpuestoDeColumna is None: - continue - if tablero[cuadrado.OpuestoDeColumna].Contenido == self.ContenidoEsperado: - resultado.add(cuadrado.Índice) - return resultado - - -class FiltroCentral(Regla): - def __init__(self): - super().__init__("es en CENTRO") - - @staticmethod - def obtener_coincidencias(tablero, cuadrados): - resultado = set() - for cuadrado in cuadrados: - if cuadrado.EsCentro: - resultado.add(cuadrado.Índice) - return resultado - - -class FiltroDeEsquina(Regla): - def __init__(self): - super().__init__("es una ESQUINA") - - @staticmethod - def obtener_coincidencias(tablero, cuadrados): - resultado = set() - for cuadrado in cuadrados: - if cuadrado.EsEsquina: - resultado.add(cuadrado.Índice) - return resultado - - -class FiltroDeLado(Regla): - def __init__(self): - super().__init__("es LADO") - - @staticmethod - def obtener_coincidencias(tablero, cuadrados): - resultado = set() - for cuadrado in cuadrados: - if cuadrado.EsLado: - resultado.add(cuadrado.Índice) - return resultado - - -tengoTresEnUnaFila = FiltroDeContenidoDeFila(TipoDeContenido.Mia, 3) -tengoTresEnUnaColumna = FiltroDeContenidoDeColumna(TipoDeContenido.Mia, 3) -tengoTresEnDiagonal = DiagonalContenidoFilter(TipoDeContenido.Mia, 3) -oponenteTieneDosEnUnaFila = FiltroDeVictorias(TipoDeContenido.Oponente) - - -class Aptitud: - def __init__(self, ganados, empates, perdidos, conteoDeGenes): - self.Ganados = ganados - self.Empatados = empates - self.Perdidos = perdidos - conteoDeJuegos = ganados + empates + perdidos - porcentajeGanados = 100 * round(ganados / conteoDeJuegos, 3) - porcentajePerdidos = 100 * round(perdidos / conteoDeJuegos, 3) - porcentajeEmpates = 100 * round(empates / conteoDeJuegos, 3) - self.PorcentajeEmpates = porcentajeEmpates - self.PorcentajeGanados = porcentajeGanados - self.PorcentajePerdidos = porcentajePerdidos - self.ConteoDeGenes = conteoDeGenes - - def __gt__(self, otro): - if self.PorcentajePerdidos != otro.PorcentajePerdidos: - return self.PorcentajePerdidos < otro.PorcentajePerdidos - - if self.Perdidos > 0: - return False - - if self.Empatados != otro.Empatados: - return self.Empatados < otro.Empatados - return self.ConteoDeGenes < otro.ConteoDeGenes - - def __str__(self): - return "{:.1f}% Perdidos ({}), {:.1f}% Empates ({}), {:.1f}% Ganados ({}), {} reglas".format( - self.PorcentajePerdidos, - self.Perdidos, - self.PorcentajeEmpates, - self.Empatados, - self.PorcentajeGanados, - self.Ganados, - self.ConteoDeGenes) - - -if __name__ == '__main__': - unittest.main() diff --git a/scripts/__init__.py b/scripts/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/scripts/ch01/__init__.py b/scripts/ch01/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/scripts/ch01/guess_password.py b/scripts/ch01/guess_password.py new file mode 100644 index 0000000..c6bd6d1 --- /dev/null +++ b/scripts/ch01/guess_password.py @@ -0,0 +1,183 @@ +from __future__ import annotations + +import logging +import random +import time +from typing import List, Union + +from src.genetic import ( + AbsoluteFitness, + AgeAnnealing, + Chromosome, + ChromosomeGenerator, + FitnessStagnationDetector, + GeneSet, + Mutation, + Runner, + StoppingCriteria, +) + + +class GuessPasswordChromosome(Chromosome): + """Chromosome for the GuessPassword problem is a string of characters.""" + + def __init__(self, genes: str, age: int = 0) -> None: + self.genes = genes + self.age = age + + def __str__(self) -> str: + """Return a visualisation of the chromosome.""" + return str(self.genes) + + def __repr__(self) -> str: + return f"{self.genes}" + + def __eq__(self, other: GuessPasswordChromosome) -> bool: + return self.genes == other.genes + + +class GuessPasswordFitness(AbsoluteFitness): + """Fitness function for the GuessPassword problem.""" + + def __init__(self, target: str) -> None: + self.target = target + + def __call__(self, chromosome: GuessPasswordChromosome) -> float: + """Return a fitness score for the guess. The higher the score, the better the + guess. The score is the sum of the number of characters in the guess that + match the corresponding character in the target. + + Parameters + ---------- + chromosome : GuessPasswordChromosome + The guess to score + + Returns + ------- + float + The fitness score + """ + + return sum( + 1 + for expected, actual in zip(self.target, chromosome.genes) + if expected == actual + ) + + +class GuessPasswordMutation(Mutation): + def __init__(self, fitness: GuessPasswordFitness, gene_set: GeneSet): + self.fitness = fitness + self.gene_set = gene_set + + def __call__(self, parent): + index = random.randrange(0, len(parent.genes)) + child_genes = list(parent.genes) + new_gene, alternate = random.sample(self.gene_set, 2) + child_genes[index] = alternate if new_gene == child_genes[index] else new_gene + genes = "".join(child_genes) + return GuessPasswordChromosome(genes) + + +class GuessPasswordStoppingCriteria(StoppingCriteria): + def __init__(self, target, fitness): + self.target = target + self.fitness = fitness + + @property + def optimal_fitness(self) -> float: + return len(self.target) + + def __call__(self, chromosome: GuessPasswordChromosome) -> bool: + """Return true if can stop the genetic algorithm.""" + + return self.fitness(chromosome) >= len(self.target) + + +class GuessPasswordChromosomeGenerator(ChromosomeGenerator): + def __init__(self, gene_set, length) -> None: + self.gene_set = gene_set + self.length = length + + def __call__(self) -> GuessPasswordChromosome: + genes = [] + while len(genes) < self.length: + sampleSize = min(self.length - len(genes), len(self.gene_set)) + genes.extend(random.sample(self.gene_set, sampleSize)) + genes = "".join(genes) + return GuessPasswordChromosome(genes) + + +class GuessPasswordRunner(Runner): + def __init__( + self, + chromosome_generator: ChromosomeGenerator, + fitness: GuessPasswordFitness, + stopping_criteria: StoppingCriteria, + mutate: Mutation, + age_annealing: AgeAnnealing, + fitness_stagnation_detector: FitnessStagnationDetector, + ): + super().__init__( + chromosome_generator=chromosome_generator, + fitness=fitness, + stopping_criteria=stopping_criteria, + mutate=mutate, + age_annealing=age_annealing, + fitness_stagnation_detector=fitness_stagnation_detector, + ) + + def display(self, candidate): + time_diff = time.time() - self.start_time + logging.debug("genes=%s", candidate.genes) + logging.debug("fitness=%s", self.fitness(candidate)) + logging.debug("time=%.5f", time_diff) + + +def guess_password( + target, + gene_set, + fitness_stagnation_limit: Union[float, int] = float("inf"), + age_limit: float = float("inf"), +) -> GuessPasswordChromosome: + + fitness = GuessPasswordFitness(target) + chromosome_generator = GuessPasswordChromosomeGenerator(gene_set, len(target)) + stopping_criteria = GuessPasswordStoppingCriteria(target, fitness) + mutate = GuessPasswordMutation(fitness, gene_set) + age_annealing = AgeAnnealing(age_limit=age_limit) + + fitness_stagnation_detector = FitnessStagnationDetector( + fitness, fitness_stagnation_limit + ) + + runner = GuessPasswordRunner( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + fitness_stagnation_detector, + ) + + best = runner.run() + return best + + +def main(): + + random.seed(0) + + logging_format = ( + "[%(levelname)8s :%(filename)25s:%(lineno)4s - %(funcName)30s] %(message)s" + ) + logging.basicConfig(format=logging_format, level=logging.INFO) + + target = "Hello World!" + gene_set = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!." + + guess_password(target, gene_set) + + +if __name__ == "__main__": + main() diff --git a/scripts/ch01/old_guess_password.py b/scripts/ch01/old_guess_password.py new file mode 100644 index 0000000..cecc34f --- /dev/null +++ b/scripts/ch01/old_guess_password.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +import random +import time +from typing import List + +from src.genetic import ( + AbsoluteFitness, + ChromosomeGenerator, + GeneSet, + Mutation, + Runner, + StoppingCriteria, +) + + +class Chromosome: + """Chromosome for the OneMax problem is a string of 1s and 0s.""" + + def __init__(self, genes: List[str]): + self.genes = genes + + def __repr__(self) -> str: + return f"Chromosome({self.genes})" + + def __eq__(self, other: Chromosome) -> bool: + return self.genes == other.genes + + +class GuessPasswordFitness(AbsoluteFitness): + def __init__(self, target: str) -> None: + self.target = target + + def __call__(self, chromosome: Chromosome) -> float: + """Return a fitness score for the guess. The higher the score, the better the + guess. The score is the sum of the number of characters in the guess that + match the corresponding character in the target. + + Parameters + ---------- + chromosome : Chromosome + The guess to score + + Returns + ------- + float + The fitness score + """ + + return sum( + 1 + for expected, actual in zip(self.target, chromosome.genes) + if expected == actual + ) + + +class GuessPasswordMutation(Mutation): + def __init__(self, fitness: GuessPasswordFitness, gene_set: GeneSet): + super().__init__(fitness, gene_set) + + def __call__(self, parent): + index = random.randrange(0, len(parent.genes)) + child_genes = list(parent.genes) + new_gene, alternate = random.sample(self.gene_set, 2) + child_genes[index] = alternate if new_gene == child_genes[index] else new_gene + genes = "".join(child_genes) + return Chromosome(genes) + + +class GuessPasswordStoppingCriteria(StoppingCriteria): + def __init__(self, target, fitness): + self.target = target + self.fitness = fitness + + @property + def optimal_fitness(self) -> float: + return len(self.target) + + def __call__(self, chromosome: Chromosome) -> bool: + """Return true if can stop the genetic algorithm.""" + + return self.fitness(chromosome) >= len(self.target) + + +class GuessPasswordChromosomeGenerator(ChromosomeGenerator): + def __init__(self, gene_set, length) -> None: + self.gene_set = gene_set + self.length = length + + def __call__(self) -> Chromosome: + genes = [] + while len(genes) < self.length: + sampleSize = min(self.length - len(genes), len(self.gene_set)) + genes.extend(random.sample(self.gene_set, sampleSize)) + genes = "".join(genes) + return Chromosome(genes) + + +class GuessPasswordRunner(Runner): + def __init__( + self, + chromosome_generator: ChromosomeGenerator, + fitness: GuessPasswordFitness, + stopping_criteria: StoppingCriteria, + mutate: Mutation, + ): + self.chromosome_generator = chromosome_generator + self.fitness = fitness + self.stopping_criteria = stopping_criteria + self.mutate = mutate + + def display(self, candidate): + timeDiff = time.time() - self.start_time + print("{}\t{}\t{}".format(candidate.genes, self.fitness(candidate), timeDiff)) + + +def guess_password(target, gene_set) -> Chromosome: + + fitness = GuessPasswordFitness(target) + chromosome_generator = GuessPasswordChromosomeGenerator(gene_set, len(target)) + stopping_criteria = GuessPasswordStoppingCriteria(target, fitness) + mutate = GuessPasswordMutation(fitness, gene_set) + + runner = GuessPasswordRunner( + chromosome_generator, fitness, stopping_criteria, mutate + ) + + best = runner.run() + return best + + +def main(): + + target = "Hello World!" + gene_set = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!." + + guess_password(target, gene_set) + + +if __name__ == "__main__": + main() diff --git a/scripts/ch01/tests/__init__.py b/scripts/ch01/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/scripts/ch01/tests/test_guess_password.py b/scripts/ch01/tests/test_guess_password.py new file mode 100644 index 0000000..50a6f0a --- /dev/null +++ b/scripts/ch01/tests/test_guess_password.py @@ -0,0 +1,34 @@ +import logging +import random + +from scripts.ch01.guess_password import guess_password + + +def test_guess_password(): + + logging_format = ( + "[%(levelname)8s :%(filename)20s:%(lineno)4s - %(funcName)10s] %(message)s" + ) + logging.basicConfig(format=logging_format, level=logging.INFO) + + random.seed(3) + target = "Hello World!" + gene_set = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!." + best = guess_password(target, gene_set) + + assert best.genes == target + + +def test_guess_password_with_stagnation_limit(): + + logging_format = ( + "[%(levelname)8s :%(filename)20s:%(lineno)4s - %(funcName)10s] %(message)s" + ) + logging.basicConfig(format=logging_format, level=logging.INFO) + + random.seed(3) + target = "Hello World!" + gene_set = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!." + best = guess_password(target, gene_set, fitness_stagnation_limit=10000) + + assert best.genes == target diff --git a/scripts/ch02/one_max.py b/scripts/ch02/one_max.py new file mode 100644 index 0000000..075c1b0 --- /dev/null +++ b/scripts/ch02/one_max.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +import logging +import random +import time +from typing import Union + +from src.genetic import ( + AbsoluteFitness, + AgeAnnealing, + Chromosome, + ChromosomeGenerator, + FitnessStagnationDetector, + GeneSet, + Mutation, + Runner, + StoppingCriteria, +) + + +class OneMaxChromosome(Chromosome): + """Chromosome for the OneMax problem is a string of 1s and 0s.""" + + def __init__(self, genes: str, age: int = 0): + self.genes = genes + self.age = age + + def __str__(self) -> str: + return f"Chromosome({self.genes}, age={self.age})" + + def __repr__(self) -> str: + return f"Chromosome({self.genes}, age={self.age})" + + def __eq__(self, other: OneMaxChromosome) -> bool: + return self.genes == other.genes + + +class OneMaxFitness(AbsoluteFitness): + def __call__(self, chromosome: OneMaxChromosome) -> float: + logging.debug("Calculating fitness for %s", chromosome) + fitness = chromosome.genes.count("1") + logging.debug("%s has fitness %.1f", chromosome, fitness) + return fitness + + +class OneMaxMutation(Mutation): + def __init__(self, fitness: AbsoluteFitness, gene_set: GeneSet): + self.fitness = fitness + self.gene_set = gene_set + + def __call__(self, parent): + + logging.debug("- " * 30) + logging.debug("Mutating parent: %s", parent) + + index = random.randrange(0, len(parent.genes)) + logging.debug("Index to mutate: %s", index) + + child_genes = list(parent.genes) + new_gene, alternate = random.sample(self.gene_set, 2) + logging.debug("New_gene: %d, alternate: %d", new_gene, alternate) + + child_genes[index] = alternate if new_gene == child_genes[index] else new_gene + genes = "".join([str(X) for X in child_genes]) + chromosome = OneMaxChromosome(genes) + logging.debug("Mutated child created: %s", chromosome) + + logging.debug("Mutation complete") + logging.debug("- " * 30) + + return chromosome + + +class OneMaxStoppingCriteria(StoppingCriteria): + def __init__(self, target: int, fitness: AbsoluteFitness): + self.target = target + self.fitness = fitness + + @property + def optimal_fitness(self) -> float: + return self.target + + def __call__(self, chromosome: OneMaxChromosome) -> bool: + return self.fitness(chromosome) >= self.target + + +class OneMaxChromosomeGenerator(ChromosomeGenerator): + def __init__(self, gene_set, length) -> None: + self.gene_set = gene_set + self.length = length + + def __call__(self) -> OneMaxChromosome: + genes = [] + + while len(genes) < self.length: + sampleSize = min(self.length - len(genes), len(self.gene_set)) + genes.extend(random.sample(self.gene_set, sampleSize)) + genes = "".join([str(X) for X in genes]) + return OneMaxChromosome(genes) + + +class OneMaxRunner(Runner): + """Runner for the OneMax problem.""" + + def __init__( + self, + chromosome_generator: ChromosomeGenerator, + fitness: OneMaxFitness, + stopping_criteria: StoppingCriteria, + mutate: Mutation, + age_annealing: AgeAnnealing, + fitness_stagnation_detector: FitnessStagnationDetector, + ) -> None: + super().__init__( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + fitness_stagnation_detector, + ) + + def display(self, candidate: OneMaxChromosome): + time_diff = time.time() - self.start_time + return f"time = {time_diff}" + + +def one_max( + target, + gene_set, + fitness_stagnation_limit: Union[float, int] = float("inf"), + age_limit: float = float("inf"), +): + + fitness = OneMaxFitness() + chromosome_generator = OneMaxChromosomeGenerator(gene_set, target) + stopping_criteria = OneMaxStoppingCriteria(target, fitness) + mutation = OneMaxMutation(fitness, gene_set) + age_annealing = AgeAnnealing(age_limit=age_limit) + + fitness_stagnation_detector = FitnessStagnationDetector( + fitness, fitness_stagnation_limit + ) + runner = OneMaxRunner( + chromosome_generator, + fitness, + stopping_criteria, + mutation, + age_annealing, + fitness_stagnation_detector, + ) + + best = runner.run() + return best + + +def main(): + + logging_format = ( + "[%(levelname)8s :%(filename)15s:%(lineno)4s - %(funcName)10s] %(message)s" + ) + logging.basicConfig(format=logging_format, level=logging.DEBUG) + + target = 30 + gene_set = [0, 1] + one_max(target, gene_set) + + +if __name__ == "__main__": + main() diff --git a/scripts/ch02/tests/test_one_max.py b/scripts/ch02/tests/test_one_max.py new file mode 100644 index 0000000..82d94b4 --- /dev/null +++ b/scripts/ch02/tests/test_one_max.py @@ -0,0 +1,11 @@ +from scripts.ch02.one_max import one_max + + +def test_one_max(): + target = 100 + gene_set = [0, 1] + best = one_max(target, gene_set) + + assert len(best.genes) == target + assert best.genes.count("1") == target + assert best.genes.count("0") == 0 \ No newline at end of file diff --git a/scripts/ch03/sort_numbers.py b/scripts/ch03/sort_numbers.py new file mode 100644 index 0000000..93f7050 --- /dev/null +++ b/scripts/ch03/sort_numbers.py @@ -0,0 +1,209 @@ +from __future__ import annotations + +import random +import time +from typing import List, Type, Union + +import numpy as np + +from src.genetic import ( + AgeAnnealing, + Chromosome, + ChromosomeGenerator, + FitnessStagnationDetector, + GeneSet, + Mutation, + RelativeFitness, + Runner, + StoppingCriteria, +) + + +class SortNumbersChromosome(Chromosome): + """Chromosome for the sort numbers problem is a list of numbers.""" + + def __init__(self, genes: List[int], age: int = 0): + self.genes = genes + self.age = age + + def __str__(self) -> str: + return f"Chromosome({self.genes}, age={self.age})" + + def __repr__(self) -> str: + return f"Chromosome({self.genes}, age={self.age})" + + def __eq__(self, other: Chromosome) -> bool: + return self.genes == other.genes + + +class SortNumbersFitness(RelativeFitness): + """Fitness function of a chromosome for the sort numbers problem.""" + + def __init__(self, chromosome: SortNumbersChromosome) -> None: + self.chromosome = chromosome + + def __gt__(self, other: SortNumbersFitness) -> bool: + + if self.numbers_in_sequence_count() != other.numbers_in_sequence_count(): + return self.numbers_in_sequence_count() > other.numbers_in_sequence_count() + + return ( + self.total_size_of_gaps_in_sequence() + < other.total_size_of_gaps_in_sequence() + ) + + def total_size_of_gaps_in_sequence(self) -> float: + """Return the total size of the gaps in the sequence. + + Returns + ------- + float + The total size of the gaps in the sequence + """ + + return sum( + [ + np.abs(self.chromosome.genes[ii] - self.chromosome.genes[ii - 1]) + for ii in range(1, len(self.chromosome.genes)) + ] + ) + + def numbers_in_sequence_count(self) -> float: + """Return the number of numbers in sequence. + + Returns + ------- + float + The number of numbers in sequence + """ + + return len( + [ + ii + for ii in range(1, len(self.chromosome.genes)) + if self.chromosome.genes[ii] > self.chromosome.genes[ii - 1] + ] + ) + + +class SortNumbersMutation(Mutation): + def __init__(self, fitness: Type[SortNumbersFitness], gene_set: GeneSet): + self.fitness = fitness + self.gene_set = gene_set + + def __call__(self, parent): + child_genes = parent.genes.copy() + index = random.randrange(0, len(parent.genes)) + new_gene, alternate = random.sample(self.gene_set, 2) + child_genes[index] = alternate if new_gene == child_genes[index] else new_gene + + # a simple option to improve performance here is to set the part of the domain + # that we know should be true to the correct value + child_genes[0] = min(self.gene_set) + child_genes[-1] = max(self.gene_set) + + return SortNumbersChromosome(child_genes) + + +class SortNumbersStoppingCriteria(StoppingCriteria): + def __init__(self, target: int, fitness: Type[SortNumbersFitness]): + self.target = target + self.fitness = fitness + + def __call__(self, chromosome: SortNumbersChromosome) -> bool: + """Return true if can stop the genetic algorithm.""" + + return self.fitness(chromosome).numbers_in_sequence_count() >= self.target + + +class SortNumbersChromosomeGenerator(ChromosomeGenerator): + def __init__(self, gene_set, length) -> None: + self.gene_set = gene_set + self.length = length + + def __call__(self) -> SortNumbersChromosome: + genes = [] + while len(genes) < self.length: + sampleSize = min(self.length - len(genes), len(self.gene_set)) + genes.extend(random.sample(self.gene_set, sampleSize)) + return SortNumbersChromosome(genes) + + +class SortNumbersRunner(Runner): + def __init__( + self, + chromosome_generator: ChromosomeGenerator, + fitness: Type[SortNumbersFitness], + stopping_criteria: StoppingCriteria, + mutate: Mutation, + age_annealing: AgeAnnealing, + fitness_stagnation_detector: FitnessStagnationDetector, + ): + super().__init__( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + fitness_stagnation_detector, + ) + + def display(self, candidate): + timeDiff = time.time() - self.start_time + + numbers_in_sequence_count = self.fitness(candidate).numbers_in_sequence_count() + total_size_of_gaps_in_sequence = self.fitness( + candidate + ).total_size_of_gaps_in_sequence() + + print( + "{}:\tIn sequence={}\tGap size={}\ttime={}".format( + candidate.genes, + numbers_in_sequence_count, + total_size_of_gaps_in_sequence, + timeDiff, + ) + ) + + +def sort_numbers( + length, + fitness_stagnation_limit: Union[float, int] = float("inf"), + age_limit: float = float("inf"), +) -> SortNumbersChromosome: + + target = length - 1 + + gene_set = list(range(length)) + + fitness = SortNumbersFitness + chromosome_generator = SortNumbersChromosomeGenerator(gene_set, length) + stopping_criteria = SortNumbersStoppingCriteria(target, fitness) + mutate = SortNumbersMutation(fitness, gene_set) + age_annealing = AgeAnnealing(age_limit=age_limit) + + fitness_stagnation_detector = FitnessStagnationDetector( + fitness, fitness_stagnation_limit + ) + + runner = SortNumbersRunner( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + fitness_stagnation_detector, + ) + + best = runner.run() + return best + + +def main(): + + length = 10 + sort_numbers(length) + + +if __name__ == "__main__": + main() diff --git a/scripts/ch03/tests/test_sort_numbers.py b/scripts/ch03/tests/test_sort_numbers.py new file mode 100644 index 0000000..72ff3a3 --- /dev/null +++ b/scripts/ch03/tests/test_sort_numbers.py @@ -0,0 +1,7 @@ +from scripts.ch03.sort_numbers import sort_numbers + + +def test_sort_numbers(): + length = 10 + best = sort_numbers(length) + assert best.genes == list(range(length)) \ No newline at end of file diff --git a/scripts/ch04/eight_queens.py b/scripts/ch04/eight_queens.py new file mode 100644 index 0000000..8d4ace2 --- /dev/null +++ b/scripts/ch04/eight_queens.py @@ -0,0 +1,269 @@ +"""you should be able to see the queens problem as a variant of a scheduling or +resource allocation problem, with the rows and columns representing resources, and +the queens being people or things that require or consume resources, possibly with +additional constraints (i.e. the diagonal attacks). With a different test class +and genes you could solve a number of scheduling or resource allocation problems +with the current engine. For example: baking pizzas in ovens, one pizza per oven. The +rows could become ovens - possibly with special features like cooks-faster or +-slower or only small pizzas. The columns become time slots, and the queens become +pizzas with features like size, required cooking time, value, bonus for faster +delivery, etc. Now you can try to maximize the number of pizzas, or the amount +of money earned. +""" +from __future__ import annotations + +import logging +import random +import time +from typing import List, Union + +from src.genetic import ( + AbsoluteFitness, + AgeAnnealing, + Chromosome, + ChromosomeGenerator, + FitnessStagnationDetector, + GeneSet, + Mutation, + Runner, + StoppingCriteria, +) + + +class EightQueensChromosome(Chromosome): + """Chromosome for the OneMax problem is a string of 1s and 0s.""" + + def __init__(self, genes: List[int], age: int = 0): + self.genes = genes + self.age = age + + def __str__(self) -> str: + return f"Chromosome({self.genes}, age={self.age})" + + def __repr__(self) -> str: + return f"Chromosome({self.genes}, age={self.age})" + + def __eq__(self, other: EightQueensChromosome) -> bool: + return self.genes == other.genes + + +class Board: + def __init__(self, genes, size): + board = [["."] * size for _ in range(size)] + for index in range(0, len(genes), 2): + row = genes[index] + column = genes[index + 1] + board[column][row] = "Q" + self._board = board + + def get(self, row, column): + return self._board[column][row] + + def print(self): + for i in reversed(range(len(self._board))): + print(" ".join(self._board[i])) + + +class EightQueensFitness(AbsoluteFitness): + """Fitness function of a chromosome for the sort numbers problem.""" + + def __init__(self, size: int): + self.size = size + + def __call__(self, chromosome: EightQueensChromosome) -> float: + """Return a fitness score for the queen positions. The score is the + number of pairs of queens that are attacking each other. + + Parameters + ---------- + chromosome : EightQueensChromosome + The chromosome to evaluate + + Returns + ------- + float + a fitness score for the queen positions, equal to -(number of queens + under attack). The higher the score, the better the fitness. + """ + + board = Board(chromosome.genes, self.size) + + rows_with_queens = set() + cols_with_queens = set() + north_east_diagonals_with_queens = set() + south_east_diagonals_with_queens = set() + + for row in range(self.size): + for col in range(self.size): + if board.get(row, col) == "Q": + rows_with_queens.add(row) + cols_with_queens.add(col) + north_east_diagonals_with_queens.add(row + col) + south_east_diagonals_with_queens.add(self.size - 1 - row + col) + + total = -( + self.size + - len(rows_with_queens) + + self.size + - len(cols_with_queens) + + self.size + - len(north_east_diagonals_with_queens) + + self.size + - len(south_east_diagonals_with_queens) + ) + + return total + + +class EightQueensMutation(Mutation): + def __init__(self, fitness: EightQueensFitness, gene_set: GeneSet): + self.fitness = fitness + self.gene_set = gene_set + + def __call__(self, parent: EightQueensChromosome) -> EightQueensChromosome: + """Mutate a chromosome by swapping the value of a chromosome's gene with + another random gene from the gene set. Mutation in this case is the + changing of a row or column position of a single queen. + + Parameters + ---------- + parent : EightQueensChromosome + The chromosome to mutate. + + Returns + ------- + EightQueensChromosome + the mutated chromosome + """ + + child_genes = parent.genes.copy() + index = random.randrange(0, len(parent.genes)) + new_gene, alternate = random.sample(self.gene_set, 2) + child_genes[index] = alternate if new_gene == child_genes[index] else new_gene + + return EightQueensChromosome(child_genes) + + +class EightQueensStoppingCriteria(StoppingCriteria): + def __init__(self, target: int, fitness: EightQueensFitness): + self.target = target + self.fitness = fitness + + def __call__(self, chromosome: EightQueensChromosome) -> bool: + """Return true if can stop the genetic algorithm.""" + + return self.fitness(chromosome) >= self.target + + +class EightQueensChromosomeGenerator(ChromosomeGenerator): + def __init__(self, gene_set, length) -> None: + self.gene_set = gene_set + self.length = length + + def __call__(self) -> EightQueensChromosome: + """Generate a chromosome from the gene set + + In this task a chromosome is a list of numbers that represent the + positions of the queens in the board. For a board of size nxn, the chromsome + will have 2n genes of the form [row1, col1, row2, col2, ..., rown, coln] + """ + + genes = [] + while len(genes) < self.length: + sampleSize = min(self.length - len(genes), len(self.gene_set)) + genes.extend(random.sample(self.gene_set, sampleSize)) + return EightQueensChromosome(genes) + + +class EightQueensRunner(Runner): + def __init__( + self, + chromosome_generator: ChromosomeGenerator, + fitness: EightQueensFitness, + stopping_criteria: StoppingCriteria, + mutate: Mutation, + age_annealing: AgeAnnealing, + fitness_stagnation_detector: FitnessStagnationDetector, + size: int, + ): + super().__init__( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + fitness_stagnation_detector, + ) + self.size = size + + def display(self, candidate: EightQueensChromosome): + time_diff = time.time() - self.start_time + + board = Board(candidate.genes, self.size) + board.print() + return f"time = {time_diff}" + + +def eight_queens( + size: int, + fitness_stagnation_limit: Union[float, int] = float("inf"), + age_limit: float = float("inf"), +) -> EightQueensChromosome: + """Run the genetic algorithm to find the solution for the eight queens problem. + + Parameters + ---------- + size : int + The size of the board (size x size) + + Returns + ------- + EightQueensChromosome + The chromosome with the solution. The genes of the chromosome are the + positions of the queens in the board. For a board of size nxn, the chromosome + will have 2n genes of the form [row1, col1, row2, col2, ..., rown, coln] + """ + + # the target is to have no queens under attack from eachother + target = 0 + + # the genes are the potential column and row positions of the queens + gene_set = list(range(size)) + + fitness = EightQueensFitness(size) + chromosome_generator = EightQueensChromosomeGenerator(gene_set, 2 * size) + stopping_criteria = EightQueensStoppingCriteria(target, fitness) + mutate = EightQueensMutation(fitness, gene_set) + age_annealing = AgeAnnealing(age_limit=age_limit) + + fitness_stagnation_detector = FitnessStagnationDetector( + fitness, fitness_stagnation_limit + ) + + runner = EightQueensRunner( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + fitness_stagnation_detector, + size, + ) + + best = runner.run() + return best + + +def main(): + + logging_format = ( + "[%(levelname)8s :%(filename)15s:%(lineno)4s - %(funcName)10s] %(message)s" + ) + logging.basicConfig(format=logging_format, level=logging.DEBUG) + + size = 8 + eight_queens(size) + + +if __name__ == "__main__": + main() diff --git a/scripts/ch04/tests/test_eight_queens.py b/scripts/ch04/tests/test_eight_queens.py new file mode 100644 index 0000000..1807854 --- /dev/null +++ b/scripts/ch04/tests/test_eight_queens.py @@ -0,0 +1,13 @@ +from scripts.ch04.eight_queens import eight_queens + + +def test_eight_queens(): + size = 8 + best = eight_queens(size) + + # list of coordinates of the queens of form [row1, col1, row2, col2, ..., rown, coln] + assert len(best.genes) == 2 * size + + # check each row and column appears only once as a coordinate + for ii in range(size): + assert best.genes.count(ii) == 2 diff --git a/scripts/ch05/graph_colouring.py b/scripts/ch05/graph_colouring.py new file mode 100644 index 0000000..5d663d2 --- /dev/null +++ b/scripts/ch05/graph_colouring.py @@ -0,0 +1,207 @@ +from __future__ import annotations + +import logging +import random +import time +from copy import deepcopy +from pathlib import Path +from typing import Any, Tuple + +import networkx as nx + +from src.genetic import ( + AbsoluteFitness, + AgeAnnealing, + Chromosome, + ChromosomeGenerator, + FitnessStagnationDetector, + GeneSet, + Mutation, + Runner, + StoppingCriteria, +) +from src.graph import NodeColouredGraph + + +class GraphColouringChromosome: + """Chromosome for the graph colouring problem.""" + + def __init__(self, genes: NodeColouredGraph, age: int = 0): + self.genes = genes + self.age = age + + +class GraphColoringFitness(AbsoluteFitness): + """Fitness function of a chromosome for the sort numbers problem.""" + + chromosome: GraphColouringChromosome + + def __init__(self) -> None: + pass + + def __call__(self, chromosome: GraphColouringChromosome) -> int: + """Return the fitness of a chromosome. The fitness is 0 minus the number of + edges that have the same colour node at each end. The higher the fitness, the + fewer nodes have the same colour as an adjacent node. + + Parameters + ---------- + chromosome : GraphColouringChromosome + The chromosome to evaluate. + + Returns + ------- + int + The fitness of the chromosome. + """ + + return -sum( + [ + chromosome.genes.node_colour_match(node1, node2) + for node1, node2 in chromosome.genes.edges + ] + ) + + +class GraphColoringMutation(Mutation): + """Mutation function for the graph colouring problem.""" + + def __init__(self, fitness: GraphColoringFitness, gene_set: GeneSet): + self.fitness = fitness + self.gene_set = gene_set + + def __call__(self, parent: GraphColouringChromosome) -> GraphColouringChromosome: + + child = deepcopy(parent) + + # pick a random node and a random colour + node = random.choice(list(child.genes.nodes)) + new_colour = random.choice(list(self.gene_set)) + + # mutate the node + child.genes.nodes[node]["colour"] = new_colour + + return child + + +class GraphColoringStoppingCriteria(StoppingCriteria): + def __init__(self, target: int, fitness: GraphColoringFitness): + self.target = target + self.fitness = fitness + + def __call__(self, chromosome: GraphColouringChromosome) -> bool: + """Return true if can stop the genetic algorithm.""" + + return self.fitness(chromosome) >= self.target + + +class GraphColoringChromosomeGenerator(ChromosomeGenerator): + def __init__(self, gene_set, base_graph: NodeColouredGraph) -> None: + self.gene_set = gene_set + self.base_graph = base_graph + + def __call__(self) -> GraphColouringChromosome: + + graph = deepcopy(self.base_graph) + + for node in graph.nodes: + random_colour = random.choice(list(self.gene_set)) + graph.nodes[node]["colour"] = random_colour + + return GraphColouringChromosome(graph, age=0) + + +class GraphColoringRunner(Runner): + def __init__( + self, + chromosome_generator: ChromosomeGenerator, + fitness: GraphColoringFitness, + stopping_criteria: StoppingCriteria, + mutate: Mutation, + age_annealing: AgeAnnealing, + stagnation_detector: FitnessStagnationDetector, + ): + super().__init__( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + stagnation_detector, + ) + + def display(self, candidate): + time_diff = time.time() - self.start_time + + logging.debug("candidate=%s", candidate.genes.colour_dict) + logging.debug("fitness=%s", self.fitness(candidate)) + + logging.info("time=%f", time_diff) + + +def graph_colouring( + base_graph: GraphColouringChromosome, + gene_set: Tuple[str], + fitness_stagnation_limit: Union[float, int] = float("inf"), + age_limit: float = float("inf"), +) -> GraphColouringChromosome: + + target = 0 # no edges with the same colour at each end + + fitness = GraphColoringFitness() + chromosome_generator = GraphColoringChromosomeGenerator(gene_set, base_graph) + stopping_criteria = GraphColoringStoppingCriteria(target, fitness) + mutate = GraphColoringMutation(fitness, gene_set) + age_annealing = AgeAnnealing(age_limit=age_limit) + + fitness_stagnation_detector = FitnessStagnationDetector( + fitness, fitness_stagnation_limit + ) + runner = GraphColoringRunner( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + fitness_stagnation_detector, + ) + + best = runner.run() + print(best) + return best + + +def main(): + + logging_format = ( + "[%(levelname)8s :%(filename)20s:%(lineno)4s - %(funcName)10s] %(message)s" + ) + logging.basicConfig(format=logging_format, level=logging.INFO) + + col_file_path = Path( + "/Users/mitchell.dawson/CodeProjects/GeneticAlgorithmsWithPython/data_fixtures/raw/graph_colouring/adjacent_states.col" + ) + + output_folder = Path( + "/Users/mitchell.dawson/CodeProjects/GeneticAlgorithmsWithPython/data/processed/graph_colouring" + ) + + base_graph = NodeColouredGraph().from_col_file(col_file_path) + + gene_set = ["red", "blue", "green", "yellow"] + + best = graph_colouring(base_graph, gene_set) + + positions = nx.planar_layout(best.genes) + positions = nx.spring_layout(best.genes, pos=positions, seed=100, k=1) + + colour_map = [] + + for node in best.genes: + colour_map.append(best.genes.nodes[node]["colour"]) + + best.genes.plot(output_folder, positions=positions, colour_map=colour_map) + + +if __name__ == "__main__": + main() diff --git a/scripts/ch05/tests/test_graph_colouring.py b/scripts/ch05/tests/test_graph_colouring.py new file mode 100644 index 0000000..fbb661c --- /dev/null +++ b/scripts/ch05/tests/test_graph_colouring.py @@ -0,0 +1,92 @@ +import random + +import networkx as nx +import pytest + +from scripts.ch05.graph_colouring import ( + GraphColoringChromosomeGenerator, + GraphColoringFitness, + GraphColoringMutation, + GraphColouringChromosome, + graph_colouring, +) +from src.graph import NodeColouredGraph + + +@pytest.fixture +def simple_col_file(data_fixtures_folder): + return data_fixtures_folder / "raw/graph_colouring/simple.col" + + +def test_call_GraphColoringFitness(): + + fitness = GraphColoringFitness() + + graph = NodeColouredGraph() + graph.add_node(1, colour="red") + graph.add_node(2, colour="red") + graph.add_node(3, colour="blue") + graph.add_node(4, colour="blue") + graph.add_node(5, colour="green") + + graph.add_edge(1, 2) + graph.add_edge(2, 3) + graph.add_edge(3, 4) + graph.add_edge(4, 5) + + assert fitness(GraphColouringChromosome(graph)) == -2 + + +def test_call_GraphColoringMutation(): + + random.seed(1) + + fitness = GraphColoringFitness() + gene_set = ["red", "blue", "green"] + + mutation = GraphColoringMutation(fitness, gene_set) + + parent = NodeColouredGraph() + parent.add_node(1, colour="red") + parent.add_node(2, colour="red") + parent.add_node(3, colour="blue") + + parent = GraphColouringChromosome(parent) + child = mutation(parent) + + assert child.genes.colour_dict == {1: "green", 2: "red", 3: "blue"} + assert parent.genes.colour_dict == {1: "red", 2: "red", 3: "blue"} + + +def test_call_GraphColoringChromosomeGenerator(): + + random.seed(1) + + graph = NodeColouredGraph() + graph.add_node(1) + graph.add_node(2) + graph.add_node(3) + graph.add_edge(1, 2) + graph.add_edge(2, 3) + + gene_set = ["red", "blue", "green"] + + generator = GraphColoringChromosomeGenerator(gene_set, graph) + + chromosome = generator() + + assert chromosome.genes.colour_dict == { + 1: "red", + 2: "green", + 3: "red", + } + + +def test_graph_colouring(simple_col_file): + + base_graph = NodeColouredGraph().from_col_file(simple_col_file) + gene_set = ["red", "blue", "green", "yellow"] + best = graph_colouring(base_graph, gene_set) + + assert set(best.genes.colour_dict.values()) == set(gene_set) + assert best.genes.colour_dict["4"] == best.genes.colour_dict["5"] diff --git a/scripts/ch06/card_problem.py b/scripts/ch06/card_problem.py new file mode 100644 index 0000000..8557e50 --- /dev/null +++ b/scripts/ch06/card_problem.py @@ -0,0 +1,250 @@ +"""We start off with the set of cards, Ace and 2-10, which we separate into 2 groups of +5 cards. The cards in each group have different constraints. The card values in one +group must have a product of 360. The card values in the other group must sum to 36. +We can only use each card once. +""" + + +from __future__ import annotations + +import logging +import random +import time +from copy import deepcopy +from pathlib import Path +from typing import Any, List, Tuple, Type + +import numpy as np + +from src.genetic import ( + AgeAnnealing, + Chromosome, + ChromosomeGenerator, + FitnessStagnationDetector, + GeneSet, + Mutation, + RelativeFitness, + Runner, + StoppingCriteria, +) + + +class CardProblemChromosome(Chromosome): + """Chromosome for the card problem.""" + + def __init__(self, genes: List[int], age: int = 0): + self.genes = genes + self.age = age + + def __str__(self) -> str: + return f"{self.genes}" + + def __repr__(self) -> str: + return self.__str__() + + @property + def left_group(self) -> List[int]: + return self.genes[:5] + + @property + def right_group(self) -> List[int]: + return self.genes[5:] + + @property + def num_duplicates(self) -> int: + return len(self.genes) - len(set(self.genes)) + + +class CardProblemFitness(RelativeFitness): + """Fitness function of a chromosome for the card problem. The fitness is the sum of + the absolute difference between the sum of the cards in the first group and 36 and + the absolute difference between the product of the cards in the second group and + 360. + """ + + def __init__(self, chromosome: CardProblemChromosome) -> None: + self.chromosome = chromosome + + def __gt__(self, other: CardProblemFitness) -> bool: + + if self.count_duplicates() != other.count_duplicates(): + return self.count_duplicates() < self.count_duplicates() + + return self.total_difference() < other.total_difference() + + def total_difference(self) -> int: + return self.sum_of_cards_fitness() + self.product_of_cards_fitness() + + def count_duplicates(self) -> int: + """Return the number of duplicates in a list of cards. + + Parameters + ---------- + cards : List[int] + The cards to evaluate. + + Returns + ------- + int + The number of duplicates in the list of cards. + """ + return len(self.chromosome.genes) - len(set(self.chromosome.genes)) + + def sum_of_cards_fitness(self, target: int = 36) -> int: + """Return the fitness of some cards from the chromosome. The fitness is the + absolute difference between the sum of the cards and the target. + + Parameters + ---------- + target : int, optional + The target value, by default 36 + + Returns + ------- + int + The fitness of the cards. + """ + return np.abs(np.sum(self.chromosome.left_group) - target) + + def product_of_cards_fitness(self, target: int = 360) -> int: + """Return the fitness of some cards from the chromosome. The fitness is the + absolute difference between the product of the cards and the target. + + Parameters + ---------- + target : int, optional + the target value, by default 360 + + Returns + ------- + int + the fitness of the cards. + """ + return np.abs(np.prod(self.chromosome.right_group) - target) + + +class CardProblemMutation(Mutation): + """Mutation function for the graph colouring problem.""" + + def __init__(self, fitness: CardProblemFitness, gene_set: GeneSet): + self.fitness = fitness + self.gene_set = gene_set + + def __call__(self, parent: CardProblemChromosome) -> CardProblemChromosome: + + child = deepcopy(parent) + + if len(child.genes) == len(set(child.genes)): + count = random.randint(1, 4) + while count > 0: + count -= 1 + indexA, indexB = random.sample(range(len(child.genes)), 2) + child.genes[indexA], child.genes[indexB] = ( + child.genes[indexB], + child.genes[indexA], + ) + else: + indexA = random.randrange(0, len(child.genes)) + indexB = random.randrange(0, len(self.gene_set)) + child.genes[indexA] = child.genes[indexB] + + return CardProblemChromosome(child.genes, age=0) + + +class CardProblemStoppingCriteria(StoppingCriteria): + def __init__(self, target: int, fitness: Type[CardProblemFitness]): + self.target = target + self.fitness = fitness + + def __call__(self, chromosome: CardProblemChromosome) -> bool: + """Return true if can stop the genetic algorithm.""" + + return (self.fitness(chromosome).total_difference() == 0) and ( + self.fitness(chromosome).count_duplicates() == 0 + ) + + +class CardProblemChromosomeGenerator(ChromosomeGenerator): + def __init__(self, gene_set) -> None: + self.gene_set = gene_set + + def __call__(self) -> CardProblemChromosome: + return CardProblemChromosome(self.gene_set, age=0) + + +class CardProblemRunner(Runner): + def __init__( + self, + chromosome_generator: ChromosomeGenerator, + fitness: Type[CardProblemFitness], + stopping_criteria: StoppingCriteria, + mutate: Mutation, + age_annealing: AgeAnnealing, + fitness_stagnation_detector: FitnessStagnationDetector, + ) -> None: + super().__init__( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + fitness_stagnation_detector, + ) + + def display(self, candidate): + time_diff = time.time() - self.start_time + + logging.debug("candidate=%s", candidate) + + logging.debug("left sum=%s", np.sum(candidate.left_group)) + logging.debug("right product=%s", np.prod(candidate.right_group)) + logging.debug("duplicates=%s", candidate.num_duplicates) + + logging.debug("time=%f", time_diff) + + +def card_problem( + gene_set: Tuple[int], + fitness_stagnation_limit: Union[float, int] = float("inf"), + age_limit: float = float("inf"), +) -> CardProblemChromosome: + + target = 0 # no duplicates, sum of left cards = 36, product of right cards = 360 + + fitness = CardProblemFitness + chromosome_generator = CardProblemChromosomeGenerator(gene_set) + stopping_criteria = CardProblemStoppingCriteria(target, fitness) + mutation = CardProblemMutation(fitness, gene_set) + age_annealing = AgeAnnealing(age_limit=age_limit) + + fitness_stagnation_detector = FitnessStagnationDetector( + fitness, fitness_stagnation_limit + ) + runner = CardProblemRunner( + chromosome_generator, + fitness, + stopping_criteria, + mutation, + age_annealing, + fitness_stagnation_detector, + ) + + best = runner.run() + print(best) + return best + + +def main(): + + logging_format = ( + "[%(levelname)8s :%(filename)20s:%(lineno)4s - %(funcName)10s] %(message)s" + ) + logging.basicConfig(format=logging_format, level=logging.INFO) + + gene_set = list(range(1, 11)) + + card_problem(gene_set) + + +if __name__ == "__main__": + main() diff --git a/scripts/ch06/tests/test_card_problem.py b/scripts/ch06/tests/test_card_problem.py new file mode 100644 index 0000000..0be3601 --- /dev/null +++ b/scripts/ch06/tests/test_card_problem.py @@ -0,0 +1,13 @@ +import numpy as np + +from scripts.ch06.card_problem import card_problem + + +def test_card_problem(): + + gene_set = list(range(1, 11)) + + best = card_problem(gene_set) + + assert np.sum(best.left_group) == 36 + assert np.prod(best.right_group) == 360 diff --git a/scripts/ch07/knight_attack.py b/scripts/ch07/knight_attack.py new file mode 100644 index 0000000..06d67b1 --- /dev/null +++ b/scripts/ch07/knight_attack.py @@ -0,0 +1,209 @@ +from __future__ import annotations + +import logging +import random +import time +from copy import deepcopy +from typing import Tuple, Union + +import numpy as np + +from src.chess import Board, Knight, PiecePosition, PieceType +from src.genetic import ( + AbsoluteFitness, + AgeAnnealing, + ChromosomeGenerator, + FitnessStagnationDetector, + Mutation, + Runner, + StoppingCriteria, +) + + +class GeneSet(Tuple[PiecePosition, ...]): + """Gene set for the knight attack problem.""" + + +class KnightAttackChromosome: + """Chromosome for the knight attack problem.""" + + def __init__(self, genes: Board, age: int = 0) -> None: + self.genes = genes + self.age = age + + def __str__(self) -> str: + return str(self.genes) + + def __repr__(self) -> str: + return str(self.genes) + + +class KnightAttackFitness(AbsoluteFitness): + """Fitness function of a chromosome for the knight attack problem. The fitness is + the number of squares on the board attacked by the knights. So the maximal fitness + is the number of squares on the board. + """ + + def __call__(self, chromosome: KnightAttackChromosome) -> float: + + attacked_positions = set() + + for position in chromosome.genes.positions(): + + if chromosome.genes[position.y, position.x].piece_type == PieceType.KNIGHT: + attacked_positions.update( + Knight().get_attacks(position, chromosome.genes) + ) + + return len(attacked_positions) + + +class KnightAttackMutation(Mutation): + """Mutation function for the graph colouring problem.""" + + def __init__( + self, fitness: KnightAttackFitness, gene_set: GeneSet, max_knights: int + ): + self.fitness = fitness + self.gene_set = gene_set + self.max_knights = max_knights + + def __call__(self, parent: KnightAttackChromosome) -> KnightAttackChromosome: + + child = deepcopy(parent) + + knight_positions = list(child.genes.positions(piece_type=PieceType.KNIGHT)) + + # choose a random new position for the knight + new_position = random.choice(self.gene_set) + + if len(knight_positions) < self.max_knights: + # add a knight + new_position = random.choice(self.gene_set) + child.genes.place(Knight(), new_position) + else: + + for _ in range(random.choice(range(4))): + # choose a random knight position + knight_position = random.choice(list(knight_positions)) + + # move the knight to the new position + child.genes.move(knight_position, new_position) + + return child + + +class KnightAttackStoppingCriteria(StoppingCriteria): + def __init__(self, target: int, fitness: KnightAttackFitness): + self.target = target + self.fitness = fitness + + def __call__(self, chromosome: KnightAttackChromosome) -> bool: + """Return true if can stop the genetic algorithm.""" + + return self.fitness(chromosome) == self.target + + +class KnightAttackChromosomeGenerator(ChromosomeGenerator): + def __init__(self, board) -> None: + self.board = board + + def __call__(self) -> KnightAttackChromosome: + return KnightAttackChromosome(self.board, age=0) + + +class KnightAttackRunner(Runner): + def __init__( + self, + chromosome_generator: ChromosomeGenerator, + fitness: KnightAttackFitness, + stopping_criteria: StoppingCriteria, + mutate: Mutation, + age_annealing: AgeAnnealing, + fitness_stagnation_detector: FitnessStagnationDetector, + ): + super().__init__( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + fitness_stagnation_detector, + ) + + def display(self, candidate): + time_diff = time.time() - self.start_time + + logging.debug("candidate=%s", str(candidate)) + logging.info("fitness=%f", self.fitness(candidate)) + logging.debug("time=%f", time_diff) + + +def knight_attack( + board: Board, + max_knights: int, + include_edges: bool = True, + fitness_stagnation_limit: Union[float, int] = float("inf"), + age_limit: float = float("inf"), +) -> KnightAttackChromosome: + + target = board.total_squares # all squares on the board attacked by a knight + + # create a gene set of all the positions on the board, excluding the edges + # this is a trick to help improve performance + gene_set = GeneSet(tuple(board.positions(include_edges=include_edges))) + + fitness = KnightAttackFitness() + chromosome_generator = KnightAttackChromosomeGenerator(board) + stopping_criteria = KnightAttackStoppingCriteria(target, fitness) + mutation = KnightAttackMutation(fitness, gene_set, max_knights=max_knights) + age_annealing = AgeAnnealing(age_limit=age_limit) + + fitness_stagnation_detector = FitnessStagnationDetector( + fitness, fitness_stagnation_limit + ) + + runner = KnightAttackRunner( + chromosome_generator, + fitness, + stopping_criteria, + mutation, + age_annealing, + fitness_stagnation_detector, + ) + + best = runner.run() + return best + + +def main(): + """Run the knight attack problem. + 4x4 board requires 6 knights to attack all + 8x8 board requires 14 knights to attack all + 10x10 board requires 22 knights to attack all + """ + + logging_format = ( + "[%(levelname)8s :%(filename)20s:%(lineno)4s - %(funcName)10s] %(message)s" + ) + logging.basicConfig(format=logging_format, level=logging.INFO) + + board_height, board_width = 40, 40 + max_knights = 1200 + include_edges = False # use edges fo small boards, but not for large boards + fitness_stagnation_limit = ( + 10000 # stop after this many generations of no improvement + ) + + board = Board.empty_board(board_height, board_width) + + knight_attack( + board, + max_knights, + include_edges, + fitness_stagnation_limit=fitness_stagnation_limit, + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/ch07/tests/test_knight_attack.py b/scripts/ch07/tests/test_knight_attack.py new file mode 100644 index 0000000..4d50809 --- /dev/null +++ b/scripts/ch07/tests/test_knight_attack.py @@ -0,0 +1,121 @@ +import numpy as np + +from scripts.ch07.knight_attack import ( + KnightAttackChromosome, + KnightAttackFitness, + KnightAttackMutation, + knight_attack, +) +from src.chess import Board, Knight, PiecePosition + + +def test_knight_attack(): + board_height, board_width = 4, 4 + max_knights = 6 + + board = Board.empty_board(board_height, board_width) + + knight_attack(board, max_knights) + + +def test_call_one_knight_in_centre_of_board_KnightAttackFitness(): + + board = Board.empty_board(8, 8) + position = PiecePosition(x=3, y=3) + knight = Knight() + board.place(knight, position) + + chromosome = KnightAttackChromosome(board) + + fitness = KnightAttackFitness() + + assert fitness(chromosome) == 8 + + +def test_call_one_knight_on_edge_of_board_KnightAttackFitness(): + + board = Board.empty_board(8, 8) + position = PiecePosition(x=0, y=3) + knight = Knight() + board.place(knight, position) + + chromosome = KnightAttackChromosome(board) + + fitness = KnightAttackFitness() + + assert fitness(chromosome) == 4 + + +def test_call_one_knight_in_corner_of_board_KnightAttackFitness(): + + board = Board.empty_board(8, 8) + position = PiecePosition(x=0, y=0) + knight = Knight() + board.place(knight, position) + chromosome = KnightAttackChromosome(board) + + fitness = KnightAttackFitness() + assert fitness(chromosome) == 2 + + +def test_call_two_knights_with_some_overlap_KnightAttackFitness(): + + board = Board.empty_board(8, 8) + + position = PiecePosition(x=3, y=3) + knight_1 = Knight() + board.place(knight_1, position) + + position = PiecePosition(x=4, y=4) + knight_2 = Knight() + board.place(knight_2, position) + + print(board) + + chromosome = KnightAttackChromosome(board) + + fitness = KnightAttackFitness() + + # 8 + 8 - 2 = 14 + assert fitness(chromosome) == 14 + + +def test_call_edge_knights_with_some_overlap_KnightAttackFitness(): + + board = Board.empty_board(8, 8) + + y = 7 + + for x in (2, 4, 6): + position = PiecePosition(x=x, y=y) + knight = Knight() + print(knight.get_attacks(position, board)) + board.place(knight, position) + + print(board) + chromosome = KnightAttackChromosome(board) + + fitness = KnightAttackFitness() + + # 8 + 8 - 2 = 14 + assert fitness(chromosome) == 8 + + +def test_call_KnightAttackMutation(): + + fitness = KnightAttackFitness() + + board = Board.empty_board(1000, 1000) + gene_set = list(board.positions()) + + mutation = KnightAttackMutation(fitness, gene_set, max_knights=1) + + position = PiecePosition(x=3, y=3) + knight = Knight() + board.place(knight, position) + + chromosome = KnightAttackChromosome(board) + + mutated_chromosome = mutation(chromosome) + + assert not np.array_equal(mutated_chromosome.genes, chromosome.genes) diff --git a/scripts/ch08/magic_squares.py b/scripts/ch08/magic_squares.py new file mode 100644 index 0000000..caeb3b5 --- /dev/null +++ b/scripts/ch08/magic_squares.py @@ -0,0 +1,371 @@ +from __future__ import annotations + +import logging +import random +import time +from copy import deepcopy +from typing import Union + +import numpy as np + +from src.genetic import ( + AbsoluteFitness, + AgeAnnealing, + Chromosome, + ChromosomeGenerator, + FitnessStagnationDetector, + Mutation, + Runner, + StoppingCriteria, +) + + +class MagicSquare(np.ndarray): + """A magic square is a square matrix of numbers where the sum of the numbers in + each row, column, and diagonal is the same. This class represents a magic square + and provides methods to check if a matrix is a magic square and to calculate the + fitness of a magic square. + """ + + def __new__(cls, input_array: np.ndarray) -> MagicSquare: + """Create a new magic square.""" + return np.asarray(input_array).view(cls) + + def __str__(self) -> str: + """return a visualisation of the chessboard""" + return "\n" + "\n".join( + ["".join([str(value).rjust(3) for value in row]) for row in self] + ) + + def __repr__(self) -> str: + """return a visualisation of the chessboard""" + return "\n" + "\n".join( + ["".join([str(value).rjust(3) for value in row]) for row in self] + ) + + def is_magic(self) -> bool: + """Check if the matrix is a magic square.""" + if self.shape[0] != self.shape[1]: + return False + + if not np.issubdtype(self.dtype, np.integer): + return False + + if np.any(self < 1): + return False + + if self.contains_duplicates: + return False + + if not np.all(self.sum_of_rows == self.expected_sum): + return False + + if not np.all(self.sum_of_columns == self.expected_sum): + return False + + if self.sum_of_major_diagonal != self.expected_sum: + return False + + if self.sum_of_minor_diagonal != self.expected_sum: + return False + + return True + + @property + def side_length(self) -> int: + """Calculate the side length of the matrix.""" + return self.shape[0] + + @property + def expected_sum(self) -> int: + """Calculate the expected sum of each the rows, columns, and diagonals.""" + return int(self.side_length * (self.side_length**2 + 1) / 2) + + @property + def contains_duplicates(self) -> bool: + """Check if the matrix contains duplicates.""" + return np.unique(self).size < self.size + + @property + def sum_of_rows(self) -> np.ndarray: + """Calculate the sum of the rows.""" + return np.array(np.sum(self, axis=1)) + + @property + def sum_of_columns(self) -> np.ndarray: + """Calculate the sum of the columns.""" + return np.array(np.sum(self, axis=0)) + + @property + def sum_of_major_diagonal(self) -> np.ndarray: + """Calculate the sum of the major diagonal.""" + return np.array(np.sum(np.diag(self))) + + @property + def sum_of_minor_diagonal(self) -> np.ndarray: + """Calculate the sum of the minor diagonal.""" + return np.array(np.sum(np.diag(np.fliplr(self)))) + + +class MagicSquaresChromosome(Chromosome): + """Chromosome for the magic squares problem.""" + + def __init__(self, genes: MagicSquare, age: int = 0) -> None: + """Create a new chromosome. + + Parameters + ---------- + genes : MagicSquare + The genes of the chromosome. + """ + self.genes = genes + self.age = age + + def __str__(self) -> str: + """Return a visualisation of the chromosome.""" + return str(self.genes) + + def __repr__(self) -> str: + """Return a visualisation of the chromosome.""" + return str(self.genes) + + +class MagicSquaresFitness(AbsoluteFitness): + """Fitness function of the magic squares problem.""" + + chromosome: MagicSquaresChromosome + + def __init__(self) -> None: + pass + + def __call__(self, chromosome: MagicSquaresChromosome) -> int: + """Return the fitness of a chromosome. The fitness is the absolute difference + between the sum of the rows, columns, and diagonals and the expected sum. + + Parameters + ---------- + chromosome : MagicSquaresChromosome + The chromosome to evaluate. + + Returns + ------- + int + The fitness of the chromosome. + """ + + self.chromosome = chromosome + + return -( + self.row_fitness() + + self.column_fitness() + + self.minor_diagonal_fitness() + + self.major_diagonal_fitness() + ) + + def row_fitness(self) -> int: + """Return the fitness of the rows. The fitness is the absolute difference + between the sum of the rows and the expected sum. + + Returns + ------- + int + The fitness of the rows. + """ + return abs( + self.chromosome.genes.sum_of_rows - self.chromosome.genes.expected_sum + ).sum() + + def column_fitness(self) -> int: + """Return the fitness of the columns. The fitness is the absolute difference + between the sum of the columns and the expected sum. + + Returns + ------- + int + The fitness of the columns. + """ + return abs( + self.chromosome.genes.sum_of_columns - self.chromosome.genes.expected_sum + ).sum() + + def minor_diagonal_fitness(self) -> int: + """Return the fitness of the minor diagonal. The fitness is the absolute + difference between the sum of the minor diagonal and the expected sum. + + Returns + ------- + int + The fitness of the minor diagonal. + """ + return abs( + self.chromosome.genes.sum_of_minor_diagonal + - self.chromosome.genes.expected_sum + ) + + def major_diagonal_fitness(self) -> int: + """Return the fitness of the major diagonal. The fitness is the absolute + difference between the sum of the major diagonal and the expected sum. + + Returns + ------- + int + The fitness of the major diagonal. + """ + return abs( + self.chromosome.genes.sum_of_major_diagonal + - self.chromosome.genes.expected_sum + ) + + +class MagicSquaresMutation(Mutation): + """Mutation function for the magic squares problem.""" + + def __init__(self, side_length: int): + super().__init__() + self.side_length = side_length + + def __call__(self, parent: MagicSquaresChromosome) -> MagicSquaresChromosome: + """Mutate a chromosome by swapping two random elements. Pick two random + indices, looping until the indices are distinct, and swap the elements at those + indices. + + Parameters + ---------- + parent : MagicSquaresChromosome + The parent chromosome to mutate. + + Returns + ------- + MagicSquaresChromosome + The mutated chromosome. + """ + + child = deepcopy(parent) + child = self.swap_two_genes(child) + return child + + def swap_two_genes(self, child: MagicSquaresChromosome): + """Swap two random numbers in the magic square""" + + idx_1 = (0, 0) + idx_2 = (0, 0) + + while idx_1 == idx_2: + idx_1 = ( + random.randint(0, self.side_length - 1), + random.randint(0, self.side_length - 1), + ) + + idx_2 = ( + random.randint(0, self.side_length - 1), + random.randint(0, self.side_length - 1), + ) + + child.genes[idx_1], child.genes[idx_2] = ( + child.genes[idx_2], + child.genes[idx_1], + ) + return child + + +class MagicSquaresStoppingCriteria(StoppingCriteria): + """Stopping criteria for the magic squares problem.""" + + def __init__(self, target: int, fitness: MagicSquaresFitness): + self.target = target + self.fitness = fitness + + def __call__(self, chromosome: MagicSquaresChromosome) -> bool: + """Return true if can stop the genetic algorithm.""" + return self.fitness(chromosome) >= self.target + + +class MagicSquaresChromosomeGenerator(ChromosomeGenerator): + """Generate a starting chromosome for the magic squares problem. + The starting chromosome is a square matrix with the numbers 1 to n^2 + in order + """ + + def __init__(self, side_length: int) -> None: + self.side_length = side_length + + def __call__(self) -> MagicSquaresChromosome: + return MagicSquaresChromosome( + MagicSquare( + np.arange(1, (self.side_length**2) + 1).reshape(self.side_length, -1) + ) + ) + + +class MagicSquaresRunner(Runner): + def __init__( + self, + chromosome_generator: MagicSquaresChromosomeGenerator, + fitness: MagicSquaresFitness, + stopping_criteria: StoppingCriteria, + mutate: Mutation, + age_annealing: AgeAnnealing, + fitness_stagnation_detector: FitnessStagnationDetector, + ): + super().__init__( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + fitness_stagnation_detector, + ) + + def display(self, candidate): + time_diff = time.time() - self.start_time + + logging.debug("candidate=%s", candidate) + logging.debug("fitness=%s", self.fitness(candidate)) + logging.info("time=%f", time_diff) + + +def magic_squares( + side_length: int, + fitness_stagnation_limit: Union[float, int] = float("inf"), + age_limit: float = float("inf"), +) -> MagicSquaresChromosome: + + target = 0 # no difference between target and sum of the rows, columns, diagonals + + fitness = MagicSquaresFitness() + chromosome_generator = MagicSquaresChromosomeGenerator(side_length) + stopping_criteria = MagicSquaresStoppingCriteria(target, fitness) + mutation = MagicSquaresMutation(side_length) + age_annealing = AgeAnnealing(age_limit=age_limit) + + fitness_stagnation_detector = FitnessStagnationDetector( + fitness, fitness_stagnation_limit + ) + runner = MagicSquaresRunner( + chromosome_generator, + fitness, + stopping_criteria, + mutation, + age_annealing, + fitness_stagnation_detector, + ) + + best = runner.run() + return best + + +def main(): + + logging_format = ( + "[%(levelname)8s :%(filename)20s:%(lineno)4s - %(funcName)10s] %(message)s" + ) + logging.basicConfig(format=logging_format, level=logging.INFO) + + side_length = 3 + age_limit = 50 + + best = magic_squares(side_length, age_limit=age_limit) + + +if __name__ == "__main__": + main() diff --git a/scripts/ch08/tests/test_magic_squares.py b/scripts/ch08/tests/test_magic_squares.py new file mode 100644 index 0000000..e1e8c93 --- /dev/null +++ b/scripts/ch08/tests/test_magic_squares.py @@ -0,0 +1,212 @@ +import numpy as np +import pytest + +from scripts.ch08.magic_squares import ( + MagicSquare, + MagicSquaresChromosome, + MagicSquaresChromosomeGenerator, + MagicSquaresFitness, + MagicSquaresMutation, + magic_squares, +) + + +@pytest.fixture(name="true_magic_square") +def fixture_true_magic_square() -> MagicSquare: + """Create a magic square. + + Returns + ------- + MagicSquare + A magic square. + + """ + return MagicSquare(np.array([[8, 1, 6], [3, 5, 7], [4, 9, 2]])) + + +######################################################################### +### MagicSquare ######################################################### +######################################################################### + + +def test_is_magic_true_MagicSquare(true_magic_square: MagicSquare): + """GIVEN a magic square + WHEN the is_magic method is called + THEN the method should return True. + """ + assert true_magic_square.is_magic() + + +def test_is_magic_false_duplicates_MagicSquare(): + """GIVEN a non-magic square with duplicates + WHEN the is_magic method is called + THEN the method should return False. + """ + + magic_square = MagicSquare(np.array([[8, 1, 6], [3, 5, 7], [4, 9, 3]])) + assert not magic_square.is_magic() + + +def test_is_magic_false_bad_sum_MagicSquare(): + """GIVEN a non-magic square with a bad sum + WHEN the is_magic method is called + THEN the method should return False. + """ + + magic_square = MagicSquare(np.array([[8, 1, 6], [3, 5, 7], [4, 2, 9]])) + assert not magic_square.is_magic() + + +def test_is_magic_false_non_square_MagicSquare(): + """GIVEN a non-magic square that is not square + WHEN the is_magic method is called + THEN the method should return False. + """ + + magic_square = MagicSquare( + np.array([[8, 1, 6], [3, 5, 7], [4, 2, 9], [10, 11, 12]]) + ) + assert not magic_square.is_magic() + + +def test_is_magic_false_negative_number_MagicSquare(): + """GIVEN a non-magic square that contains a negative number + WHEN the is_magic method is called + THEN the method should return False. + """ + + magic_square = MagicSquare(np.array([[-1, 1, 6], [3, 5, 7], [4, 2, 0]])) + assert not magic_square.is_magic() + + +def test_is_magic_false_MagicSquare(): + """GIVEN a non-magic square that contains a float + WHEN the is_magic method is called + THEN the method should return False. + """ + + magic_square = MagicSquare(np.array([[8, 1, 6], [3, 5, 7], [4, 9.0, 2]])) + assert not magic_square.is_magic() + + +######################################################################### +### MagicSquaresFitness ################################################# +######################################################################### + + +def test_call_true_MagicSquaresFitness(true_magic_square: MagicSquare): + """GIVEN a magic square + WHEN the MagicSquaresFitness class is called + THEN the method should return 0. + """ + + fitness = MagicSquaresFitness() + + chromosome = MagicSquaresChromosome(genes=true_magic_square) + + assert fitness(chromosome) == 0 + + +def test_call_on_diagonal_change_MagicSquaresFitness(): + """GIVEN a non-magic square with a change on the major diagonal + WHEN the MagicSquaresFitness class is called + THEN the method should return the expected value. + """ + + fitness = MagicSquaresFitness() + + chromosome = MagicSquaresChromosome( + genes=MagicSquare((np.array([[9, 1, 6], [3, 5, 7], [4, 9, 2]]))) + ) + + expected_row_fitness = -1 + expected_column_fitness = -1 + expected_major_diagonal_fitness = -1 + expected_minor_diagonal_fitness = 0 + + assert fitness(chromosome) == ( + expected_row_fitness + + expected_column_fitness + + expected_major_diagonal_fitness + + expected_minor_diagonal_fitness + ) + + +def test_call_off_diagonal_change_MagicSquaresFitness(): + """GIVEN a non-magic square with a change off the diagonal + WHEN the MagicSquaresFitness class is called + THEN the method should return the expected value. + """ + + fitness = MagicSquaresFitness() + + magic_square = MagicSquaresChromosome( + genes=MagicSquare(np.array([[8, 2, 6], [3, 5, 7], [4, 9, 2]])) + ) + + expected_row_fitness = -1 + expected_column_fitness = -1 + expected_major_diagonal_fitness = 0 + expected_minor_diagonal_fitness = 0 + + assert fitness(magic_square) == ( + expected_row_fitness + + expected_column_fitness + + expected_major_diagonal_fitness + + expected_minor_diagonal_fitness + ) + + +######################################################################### +### MagicSquaresChromosomeGenerator ##################################### +######################################################################### + + +@pytest.mark.parametrize( + "side_length, expected", + [ + (2, np.array([[1, 2], [3, 4]])), + (3, np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])), + (4, np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])), + ], +) +def test_call_MagicSquaresChromosomeGenerator(side_length: int, expected: np.ndarray): + + chromosome_generator = MagicSquaresChromosomeGenerator(side_length) + + magic_square = chromosome_generator() + assert np.array_equal(magic_square.genes, expected) + + +######################################################################### +### MagicSquaresMutation ################################################ +######################################################################### + + +def test_call_MagicSquaresMutation(): + """GIVEN a magic square + WHEN the MagicSquaresMutation class is called + THEN the method should return a magic square. + """ + + mutation = MagicSquaresMutation(side_length=3) + + magic_square = MagicSquaresChromosome( + MagicSquare(np.array([[8, 1, 6], [3, 5, 7], [4, 9, 2]])) + ) + + mutated_magic_square = mutation(magic_square) + + assert not np.array_equal(mutated_magic_square.genes, magic_square.genes) + assert np.sum(np.array((mutated_magic_square.genes != magic_square.genes))) == 2 + + +######################################################################### +### magic_squares ####################################################### +######################################################################### + + +def test_magic_squares(): + side_length = 3 + best = magic_squares(side_length, age_limit=50) + assert best.genes.is_magic() diff --git a/scripts/ch09/knapsack_problem.py b/scripts/ch09/knapsack_problem.py new file mode 100644 index 0000000..7af9007 --- /dev/null +++ b/scripts/ch09/knapsack_problem.py @@ -0,0 +1,531 @@ +from __future__ import annotations + +import logging +import random +import sys +import time +from copy import deepcopy +from dataclasses import dataclass +from typing import List, Type, Union + +from src.genetic import ( + AgeAnnealing, + Chromosome, + ChromosomeGenerator, + FitnessStagnationDetector, + Mutation, + RelativeFitness, + Runner, + StoppingCriteria, +) + + +@dataclass(eq=True, frozen=True) +class Resource: + """A dataclass to represent a single resource in the knapsack problem""" + + name: str + value: int + weight: float + volume: float + + def max_quantity(self, max_weight: float, max_volume: float): + """Return the maximum number of the item that can be added to the chromosome + without exceeding the maximum weight or volume. + + Parameters + ---------- + item : Resource + The item to add to the chromosome + max_weight : float + The maximum weight allowed of the chromosome + max_volume : float + The maximum volume allowed of the chromosome + + Returns + ------- + int + The maximum number of the item that can be added to the chromosome + without exceeding the maximum weight or volume + """ + + return min( + int(max_weight / self.weight) if self.weight > 0 else sys.maxsize, + int(max_volume / self.volume) if self.volume > 0 else sys.maxsize, + ) + + +@dataclass +class ResourceQuantity: + """A dataclass to represent the quantity of a resource in the knapsack problem""" + + resource: Resource + quantity: int + + +class KnapsackChromosome(Chromosome): + """Chromosome for the magic squares problem.""" + + def __init__(self, genes: List[ResourceQuantity], age: int = 0) -> None: + """Create a new chromosome. + + Parameters + ---------- + genes : List[Resource] + A list of resources + age : int, optional + The age of the chromosome, by default 0 + """ + self.genes = genes + self.age = age + + def __len__(self) -> int: + """Return the length of the chromosome.""" + return len(self.genes) + + def __getitem__(self, index: int): + """Return the gene at the given index.""" + return self.genes[index] + + def __str__(self) -> str: + """Return a visualisation of the chromosome.""" + return str(self.genes) + + def __repr__(self) -> str: + """Return a visualisation of the chromosome.""" + return str(self.genes) + + @property + def total_weight(self) -> float: + """Return the total weight of the chromosome.""" + return sum( + [ + resource_quantity.resource.weight * resource_quantity.quantity + for resource_quantity in self.genes + ] + ) + + @property + def total_volume(self) -> float: + """Return the total volume of the chromosome.""" + return sum( + [ + resource_quantity.resource.volume * resource_quantity.quantity + for resource_quantity in self.genes + ] + ) + + @property + def total_value(self) -> float: + """Return the total value of the chromosome.""" + return sum( + [ + resource_quantity.resource.value * resource_quantity.quantity + for resource_quantity in self.genes + ] + ) + + def remaining_weight( + self, + max_weight: float, + ) -> float: + """Calculate the remaining weight of the knapsack. + + Parameters + ---------- + max_weight : float + The maximum weight of the knapsack. + + Returns + ------- + float + The remaining weight of the knapsack. + """ + + return max_weight - self.total_weight + + def remaining_volume( + self, + max_volume: float, + ) -> float: + """Calculate the remaining volume of the knapsack. + + Parameters + ---------- + max_volume : float + The maximum volume of the knapsack. + + Returns + ------- + float + The remaining volume of the knapsack. + """ + + return max_volume - self.total_volume + + +class KnapsackFitness(RelativeFitness): + """Fitness function of the magic knapsack problem.""" + + def __init__(self, chromosome: KnapsackChromosome) -> None: + self.chromosome = chromosome + + def __gt__(self, other: KnapsackFitness) -> bool: + """Return true if the fitness of the current chromosome is better than + the fitness of the other chromosome. In the knapsack problem the fitness + is the total value of the resources in the knapsack. If the total value + is the same then the fitness is the total weight of the resources in the + knapsack. If the total weight is the same then the fitness is the total + volume of the resources in the knapsack. + """ + + if self.chromosome.total_value != other.chromosome.total_value: + return self.chromosome.total_value > other.chromosome.total_value + + if self.chromosome.total_weight != other.chromosome.total_weight: + return self.chromosome.total_weight < other.chromosome.total_weight + + return self.chromosome.total_volume < other.chromosome.total_volume + + +class KnapsackMutation(Mutation): + """Mutation function of the knapsack problem.""" + + def __init__( + self, + gene_set: List[Resource], + max_weight: float, + max_volume: float, + ): + self.gene_set = gene_set + self.max_weight = max_weight + self.max_volume = max_volume + self.remaining_weight = max_weight + self.remaining_volume = max_volume + + def __call__(self, parent: KnapsackChromosome): + + genes = deepcopy(parent.genes) + + if self.choose_to_remove_item(genes): + genes = self.remove_random_item(genes) + # We don’t immediately return when removing an item because we know + # removing an item reduces the fitness. + + if self.choose_to_add_item(genes): + genes = self.add_random_item(genes) + return KnapsackChromosome(genes, parent.age) + + # If we get to this point, we have removed an item and not added a new item. + # So now we will change the quantity of an existing item. + self.change_item_quantity(genes) + + genes = sorted(genes, key=lambda x: x.resource.name) + + return KnapsackChromosome(genes, parent.age) + + def change_item_quantity(self, genes): + idx = random.randrange(0, len(genes)) + resource_to_change = genes[idx].resource + + # add an amount between 1 and the maximum amount that can be added + # without exceeding the maximum weight or volume. + max_quantity = resource_to_change.max_quantity( + KnapsackChromosome(genes).remaining_weight(self.max_weight), + KnapsackChromosome(genes).remaining_volume(self.max_volume), + ) + + if max_quantity > 0: + new_quantity = random.randint(1, max_quantity) + genes[idx] = ResourceQuantity(resource_to_change, new_quantity) + else: + # if the maximum quantity is zero, then we remove the gene. + del genes[idx] + + def choose_to_change_item(self, genes: List[ResourceQuantity]) -> bool: + """Return true if a random item should be changed in the knapsack. + + Then we give the algorithm a chance to pick a different item type. + + Parameters + ---------- + genes : List[ResourceQuantity] + The list of resources in the knapsack. + + Returns + ------- + bool + True if a random item should be changed in the knapsack. + """ + + rng = random.randint(0, 4) == 0 + not_all_resources_added = len(genes) < len(self.gene_set) + return not_all_resources_added and rng + + def add_random_item(self, genes): + + chromosome = KnapsackChromosome(genes) + + new_gene = add( + genes, + self.gene_set, + chromosome.remaining_weight(self.max_weight), + chromosome.remaining_volume(self.max_volume), + ) + + if new_gene is not None: + genes.append(new_gene) + + return genes + + def choose_to_add_item(self, genes: List[ResourceQuantity]) -> bool: + """Return true if a new item should be added to the knapsack. + The conditions are that the knapsack is not full and that a random + the knapsack is not full or that not all items have been added to the + knapsack and that a random number is 0. + + We’ll always add if the length is zero and when there is weight or volume + available. Otherwise, if we haven’t used all the item types, we’ll give the + algorithm a small chance of adding another item type. + + Parameters + ---------- + genes : List[ResourceQuantity] + A list of resources and their quantities + + Returns + ------- + bool + True if a new item should be added to the knapsack. + """ + + chromosome = KnapsackChromosome(genes) + + weight_ok = chromosome.remaining_weight(self.max_weight) > 0 + volume_ok = chromosome.remaining_volume(self.max_volume) > 0 + + knapsack_empty = len(genes) == 0 + not_all_resources_added = len(genes) < len(self.gene_set) + rng = random.randint(0, 100) == 0 + + return (weight_ok or volume_ok) and ( + knapsack_empty or (not_all_resources_added and rng) + ) + + @staticmethod + def remove_random_item( + genes: List[ResourceQuantity], + ) -> List[ResourceQuantity]: + """Remove a random item from the knapsack. + + Parameters + ---------- + genes : List[ResourceQuantity] + A list of resources and their quantities in the knapsack + + Returns + ------- + List[ResourceQuantity] + A list of resources and their quantities in the knapsack + """ + + idx = random.randrange(0, len(genes)) + del genes[idx] + return genes + + @staticmethod + def choose_to_remove_item(genes: List[ResourceQuantity]) -> bool: + """Return true if the mutation should remove an item from the knapsack. We + to remove an item from the knapsack if the knapsack is not empty and if + the random number generator returns 0 (happens with probability = 0.1). + + We need to give it a small chance of removing an item from the knapsack. We’ll + only do that if we have more than one item so that the knapsack is never empty. + + Parameters + ---------- + genes : List[ResourceQuantity] + A list of resources and their quantities in the knapsack + + Returns + ------- + bool + True if the mutation should remove an item from the knapsack + """ + + rng = random.randint(0, 10) == 0 + return (len(genes) > 1) and rng + + +class KnapsackStoppingCriteria(StoppingCriteria): + """Stopping criteria for the magic squares problem.""" + + def __call__(self, chromosome: KnapsackChromosome) -> bool: + """Return true if can stop the genetic algorithm. In the knapsack problem + the stopping criteria will be handled by the fitness stagnation detector + """ + return False + + +class KnapsackChromosomeGenerator(ChromosomeGenerator): + """Generate a starting chromosome for the magic squares problem. + The starting chromosome is a square matrix with the numbers 1 to n^2 + in order + """ + + def __init__( + self, gene_set: List[Resource], max_weight: float, max_volume: float + ) -> None: + self.gene_set = gene_set + self.max_weight = max_weight + self.max_volume = max_volume + + def __call__(self) -> KnapsackChromosome: + + genes = [] + remaining_weight, remaining_volume = self.max_weight, self.max_volume + + for _ in range(random.randrange(1, len(self.gene_set))): + + new_gene = add(genes, self.gene_set, remaining_weight, remaining_volume) + + if new_gene is not None: + genes.append(new_gene) + remaining_weight -= new_gene.quantity * new_gene.resource.weight + remaining_volume -= new_gene.quantity * new_gene.resource.volume + + return KnapsackChromosome(genes, age=0) + + +class KnapsackRunner(Runner): + def __init__( + self, + chromosome_generator: KnapsackChromosomeGenerator, + fitness: Type[KnapsackFitness], + stopping_criteria: StoppingCriteria, + mutate: Mutation, + age_annealing: AgeAnnealing, + fitness_stagnation_detector: FitnessStagnationDetector, + ): + super().__init__( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + fitness_stagnation_detector, + ) + + def display(self, candidate): + time_diff = time.time() - self.start_time + + logging.debug("candidate=%s", candidate) + logging.debug("total_weight=%f", candidate.total_weight) + logging.debug("total_volume=%f", candidate.total_volume) + logging.info("time=%f", time_diff) + + +def add( + genes: List[ResourceQuantity], + gene_set: List[Resource], + max_weight: float, + max_volume: float, +) -> Union[ResourceQuantity, None]: + """Choose a random item from the gene set and add it to the chromosome. Add + as many of the item as possible without exceeding the maximum weight or + volume. + + When adding an item we’re going to exclude item types that are already in the + knapsack from our options because we don’t want to have to sum multiple groups of + a particular item type. Then we pick a random item and add as much of that item to + the knapsack as we can. + + Parameters + ---------- + genes : List[ResourceQuantity] + A list of resources already in the chromosome + max_weight : float + The maximum weight allowed of the chromosome + max_volume : float + The maximum volume allowed of the chromosome + + Returns + ------- + ResourceQuantity + A resource quantity object for the new item + """ + + used_resources = {resource_quantity.resource for resource_quantity in genes} + + resource = random.choice(gene_set) + + while resource in used_resources: + resource = random.choice(gene_set) + + max_quantity = resource.max_quantity(max_weight, max_volume) + + return ResourceQuantity(resource, max_quantity) if max_quantity > 0 else None + + +def fill_knapsack( + gene_set: List[Resource], + max_weight: float, + max_volume: float, + fitness_stagnation_limit: Union[float, int] = float("inf"), + age_limit: float = float("inf"), +) -> KnapsackChromosome: + + fitness = KnapsackFitness + chromosome_generator = KnapsackChromosomeGenerator(gene_set, max_weight, max_volume) + stopping_criteria = KnapsackStoppingCriteria() + mutation = KnapsackMutation(gene_set, max_weight, max_volume) + age_annealing = AgeAnnealing(age_limit=age_limit) + + fitness_stagnation_detector = FitnessStagnationDetector( + fitness, fitness_stagnation_limit + ) + runner = KnapsackRunner( + chromosome_generator, + fitness, + stopping_criteria, + mutation, + age_annealing, + fitness_stagnation_detector, + ) + + best = runner.run() + return best + + +def main(): + + logging_format = ( + "[%(levelname)8s :%(filename)20s:%(lineno)4s - %(funcName)25s] %(message)s" + ) + logging.basicConfig(format=logging_format, level=logging.INFO) + + max_weight = 10 + max_volume = 4 + fitness_stagnation_limit = 1000 + + gene_set = [ + Resource("Flour", 1680, 0.265, 0.41), # 1 + Resource("Butter", 1440, 0.5, 0.13), # 14 + Resource("Sugar", 1840, 0.441, 0.29), # 6 + ] + + best = fill_knapsack( + gene_set, + max_weight, + max_volume, + fitness_stagnation_limit=fitness_stagnation_limit, + ) + + logging.info("best=%s", best) + logging.info("total_weight=%f", best.total_weight) + logging.info("total_volume=%f", best.total_volume) + logging.info("total_value=%f", best.total_value) + + +if __name__ == "__main__": + main() diff --git a/scripts/ch09/tests/test_knapsack_problem.py b/scripts/ch09/tests/test_knapsack_problem.py new file mode 100644 index 0000000..3b9a2b0 --- /dev/null +++ b/scripts/ch09/tests/test_knapsack_problem.py @@ -0,0 +1,605 @@ +import random +from typing import List + +import numpy as np +import pytest + +from scripts.ch09.knapsack_problem import ( + KnapsackChromosome, + KnapsackChromosomeGenerator, + KnapsackFitness, + KnapsackMutation, + KnapsackStoppingCriteria, + Resource, + ResourceQuantity, + add, + fill_knapsack, +) + + +@pytest.fixture(name="resources") +def fixture_resources() -> List[Resource]: + """Create a list of resources. + + Returns + ------- + List[Resource] + A list of resources. + + """ + return [ + Resource("Flour", 1680, 0.265, 0.41), + Resource("Butter", 1440, 0.5, 0.13), + Resource("Sugar", 1840, 0.441, 0.29), + ] + + +@pytest.fixture(name="resource_quantities") +def fixture_resource_quantities(resources) -> List[ResourceQuantity]: + """Create a list of resource quantities. The quantity of each resource is + 1,2,3. + + Parameters + ---------- + resources : List[Resource] + A list of resources. + + Returns + ------- + List[ResourceQuantity] + A list of resource quantities. + + """ + return [ + ResourceQuantity(resource, amount + 1) + for amount, resource in enumerate(resources) + ] + + +def test_init_Resource(): + + name = "Flour" + value = 1680 + weight = 0.265 + volume = 0.41 + + resource = Resource(name, value, weight, volume) + + assert resource.name == name + assert resource.value == value + assert resource.weight == weight + assert resource.volume == volume + + +def test_max_quantity_Resource(resources): + """GIVEN a resource + WHEN the max_quantity method is called with a max weight and max volume + THEN the maximum quantity of the resource that fits within the max weight and + max volume constraints is returned + """ + random.seed(1) + + max_weight = 50 + max_volume = 100 + + for resource in resources: + + max_quantity = resource.max_quantity(max_weight, max_volume) + + assert resource.weight * max_quantity <= max_weight + assert resource.volume * max_quantity <= max_volume + + assert (resource.weight * (max_quantity + 1) > max_weight) or ( + resource.volume * (max_quantity + 1) > max_volume + ) + + +def test_init_ResourceQuantity(): + """GIVEN a resource + WHEN a ResourceQuantity is created + THEN the resource and quantity are set + """ + + name = "Flour" + value = 1680 + weight = 0.265 + volume = 0.41 + + resource = Resource(name, value, weight, volume) + quantity = 3 + + resource_quantity = ResourceQuantity(resource, quantity) + + assert resource_quantity.resource == resource + assert resource_quantity.quantity == quantity + + +def test_init_KnapsackChromosome(resource_quantities): + """GIVEN a list of resource quantities + WHEN a KnapsackChromosome is created + THEN the genes and age are set + """ + + genes = resource_quantities + age = 3 + + chromosome = KnapsackChromosome(genes, age) + + assert chromosome.genes == genes + assert chromosome.age == age + + +def test_len_KnapsackChromosome(resource_quantities): + """GIVEN a list of resource quantities + WHEN the length of the chromosome is calculated + THEN the correct length is returned + """ + + chromosome = KnapsackChromosome(resource_quantities) + assert len(chromosome) == len(resource_quantities) + + +def test_getitem_KnapsackChromosome(resource_quantities): + """GIVEN a list of resource quantities + WHEN a gene is retrieved from the chromosome + THEN the correct gene is returned + """ + + chromosome = KnapsackChromosome(resource_quantities) + assert chromosome[0] == resource_quantities[0] + assert chromosome[1] == resource_quantities[1] + assert chromosome[2] == resource_quantities[2] + + +def test_total_weight_KnapsackChromosome(resource_quantities): + """GIVEN a list of resource_quantities + WHEN the total weight of the chromosome is calculated + THEN the correct total weight is returned + """ + chromosome = KnapsackChromosome(resource_quantities) + assert chromosome.total_weight == 1 * 0.265 + 2 * 0.5 + 3 * 0.441 + + +def test_total_value_KnapsackChromosome(resource_quantities): + """GIVEN a list of resource_quantities + WHEN the total value of the chromosome is calculated + THEN the correct total value is returned + """ + + chromosome = KnapsackChromosome(resource_quantities) + assert chromosome.total_value == 1 * 1680 + 2 * 1440 + 3 * 1840 + + +def test_total_volume_KnapsackChromosome(resource_quantities): + """GIVEN a list of resource_quantities + WHEN the total volume of the chromosome is calculated + THEN the correct total volume is returned + """ + chromosome = KnapsackChromosome(resource_quantities) + assert chromosome.total_volume == 1 * 0.41 + 2 * 0.13 + 3 * 0.29 + + +def test_different_total_value_KnapsackFitness(): + """GIVEN two chromosomes with different total values + WHEN the fitness of the chromosomes is compared + THEN the chromosome with the higher total value is greater + """ + + chromosome_1 = KnapsackChromosome( + [ + ResourceQuantity(Resource("Flour", 1680, 0.265, 0.41), 1), + ResourceQuantity(Resource("Butter", 1440, 0.5, 0.13), 2), + ResourceQuantity(Resource("Sugar", 1840, 0.441, 0.29), 3), + ] + ) + + # note value for flour is higher in chromosome_2 + chromosome_2 = KnapsackChromosome( + [ + ResourceQuantity(Resource("Flour", 1700, 0.265, 0.41), 1), + ResourceQuantity(Resource("Butter", 1440, 0.5, 0.13), 2), + ResourceQuantity(Resource("Sugar", 1840, 0.441, 0.29), 3), + ] + ) + + assert KnapsackFitness(chromosome_2) > KnapsackFitness(chromosome_1) + + +def test_different_total_weight_KnapsackFitness(): + """GIVEN two chromosomes with different total weights + WHEN the fitness of the chromosomes is compared + THEN the chromosome with the lower total weight is greater + """ + + chromosome_1 = KnapsackChromosome( + [ + ResourceQuantity(Resource("Flour", 1680, 0.265, 0.41), 1), + ResourceQuantity(Resource("Butter", 1440, 0.5, 0.13), 2), + ResourceQuantity(Resource("Sugar", 1840, 0.441, 0.29), 3), + ] + ) + + # note weight for flour is lower in chromosome_2 + chromosome_2 = KnapsackChromosome( + [ + ResourceQuantity(Resource("Flour", 1680, 0.25, 0.41), 1), + ResourceQuantity(Resource("Butter", 1440, 0.5, 0.13), 2), + ResourceQuantity(Resource("Sugar", 1840, 0.441, 0.29), 3), + ] + ) + + assert KnapsackFitness(chromosome_2) > KnapsackFitness(chromosome_1) + + +def test_different_total_volume_KnapsackFitness(): + """GIVEN two chromosomes with different total volumes + WHEN the fitness of the chromosomes is compared + THEN the chromosome with the lower total volume is greater + """ + + chromosome_1 = KnapsackChromosome( + [ + ResourceQuantity(Resource("Flour", 1680, 0.265, 0.41), 1), + ResourceQuantity(Resource("Butter", 1440, 0.5, 0.13), 2), + ResourceQuantity(Resource("Sugar", 1840, 0.441, 0.29), 3), + ] + ) + + # note volume for flour is lower in chromosome_2 + chromosome_2 = KnapsackChromosome( + [ + ResourceQuantity(Resource("Flour", 1680, 0.265, 0.4), 1), + ResourceQuantity(Resource("Butter", 1440, 0.5, 0.13), 2), + ResourceQuantity(Resource("Sugar", 1840, 0.441, 0.29), 3), + ] + ) + + assert KnapsackFitness(chromosome_2) > KnapsackFitness(chromosome_1) + + +def test_call_KnapsackStoppingCriteria(resources): + """GIVEN a KnapsackStoppingCriteria + WHEN the knapack problem stopping criteria is called + THEN a False value is returned + """ + + stopping_criteria = KnapsackStoppingCriteria() + + for resource in resources: + assert stopping_criteria(resource) is False + + +def test_init_KnapsackChromosomeGenerator(resources): + """GIVEN a KnapsackChromosomeGenerator + WHEN a KnapsackChromosomeGenerator is created + THEN the max_weight, max_volume are set + """ + max_weight = 50 + max_volume = 100 + + chromosome_generator = KnapsackChromosomeGenerator( + resources, max_weight, max_volume + ) + + assert chromosome_generator.gene_set == resources + assert chromosome_generator.max_weight == max_weight + assert chromosome_generator.max_volume == max_volume + + +def test_call_KnapsackChromosomeGenerator(resources): + """GIVEN a KnapsackChromosomeGenerator + WHEN the knapack problem chromosome generator is called + THEN a KnapsackChromosome is returned + """ + random.seed(1) + + max_weight = 50 + max_volume = 100 + + chromosome_generator = KnapsackChromosomeGenerator( + resources, max_weight, max_volume + ) + + chromosome = chromosome_generator() + + assert isinstance(chromosome, KnapsackChromosome) + assert len(chromosome) == 1 + assert chromosome[0].resource.name == "Sugar" + assert np.isclose(chromosome.total_weight, 49.833) + assert np.isclose(chromosome.total_volume, 32.77) + assert chromosome.total_value == 207920 + + +def test_add(resources): + """GIVEN a list of genes and a list of resources + WHEN the add method is called + THEN a resource quantity is returned that fits within the max weight and max + volume constraints + """ + random.seed(1) + + max_weight = 50 + max_volume = 100 + + genes = [] + + resource_quantity = add(genes, resources, max_weight, max_volume) + + # the resource should fit within the max weight and max volume constraints + total_weight = resource_quantity.resource.weight * resource_quantity.quantity + total_volume = resource_quantity.resource.volume * resource_quantity.quantity + + assert total_weight <= max_weight + assert total_volume <= max_volume + + # show that adding one more of the same resource would exceed the max weight or + # max volume + total_weight_with_one_more = resource_quantity.resource.weight * ( + resource_quantity.quantity + 1 + ) + + total_volume_with_one_more = resource_quantity.resource.volume * ( + resource_quantity.quantity + 1 + ) + + assert ( + total_weight_with_one_more > max_weight + or total_volume_with_one_more > max_volume + ) + + +def test_choose_to_remove_item_empty_KnapsackMutation(): + """GIVEN a KnapsackMutation + WHEN the choose_to_remove_item method is called on an empty list + THEN False is returned as there is nothing to remove + """ + + genes = [] + assert not KnapsackMutation.choose_to_remove_item(genes) + + +def test_choose_to_remove_item_single_item_KnapsackMutation(): + """GIVEN a KnapsackMutation + WHEN the choose_to_remove_item method is called on list of a single item + THEN False is returned as then there would be nothing in the knapsack + """ + + genes = [ResourceQuantity(Resource("Flour", 1680, 0.265, 0.41), 1)] + assert not KnapsackMutation.choose_to_remove_item(genes) + + +def test_choose_to_remove_item_KnapsackMutation(resource_quantities): + """GIVEN a KnapsackMutation + WHEN the choose_to_remove_item method is called on a list of genes + THEN True is returned as there is something to remove + """ + + random.seed(1) + + decisions_to_remove = [ + KnapsackMutation.choose_to_remove_item(resource_quantities) + for ii in range(10000) + ] + + # roughly 10% of the time, an item should be removed + assert sum(decisions_to_remove) == 914 + + +def test_init_KnapsackMutation(resources): + + max_weight = 50 + max_volume = 100 + + mutation = KnapsackMutation(resources, max_weight, max_volume) + + assert mutation.gene_set == resources + assert mutation.max_weight == max_weight + assert mutation.max_volume == max_volume + + +def test_remaining_weight_KnapsackChromosome(): + """GIVEN a KnapsackChromosome + WHEN the remaining_weight method is called with a max_weight + THEN the correct remaining weight is returned + """ + + max_weight = 50 + + genes = [ResourceQuantity(Resource("Flour", 1680, 0.265, 0.41), 3)] + + assert np.isclose( + KnapsackChromosome(genes).remaining_weight(max_weight), max_weight - 3 * 0.265 + ) + + +def test_remaining_weight_KnapsackChromosome(): + """GIVEN a KnapsackChromosome + WHEN the remaining_volumne method is called with a max_volumne + THEN the correct remaining volumne is returned + """ + + max_volume = 100 + + genes = [ResourceQuantity(Resource("Flour", 1680, 0.265, 0.41), 3)] + + assert np.isclose( + KnapsackChromosome(genes).remaining_volume(max_volume), max_volume - 3 * 0.41 + ) + + +def test_remove_random_item_KnapsackMutation(resources, resource_quantities): + """GIVEN a KnapsackMutation + WHEN the remove_random_item method is called on a list of genes + THEN a random item is removed from the list + """ + + random.seed(1) + + max_weight = 50 + max_volume = 100 + + mutation = KnapsackMutation(resources, max_weight, max_volume) + + genes = resource_quantities.copy() + assert len(genes) == 3 + + mutation.remove_random_item(genes) + + assert len(genes) == 2 + assert genes[0].resource.name == "Butter" + assert genes[1].resource.name == "Sugar" + + KnapsackMutation.remove_random_item(genes) + + assert len(genes) == 1 + assert genes[0].resource.name == "Sugar" + + KnapsackMutation.remove_random_item(genes) + + assert len(genes) == 0 + + +def test_choose_to_add_item_empty_KnapsackMutation(resources): + """GIVEN a KnapsackMutation + WHEN the choose_to_add_item method is called on an empty list + THEN True is returned as there is something to add + """ + + random.seed(1) + + max_weight = 50 + max_volume = 100 + + mutation = KnapsackMutation(resources, max_weight, max_volume) + + decisions_to_add = [mutation.choose_to_add_item([]) for ii in range(100)] + + assert sum(decisions_to_add) == 100 + + +def test_choose_to_add_item_not_all_items_KnapsackMutation( + resources, resource_quantities +): + """GIVEN a KnapsackMutation + WHEN the choose_to_add_item method is called on a list of genes + THEN True is returned as there is something to add + """ + + random.seed(1) + + max_weight = 50 + max_volume = 100 + + mutation = KnapsackMutation(resources, max_weight, max_volume) + + decisions_to_add = [ + mutation.choose_to_add_item(resource_quantities[:2]) for ii in range(10000) + ] + + # roughly 1% of the time, we should choose to add an item should be added + assert sum(decisions_to_add) == 83 + + +def test_add_random_item_KnapsackMutation(resources): + """GIVEN a KnapsackMutation + WHEN the add_random_item method is called on a list of genes + THEN a random item is added to the list + """ + + random.seed(1) + + max_weight = 50 + max_volume = 100 + + mutation = KnapsackMutation(resources, max_weight, max_volume) + + genes = [] + assert len(genes) == 0 + + genes = mutation.add_random_item(genes) + + assert len(genes) == 1 + assert genes[0].resource.name == "Flour" + + +def test_choose_to_change_item_full_KnapsackMutation(resources, resource_quantities): + """GIVEN a KnapsackMutation + WHEN the choose_to_change_item method is called on a full list of genes + THEN False is returned as there is nothing to change + """ + + random.seed(1) + + max_weight = 50 + max_volume = 100 + + mutation = KnapsackMutation(resources, max_weight, max_volume) + + assert not mutation.choose_to_change_item(resource_quantities) + + +def test_choose_to_change_item_empty_KnapsackMutation(resources, resource_quantities): + """GIVEN a KnapsackMutation + WHEN the choose_to_change_item method is called on an empty list + THEN True is returned as there is something to change + """ + + random.seed(2) + + max_weight = 50 + max_volume = 100 + + mutation = KnapsackMutation(resources, max_weight, max_volume) + + decisions_to_add = [ + mutation.choose_to_change_item(resource_quantities[:2]) for ii in range(10000) + ] + + # roughly 20% of the time, we should choose to add an item should be added + assert sum(decisions_to_add) == 2032 + + +def test_call_KnapsackMutation(resources, resource_quantities): + + random.seed(2) + + max_weight = 50 + max_volume = 100 + + parent = KnapsackChromosome(resource_quantities.copy()) + + mutation = KnapsackMutation(resources, max_weight, max_volume) + + child = mutation(parent) + + assert isinstance(child, KnapsackChromosome) + assert child.age == parent.age + assert child.genes != parent.genes + assert len(parent.genes) == 3 + assert len(child.genes) == 2 + + +def test_cookies_fill_knapsack(): + + random.seed(1) + + max_weight = 10 + max_volume = 4 + fitness_stagnation_limit = 1000 + + gene_set = [ + Resource("Flour", 1680, 0.265, 0.41), # 1 + Resource("Butter", 1440, 0.5, 0.13), # 14 + Resource("Sugar", 1840, 0.441, 0.29), # 6 + ] + + best = fill_knapsack( + gene_set, + max_weight, + max_volume, + fitness_stagnation_limit=fitness_stagnation_limit, + ) + + assert best.total_value == 29200 + assert best.total_weight <= max_weight + assert best.total_volume <= max_volume diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..3bdaef7 --- /dev/null +++ b/setup.py @@ -0,0 +1,10 @@ +import setuptools + +setuptools.setup( + name="GeneticAlgorithmsWithPython", + version="0.0.1", + author="Mitchell Dawson", + description="Package for genetic algorithms with Python", + packages=setuptools.find_packages(), + python_requires=">=3.9", +) diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/chess.py b/src/chess.py new file mode 100644 index 0000000..2661dca --- /dev/null +++ b/src/chess.py @@ -0,0 +1,180 @@ +from dataclasses import dataclass +from enum import Enum +from typing import List, Optional, Tuple + +import numpy as np + + +class PieceType(Enum): + """Represents the type of a chess piece.""" + + KING = "K" + QUEEN = "Q" + ROOK = "R" + BISHOP = "B" + KNIGHT = "N" + PAWN = "P" + EMPTY = "." + + +class PieceColour(Enum): + """Represents the colour of a chess piece.""" + + WHITE = "w" + BLACK = "b" + + +@dataclass +class PiecePosition: + """Represents the position of a chess piece.""" + + x: int + y: int + + def __hash__(self) -> int: + return hash((self.x, self.y)) + + def xy(self) -> Tuple[int, int]: + return self.x, self.y + + def yx(self) -> Tuple[int, int]: + return self.y, self.x + + def __str__(self): + return f"({self.x},{self.y})" + + +@dataclass +class Piece: + """Represents a chess piece.""" + + piece_type: PieceType + colour: PieceColour = PieceColour.WHITE + captured: bool = False + + def __str__(self): + if self.colour == PieceColour.WHITE: + return self.piece_type.value + else: + return self.piece_type.value.lower() + + def get_attacks(self, board) -> Tuple[PiecePosition, ...]: + """Get all the positions that this piece can attack.""" + raise NotImplementedError + + +@dataclass +class EmptyPiece(Piece): + """Represents an empty chess piece.""" + + piece_type: PieceType = PieceType.EMPTY + + def get_attacks(self, board) -> Tuple[PiecePosition, ...]: + return tuple() + + +class Board(np.ndarray): + """Represents a chess board.""" + + def __new__(cls, input_array): + obj = np.asarray(input_array).view(cls) + return obj + + @property + def height(self) -> int: + """Get the height of the board""" + return self.shape[0] + + @property + def width(self) -> int: + """Get the width of the board""" + return self.shape[1] + + @property + def total_squares(self) -> int: + """Get the total number of squares on the board""" + return self.height * self.width + + def positions( + self, piece_type: Optional[PieceType] = None, include_edges: bool = True + ): + """Get all the positions on the board""" + + if include_edges: + y_range = range(0, self.height) + x_range = range(0, self.width) + else: + y_range = range(1, self.height - 1) + x_range = range(1, self.width - 1) + + for y in y_range: + for x in x_range: + + if piece_type is None: + yield PiecePosition(x, y) + else: + if self[y, x].piece_type == piece_type: + yield PiecePosition(x, y) + + def __str__(self) -> str: + """return a visualisation of the chessboard""" + return "\n" + "\n".join( + ["".join([str(piece).rjust(3) for piece in row]) for row in self] + ) + + def __repr__(self) -> str: + """return a visualisation of the chessboard""" + return "\n" + "\n".join( + ["".join([str(piece).rjust(3) for piece in row]) for row in self] + ) + + def place(self, piece: Piece, position: PiecePosition): + """Place a piece on the board at the given position.""" + self[position.y, position.x] = piece + + def move(self, old_position: PiecePosition, new_position: PiecePosition): + """Move a piece to a new position.""" + piece = self[old_position.y, old_position.x] + self.place(piece, new_position) + self.place(EmptyPiece(), old_position) + + @staticmethod + def empty_board(height: int = 8, width: int = 8): + """Create an empty chess board.""" + return Board(np.full((height, width), Piece(PieceType.EMPTY))) + + +@dataclass +class Knight(Piece): + """Represents a knight chess piece.""" + + piece_type: PieceType = PieceType.KNIGHT + + def get_attacks( + self, position: PiecePosition, board: Board + ) -> Tuple[PiecePosition, ...]: + """Get all the positions that this piece can attack. First look for all + possible attacks, then filter out the ones that are off the board. + """ + + assert position is not None + x, y = position.xy() + + all_possible_attacks = [ + PiecePosition(x + 1, y + 2), + PiecePosition(x + 2, y + 1), + PiecePosition(x + 2, y - 1), + PiecePosition(x + 1, y - 2), + PiecePosition(x - 1, y - 2), + PiecePosition(x - 2, y - 1), + PiecePosition(x - 2, y + 1), + PiecePosition(x - 1, y + 2), + ] + + in_bounds_positions_that_can_be_attacked = [ + position + for position in all_possible_attacks + if 0 <= position.x < board.width and 0 <= position.y < board.height + ] + + return tuple(in_bounds_positions_that_can_be_attacked) diff --git a/src/cricket_fixtures/README.md b/src/cricket_fixtures/README.md new file mode 100644 index 0000000..7ece733 --- /dev/null +++ b/src/cricket_fixtures/README.md @@ -0,0 +1,21 @@ +# Cricket Fixtures + +### Setup +- I installed in a virtual environment using `pip install -e ./` +- Not many packages are required for this to run pandas, numpy, tqdm etc. + +### Entry points +- `src/cricket_fixtures/cricket_fixtures.py` +- Unit tests will show you how the implementation works + +### Data input +- See `data fixtures/raw/cricket_fixtures` + +### Output +- See the files produced in `data/processed/cricket_fixtures/outputs` +- The files are updated live during a run + +### How to make changes +- Define a new mutation function in `src/cricket_fixtures/mutation.py` +- Define a new fitness function in `src/cricket_fixtures/fitness.py` +- Reconfigure the run in `src/cricket_fixtures/cricket_fixtures.py` \ No newline at end of file diff --git a/src/cricket_fixtures/chromosome.py b/src/cricket_fixtures/chromosome.py new file mode 100644 index 0000000..0b66591 --- /dev/null +++ b/src/cricket_fixtures/chromosome.py @@ -0,0 +1,236 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Optional, Set + +import numpy as np + +from src.genetic import Chromosome + + +@dataclass(slots=True) +class Team: + """A cricket team""" + + name: str + ground: Ground + division: Division + team_num: int + + def __eq__(self, other: Team) -> bool: + return self.team_num == other.team_num + + def __hash__(self) -> int: + return hash(self.name) + + +@dataclass(slots=True) +class Ground: + """A cricket ground where fixtures are played""" + + name: str + ground_num: int + + def __hash__(self) -> int: + return hash(self.name) + + def __eq__(self, other: Ground) -> bool: + return self.name == other.name + + def __lt__(self, other: Ground) -> bool: + return self.name < other.name + + +@dataclass(slots=True) +class Division: + """A cricket division""" + + name: str + division_num: int + + def __hash__(self) -> int: + return hash(self.division_num) + + +@dataclass +class Fixture: + """A fixture between two teams""" + + home_team: Team + away_team: Team + + def __post_init__(self): + self.ground = self.home_team.ground + self.division = self.home_team.division + + def __str__(self): + return f"{self.home_team} vs {self.away_team}" + + def __repr__(self): + return f"[{self.home_team.team_num}, {self.away_team.team_num}]" + + def __eq__(self, other: Fixture) -> bool: + return self.home_team == other.home_team and self.away_team == other.away_team + + def __lt__(self, other: Optional[Fixture]) -> bool: + + if other is None: + return False + + return self.home_team.team_num < other.home_team.team_num + + def has_same_teams(self, other: Fixture) -> bool: + """Check whether this fixture involves the same teams + as another fixtures regardless of home or away + + Parameters + ---------- + other : Fixture + Another feature to compare to + + Returns + ------- + bool + True if other fixtures involves same teams + """ + return ( + self.home_team == other.home_team and self.away_team == other.away_team + ) or (self.home_team == other.away_team and self.away_team == other.home_team) + + +@dataclass +class FixtureListChromosome(Chromosome): + """Chromosome for the cricket fixtures problem.""" + + genes: np.ndarray + age: int = 0 + + def __post_init__(self): + ( + self.num_divisions, + self.season_length_in_weeks, + self.max_games_per_week, + _, + ) = self.genes.shape + + def __str__(self) -> str: + """Return a visualisation of the chromosome.""" + return str(self.genes) + + def __repr__(self) -> str: + """Return a visualisation of the chromosome.""" + return str(self.genes) + + @staticmethod + def empty( + num_divisions, + season_length_in_weeks: int, + max_games_per_week_in_largest_division: int, + ): + """Create an empty chromosome.""" + return FixtureListChromosome( + genes=np.zeros( + ( + num_divisions, + season_length_in_weeks, + max_games_per_week_in_largest_division, + 3, + ), + dtype=int, + ) + ) + + def unique_teams(self) -> Set[Team]: + """Return a set of unique teams in the chromosome.""" + + return set( + [ + fixture.home_team + for fixture in self.genes.flatten() + if fixture is not None + ] + ) + + def is_fixture_set(self, division_num: int, week_num: int, game_num: int) -> bool: + """Check whether a fixture is set at a given position + + Parameters + ---------- + division_num : int + The division number to check + week_num : int + The week number to check + game_num : int + The game number to check + + Returns + ------- + bool + True if a fixture is set at the given position, False otherwise + """ + return np.all(self.genes[division_num, week_num, game_num] != 0) + + def add_fixture( + self, fixture: Fixture, division_num: int, week_num: int, game_num: int + ) -> None: + """Add a fixture to the chromosome at a given position + + Parameters + ---------- + fixture : Fixture + A fixture to add to the chromosome + division_num : int + The division number to add the fixture to + week_num : int + The week number to add the fixture to + game_num : int + The game number to add the fixture to + """ + + self.genes[division_num, week_num, game_num, :] = [ + fixture.home_team.team_num, + fixture.away_team.team_num, + fixture.ground.ground_num, + ] + + def add_fixture_to_empty_slot(self, fixture: Fixture, division_num: int) -> None: + """Add a fixture to the chromosome at the first empty slot + + Parameters + ---------- + fixture : Fixture + A fixture to add to the chromosome + division_num : int + The division number to add the fixture to + + Raises + ------ + IndexError + If there are no empty slots in the chromosome for the given division + """ + + for game_num in range(self.max_games_per_week): + for week_num in range(self.season_length_in_weeks): + + if not self.is_fixture_set(division_num, week_num, game_num): + self.add_fixture(fixture, division_num, week_num, game_num) + return + + raise IndexError("No empty slots, Season is likely too short") + + +def print_chromosome(chromosome: FixtureListChromosome): + + for division_num in range(chromosome.num_divisions): + + print(f"Division {division_num}") + + for week_num in range(chromosome.season_length_in_weeks): + print(f"Week {week_num} (Division {division_num})") + + for fixture in chromosome.genes[division_num, week_num, :, :]: + print(f"{fixture}") + + print("") + + print("") diff --git a/src/cricket_fixtures/chromosome_generator.py b/src/cricket_fixtures/chromosome_generator.py new file mode 100644 index 0000000..eae9e48 --- /dev/null +++ b/src/cricket_fixtures/chromosome_generator.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +import itertools +import random + +from src.cricket_fixtures.chromosome import Fixture, FixtureListChromosome, Team +from src.cricket_fixtures.database import Database +from src.genetic import ChromosomeGenerator + + +class FixtureListChromosomeGenerator(ChromosomeGenerator): + def __init__(self, db: Database, season_length_in_weeks: int) -> None: + self.season_length_in_weeks = season_length_in_weeks + self.db = db + + def __call__(self) -> FixtureListChromosome: + """Generate a starting chromosome for the cricket fixture list problem. The + chromosome is an array of fixtures, with each fixture containing a home team and + an away team. The fixture list is first initialised as empty, then all possible + combinations of teams are added to the fixture list, with each team playing + home and away against each other. + + Returns + ------- + FixtureListChromosome + The starting chromosome. + """ + + chromosome = FixtureListChromosome.empty( + self.db.num_divisions(), + self.season_length_in_weeks, + self.db.get_max_games_per_week_in_largest_division(), + ) + + for division_num in range(self.db.num_divisions()): + + # find teams in this division + division_teams = self.db.get_team_nums_in_division(division_num) + + division_team_pairs = list(itertools.combinations(division_teams, 2)) + + random.shuffle(division_team_pairs) + + for team_1_num, team_2_num in division_team_pairs: + + team_1_division_name = self.db.get_division_name_by_team_num(team_1_num) + team_2_division_name = self.db.get_division_name_by_team_num(team_2_num) + + if team_1_division_name != team_2_division_name: + continue + + team_1_name = self.db.get_team_name_by_team_num(team_1_num) + + team_1 = Team( + team_1_name, + self.db.get_ground_by_team_num(team_1_num), + self.db.get_division_by_team_num(team_1_num), + team_num=team_1_num, + ) + + team_2_name = self.db.get_team_name_by_team_num(team_2_num) + + team_2 = Team( + team_2_name, + self.db.get_ground_by_team_num(team_2_num), + self.db.get_division_by_team_num(team_2_num), + team_num=team_2_num, + ) + + chromosome.add_fixture_to_empty_slot( + Fixture(team_1, team_2), division_num + ) + + chromosome.add_fixture_to_empty_slot( + Fixture(team_2, team_1), division_num + ) + + return chromosome diff --git a/src/cricket_fixtures/cricket_fixtures.py b/src/cricket_fixtures/cricket_fixtures.py new file mode 100644 index 0000000..d4e9cb3 --- /dev/null +++ b/src/cricket_fixtures/cricket_fixtures.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +import logging +import random +from pathlib import Path +from typing import Sequence, Union + +from src.cricket_fixtures.chromosome import FixtureListChromosome, print_chromosome +from src.cricket_fixtures.chromosome_generator import FixtureListChromosomeGenerator +from src.cricket_fixtures.database import Database +from src.cricket_fixtures.fitness import ( + HIGH_WEIGHT, + LOW_WEIGHT, + FixtureListFitness, + GroundClashes, + TeamsPlayingMoreThanOnceInAWeek, +) +from src.cricket_fixtures.mutation import ( + FixtureListMutation, + SwapUpToNFixturesMutation, + TheNicolaSwitchProcesserMutation, +) +from src.cricket_fixtures.report_writers import ( + FitnessDetailsReportWriter, + FitnessReportReportWriter, + FormattedGenesReportWriter, + RawGenesReportWriter, + ReportWriter, +) +from src.cricket_fixtures.stopping_criteria import FixtureListStoppingCriteria +from src.genetic import ( + AgeAnnealing, + FitnessStagnationDetector, + Mutation, + Runner, + StoppingCriteria, +) + +random.seed(42) + + +class FixtureListRunner(Runner): + def __init__( + self, + chromosome_generator: FixtureListChromosomeGenerator, + fitness: FixtureListFitness, + stopping_criteria: StoppingCriteria, + mutate: Mutation, + age_annealing: AgeAnnealing, + fitness_stagnation_detector: FitnessStagnationDetector, + report_writers: Sequence[ReportWriter], + ): + super().__init__( + chromosome_generator, + fitness, + stopping_criteria, + mutate, + age_annealing, + fitness_stagnation_detector, + ) + self.report_writers = report_writers + + def display(self, candidate): + # time_diff = time.time() - self.start_time + + # logging.info("fitness=%s", self.fitness(candidate)) + + for report_writer in self.report_writers: + report_writer.write(candidate) + + +def cricket_fixtures_problem( + db: Database, + season_length_in_weeks: int, + output_folder: Path, + fitness_stagnation_limit: Union[float, int] = float("inf"), + age_limit: float = float("inf"), +) -> FixtureListChromosome: + + target = 0 # all league fixture criteria are met + + fitness_config = { + "teams_playing_more_than_once_in_a_week": ( + HIGH_WEIGHT, + TeamsPlayingMoreThanOnceInAWeek(db), + ), + "ground_clashes": (LOW_WEIGHT, GroundClashes(db)), + } + + fitness = FixtureListFitness(db, fitness_config) + chromosome_generator = FixtureListChromosomeGenerator(db, season_length_in_weeks) + stopping_criteria = FixtureListStoppingCriteria(target, fitness) + age_annealing = AgeAnnealing(age_limit=age_limit) + + mutation = SwapUpToNFixturesMutation(2) + mutation = ( + TheNicolaSwitchProcesserMutation() + ) # <- this is the best mutation I have found so far + + fitness_stagnation_detector = FitnessStagnationDetector( + fitness, fitness_stagnation_limit + ) + + report_writers = [ + FormattedGenesReportWriter(db, output_folder), + RawGenesReportWriter(output_folder), + FitnessReportReportWriter(fitness, db, output_folder), + FitnessDetailsReportWriter(fitness, db, output_folder), + ] + + runner = FixtureListRunner( + chromosome_generator, + fitness, + stopping_criteria, + mutation, + age_annealing, + fitness_stagnation_detector, + report_writers, + ) + + best = runner.run() + return best + + +def check_season_length_validity(db: Database, season_length_in_weeks: int): + + num_division_teams = [ + len(db.get_team_nums_in_division(division_num)) + for division_num in db.division_nums() + ] + + max_division_size = max(num_division_teams) + + min_season_length_in_weeks = 2 * (max_division_size - 1) + + if not season_length_in_weeks >= min_season_length_in_weeks: + raise ValueError( + f"Season length must be at least {min_season_length_in_weeks} weeks." + ) + + +def main(): + + logging_format = ( + "[%(levelname)8s :%(filename)20s:%(lineno)4s - %(funcName)10s] %(message)s" + ) + logging.basicConfig(format=logging_format, level=logging.INFO) + + season_length_in_weeks = 27 + age_limit = 2000 + + root_folder = Path( + "/Users/mitchell.dawson/CodeProjects/GeneticAlgorithmsWithPython/" + ) + + output_folder = root_folder / "data/processed/cricket_fixtures/outputs" + + csv_file_path = root_folder / "data_fixtures/raw/cricket_fixtures/cricket_clubs.csv" + # csv_file_path = ( + # root_folder + # / "data_fixtures/raw/cricket_fixtures/three_divisions_shared_grounds.csv" + # ) + # csv_file_path = ( + # root_folder + # / "data_fixtures/raw/cricket_fixtures/three_divisions_unique_grounds.csv" + # ) + # csv_file_path = ( + # root_folder + # / "data_fixtures/raw/cricket_fixtures/single_division_unique_grounds.csv" + # ) + + db = Database(csv_file_path) + + check_season_length_validity(db, season_length_in_weeks) + + best = cricket_fixtures_problem( + db, season_length_in_weeks, output_folder, age_limit=age_limit + ) + + print_chromosome(best) + + logging.info("best=%s", best) + + +if __name__ == "__main__": + main() diff --git a/src/cricket_fixtures/database.py b/src/cricket_fixtures/database.py new file mode 100644 index 0000000..65e46c6 --- /dev/null +++ b/src/cricket_fixtures/database.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +from pathlib import Path + +import pandas as pd + +from src.cricket_fixtures.chromosome import Division, Ground + + +class Database: + def __init__(self, csv_file_path: Path) -> None: + self.csv_file_path = csv_file_path + self.df = pd.read_csv(self.csv_file_path) + self._num_divisions = None + self._division_nums = None + + def __len__(self) -> int: + return len(self.df) + + def get_team_names(self) -> list[str]: + return self.df["name"].values + + def get_team_num_by_name(self, name: str) -> int: + return self.df[self.df.name == name]["team_num"].values[0] + + def get_team_name_by_team_num(self, team_num: int) -> str: + return self.df[self.df.team_num == team_num]["name"].values[0] + + def get_ground_num_by_name(self, ground_name: str) -> int: + return self.df[self.df.ground == ground_name]["ground_num"].values[0] + + def get_ground_name_by_ground_num(self, ground_num: int) -> str: + return self.df[self.df.ground_num == ground_num]["ground"].values[0] + + def get_division_num_by_name(self, division_name: str) -> int: + return self.df[self.df.division == division_name]["division_num"].values[0] + + def get_division_name_by_division_num(self, division_num: int) -> str: + return self.df[self.df.division_num == division_num]["division"].values[0] + + def get_max_games_per_week_in_largest_division(self) -> int: + max_teams_in_a_division = self.df.groupby("division_num").size().max() + return max_teams_in_a_division // 2 + + def get_ground_by_team_num(self, team_num: int) -> Ground: + ground_name = self.df[self.df.team_num == team_num]["ground"].values[0] + ground_num = self.df[self.df.team_num == team_num]["ground_num"].values[0] + return Ground(ground_name, ground_num) + + def get_division_by_team_num(self, team_num: int) -> Division: + division_name = self.df[self.df.team_num == team_num]["division"].values[0] + division_num = self.df[self.df.team_num == team_num]["division_num"].values[0] + return Division(division_name, division_num) + + def num_divisions(self) -> int: + + if not self._num_divisions: + self._num_divisions = self.df.division_num.nunique() + + return self._num_divisions + + def get_ground_name_by_team_num(self, team_num: int) -> str: + ground_name = self.df[self.df.team_num == team_num]["ground"].values[0] + return ground_name + + def get_division_num_by_team_num(self, team_num: int) -> str: + division_name = self.df[self.df.team_num == team_num]["division_num"].values[0] + return division_name + + def get_division_name_by_team_num(self, team_num: int) -> str: + division_num = self.df[self.df.team_num == team_num]["division"].values[0] + return division_num + + def get_team_nums_in_division(self, division_num): + return list(self.df[self.df.division_num == division_num]["team_num"]) + + def division_nums(self): + + if self._division_nums is None: + self._division_nums = self.df.division_num.unique() + + return self._division_nums diff --git a/src/cricket_fixtures/fitness.py b/src/cricket_fixtures/fitness.py new file mode 100644 index 0000000..24349ef --- /dev/null +++ b/src/cricket_fixtures/fitness.py @@ -0,0 +1,471 @@ +from __future__ import annotations + +import itertools +from abc import abstractmethod +from collections import Counter +from typing import Dict, List, Tuple + +import numpy as np + +from src.cricket_fixtures.chromosome import FixtureListChromosome +from src.cricket_fixtures.database import Database +from src.genetic import AbsoluteFitness + +HIGH_WEIGHT = 100 +MEDIUM_WEIGHT = 5 +LOW_WEIGHT = 1 + + +class FixtureListGranularFitness(AbsoluteFitness): + @abstractmethod + def report(self, chromosome: FixtureListChromosome) -> List[str]: + """Returns a list of strings that can be used to report on the fitness + of the chromosome""" + + +class FitnessConfig(Dict[str, Tuple[float, FixtureListGranularFitness]]): + """A dictionary of fitness functions and their weights""" + + +class TeamsPlayingMoreThanOnceInAWeek(FixtureListGranularFitness): + """Counts the number of teams playing more than once in a week across the season""" + + def __init__(self, db: Database): + self.db = db + + def report(self, chromosome: FixtureListChromosome) -> List[str]: + """Creates a dict where each key is the team name, and each value is the number + of times that team plays more than once in a week, only for teams who play more + than once in a week over the season""" + + lines = [] + + for division_num in range(chromosome.num_divisions): + + lines.append(f"Division {division_num}\n\n") + + unique_teams = np.unique(chromosome.genes[division_num, :, :, 0:2]) + unique_teams = unique_teams[unique_teams != 0] + + for week_num in range(chromosome.season_length_in_weeks): + + teams_playing_this_week = chromosome.genes[ + division_num, week_num, :, 0:2 + ] + + team_nums, week_counts = np.unique( + teams_playing_this_week[teams_playing_this_week != 0], + return_counts=True, + ) + + team_nums = team_nums[week_counts > 1] + week_counts = week_counts[week_counts > 1] + + if len(team_nums) > 0: + lines.append(f"\tWeek {week_num}\n") + + for team_num, count in zip(team_nums, week_counts): + lines.append( + f"\t\t{self.db.get_team_name_by_team_num(team_num).title()} plays {count} times\n" + ) + lines.append(f"{'='*50}\n") + + return lines + + @staticmethod + def __call__(chromosome: FixtureListChromosome) -> int: + """This is the number of teams playing more than once in a week. Counted + across all weeks of the season + + Returns + ------- + int + The number of teams playing more than once in a week across the season + """ + total_count = 0 + + for division in range(chromosome.num_divisions): + + division_count = 0 + + for week_num in range(chromosome.season_length_in_weeks): + + teams_playing_this_week = chromosome.genes[division, week_num, :, 0:2] + + _, week_counts = np.unique( + teams_playing_this_week[teams_playing_this_week != 0], + return_counts=True, + ) + + division_count += np.sum(week_counts - 1) + + total_count += division_count + + return total_count + + +class GroundClashes(AbsoluteFitness): + """There cannot be two games at the same ground in a week""" + + def __init__(self, db: Database): + self.db = db + + def report(self, chromosome: FixtureListChromosome) -> List[str]: + """Creates a dict where each key is the ground name, and each value is the number + of times that ground is used more than once in a week, only for grounds which are + used than once in a week over the season""" + + lines = [] + + for week_num in range(chromosome.season_length_in_weeks): + + grounds_used_in_week = chromosome.genes[:, week_num, :, 2] + grounds_used_in_week = grounds_used_in_week[grounds_used_in_week != 0] + + ground_nums, week_counts = np.unique( + grounds_used_in_week, return_counts=True + ) + + ground_nums = ground_nums[week_counts > 1] + week_counts = week_counts[week_counts > 1] + + if len(ground_nums) > 0: + + lines.append(f"\tWeek {week_num}\n") + + for ground_num, count in zip(ground_nums, week_counts): + lines.append( + f"\t\t{self.db.get_ground_name_by_ground_num(ground_num).title()} is used {count} times\n" + ) + lines.append(f"{'='*50}\n") + + return lines + + @staticmethod + def __call__(chromosome: FixtureListChromosome) -> float: + + total_count = 0 + + for week_num in range(chromosome.season_length_in_weeks): + + grounds_used_in_week = chromosome.genes[:, week_num, :, 2] + grounds_used_in_week = grounds_used_in_week[grounds_used_in_week != 0] + + _, ground_counts = np.unique(grounds_used_in_week, return_counts=True) + + total_count += sum(ground_counts - 1) + + return total_count + + +class IncorrectNumberOfFixturesBetweenTwoTeams(AbsoluteFitness): + """Each pair of teams play each other home and away over a season""" + + @staticmethod + def __call__(chromosome: FixtureListChromosome) -> float: + total_count = 0 + + for division_num in range(chromosome.num_divisions): + + division_count = 0 + + fixtures_in_division = chromosome.genes[division_num, :, :, :2] + + teams_in_division = np.unique(fixtures_in_division) + teams_in_division = teams_in_division[teams_in_division != 0] + + for team_1 in teams_in_division: + for team_2 in teams_in_division: + + if team_1 == team_2: + continue + + division_count += np.abs( + np.sum(np.equal([team_1, team_2], fixtures_in_division).all(2)) + - 1 + ) + + return total_count + + +class SameTeamsPlayingConsecutively(AbsoluteFitness): + """The home and away leg of the same fixture does not happen in consecutive weeks""" + + @staticmethod + def __call__(chromosome: FixtureListChromosome) -> float: + + total_count = 0 + + for division_num in range(chromosome.num_divisions): + + division_count = 0 + + # count the number of consecutive fixtures between them + # if not 0, add to fitness + for week_1 in range(chromosome.season_length_in_weeks - 1): + + week_2 = week_1 + 1 + + # get division fixtures in week 1 + week_1_fixtures = chromosome.genes[division_num, week_1, :] + + # get division fixtures in week 2 + week_2_fixtures = chromosome.genes[division_num, week_2, :] + + week_consecutive_fixtures = [ + [ + int( + fixture_1[0] == fixture_2[1] + and fixture_1[1] == fixture_2[0] + ) + for fixture_1 in week_1_fixtures + if fixture_1[0] != 0 + ] + for fixture_2 in week_2_fixtures + if fixture_2[0] != 0 + ] + + division_count += np.sum(week_consecutive_fixtures) + + total_count += division_count + + return total_count + + +class TeamHasMoreThanOneWeekOff(AbsoluteFitness): + """A team does not have two weeks off in a row""" + + def __call__(self, chromosome: FixtureListChromosome) -> float: + total_count = 0 + + for division_num in range(chromosome.num_divisions): + + division_count = self.count_teams_has_more_than_one_week_off_in_division( + chromosome, division_num + ) + + total_count += division_count + + return total_count + + def count_teams_has_more_than_one_week_off_in_division( + self, chromosome, division_num + ): + + division_count = 0 + + # get unique teams in division + unique_teams_in_division = np.unique(chromosome.genes[division_num, :, :, 0:2]) + + unique_teams_in_division = unique_teams_in_division[ + unique_teams_in_division != 0 + ] + + # for each team + for team in unique_teams_in_division: + + longest_team_break = self.count_longest_team_break( + chromosome, division_num, team + ) + + if longest_team_break > 1: + division_count += longest_team_break - 1 + + return division_count + + def count_longest_team_break(self, chromosome, division_num, team): + longest_team_break = 0 + current_team_break = 0 + + for week_num in range(chromosome.season_length_in_weeks): + + weekly_fixtures = chromosome.genes[division_num, week_num, :] + + team_is_playing_in_week = any( + [ + fixture[0] == team or fixture[1] == team + for fixture in weekly_fixtures + if fixture[0] != 0 + ] + ) + + if team_is_playing_in_week: + current_team_break = 0 + + else: + current_team_break += 1 + + if current_team_break > longest_team_break: + longest_team_break = current_team_break + + return longest_team_break + + +class GroundUsedTwiceInARow(AbsoluteFitness): + """A ground is not used more than once in two weeks + Each venue should have at least one week rest in between games + """ + + def __call__(self, chromosome: FixtureListChromosome) -> float: + total_count = 0 + + for week_num_1 in range(chromosome.season_length_in_weeks - 1): + + week_count = 0 + + week_num_2 = week_num_1 + 1 + + week_1_grounds = chromosome.genes[:, week_num_1, :, 2].flatten() + week_2_grounds = chromosome.genes[:, week_num_2, :, 2].flatten() + + week_1_grounds = week_1_grounds[week_1_grounds != 0] + week_2_grounds = week_2_grounds[week_2_grounds != 0] + + week_count = len( + list((Counter(week_1_grounds) & Counter(week_2_grounds)).elements()) + ) + + total_count += week_count + + return total_count + + +class TeamHasMoreThanTwoHomeGamesInARow(AbsoluteFitness): + """A team should not play three home games in a row""" + + def __call__(self, chromosome: FixtureListChromosome) -> float: + + total_count = 0 + + for division_num in range(chromosome.num_divisions): + + division_count = 0 + + # get unique teams in division + unique_teams_in_division = np.unique( + chromosome.genes[division_num, :, :, 0:2].flatten() + ) + + unique_teams_in_division = unique_teams_in_division[ + unique_teams_in_division != 0 + ] + + for team in unique_teams_in_division: + + team_count = 0 + + most_consecutive_home_games = 0 + current_consecutive_home_games = 0 + + for week_num in range(chromosome.season_length_in_weeks): + + # find all fixtures in division in week + week_fixtures = [ + fixture + for fixture in chromosome.genes[division_num, week_num, :] + if fixture is not None + ] + + # if team has a home fixture + team_has_home_fixture = team in [ + fixture[0] for fixture in week_fixtures + ] + + # if team has a away fixture + team_has_away_fixture = team in [ + fixture[1] for fixture in week_fixtures + ] + + if team_has_home_fixture: + current_consecutive_home_games += 1 + + if current_consecutive_home_games > most_consecutive_home_games: + most_consecutive_home_games = current_consecutive_home_games + + elif team_has_away_fixture: + current_consecutive_home_games = 0 + else: + # team has no fixture in week + pass + + if most_consecutive_home_games > 2: + team_count += most_consecutive_home_games - 2 + + division_count += team_count + + total_count += division_count + + return total_count + + +class FixtureListFitness(AbsoluteFitness): + """Fitness function for a fixture list chromosome""" + + chromosome: FixtureListChromosome + + def __init__(self, db, fitness_config: FitnessConfig) -> None: + + self.fitness_config = fitness_config + + self.unique_teams_in_division = [ + db.get_team_nums_in_division(division_num) + for division_num in db.division_nums() + ] + + self.unique_pairs_of_teams_in_division = [ + list(itertools.combinations(teams, 2)) + for teams in self.unique_teams_in_division + ] + + multi_division_pairs_with_duplicates = [ + list(itertools.product(teams, teams)) + for teams in self.unique_teams_in_division + ] + + self.multi_division_pairs = [] + + for division_pairs_with_duplicates in multi_division_pairs_with_duplicates: + self.multi_division_pairs.append( + [ + division_pairs + for division_pairs in division_pairs_with_duplicates + if division_pairs[0] != division_pairs[1] + ] + ) + + self.empty_fixture_count_dict = [ + { + f"{team_1}_{team_2}": 0 + for team_1, team_2 in self.multi_division_pairs[division_num] + } + for division_num in db.division_nums() + ] + + def report(self, chromosome: FixtureListChromosome) -> Dict[str, List[str]]: + + return { + fitness_name: fitness_fn.report(chromosome) + for fitness_name, (weight, fitness_fn) in self.fitness_config.items() + } + + def __call__(self, chromosome: FixtureListChromosome) -> float: + """Return the fitness of a chromosome. The fitness is the absolute difference + between the sum of the rows, columns, and diagonals and the expected sum. + + Parameters + ---------- + chromosome : FixtureListChromosome + The chromosome to evaluate. + + Returns + ------- + int + The fitness of the chromosome. + """ + + return -sum( + [ + weight * fitness_fn(chromosome) + for weight, fitness_fn in self.fitness_config.values() + ] + ) diff --git a/src/cricket_fixtures/mutation.py b/src/cricket_fixtures/mutation.py new file mode 100644 index 0000000..b13dac5 --- /dev/null +++ b/src/cricket_fixtures/mutation.py @@ -0,0 +1,247 @@ +from __future__ import annotations + +import copy +import logging +import random +from abc import abstractmethod + +import numpy as np + +from src.cricket_fixtures.chromosome import FixtureListChromosome +from src.genetic import Mutation + + +class FixtureListMutation(Mutation): + """Mutation function for the magic squares problem.""" + + @abstractmethod + def mutate(self, chromosome: FixtureListChromosome) -> FixtureListChromosome: + """Mutate a chromosome.""" + + def __call__(self, parent: FixtureListChromosome) -> FixtureListChromosome: + """Mutate a chromosome by swapping two random elements. Pick two random + indices, looping until the indices are distinct, and swap the elements at those + indices. + + Parameters + ---------- + parent : FixtureListChromosome + The parent chromosome to mutate. + + Returns + ------- + FixtureListChromosome + The mutated chromosome. + """ + + copy_of_parent = copy.deepcopy(parent) + return self.mutate(copy_of_parent) + + def choose_two_fixtures(self, child): + + # Choose a random game + week_num_1 = self.choose_random_week(child) + game_num_1 = self.choose_random_game(child) + + # choose a random game from another week + while True: + week_num_2 = self.choose_random_week(child) + if week_num_1 != week_num_2: + break + + game_num_2 = self.choose_random_game(child) + + return week_num_1, game_num_1, week_num_2, game_num_2 + + @staticmethod + def choose_random_week(child): + return random.randint(0, child.season_length_in_weeks - 1) + + @staticmethod + def choose_random_game(child): + return random.randint(0, child.max_games_per_week - 1) + + @staticmethod + def swap_two_fixtures( + division_num, week_num_1, week_num_2, game_num_1, game_num_2, child + ): + + fixture_1 = np.copy(child.genes[division_num, week_num_1, game_num_1, :]) + fixture_2 = np.copy(child.genes[division_num, week_num_2, game_num_2, :]) + + child.genes[division_num, week_num_1, game_num_1, :] = fixture_2 + child.genes[division_num, week_num_2, game_num_2, :] = fixture_1 + + return child + + +class SwapUpToNFixturesMutation(FixtureListMutation): + """Mutation function which swaps up to N fixtures""" + + def __init__(self, max_num_to_swap: int): + self.max_num_to_swap = max_num_to_swap + + def mutate(self, chromosome: FixtureListChromosome) -> FixtureListChromosome: + + # for each division + divisions = random.sample( + range(chromosome.num_divisions), + k=random.randrange(1, chromosome.num_divisions + 1), + ) + + # for division_num in range(chromosome.num_divisions): + for division_num in divisions: + + for _ in range(random.randrange(1, self.max_num_to_swap + 1)): + + ( + week_num_1, + game_num_1, + week_num_2, + game_num_2, + ) = self.choose_two_fixtures(chromosome) + + logging.debug( + "Swapping week {%d}, game {%d} with week {%d}, game {%d}", + week_num_1, + game_num_1, + week_num_2, + game_num_2, + ) + + chromosome = self.swap_two_fixtures( + division_num, + week_num_1, + week_num_2, + game_num_1, + game_num_2, + chromosome, + ) + + return chromosome + + +class TheNicolaSwitchProcesserMutation(FixtureListMutation): + """I asked Nicola to take a look at the fixture list when it got to a local minimum to see + if she could see how to improve it and she came up with this. It looks for the first division + and week where a team plays twice, then tries to move one of those games to a week with a + free slot. It turns out this is ridiculously powerful and is more efficient temporally and + computationally than the random swapping mutation. This mutation alone is able to solve + the cricket fixtures problem for 16 divisions in 28 weeks with the simple fitness + (plays can’t play twice in a week, teams must all play eachother twice). + """ + + def mutate(self, chromosome: FixtureListChromosome) -> FixtureListChromosome: + + for division_num in range(chromosome.num_divisions): + + team_nums, week_nums = self.highlight_duplicate_in_division( + chromosome, division_num + ) + + for zip_ in zip(team_nums, week_nums): + + team_num, week_num = zip_ + + duplicate_fixtures, game_nums = self.find_duplicate_fixtures( + chromosome, + division_num, + week_num, + team_num, + ) + + for ii, duplicate_fixture in enumerate(duplicate_fixtures): + + for other_week_num in range(chromosome.season_length_in_weeks): + + if other_week_num == week_num: + continue + + if self.team_plays_in_week( + chromosome, + division_num, + other_week_num, + duplicate_fixture[0], + ): + continue + + if self.team_plays_in_week( + chromosome, + division_num, + other_week_num, + duplicate_fixture[1], + ): + continue + + for other_game_num in range(chromosome.max_games_per_week): + + if ( + chromosome.genes[ + division_num, other_week_num, other_game_num, 0 + ] + != 0 + ): + continue + + chromosome = self.swap_two_fixtures( + division_num, + week_num, + other_week_num, + game_nums[ii], + other_game_num, + chromosome, + ) + + return chromosome + return chromosome + + def team_plays_in_week(self, chromosome, division_num, week_num, team_num): + return np.any(chromosome.genes[division_num, week_num, :, 0:2] == team_num) + + def find_duplicate_fixtures(self, chromosome, division_num, week_num, team_num): + return ( + chromosome.genes[ + division_num, + week_num, + np.any( + chromosome.genes[division_num, week_num, :, 0:2] == team_num, axis=1 + ), + :, + ], + np.where( + np.any( + chromosome.genes[division_num, week_num, :, 0:2] == team_num, axis=1 + ) + )[0], + ) + + def highlight_duplicate_in_division(self, chromosome, division_num): + + unique_teams = np.unique(chromosome.genes[division_num, :, :, 0:2]) + unique_teams = unique_teams[unique_teams != 0] + + team_nums = [] + week_nums = [] + + for week_num in range(chromosome.season_length_in_weeks): + + teams_playing_this_week = chromosome.genes[division_num, week_num, :, 0:2] + + week_team_nums, week_counts = np.unique( + teams_playing_this_week[teams_playing_this_week != 0], + return_counts=True, + ) + + week_team_nums = week_team_nums[week_counts > 1] + week_counts = week_counts[week_counts > 1] + + # if can't find any duplicates, skip to next week + if len(week_counts) == 0: + continue + + # if can find duplicates, find the teams that are playing more than once + for team_num in week_team_nums: + team_nums.append(team_num) + week_nums.append(week_num) + + return team_nums, week_nums diff --git a/src/cricket_fixtures/report_writers.py b/src/cricket_fixtures/report_writers.py new file mode 100644 index 0000000..61f7c07 --- /dev/null +++ b/src/cricket_fixtures/report_writers.py @@ -0,0 +1,170 @@ +from abc import ABC, abstractmethod +from pathlib import Path +from typing import List + +from src.cricket_fixtures.chromosome import FixtureListChromosome +from src.cricket_fixtures.database import Database +from src.cricket_fixtures.fitness import FixtureListFitness + + +class ReportWriter(ABC): + + output_folder: Path + output_file_name: str + + @abstractmethod + def get_formatted_lines(self, candidate: FixtureListChromosome) -> List[str]: + """Get the formatted lines to write to the output file.""" + + def write(self, candidate: FixtureListChromosome): + + output_lines = self.get_formatted_lines(candidate) + + output_file = self.output_folder / self.output_file_name + + self.write_output_lines_to_file(output_lines, output_file) + + @staticmethod + def write_output_lines_to_file(output_lines: List[str], output_file: str): + + with open(output_file, "w", encoding="utf-8") as out_f: + for output_line in output_lines: + out_f.write(output_line) + + +class RawGenesReportWriter(ReportWriter): + + output_file_name = "raw_genes.txt" + + def __init__(self, output_folder: Path): + self.output_folder = output_folder + + def get_formatted_lines(self, candidate: FixtureListChromosome) -> List[str]: + + lines = [] + + for division_num in range(candidate.num_divisions): + lines.append(f"Division {division_num}\n\n") + + for week_num in range(candidate.season_length_in_weeks): + lines.append(f"\tWeek {week_num}\n") + + for game_num in range(candidate.max_games_per_week): + + fixture = candidate.genes[division_num, week_num, game_num] + + if fixture[0] == 0: + continue + + lines.append(f"\t\t{fixture}\n") + + if week_num != candidate.season_length_in_weeks - 1: + lines.append(f"\t{'- '*20}\n") + else: + lines.append("\n") + + lines.append(f"{'='*50}\n") + + return lines + + +class FormattedGenesReportWriter(ReportWriter): + + output_file_name = "formatted_genes.txt" + + def __init__(self, db: Database, output_folder: Path): + self.db = db + self.output_folder = output_folder + + self.max_team_name_length = max( + len(team_name) for team_name in self.db.get_team_names() + ) + + def pad_team_name(self, team_name: str) -> str: + return team_name.ljust(self.max_team_name_length) + + def get_formatted_lines(self, candidate: FixtureListChromosome) -> List[str]: + + lines = [] + + for division_num in range(candidate.num_divisions): + lines.append(f"Division {division_num}\n\n") + + for week_num in range(candidate.season_length_in_weeks): + lines.append(f"\tWeek {week_num}\n") + + for game_num in range(candidate.max_games_per_week): + + fixture = candidate.genes[division_num, week_num, game_num] + + if fixture[0] == 0: + continue + + home_team_name = self.pad_team_name( + self.db.get_team_name_by_team_num(fixture[0]).title() + ) + away_team_name = self.pad_team_name( + self.db.get_team_name_by_team_num(fixture[1]).title() + ) + ground_name = self.db.get_ground_name_by_ground_num( + fixture[2] + ).title() + + lines.append( + f"\t\t{home_team_name} vs {away_team_name} at {ground_name}\n" + ) + + if week_num != candidate.season_length_in_weeks - 1: + lines.append(f"\t{'- '*20}\n") + else: + lines.append("\n") + + lines.append(f"{'='*50}\n") + + return lines + + +class FitnessReportReportWriter(ReportWriter): + + output_file_name = "fitness_report.txt" + + def __init__(self, fitness: FixtureListFitness, db: Database, output_folder: Path): + + self.fitness = fitness + self.db = db + self.output_folder = output_folder + + def get_formatted_lines(self, candidate: FixtureListChromosome) -> List[str]: + + lines = [] + + lines.append(f"Candidate Fitness: {self.fitness(candidate)}\n") + + return lines + + +class FitnessDetailsReportWriter(ReportWriter): + output_file_name = "fitness_details.txt" + + def __init__(self, fitness: FixtureListFitness, db: Database, output_folder: Path): + + self.fitness = fitness + self.db = db + self.output_folder = output_folder + + def get_formatted_lines(self, candidate: FixtureListChromosome) -> List[str]: + + lines = [] + + report = self.fitness.report(candidate) + + for report_type, report_lines in report.items(): + lines.append(f"{report_type}\n\n") + lines.extend(report_lines) + lines.append("\n\n\n") + lines.append("*" * 50) + lines.append("*" * 50) + lines.append("*" * 50) + lines.append("\n\n\n") + + return lines diff --git a/src/cricket_fixtures/stopping_criteria.py b/src/cricket_fixtures/stopping_criteria.py new file mode 100644 index 0000000..7450f12 --- /dev/null +++ b/src/cricket_fixtures/stopping_criteria.py @@ -0,0 +1,15 @@ +from src.cricket_fixtures.chromosome import FixtureListChromosome +from src.cricket_fixtures.fitness import FixtureListFitness +from src.genetic import StoppingCriteria + + +class FixtureListStoppingCriteria(StoppingCriteria): + """Stopping criteria for the magic squares problem.""" + + def __init__(self, target: int, fitness: FixtureListFitness): + self.target = target + self.fitness = fitness + + def __call__(self, chromosome: FixtureListChromosome) -> bool: + """Return true if can stop the genetic algorithm.""" + return self.fitness(chromosome) >= self.target diff --git a/src/cricket_fixtures/tests/test_chromosome.py b/src/cricket_fixtures/tests/test_chromosome.py new file mode 100644 index 0000000..37bfe57 --- /dev/null +++ b/src/cricket_fixtures/tests/test_chromosome.py @@ -0,0 +1,252 @@ +import numpy as np + +from src.cricket_fixtures.chromosome import ( + Division, + Fixture, + FixtureListChromosome, + Ground, + Team, +) + +######################################################################### +### Team ################################################################ +######################################################################### + + +def test_init_Team(): + """GIVEN a team with a name, ground, division and team number + WHEN the Team is initialized + THEN the name, ground, division and team number should be set. + """ + + name = "Test Team" + team_num = 1 + ground = Ground("Test Ground", 2) + division = Division("Test Division", 3) + team = Team(name, ground, division, team_num) + assert team.name == name + assert team.ground == ground + assert team.division == division + assert team.team_num == team_num + + +def test_equal_Team(): + """GIVEN two teams with the same team number + WHEN the teams are compared + THEN the teams should be equal, even if they have different names, grounds or + divisions. + """ + + team_1_name = "Test Team 1" + team_1_ground = Ground("Test Ground 1", 1) + team_1_division = Division("Test Division 1", 1) + team_1_team_num = 1 + team_1 = Team(team_1_name, team_1_ground, team_1_division, team_1_team_num) + + team_2_name = "Test Team 2" + team_2_ground = Ground("Test Ground 2", 2) + team_2_division = Division("Test Division 2", 2) + team_2_team_num = 1 + team_2 = Team(team_2_name, team_2_ground, team_2_division, team_2_team_num) + + team_3_name = "Test Team 1" + team_3_ground = Ground("Test Ground 1", 1) + team_3_division = Division("Test Division 1", 1) + team_3_team_num = 2 + team_3 = Team(team_3_name, team_3_ground, team_3_division, team_3_team_num) + + assert team_1 == team_2 + assert team_1 != team_3 + + +######################################################################### +### Fixture ############################################################# +######################################################################### + + +def test_init_Fixture(): + """GIVEN a Fixture + WHEN the Fixture is initialized with a home team and an away team + THEN the home team and away team should be set. + """ + + team_1_name = "Test Team 1" + team_1_ground = Ground("Test Ground 1", 1) + team_1_division = Division("Test Division 1", 1) + team_1_team_num = 1 + team_1 = Team(team_1_name, team_1_ground, team_1_division, team_1_team_num) + + team_2_name = "Test Team 2" + team_2_ground = Ground("Test Ground 2", 2) + team_2_division = Division("Test Division 2", 2) + team_2_team_num = 1 + team_2 = Team(team_2_name, team_2_ground, team_2_division, team_2_team_num) + + fixture = Fixture(home_team=team_1, away_team=team_2) + + assert fixture.home_team == team_1 + assert fixture.away_team == team_2 + assert fixture.ground == team_1.ground + assert fixture.division == team_1.division + + +def test_has_same_teams_Fixture(): + """GIVEN a Fixture + WHEN the has_same_teams method is called with a fixture + THEN the method should return True if the teams involved in the fixtures are + the same. + """ + ground = Ground("Test Ground", 1) + division = Division("Test Division", 1) + + team_1 = Team("Team 1", ground, division, 1) + team_2 = Team("Team 2", ground, division, 2) + team_3 = Team("Team 3", ground, division, 3) + + fixture1 = Fixture(home_team=team_1, away_team=team_2) + fixture2 = Fixture(home_team=team_1, away_team=team_2) + fixture3 = Fixture(home_team=team_2, away_team=team_1) + fixture4 = Fixture(home_team=team_1, away_team=team_3) + + assert fixture1.has_same_teams(fixture2) + assert fixture1.has_same_teams(fixture3) + assert not fixture1.has_same_teams(fixture4) + + +######################################################################### +### FixtureList ######################################################### +######################################################################### + + +def test_empty_FixtureListChromosome(): + """GIVEN a FixtureList initialized with an empty list + WHEN the FixtureList is initialized + THEN the FixtureList should contain zeros and be of the correct shape. + """ + + num_divisions = 3 + largest_division_size = 5 + season_length_in_weeks = 7 + + # this is the most games that can be played in a week + max_games_per_week_in_largest_league = largest_division_size // 2 + + fixture_list = FixtureListChromosome.empty( + num_divisions, season_length_in_weeks, max_games_per_week_in_largest_league + ) + + assert np.all(fixture_list.genes == 0) + assert fixture_list.genes.shape == ( + num_divisions, + season_length_in_weeks, + max_games_per_week_in_largest_league, + 3, + ) + + +def test_attributes_FixtureListChromosome(): + """GIVEN a FixtureList with genes + WHEN attributes of the chromosome are queried + THEN the correct values are returned + """ + num_divisions = 3 + largest_division_size = 5 + season_length_in_weeks = 7 + + # this is the most games that can be played in a week + max_games_per_week_in_largest_league = largest_division_size // 2 + + fixture_list = FixtureListChromosome.empty( + num_divisions, season_length_in_weeks, max_games_per_week_in_largest_league + ) + + assert fixture_list.num_divisions == num_divisions + assert fixture_list.season_length_in_weeks == season_length_in_weeks + assert fixture_list.max_games_per_week == max_games_per_week_in_largest_league + + +def test_false_is_fixture_set(): + """GIVEN a FixtureList + WHEN no_fixture_set is called + THEN the method should return false if there is no in the fixture list. + """ + + num_divisions = 3 + largest_division_size = 8 + season_length_in_weeks = 7 + + # this is the most games that can be played in a week + max_games_per_week_in_largest_league = largest_division_size // 2 + + fixture_list = FixtureListChromosome.empty( + num_divisions, season_length_in_weeks, max_games_per_week_in_largest_league + ) + + assert not fixture_list.is_fixture_set(0, 0, 0) + assert not fixture_list.is_fixture_set(0, 2, 1) + + +def test_true_is_fixture_set(): + """GIVEN a FixtureList + WHEN no_fixture_set is called + THEN the method should return true if there is a fixture in the fixture list. + """ + num_divisions = 4 + largest_division_size = 8 + season_length_in_weeks = 7 + + # this is the most games that can be played in a week + max_games_per_week_in_largest_league = largest_division_size // 2 + + fixture_list = FixtureListChromosome.empty( + num_divisions, season_length_in_weeks, max_games_per_week_in_largest_league + ) + + division_num = 3 + week_num = 0 + game_num = 1 + + fixture_list.genes[division_num, week_num, game_num] = [1, 2, 1] + assert fixture_list.is_fixture_set(division_num, week_num, game_num) + + +def test_add_fixture(): + """GIVEN a FixtureList + WHEN add_fixture is called + THEN the method should add the team ids of the fixture to the fixture list. + """ + num_divisions = 4 + largest_division_size = 8 + season_length_in_weeks = 7 + + # this is the most games that can be played in a week + max_games_per_week_in_largest_league = largest_division_size // 2 + + fixture_list = FixtureListChromosome.empty( + num_divisions, season_length_in_weeks, max_games_per_week_in_largest_league + ) + + division_num = 3 + week_num = 0 + game_num = 1 + + fixture = Fixture( + home_team=Team( + "home", Ground("home ground", 1), Division("test division", division_num), 3 + ), + away_team=Team( + "away", Ground("away ground", 1), Division("test division", division_num), 2 + ), + ) + + fixture_list.add_fixture(fixture, division_num, week_num, game_num) + assert fixture_list.is_fixture_set(division_num, week_num, game_num) + + assert np.array_equal( + fixture_list.genes[division_num, week_num, game_num, :], + [ + fixture.home_team.team_num, + fixture.away_team.team_num, + fixture.ground.ground_num, + ], + ) diff --git a/src/cricket_fixtures/tests/test_chromosome_generator.py b/src/cricket_fixtures/tests/test_chromosome_generator.py new file mode 100644 index 0000000..68cf54b --- /dev/null +++ b/src/cricket_fixtures/tests/test_chromosome_generator.py @@ -0,0 +1,47 @@ +from typing import List + +import pytest + +from src.cricket_fixtures.chromosome import FixtureListChromosome, Team +from src.cricket_fixtures.cricket_fixtures import FixtureListChromosomeGenerator +from src.cricket_fixtures.database import Database + + +@pytest.fixture(name="single_division_teams_db") +def fixture_single_division_teams(data_fixtures_folder) -> List[Team]: + """Fixture to create a list of teams.""" + + csv_file_path = ( + data_fixtures_folder / "raw/cricket_fixtures/single_division_unique_grounds.csv" + ) + + db = Database(csv_file_path) + + return db + + +def test_call_FixtureListChromosomeGenerator(single_division_teams_db): + """GIVEN a FixtureListChromosomeGenerator + WHEN the FixtureListChoromosomeGenerator is called + THEN the method should return a FixtureList filled with fixtures. + """ + + num_divisions = 1 + season_length_in_weeks = len(single_division_teams_db) * 2 + + generator = FixtureListChromosomeGenerator( + single_division_teams_db, + season_length_in_weeks, + ) + + chromosome = generator() + + assert isinstance(chromosome, FixtureListChromosome) + assert chromosome.age == 0 + + assert chromosome.genes.shape == ( + num_divisions, + season_length_in_weeks, + len(single_division_teams_db) // 2, + 3, + ) diff --git a/src/cricket_fixtures/tests/test_database.py b/src/cricket_fixtures/tests/test_database.py new file mode 100644 index 0000000..2815e31 --- /dev/null +++ b/src/cricket_fixtures/tests/test_database.py @@ -0,0 +1,181 @@ +from typing import List + +import pytest + +from src.cricket_fixtures.chromosome import Team +from src.cricket_fixtures.cricket_fixtures import Database + + +@pytest.fixture(name="single_division_teams_db") +def fixture_single_division_teams(data_fixtures_folder) -> List[Team]: + """Fixture to create a list of teams.""" + + csv_file_path = ( + data_fixtures_folder / "raw/cricket_fixtures/single_division_unique_grounds.csv" + ) + + db = Database(csv_file_path) + + return db + + +@pytest.fixture(name="three_divisions_unique_grounds_teams_db") +def fixture_three_divisions_unique_grounds_teams(data_fixtures_folder) -> List[Team]: + """Fixture to create a list of teams.""" + + csv_file_path = ( + data_fixtures_folder / "raw/cricket_fixtures/three_divisions_unique_grounds.csv" + ) + + db = Database(csv_file_path) + + return db + + +@pytest.fixture(name="three_divisions_shared_grounds_teams_db") +def fixture_three_divisions_shared_grounds_teams(data_fixtures_folder) -> List[Team]: + """Fixture to create a list of teams.""" + + csv_file_path = ( + data_fixtures_folder / "raw/cricket_fixtures/three_divisions_shared_grounds.csv" + ) + + db = Database(csv_file_path) + + return db + + +def test_get_team_id_by_name(single_division_teams_db): + """GIVEN a list of teams + WHEN the team_id is retrieved by name + THEN the correct team_id should be returned. + """ + + team_id = single_division_teams_db.get_team_num_by_name("manchester united") + assert team_id == 1 + + +def test_get_team_name_by_team_num(single_division_teams_db): + """GIVEN a list of teams + WHEN the team_name is retrieved by team_num + THEN the correct team_name should be returned. + """ + + team_name = single_division_teams_db.get_team_name_by_team_num(1) + assert team_name == "manchester united" + + +def test_get_ground_num_by_name(single_division_teams_db): + """GIVEN a list of teams + WHEN the ground_id is retrieved by name + THEN the correct ground_id should be returned. + """ + + ground_id = single_division_teams_db.get_ground_num_by_name("old trafford") + assert ground_id == 1 + + +def test_get_ground_name_by_ground_num(single_division_teams_db): + """GIVEN a list of teams + WHEN the ground_name is retrieved by ground_num + THEN the correct ground_name should be returned. + """ + + ground_name = single_division_teams_db.get_ground_name_by_ground_num(1) + assert ground_name == "old trafford" + + +def test_get_division_num_by_name(single_division_teams_db): + """GIVEN a list of teams + WHEN the division_id is retrieved by name + THEN the correct division_id should be returned. + """ + + division_id = single_division_teams_db.get_division_num_by_name("premier league") + assert division_id == 0 + + +def test_get_division_name_by_division_num(single_division_teams_db): + """GIVEN a list of teams + WHEN the division_name is retrieved by division_num + THEN the correct division_name should be returned. + """ + + division_name = single_division_teams_db.get_division_name_by_division_num(0) + assert division_name == "premier league" + + +def test_get_max_games_per_week_in_largest_division(single_division_teams_db): + """GIVEN a list of teams + WHEN the max_games_per_week_in_largest_division is retrieved + THEN the correct max_games_per_week_in_largest_division should be returned. + """ + + max_games_per_week_in_largest_division = ( + single_division_teams_db.get_max_games_per_week_in_largest_division() + ) + assert max_games_per_week_in_largest_division == 4 + + +def test_num_divisions(three_divisions_shared_grounds_teams_db): + """GIVEN a list of teams + WHEN the number of divisions is retrieved + THEN the correct number of divisions should be returned. + """ + + num_divisions = three_divisions_shared_grounds_teams_db.num_divisions() + assert num_divisions == 3 + + +def test_get_ground_name_by_team_num(single_division_teams_db): + """GIVEN a list of teams + WHEN the ground is retrieved by team_num + THEN the correct ground should be returned. + """ + + ground = single_division_teams_db.get_ground_name_by_team_num(1) + assert ground == "old trafford" + + +def test_get_division_name_by_team_num(single_division_teams_db): + """GIVEN a list of teams + WHEN the division is retrieved by team_num + THEN the correct division should be returned. + """ + + division = single_division_teams_db.get_division_name_by_team_num(1) + assert division == "premier league" + + +def test_read_single_division_Dataset(single_division_teams_db): + assert single_division_teams_db.df["division"].unique() == ["premier league"] + + +def test_read_three_division_unique_grounds_Dataset( + three_divisions_unique_grounds_teams_db, +): + + assert set(three_divisions_unique_grounds_teams_db.df["division"].unique()) == set( + [ + "premier league", + "championship", + "division 2", + ] + ) + + assert len(three_divisions_unique_grounds_teams_db.df["ground"].unique()) == 31 + + +def test_read_three_division_shared_grounds_Dataset( + three_divisions_shared_grounds_teams_db, +): + + assert set(three_divisions_shared_grounds_teams_db.df["division"].unique()) == set( + [ + "premier league", + "championship", + "division 2", + ] + ) + + assert len(three_divisions_shared_grounds_teams_db.df["ground"].unique()) == 20 diff --git a/src/cricket_fixtures/tests/test_fitness.py b/src/cricket_fixtures/tests/test_fitness.py new file mode 100644 index 0000000..8bd258d --- /dev/null +++ b/src/cricket_fixtures/tests/test_fitness.py @@ -0,0 +1,187 @@ +import numpy as np +import pytest + +from src.cricket_fixtures.chromosome import FixtureListChromosome +from src.cricket_fixtures.fitness import ( + GroundClashes, + GroundUsedTwiceInARow, + IncorrectNumberOfFixturesBetweenTwoTeams, + SameTeamsPlayingConsecutively, + TeamHasMoreThanOneWeekOff, + TeamHasMoreThanTwoHomeGamesInARow, + TeamsPlayingMoreThanOnceInAWeek, +) + + +def get_two_team_one_division_fixture_list_chromosome(): + """A fixture for a two team fixture list chromosome""" + + genes = np.array( + [ + [ + [[1, 2, 1]], + [[2, 1, 2]], + ] + ] + ) + assert genes.shape == (1, 2, 1, 3) + return FixtureListChromosome(genes=genes) + + +def get_two_team_one_division_with_zeros_fixture_list_chromosome(): + """A fixture for a two team fixture list chromosome""" + + genes = np.array( + [ + [ + [[1, 2, 1], [0, 0, 0]], + [[2, 1, 2], [0, 0, 0]], + [[0, 0, 0], [0, 0, 0]], + [[0, 0, 0], [0, 0, 0]], + ] + ] + ) + assert genes.shape == (1, 4, 2, 3) + return FixtureListChromosome(genes=genes) + + +def get_two_team_two_division_fixture_list_chromosome(): + """A fixture for a two team fixture list chromosome""" + + genes = np.array( + [ + [ + [[1, 2, 1]], + [[2, 1, 2]], + ], + [ + [[3, 4, 1]], + [[4, 3, 2]], + ], + ] + ) + assert genes.shape == (2, 2, 1, 3) + return FixtureListChromosome(genes=genes) + + +def get_three_team_one_division_fixture_list_chromosome(): + """A fixture for a three team fixture list chromosome""" + + genes = np.array( + [ + [ + [[1, 3, 1]], + [[1, 2, 1]], + [[2, 1, 2]], + [[3, 1, 3]], + [[3, 2, 3]], + [[2, 3, 2]], + ] + ] + ) + + assert genes.shape == (1, 6, 1, 3) + return FixtureListChromosome(genes=genes) + + +@pytest.mark.parametrize( + "chromosome,expected_fitness", + [ + (get_three_team_one_division_fixture_list_chromosome(), 0), + (get_two_team_one_division_fixture_list_chromosome(), 0), + (get_two_team_one_division_with_zeros_fixture_list_chromosome(), 0), + (get_two_team_two_division_fixture_list_chromosome(), 2), + ], +) +def test_call_GroundClashes(chromosome, expected_fitness): + """GIVEN a fixture list chromosome + WHEN the ground clashes fitness function is called + THEN the number of ground clashes should be returned. + """ + + fitness = GroundClashes() + assert fitness(chromosome) == expected_fitness + + +@pytest.mark.parametrize( + "chromosome,expected_fitness", + [ + (get_three_team_one_division_fixture_list_chromosome(), 0), + (get_two_team_one_division_fixture_list_chromosome(), 0), + (get_two_team_one_division_with_zeros_fixture_list_chromosome(), 0), + (get_two_team_two_division_fixture_list_chromosome(), 0), + ], +) +def test_call_IncorrectNumberOfFixturesBetweenTwoTeams(chromosome, expected_fitness): + fitness = IncorrectNumberOfFixturesBetweenTwoTeams() + assert fitness(chromosome) == expected_fitness + + +@pytest.mark.parametrize( + "chromosome,expected_fitness", + [ + (get_three_team_one_division_fixture_list_chromosome(), 2), + (get_two_team_one_division_fixture_list_chromosome(), 1), + (get_two_team_one_division_with_zeros_fixture_list_chromosome(), 1), + (get_two_team_two_division_fixture_list_chromosome(), 2), + ], +) +def test_call_SameTeamsPlayingConsecutively(chromosome, expected_fitness): + fitness = SameTeamsPlayingConsecutively() + assert fitness(chromosome) == expected_fitness + + +@pytest.mark.parametrize( + "chromosome,expected_fitness", + [ + (get_three_team_one_division_fixture_list_chromosome(), 0), + (get_two_team_one_division_fixture_list_chromosome(), 0), + (get_two_team_one_division_with_zeros_fixture_list_chromosome(), 0), + (get_two_team_two_division_fixture_list_chromosome(), 0), + ], +) +def test_call_TeamsPlayingMoreThanOnceInAWeek(chromosome, expected_fitness): + fitness = TeamsPlayingMoreThanOnceInAWeek() + assert fitness(chromosome) == expected_fitness + + +@pytest.mark.parametrize( + "chromosome,expected_fitness", + [ + (get_three_team_one_division_fixture_list_chromosome(), 2), + (get_two_team_one_division_fixture_list_chromosome(), 0), + (get_two_team_one_division_with_zeros_fixture_list_chromosome(), 2), + (get_two_team_two_division_fixture_list_chromosome(), 0), + ], +) +def test_call_TeamHasMoreThanOneWeekOff(chromosome, expected_fitness): + fitness = TeamHasMoreThanOneWeekOff() + assert fitness(chromosome) == expected_fitness + + +@pytest.mark.parametrize( + "chromosome,expected_fitness", + [ + (get_three_team_one_division_fixture_list_chromosome(), 2), + (get_two_team_one_division_fixture_list_chromosome(), 0), + (get_two_team_one_division_with_zeros_fixture_list_chromosome(), 0), + (get_two_team_two_division_fixture_list_chromosome(), 0), + ], +) +def test_call_GroundUsedTwiceInARow(chromosome, expected_fitness): + fitness = GroundUsedTwiceInARow() + assert fitness(chromosome) == expected_fitness + + +@pytest.mark.parametrize( + "chromosome,expected_fitness", + [ + (get_three_team_one_division_fixture_list_chromosome(), 0), + (get_two_team_one_division_fixture_list_chromosome(), 0), + (get_two_team_one_division_with_zeros_fixture_list_chromosome(), 0), + (get_two_team_two_division_fixture_list_chromosome(), 0), + ], +) +def test_call_TeamHasMoreThanTwoHomeGamesInARow(chromosome, expected_fitness): + fitness = TeamHasMoreThanTwoHomeGamesInARow() + assert fitness(chromosome) == expected_fitness diff --git a/src/cricket_fixtures/tests/test_mutation.py b/src/cricket_fixtures/tests/test_mutation.py new file mode 100644 index 0000000..bca84b7 --- /dev/null +++ b/src/cricket_fixtures/tests/test_mutation.py @@ -0,0 +1,272 @@ +import random + +import numpy as np + +from src.cricket_fixtures.chromosome import FixtureListChromosome +from src.cricket_fixtures.mutation import ( + SwapUpToNFixturesMutation, + TheNicolaSwitchProcesserMutation, +) + + +def get_three_team_one_division_fixture_list_chromosome(): + """A fixture for a three team fixture list chromosome""" + + genes = np.array( + [ + [ + [[1, 3, 1]], + [[1, 2, 1]], + [[2, 1, 2]], + [[3, 1, 3]], + [[3, 2, 3]], + [[2, 3, 2]], + ] + ] + ) + + assert genes.shape == (1, 6, 1, 3) + return FixtureListChromosome(genes=genes) + + +def get_hard_test_case(): + + genes = np.array( + [ + [ + [ + [16, 10, 16], + [11, 15, 11], + [18, 19, 18], + [20, 13, 20], + [17, 9, 17], + [0, 0, 0], + ], + [ + [19, 18, 19], + [20, 15, 20], + [10, 12, 10], + [12, 9, 12], + [16, 17, 16], + [14, 11, 14], + ], + [ + [16, 11, 16], + [9, 17, 9], + [20, 16, 20], + [13, 19, 13], + [10, 15, 10], + [14, 18, 14], + ], + [ + [16, 18, 16], + [10, 17, 10], + [20, 9, 20], + [15, 13, 15], + [11, 14, 11], + [12, 19, 12], + ], + [ + [13, 18, 13], + [16, 15, 16], + [17, 14, 17], + [9, 18, 9], + [18, 10, 18], + [19, 20, 19], + ], + [ + [11, 9, 11], + [10, 19, 10], + [12, 14, 12], + [16, 20, 16], + [15, 17, 15], + [18, 14, 18], + ], + [ + [12, 11, 12], + [9, 13, 9], + [10, 16, 10], + [17, 15, 17], + [18, 11, 18], + [14, 20, 14], + ], + [ + [10, 13, 10], + [16, 9, 16], + [20, 12, 20], + [17, 11, 17], + [15, 11, 15], + [14, 12, 14], + ], + [ + [18, 13, 18], + [12, 15, 12], + [10, 14, 10], + [17, 16, 17], + [9, 20, 9], + [0, 0, 0], + ], + [ + [15, 12, 15], + [19, 9, 19], + [14, 19, 14], + [18, 20, 18], + [16, 13, 16], + [17, 10, 17], + ], + [ + [10, 20, 10], + [19, 12, 19], + [17, 18, 17], + [16, 14, 16], + [13, 11, 13], + [15, 19, 15], + ], + [ + [10, 11, 10], + [18, 16, 18], + [13, 12, 13], + [17, 20, 17], + [19, 10, 19], + [9, 14, 9], + ], + [ + [20, 17, 20], + [13, 15, 13], + [9, 11, 9], + [16, 12, 16], + [14, 10, 14], + [0, 0, 0], + ], + [ + [14, 17, 14], + [9, 16, 9], + [15, 20, 15], + [12, 18, 12], + [11, 19, 11], + [13, 10, 13], + ], + [ + [15, 18, 15], + [9, 10, 9], + [11, 12, 11], + [19, 14, 19], + [17, 13, 17], + [0, 0, 0], + ], + [ + [11, 13, 11], + [15, 16, 15], + [9, 12, 9], + [14, 13, 14], + [20, 10, 20], + [17, 19, 17], + ], + [ + [18, 15, 18], + [12, 16, 12], + [13, 14, 13], + [11, 17, 11], + [20, 19, 20], + [10, 9, 10], + ], + [ + [10, 18, 10], + [12, 17, 12], + [14, 15, 14], + [19, 13, 19], + [20, 11, 20], + [16, 19, 16], + ], + [ + [19, 11, 19], + [15, 14, 15], + [13, 9, 13], + [20, 18, 20], + [18, 12, 18], + [0, 0, 0], + ], + [ + [12, 13, 12], + [19, 17, 19], + [20, 14, 20], + [11, 16, 11], + [18, 17, 18], + [15, 9, 15], + ], + [ + [15, 10, 15], + [17, 12, 17], + [13, 20, 13], + [18, 9, 18], + [11, 18, 11], + [19, 16, 19], + ], + [ + [14, 9, 14], + [11, 20, 11], + [13, 16, 13], + [19, 15, 19], + [12, 10, 12], + [0, 0, 0], + ], + [ + [11, 10, 11], + [13, 17, 13], + [14, 16, 14], + [9, 19, 9], + [12, 20, 12], + [9, 15, 9], + ], + ] + ] + ) + + assert genes.shape == (1, 23, 6, 3) + return FixtureListChromosome(genes=genes) + + +def test_call_TheNicolaSwitchProcesserMutation(): + random.seed(1) + + parent = get_hard_test_case() + + mutation = TheNicolaSwitchProcesserMutation() + + child = mutation(parent) + + +def test_call_SwapUpToNFixturesMutation(): + random.seed(1) + + max_num_fixtures_to_swap = 2 + + parent = get_three_team_one_division_fixture_list_chromosome() + + mutation = SwapUpToNFixturesMutation(max_num_fixtures_to_swap) + + child = mutation(parent) + + assert child.genes.shape == (1, 6, 1, 3) + assert child.genes[0, 0, 0, 0] == 1 + + assert np.array_equal( + parent.genes, get_three_team_one_division_fixture_list_chromosome().genes + ) + assert not np.array_equal(child.genes, parent.genes) + + assert np.array_equal( + child.genes, + np.array( + [ + [ + [[1, 3, 1]], + [[1, 2, 1]], + [[3, 2, 3]], + [[3, 1, 3]], + [[2, 1, 2]], + [[2, 3, 2]], + ] + ] + ), + ) diff --git a/src/genetic.py b/src/genetic.py new file mode 100644 index 0000000..7c54e56 --- /dev/null +++ b/src/genetic.py @@ -0,0 +1,406 @@ +from __future__ import annotations + +import copy +import sys + +from tqdm import tqdm + +# File: genetic.py +# from chapter 1 of _Genetic Algorithms with Python_ +# +# Author: Clinton Sheppard +# Copyright (c) 2016 Clinton Sheppard +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing +# permissions and limitations under the License. + + +print(sys.path) + + +import logging +import random +import time +from abc import ABC, abstractmethod +from bisect import bisect_left +from copy import deepcopy +from math import exp +from typing import Any, List, Optional, Protocol, Tuple, Type, Union + + +class Gene(Protocol): + pass + + +class Chromosome(Protocol): + """Chromosome for the genetic algorithm.""" + + genes: Any + age: int + + @abstractmethod + def __str__(self) -> str: + """Return a string representation of the chromosome.""" + + @abstractmethod + def __repr__(self) -> str: + """Return a string representation of the chromosome.""" + + +class GeneSet(Protocol): + """Gene set for the genetic algorithm.""" + + +class Generation: + pass + + +class Fitness(ABC): + """Fitness is the abstract base class for fitness functions.""" + + +class AbsoluteFitness(Fitness): + """AbsoluteFitness is a fitness function that returns the absolute value + of the candidate fitness + """ + + @abstractmethod + def __call__(self, chromosome: Chromosome) -> float: + """Return a fitness score for the guess""" + + +class RelativeFitness(Fitness): + """A fitness function that can be computed from the chromosome's genes.""" + + def __init__(self, chromosome: Chromosome): + self.chromosome = chromosome + + @abstractmethod + def __gt__(self, other: RelativeFitness) -> bool: + """Return True if this fitness is better than the other.""" + + +class Mutation(ABC): + """Abstract base class for mutation functions.""" + + @abstractmethod + def __call__(self, parent: Chromosome) -> Chromosome: + """Mutate the parent to create a child""" + + +class Selection: + pass + + +class Crossover: + pass + + +class Population: + pass + + +class StoppingCriteria(ABC): + """Abstract base class for stopping criteria functions.""" + + @abstractmethod + def __call__(self, chromosome: Chromosome) -> bool: + """Return true if can stop the genetic algorithm.""" + + +class ChromosomeGenerator(ABC): + """Abstract base class for generating chromosomes.""" + + gene_set: Any + + @abstractmethod + def __call__(self) -> Chromosome: + """Generate a chromosome from the gene set""" + + +class AgeAnnealing: + """Class for annealing the genetic algorithm process based on a chromosomes age. + Annealing is done by reducing the mutation rate as the chromosome ages. + """ + + def __init__(self, age_limit: float = float("inf")): + self.age_limit = age_limit + self.historical_fitnesses: List[float] = [] + + +class Runner(ABC): + """Class for running the genetic algorithm.""" + + start_time: float + iteration_num: int + best_parent: Chromosome + parent: Chromosome + child: Chromosome + + def __init__( + self, + chromosome_generator: ChromosomeGenerator, + fitness: Fitness, + stopping_criteria: StoppingCriteria, + mutate: Mutation, + age_annealing: AgeAnnealing, + fitness_stagnation_detector: FitnessStagnationDetector, + ) -> None: + + self.iteration_num = 0 + self.chromosome_generator = chromosome_generator + self.fitness = fitness + self.stopping_criteria = stopping_criteria + self.mutate = mutate + self.age_annealing = age_annealing + self.fitness_stagnation_detector = fitness_stagnation_detector + + @abstractmethod + def display(self, candidate): + """Display the candidate in a runner specific way""" + + def run(self) -> Chromosome: + """Run the genetic algorithm. + + Returns + ------- + Chromosome + The best chromosome found + """ + logging.info("Starting genetic algorithm run") + self.start_time = time.time() + + self.best_parent = self.chromosome_generator() + logging.info("Initial chromosome: %s", self.best_parent) + + if self.stopping_criteria(self.best_parent): + raise StoppingCriteriaMet(self.best_parent, self.iteration_num) + + logging.debug("Adding initial chromosome fitness to historical fitnesses") + self.age_annealing.historical_fitnesses.append(self.fitness(self.best_parent)) + + logging.debug("Creating parent copy from initial chromosome") + self.parent = deepcopy(self.best_parent) + + def generator(): + while True: # repeat until child is as good or better than the parent + yield + + for _ in tqdm(generator()): + self.iteration_num += 1 + logging.debug("Starting iteration %s", self.iteration_num) + + try: + self.main_loop() + except FitnessStagnationDetected as exception: + return exception.chromosome + except StoppingCriteriaMet as exception: + return exception.chromosome + except ContinueLoop: + continue + + def main_loop(self): + """Main loop for the genetic algorithm.""" + self.create_child() + + ( + parent_fitness, + child_fitness, + ) = self.calculate_parent_child_fitnesses() + self.compare_parent_and_child(parent_fitness, child_fitness) + + best_parent_fitness = self.fitness(self.best_parent) + self.compare_best_parent_and_child(best_parent_fitness, child_fitness) + self.check_stopping_criteria() + + self.best_parent = self.child + logging.debug("Iteration complete") + logging.debug("= " * 30) + + def calculate_parent_child_fitnesses(self) -> Tuple[float, float, float]: + return map(self.fitness, (self.parent, self.child)) + + def compare_best_parent_and_child(self, best_parent_fitness, child_fitness): + """Compare the best parent and child fitnesses.""" + + logging.debug("Comparing child to best parent...") + if best_parent_fitness < child_fitness: + logging.debug("Child is more fit than best parent") + self.best_parent = self.child + self.age_annealing.historical_fitnesses.append(best_parent_fitness) + + logging.info( + "Iteration %s - New best chromosome found: %s", + self.iteration_num, + self.best_parent, + ) + + self.display(self.child) + else: + logging.debug("Best parent is as fit or more fit than child") + + def compare_parent_and_child(self, parent_fitness, child_fitness): + """Compare the parent and child fitnesses.""" + + logging.debug("Comparing child and parent fitness...") + if parent_fitness > child_fitness: + logging.debug("Child is not as fit as parent") + self.detect_fitness_stagnation() + self.run_age_annealing(child_fitness) + + if parent_fitness == child_fitness: + self.child.age = self.parent.age + 1 + self.parent = deepcopy(self.child) + raise ContinueLoop("Child is as fit as parent") + + logging.debug("Child is more fit than parent") + self.child.age = 0 + self.parent = deepcopy(self.child) + + def check_stopping_criteria(self): + """Check if the stopping criteria has been met.""" + + logging.debug("Checking stopping criteria...") + if self.stopping_criteria(self.child): + raise StoppingCriteriaMet(self.child, self.iteration_num) + logging.debug("Stopping criteria not met by child") + + def create_child(self): + """Create a child by mutating the parent.""" + + logging.debug("Creating child by mutating parent...") + self.child = self.mutate(self.parent) + logging.debug("Child created: %s", str(self.child)) + + def detect_fitness_stagnation(self): + """Detect fitness stagnation.""" + + logging.debug("Checking fitness stagnation...") + if self.fitness_stagnation_detector(self.best_parent): + raise FitnessStagnationDetected(self.best_parent, self.iteration_num) + logging.debug("Fitness stagnation not detected") + + def run_age_annealing(self, child_fitness): + """Run age annealing.""" + + logging.debug("Checking age annealing...") + if not self.age_annealing.age_limit: + raise ContinueLoop("No age limit set, skipping age annealing") + + logging.debug("Incrementing parent age") + self.parent.age += 1 + logging.debug("Parent age: %s", self.parent.age) + + logging.debug( + "Comparing parent age to age annealing limit (%s)...", + self.age_annealing.age_limit, + ) + if self.parent.age < self.age_annealing.age_limit: + raise ContinueLoop("Parent age below limit, skipping age annealing") + + logging.debug("Parent age above limit, considering age annealing...") + index = bisect_left( + self.age_annealing.historical_fitnesses, + child_fitness, + 0, + len(self.age_annealing.historical_fitnesses), + ) + + proportion_similar = index / len(self.age_annealing.historical_fitnesses) + logging.debug( + "Proportion of historical fitnesses similar to child: %s", + proportion_similar, + ) + + if random.random() < exp(-proportion_similar): + self.parent = self.child + raise ContinueLoop("Annealing not chosen, skipping age annealing") + + logging.debug("Annealing chosen, resetting parent to best parent") + self.best_parent.age = 0 + self.parent = self.best_parent + + +class StoppingCriteriaMet(Exception): + """Exception raised when stopping criteria is met.""" + + def __init__(self, chromosome: Chromosome, iteration_num: int): + self.chromosome = chromosome + self.iteration_num = iteration_num + logging.info( + "Stopping criteria met by chromosome %s on iteration %d", + chromosome, + iteration_num, + ) + logging.debug("Iteration complete") + logging.debug("= " * 30) + + +class FitnessStagnationDetected(Exception): + """Exception raised when fitness stagnation is detected.""" + + def __init__(self, chromosome: Chromosome, iteration_num: int): + self.chromosome = chromosome + self.iteration_num = iteration_num + logging.info("Fitness stagnation detected") + logging.info("Best chromosome found: %s", chromosome) + logging.debug("Iteration complete") + logging.debug("= " * 30) + + +class ContinueLoop(Exception): + """Exception raised to continue the loop.""" + + def __init__(self, message): + logging.debug(message) + logging.debug("Iteration complete") + logging.debug("= " * 30) + + +class FitnessStagnationDetector(StoppingCriteria): + """Stop the genetic algorithm if the fitness has not improved in the + last 10 generations. + """ + + def __init__( + self, fitness: Fitness, generations_limit: Union[float, int] = float("inf") + ): + self.fitness = fitness + self.generations_limit = generations_limit + self.last_fitness = None + self.last_generation = 0 + + def __call__(self, chromosome) -> bool: + """Return true if can stop the genetic algorithm.""" + + chromosome_fitness = self.fitness(chromosome) + + if self.last_fitness is None: + self.last_fitness = chromosome_fitness + self.last_generation = 0 + logging.debug("FitnessStagnationDetection: setting first fitness") + return False + + if chromosome_fitness > self.last_fitness: + self.last_fitness = chromosome_fitness + self.last_generation = 0 + logging.debug("FitnessStagnationDetection: fitness improved") + return False + + self.last_generation += 1 + + if self.last_generation >= self.generations_limit: + logging.info( + "FitnessStagnationDetection: %s generations without improvement", + self.last_generation, + ) + + return self.last_generation >= self.generations_limit diff --git a/src/graph.py b/src/graph.py new file mode 100644 index 0000000..503d328 --- /dev/null +++ b/src/graph.py @@ -0,0 +1,185 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any, List + +import networkx as nx +from matplotlib import pyplot as plt + + +class Graph(nx.Graph): + """A graph, represented as a set of nodes and a set of edges.""" + + def set_node_attribute(self, node: Any, attribute: str, value: Any) -> None: + """Set an attribute of a node. + + Parameters + ---------- + node : Any + The node to set the attribute of. + attribute : str + The attribute to set. + value : Any + The value to set the attribute to. + + Raises + ------ + ValueError + If the node is not in the graph. + """ + if node not in self.nodes: + raise ValueError(f"Node {node} not in graph") + + nx.set_node_attributes(self, value, attribute) + + def from_col_file(self, file_name: Path) -> Graph: + """Read a graph from a .col file. This is an alternative constructor. + + Parameters + ---------- + file_name : str + The name of the file to read. + + Returns + ------- + Graph + The graph read from the file. + """ + + assert file_name.suffix == ".col" + + with open(file_name, "r") as col_file: + lines = col_file.readlines() + + ( + graph, + checksum_num_nodes, + checksum_num_edges, + ) = self._populate_graph_from_col_file(lines) + + self._validate_col_file_checksum(graph, checksum_num_nodes, checksum_num_edges) + + return graph + + def _populate_graph_from_col_file(self, lines): + + graph = self.empty_graph() + + for line in lines: + if line.startswith("c"): + continue + + elif line.startswith("p"): + _, _, checksum_num_nodes, checksum_num_edges = line.strip().split() + checksum_num_nodes = int(checksum_num_nodes) + checksum_num_edges = int(checksum_num_edges) + + elif line.startswith("e"): + node1, node2 = line.split()[1:] + graph.add_nodes_from((node1, node2)) + graph.add_edge(node1, node2) + + elif line.startswith("n"): + node = line.split()[1] + graph.add_node(node) + else: + raise ValueError(f"Unknown line type: {line}") + + return graph, checksum_num_nodes, checksum_num_edges + + @staticmethod + def empty_graph() -> Graph: + """Return an empty graph. + + Returns + ------- + Graph + An empty graph. + """ + return Graph() + + @staticmethod + def _validate_col_file_checksum(graph, checksum_num_nodes, checksum_num_edges): + + if len(graph.nodes) != checksum_num_nodes: + raise ColFileReadError( + f"Number of nodes ({len(graph.nodes)}) does not match checksum ({checksum_num_nodes})" + ) + + if len(graph.edges) != checksum_num_edges: + raise ColFileReadError( + f"Number of edges ({len(graph.edges)}) does not match checksum ({checksum_num_edges})" + ) + + def plot( + self, + output_folder: Path, + positions, + colour_map: List[str] = ["blue"], + file_name: str = "graph.png", + ) -> Path: + """Plot the graph. + + Parameters + ---------- + output_folder : Path + The folder to save the plot to. + file_name : str, optional + The name of the file to save the plot to, by default "graph.png" + + Returns + ------- + Path + The path to the plot. + """ + + output_path = output_folder / file_name + + nx.draw_networkx(self, positions, node_color=colour_map, with_labels=True) + + plt.axis("off") + plt.savefig(output_path) + + return output_path + + +class NodeColouredGraph(Graph): + """A graph where each node has a colour.""" + + @property + def colour_dict(self) -> dict: + """Return a dictionary mapping nodes to their colours. + + Returns + ------- + dict + A dictionary mapping nodes to their colours. + """ + + return nx.get_node_attributes(self, "colour") + + def node_colour_match(self, node1: Any, node2: Any) -> bool: + """Return true if the nodes have the same colour + + Parameters + ---------- + node1 : Any + The first node. + node2 : Any + The second node. + + Returns + ------- + bool + True if the nodes have the same colour. + """ + return self.nodes[node1]["colour"] == self.nodes[node2]["colour"] + + def from_col_file(self, file_name: Path) -> NodeColouredGraph: + graph = super().from_col_file(file_name) + nx.set_node_attributes(graph, None, "colour") + return NodeColouredGraph(graph) + + +class ColFileReadError(Exception): + """An error occurred while reading a .col file.""" diff --git a/src/tests/test_chess.py b/src/tests/test_chess.py new file mode 100644 index 0000000..42914cf --- /dev/null +++ b/src/tests/test_chess.py @@ -0,0 +1,214 @@ +import numpy as np + +from src.chess import Board, Knight, Piece, PieceColour, PiecePosition, PieceType + + +def test_piece_type(): + """GIVEN a piece type + WHEN the value is requested + THEN the correct value is returned + """ + + piece_type = PieceType.KING + assert piece_type.value == "K" + + piece_type = PieceType.ROOK + assert piece_type.value == "R" + + +def test_piece_colour(): + """GIVEN a piece colour + WHEN the value is requested + THEN the correct value is returned + """ + piece_colour = PieceColour.WHITE + assert piece_colour.value == "w" + + piece_colour = PieceColour.BLACK + assert piece_colour.value == "b" + + +def test_piece(): + """GIVEN a piece type and colour + WHEN the piece is created + THEN the correct piece type and colour are returned + """ + + piece_type = PieceType.KING + piece_colour = PieceColour.WHITE + piece = Piece(piece_type, piece_colour) + assert str(piece) == "K" + + piece_type = PieceType.ROOK + piece_colour = PieceColour.BLACK + piece = Piece(piece_type, piece_colour) + assert str(piece) == "r" + + +################################################################################ +### Board tests ################################################################ +################################################################################ + + +def test_empty_Board(): + """GIVEN a board + WHEN the board is created + THEN the board is empty + """ + + board = Board.empty_board() + assert board.shape == (8, 8) + assert board[0, 0] == Piece(PieceType.EMPTY) + + +def test_str_Board(): + """GIVEN a board + WHEN the board is created + THEN the board is empty + """ + + board = Board.empty_board() + print(board) + + +def test_str_with_pieces_Board(): + """GIVEN a board with some pieces on it + WHEN the board is printed + THEN the board is printed with the pieces on it + """ + + board = Board.empty_board() + + piece_1 = Piece(PieceType.KING, PieceColour.WHITE) + board.place(piece_1, PiecePosition(x=0, y=0)) + + piece_2 = Piece(PieceType.ROOK, PieceColour.BLACK) + board.place(piece_2, PiecePosition(x=3, y=1)) + + print(board) + + +def test_place_piece_Board(): + """GIVEN a board + WHEN a piece is placed on the board + THEN the piece is placed on the board + """ + + board = Board.empty_board() + piece = Piece(PieceType.KING, PieceColour.WHITE) + board.place(piece, PiecePosition(x=0, y=0)) + assert board[0, 0] == piece + + +def test_place_piece_two_pieces_Board(): + """GIVEN a board + WHEN two pieces are placed on the board + THEN the pieces found d on the board + """ + + board = Board.empty_board() + + piece_1 = Piece(PieceType.KING, PieceColour.WHITE) + board.place(piece_1, PiecePosition(x=0, y=0)) + + piece_2 = Piece(PieceType.ROOK, PieceColour.BLACK) + board.place(piece_2, PiecePosition(x=1, y=1)) + + assert board[0, 0] == piece_1 + assert board[1, 1] == piece_2 + + +def test_place_piece_replace_a_piece_Board(): + """GIVEN a board + WHEN a piece is placed on the board where another piece is already placed + THEN the new piece is placed on the board + """ + + board = Board.empty_board() + + piece_1 = Piece(PieceType.KING, PieceColour.WHITE) + board.place(piece_1, PiecePosition(x=0, y=0)) + + assert board[0, 0] == piece_1 + + piece_2 = Piece(PieceType.ROOK, PieceColour.BLACK) + board.place(piece_2, PiecePosition(x=0, y=0)) + + assert board[0, 0] == piece_2 + + +def test_move_Board(): + """GIVEN a board + WHEN a piece is moved on the board + THEN the piece is moved on the board + """ + + board = Board.empty_board() + position = PiecePosition(x=0, y=0) + piece = Knight() + board.place(piece, position) + assert board[0, 0] == piece + + board.move(position, PiecePosition(x=1, y=1)) + assert board[0, 0].piece_type == PieceType.EMPTY + assert board[1, 1] == piece + + +################################################################################ +### Knight tests ############################################################### +################################################################################ + + +def test_init_Knight(): + """GIVEN a knight + WHEN the knight is created + THEN the knight is created with the correct piece type and colour + """ + + knight = Knight(colour=PieceColour.WHITE) + assert str(knight) == "N" + + knight = Knight(colour=PieceColour.BLACK) + assert str(knight) == "n" + + +def test_get_attacks_centre_of_board_Knight(): + """GIVEN a knight + WHEN the knight is placed in the centre of the board + THEN the knight has 8 possible attacks + """ + + board = Board.empty_board(8, 8) + position = PiecePosition(x=3, y=3) + knight = Knight() + attacks = knight.get_attacks(position, board) + + assert len(attacks) == 8 + + +def test_get_attacks_edge_of_board_Knight(): + """GIVEN a knight + WHEN the knight is placed on the edge of the board + THEN the knight has 4 possible attacks + """ + + board = Board.empty_board(8, 8) + position = PiecePosition(x=0, y=3) + knight = Knight() + attacks = knight.get_attacks(position, board) + + assert len(attacks) == 4 + + +def test_get_attacks_corner_of_board_Knight(): + """GIVEN a knight + WHEN the knight is placed on the corner of the board + THEN the knight has 2 possible attacks + """ + + board = Board.empty_board(8, 8) + position = PiecePosition(x=0, y=0) + knight = Knight() + attacks = knight.get_attacks(position, board) + + assert len(attacks) == 2 diff --git a/src/tests/test_genetic.py b/src/tests/test_genetic.py new file mode 100644 index 0000000..c017c17 --- /dev/null +++ b/src/tests/test_genetic.py @@ -0,0 +1,133 @@ +import random + +from src.genetic import AbsoluteFitness, Chromosome, Mutation, RelativeFitness + + +class TestChromosome(Chromosome): + """A simple test chromosome.""" + + def __init__(self, genes: str, age: int): + self.genes = genes + self.age = age + + def __str__(self) -> str: + return f"Chromosome({self.genes}, age={self.age})" + + def __repr__(self) -> str: + return str(self) + + +class TestAbsoluteFitness(AbsoluteFitness): + def __init__(self, value: float): + self.value = value + + def __call__(self, chromosome: TestChromosome) -> float: + return len(chromosome.genes) + (chromosome.age * self.value) + + +class TestRelativeFitness(RelativeFitness): + """A simple test RelativeFitness.""" + + def __gt__(self, other: RelativeFitness) -> bool: + """A simple relative fitness. In this case a shorter chromosome is better, and + a if chromosomes are of equal length, the older one is better + + Parameters + ---------- + other : RelativeFitness + TestRelativeFitness + + Returns + ------- + bool + True if self is better than other, False otherwise + """ + + if len(self.chromosome.genes) == len(other.chromosome.genes): + return self.chromosome.age > other.chromosome.age + else: + return len(self.chromosome.genes) > len(other.chromosome.genes) + + +class TestMutation(Mutation): + """A simple test Mutation.""" + + def __init__(self, fitness: AbsoluteFitness, gene_set: str): + self.fitness = fitness + self.gene_set = gene_set + + def __call__(self, parent: TestChromosome) -> TestChromosome: + index = 0 + new_genes = parent.genes.replace(parent.genes[index], self.gene_set[index]) + return TestChromosome(genes=new_genes, age=parent.age) + + +def test_simple_Chromosome(): + """GIVEN a simple Chromosome + WHEN a new instance is created + THEN the attributes are set correctly + """ + + chromosome = TestChromosome(genes="abc", age=2) + + assert chromosome.genes == "abc" + assert chromosome.age == 2 + + assert str(chromosome) == "Chromosome(abc, age=2)" + + +def test_simple_AbsoluteFitness(): + """GIVEN a simple AbsoluteFitness + WHEN a chromosome is evaluated + THEN the correct fitness value is returned + """ + + value = 30.0 + + # len(genes) = 3, age = 2 + chromosome = TestChromosome(genes="abc", age=2) + + fitness = TestAbsoluteFitness(value=value) + + # 3 + (2*30) = 63 + assert fitness(chromosome) == 63.0 + + +def test_simple_RelativeFitness(): + """GIVEN a simple RelativeFitness + WHEN a chromosomes are compared + THEN the order of chromosome fitness is correct + """ + + chromosome_1 = TestChromosome(genes="abc", age=2) + chromosome_2 = TestChromosome(genes="abc", age=3) + chromosome_3 = TestChromosome(genes="abcd", age=2) + chromosome_4 = TestChromosome(genes="abcd", age=4) + + # shorter chromosome is better here + assert TestRelativeFitness(chromosome_1) < TestRelativeFitness(chromosome_3) + assert TestRelativeFitness(chromosome_2) < TestRelativeFitness(chromosome_3) + assert TestRelativeFitness(chromosome_1) < TestRelativeFitness(chromosome_4) + assert TestRelativeFitness(chromosome_2) < TestRelativeFitness(chromosome_4) + + # If chromosomes are of equal length, the older one is better + assert TestRelativeFitness(chromosome_1) < TestRelativeFitness(chromosome_2) + assert TestRelativeFitness(chromosome_3) < TestRelativeFitness(chromosome_4) + + +def test_call_Mutation(): + """GIVEN a simple Mutation + WHEN a chromosome is mutated + THEN the chromosome is mutated correctly + """ + + value = 30.0 + gene_set = "dcba" + chromosome = TestChromosome(genes="abc", age=2) + fitness = TestAbsoluteFitness(value=value) + mutation = TestMutation(fitness, gene_set) + + child = mutation(chromosome) + + assert child.genes == "dbc" + assert child.age == 2 diff --git a/src/tests/test_graph.py b/src/tests/test_graph.py new file mode 100644 index 0000000..eb8ffa7 --- /dev/null +++ b/src/tests/test_graph.py @@ -0,0 +1,141 @@ +import networkx as nx +import pytest + +from src.graph import Graph, NodeColouredGraph + + +@pytest.fixture +def simple_col_file(data_fixtures_folder): + return data_fixtures_folder / "raw/graph_colouring/simple.col" + + +@pytest.fixture +def adjacent_states_col_file(data_fixtures_folder): + return data_fixtures_folder / "raw/graph_colouring/adjacent_states.col" + + +def test_add_node_Graph(): + """GIVEN a graph + WHEN a node is added + THEN the node is in the graph + """ + + graph = Graph() + graph.add_node(1) + graph.add_node("a") + + assert 1 in graph.nodes + assert "a" in graph.nodes + + +def test_add_node_with_attributes_Graph(): + """GIVEN a graph + WHEN a node is added with attributes + THEN the node is in the graph with the attributes + """ + + graph = Graph() + graph.add_node(1, colour="red") + graph.add_node("a", colour="green") + + assert 1 in graph.nodes + assert "a" in graph.nodes + assert graph.nodes[1]["colour"] == "red" + assert graph.nodes["a"]["colour"] == "green" + + +def test_add_edge_Graph(): + """GIVEN a graph + WHEN an edge is added + THEN the edge is in the graph + """ + + graph = Graph() + graph.add_node(1) + graph.add_node("a") + graph.add_edge(1, "a") + + assert len(graph.edges) == 1 + assert (1, "a") in graph.edges + assert ("a", 1) in graph.edges + + +def test_adj_Graph(): + """GIVEN a graph with several nodes and edges + WHEN the adjacency list is accessed + THEN the adjacency list is correct + """ + + graph = Graph() + graph.add_node(1) + graph.add_node(2) + graph.add_node(3) + + graph.add_edge(1, 2) + graph.add_edge(2, 3) + + assert graph.adj[1] == {2: {}} + assert graph.adj[2] == {1: {}, 3: {}} + assert graph.adj[3] == {2: {}} + + +def test_from_col_file__simple_Graph(simple_col_file): + """GIVEN a col file for a simple graph + WHEN a graph is created using the col file + THEN the graph has the correct number of nodes and edges + """ + graph = Graph().from_col_file(simple_col_file) + assert len(graph.nodes) == 5 + assert len(graph.edges) == 9 + + +def test_from_col_file_states_Graph(adjacent_states_col_file): + """GIVEN a col file containing states + WHEN a graph is created using the col file + THEN the graph has the correct number of nodes and edges + """ + graph = Graph().from_col_file(adjacent_states_col_file) + assert len(graph.nodes) == 51 + assert len(graph.edges) == 107 + + +def test_plot_simple_Graph(simple_col_file, temp_folder): + """GIVEN a simple graph + WHEN the graph is plotted + THEN a file is created + """ + graph = Graph().from_col_file(simple_col_file) + positions = nx.planar_layout(graph) + output_path = graph.plot(temp_folder, positions=positions) + assert output_path.exists() + + +def test_plot_states_Graph(adjacent_states_col_file, temp_folder): + """GIVEN a simple graph + WHEN the graph is plotted + THEN a file is created + """ + graph = Graph().from_col_file(adjacent_states_col_file) + + positions = nx.planar_layout(graph) + positions = nx.spring_layout(graph, pos=positions, seed=100, k=1) + + output_path = graph.plot(temp_folder, positions=positions) + assert output_path.exists() + + +def test_from_col_file_NodeColouredGraph(simple_col_file): + """GIVEN a col file for a simple graph + WHEN a graph is created using the col file + THEN the graph has the correct number of nodes and edges + """ + graph = NodeColouredGraph().from_col_file(simple_col_file) + + assert len(graph.nodes) == 5 + assert len(graph.edges) == 9 + + assert graph.nodes["1"]["colour"] == None + assert graph.nodes["2"]["colour"] == None + assert graph.nodes["3"]["colour"] == None + assert graph.nodes["4"]["colour"] == None + assert graph.nodes["5"]["colour"] == None diff --git a/src/timing.py b/src/timing.py new file mode 100644 index 0000000..1428eda --- /dev/null +++ b/src/timing.py @@ -0,0 +1,24 @@ +import statistics +import sys +import time + + +class Benchmark: + @staticmethod + def run(function): + timings = [] + stdout = sys.stdout + for i in range(100): + sys.stdout = None + startTime = time.time() + function() + seconds = time.time() - startTime + sys.stdout = stdout + timings.append(seconds) + mean = statistics.mean(timings) + if i < 10 or i % 10 == 9: + print( + "{} {:3.2f} {:3.2f}".format( + 1 + i, mean, statistics.stdev(timings, mean) if i > 1 else 0 + ) + )