From 052d8ca7ce999ce0c60df286eff8adeac71ca3fd Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewski Date: Sat, 16 May 2020 16:22:53 +0200 Subject: [PATCH] pre-alpha multithreading --- src/AI/GA.py | 22 +++++++++++++++++----- src/AI/ThreadedSimulation.py | 27 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 5 deletions(-) create mode 100644 src/AI/ThreadedSimulation.py diff --git a/src/AI/GA.py b/src/AI/GA.py index 41103c5..6b12523 100644 --- a/src/AI/GA.py +++ b/src/AI/GA.py @@ -1,12 +1,15 @@ import random import numpy +import copy from src.AI.Affinities import Affinities +from src.AI.ThreadedSimulation import ThreadedSimulation from src.entities.Enums import Classifiers from src.entities.Player import Player +from src.game.Map import Map -def geneticAlgorithm(map, iter, solutions, mutationAmount=0.05): +def geneticAlgorithm(map, iter, solutions, mutationAmount=0.05, multithread=False, threadCount=4): """ This algorithm will attempt to find the best affinities for player's goal choices. @@ -22,14 +25,23 @@ def geneticAlgorithm(map, iter, solutions, mutationAmount=0.05): initialPopulation = numpy.random.uniform(low=0.0, high=1.0, size=(solutions, weightsCount)) population = initialPopulation for i in range(iter): - print("Running {} generation...".format(i)) + print("\nRunning {} generation...".format(i)) fitness = [] - for player in population: - fitness.append(doSimulation(player, map)) - + if not multithread: + for player in population: + fitness.append(doSimulation(player, map)) + else: + threads = [] + for p in range(len(population)): + threads.append(ThreadedSimulation(p+1, p+1, population[p], map)) + threads[-1].start() + for t in threads: + t.join() + fitness.append(t.getResult()) parents = selectMatingPool(population, fitness, int(solutions / 2)) print("Best fitness: {}".format(max(fitness))) offspring = mating(parents, solutions, mutationAmount) + print("Best offspring: ", offspring[0]) population = offspring diff --git a/src/AI/ThreadedSimulation.py b/src/AI/ThreadedSimulation.py new file mode 100644 index 0000000..d5a0d89 --- /dev/null +++ b/src/AI/ThreadedSimulation.py @@ -0,0 +1,27 @@ +import threading +import time + + +exitFlag = 0 + + +class ThreadedSimulation(threading.Thread): + def __init__(self, threadID, counter, player, map): + threading.Thread.__init__(self) + self.threadID = threadID + self.counter = counter + + self.player = player + + self.result = None + + self.map = map + + def run(self): + from src.AI.GA import doSimulation + from src.game.Map import Map + newMap = Map(self.map.filename, None) + self.result = doSimulation(self.player, newMap) + + def getResult(self): + return self.result