From 92490789eaf3f253679833bf6ff4f69a8845b8d9 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewski Date: Sun, 17 May 2020 00:14:10 +0200 Subject: [PATCH] Improved multithreading --- src/AI/GA.py | 20 ++++++++++++++------ src/AI/ThreadedSimulation.py | 5 ++--- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/AI/GA.py b/src/AI/GA.py index afd7f92..3a8c66c 100644 --- a/src/AI/GA.py +++ b/src/AI/GA.py @@ -24,6 +24,14 @@ def geneticAlgorithm(map, iter, solutions, mutationAmount=0.05, multithread=Fals # Initialize the first population with random values initialPopulation = numpy.random.uniform(low=0.0, high=1.0, size=(solutions, weightsCount)) population = initialPopulation + maps = [] + + if multithread: + # Create a map for each thread + print("Creating a map for each thread...") + for i in range(solutions): + maps.append(Map(map.filename, map.screen)) + for i in range(iter): print("\nRunning {} generation...".format(i + 1)) fitness = [] @@ -32,9 +40,10 @@ def geneticAlgorithm(map, iter, solutions, mutationAmount=0.05, multithread=Fals 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 a in range(solutions): + thread = ThreadedSimulation(a+1, a+1, population[a], maps[a]) + threads.append(thread) + thread.start() for t in threads: t.join() fitness.append(t.getResult()) @@ -171,7 +180,6 @@ def pickEntity(player, map): if not finalEntities: # If all items are gone, pick random one finalEntities = map.getInteractablesByClassifier() - random.seed(10) - choice = random.choices(finalEntities, finalWeights)[0] - random.seed() + rng = random.Random() + choice = rng.choices(finalEntities, finalWeights)[0] return choice diff --git a/src/AI/ThreadedSimulation.py b/src/AI/ThreadedSimulation.py index d5a0d89..3051f26 100644 --- a/src/AI/ThreadedSimulation.py +++ b/src/AI/ThreadedSimulation.py @@ -19,9 +19,8 @@ class ThreadedSimulation(threading.Thread): 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) + self.map.respawn() + self.result = doSimulation(self.player, self.map) def getResult(self): return self.result