Improved multithreading
This commit is contained in:
parent
6725c4ae0c
commit
92490789ea
20
src/AI/GA.py
20
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
|
# Initialize the first population with random values
|
||||||
initialPopulation = numpy.random.uniform(low=0.0, high=1.0, size=(solutions, weightsCount))
|
initialPopulation = numpy.random.uniform(low=0.0, high=1.0, size=(solutions, weightsCount))
|
||||||
population = initialPopulation
|
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):
|
for i in range(iter):
|
||||||
print("\nRunning {} generation...".format(i + 1))
|
print("\nRunning {} generation...".format(i + 1))
|
||||||
fitness = []
|
fitness = []
|
||||||
@ -32,9 +40,10 @@ def geneticAlgorithm(map, iter, solutions, mutationAmount=0.05, multithread=Fals
|
|||||||
fitness.append(doSimulation(player, map))
|
fitness.append(doSimulation(player, map))
|
||||||
else:
|
else:
|
||||||
threads = []
|
threads = []
|
||||||
for p in range(len(population)):
|
for a in range(solutions):
|
||||||
threads.append(ThreadedSimulation(p+1, p+1, population[p], map))
|
thread = ThreadedSimulation(a+1, a+1, population[a], maps[a])
|
||||||
threads[-1].start()
|
threads.append(thread)
|
||||||
|
thread.start()
|
||||||
for t in threads:
|
for t in threads:
|
||||||
t.join()
|
t.join()
|
||||||
fitness.append(t.getResult())
|
fitness.append(t.getResult())
|
||||||
@ -171,7 +180,6 @@ def pickEntity(player, map):
|
|||||||
if not finalEntities:
|
if not finalEntities:
|
||||||
# If all items are gone, pick random one
|
# If all items are gone, pick random one
|
||||||
finalEntities = map.getInteractablesByClassifier()
|
finalEntities = map.getInteractablesByClassifier()
|
||||||
random.seed(10)
|
rng = random.Random()
|
||||||
choice = random.choices(finalEntities, finalWeights)[0]
|
choice = rng.choices(finalEntities, finalWeights)[0]
|
||||||
random.seed()
|
|
||||||
return choice
|
return choice
|
||||||
|
@ -19,9 +19,8 @@ class ThreadedSimulation(threading.Thread):
|
|||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
from src.AI.GA import doSimulation
|
from src.AI.GA import doSimulation
|
||||||
from src.game.Map import Map
|
self.map.respawn()
|
||||||
newMap = Map(self.map.filename, None)
|
self.result = doSimulation(self.player, self.map)
|
||||||
self.result = doSimulation(self.player, newMap)
|
|
||||||
|
|
||||||
def getResult(self):
|
def getResult(self):
|
||||||
return self.result
|
return self.result
|
||||||
|
Loading…
Reference in New Issue
Block a user