Machine_learning_2023/AI_brain/genetic_algorytm.py
2023-06-15 16:46:08 +02:00

75 lines
2.2 KiB
Python

import random
import configparser
import math
from domain.entities.entity import Entity
config = configparser.ConfigParser()
config.read("config.ini")
from domain.world import World
from AI_brain.rotate_and_go_aStar import RotateAndGoAStar, State
steps_distance_cashed = {}
class Path:
def __init__(self):
self.walk = []
self.distance = 0
def random_walk(self, dusts: list[Entity]):
random_permutation = generate_random_permutation(len(dusts))
self.walk = addStopsForStopStation(
random_permutation, config.getint("CONSTANT", "BananaFilling")
)
def calculate_distance(self, world: World):
distance = 0
for i in range(len(self.walk) - 1):
distance += self.step_distance(self.walk[i], self.walk[i + 1], world)
self.distance = distance
def step_distance(self, from_id: int, to_id: int, world: World) -> int:
if (from_id, to_id) in steps_distance_cashed:
return steps_distance_cashed[(from_id, to_id)]
path_searcher = RotateAndGoAStar(
world,
self.getPosition(from_id, world.dustList, world.doc_station),
self.getPosition(to_id, world.dustList, world.doc_station),
)
path_searcher.search()
number_of_go = path_searcher.number_of_moves_forward()
steps_distance_cashed[(from_id, to_id)] = path_searcher.cost
steps_distance_cashed[(to_id, from_id)] = path_searcher.cost
return path_searcher.cost
def getPosition(self, number: int, dusts: list[Entity], station: Entity) -> State:
if number == -1:
return State(station.x, station.y)
return State(dusts[number].x, dusts[number].y)
def generate_random_permutation(n):
# Create a list of numbers from 1 to n
numbers = list(range(0, n))
# Shuffle the list using the random.shuffle function
random.shuffle(numbers)
return numbers
def addStopsForStopStation(permutation: list[int], bananaFilling: int):
frequency = math.ceil(100 / bananaFilling)
numer_of_stops = math.ceil(len(permutation) / frequency)
for i in range(1, numer_of_stops):
permutation.insert((frequency + 1) * i - 1, -1)
permutation.insert(len(permutation), -1)
return permutation