Я так устал, хочу спать. Но а так, вроде более мене ГА починил, осталось найти биг json

This commit is contained in:
maksim 2024-06-05 00:38:13 +04:00
parent a7aacfa323
commit 2d83c5c9ed
3 changed files with 71 additions and 25 deletions

View File

@ -8,23 +8,26 @@ from schemas import TripRequest
def load_graph_from_request(request: TripRequest) -> Tuple[Dict[str, Dict[str, List[Any]]], str, str, List[Dict]]:
graph = {}
flights_data = []
graphTo = {}
flightsDataTo = []
graphBack = {}
flightsDataBack = []
# Загрузить данные о полетах из запроса
flights = request.flights
flightsTo = request.flightsTo
flightsBack = request.flightsBack
start_point = request.fromPoint
end_point = request.toPoint
# Добавить каждый полет в граф
for flight in flights:
for flight in flightsTo:
departure_point = flight.departurePoint
destination_point = flight.destinationPoint
departure_time = datetime.fromisoformat(flight.departureTime)
destination_time = datetime.fromisoformat(flight.destinationTime)
# Сохранение данных о полете для вывода
flights_data.append({
flightsDataTo.append({
"id": flight.id,
"departurePoint": departure_point,
"destinationPoint": destination_point,
@ -33,15 +36,40 @@ def load_graph_from_request(request: TripRequest) -> Tuple[Dict[str, Dict[str, L
})
# Проверка наличия вершин в графе и их создание при необходимости
if departure_point not in graph:
graph[departure_point] = {}
if destination_point not in graph:
graph[destination_point] = {}
if departure_point not in graphTo:
graphTo[departure_point] = {}
if destination_point not in graphTo:
graphTo[destination_point] = {}
# Добавление ребра в граф
graph[departure_point][destination_point] = [flight.distance, departure_time, destination_time]
graphTo[departure_point][destination_point] = [flight.distance, departure_time, destination_time]
return graph, start_point, end_point, flights_data
# Добавить каждый полет в граф
for flight in flightsBack:
departure_point = flight.departurePoint
destination_point = flight.destinationPoint
departure_time = datetime.fromisoformat(flight.departureTime)
destination_time = datetime.fromisoformat(flight.destinationTime)
# Сохранение данных о полете для вывода
flightsDataBack.append({
"id": flight.id,
"departurePoint": departure_point,
"destinationPoint": destination_point,
"departureTime": departure_time,
"destinationTime": destination_time
})
# Проверка наличия вершин в графе и их создание при необходимости
if departure_point not in graphBack:
graphBack[departure_point] = {}
if destination_point not in graphBack:
graphBack[destination_point] = {}
# Добавление ребра в граф
graphBack[departure_point][destination_point] = [flight.distance, departure_time, destination_time]
return graphTo,graphBack, start_point, end_point, flightsDataTo, flightsDataBack
def path_length_and_time(path, graph):
@ -90,7 +118,9 @@ def generate_population(size, start, end, graph, max_attempts=1000):
def select_parents(population, graph):
sorted_population = sorted(population, key=lambda p: path_length_and_time(p, graph)[0])
return sorted_population[:len(sorted_population) // 2]
valid_parents = [p for p in sorted_population if path_length_and_time(p, graph)[0] != float('inf')]
return valid_parents[:len(valid_parents) // 2]
def crossover(parent1, parent2):
@ -120,11 +150,16 @@ def update_best_paths(best_paths, path, graph, max_best_paths=3):
del best_paths[worst_path]
def genetic_algorithm(start, end, graph, flights_data, population_size=100, generations=100):
def genetic_algorithm(start, end, graph, flights_data, type, population_size=100, generations=100):
population = generate_population(population_size, start, end, graph)
best_paths = {} # Словарь для хранения уникальных лучших маршрутов и их длин
for generation in range(generations):
parents = select_parents(population, graph)
# Если не удалось выбрать родителей, завершить алгоритм
if not parents:
break
new_population = parents[:]
while len(new_population) < population_size:
parent1 = random.choice(parents)
@ -157,10 +192,11 @@ def genetic_algorithm(start, end, graph, flights_data, population_size=100, gene
if length == float('inf') or start_time is None or end_time is None:
continue
result.append({
"to": path_data,
"start_time": start_time.isoformat() if start_time else None,
"end_time": end_time.isoformat() if end_time else None,
"best_length": length
type: path_data
# "start_time": start_time.isoformat() if start_time else None,
# "end_time": end_time.isoformat() if end_time else None,
# "best_length": length
})
return result

View File

@ -17,11 +17,20 @@ router = APIRouter(
@router.post("/get_flight/")
async def get_flight(request: TripRequest):
graph, start_point, end_point, flights_data = load_graph_from_request(request)
result = genetic_algorithm(start_point, end_point, graph, flights_data)
if not result:
raise HTTPException(status_code=404, detail="No valid paths found")
return result
graphTo, graphBack, start_point, end_point, flightsDataTo, flightsDataBack = load_graph_from_request(request)
if request.returnDate:
resultTo = genetic_algorithm(start=start_point, end=end_point, graph=graphTo, flights_data=flightsDataTo, type = "to")
resulFrom = genetic_algorithm(end=start_point, start=end_point, graph=graphBack, flights_data=flightsDataBack, type = "back")
if not resultTo or not resulFrom:
raise HTTPException(status_code=404, detail="No valid paths found")
return resultTo, resulFrom
if not request.returnDate:
resultTo = genetic_algorithm(start=start_point, end=end_point, graph=graphTo, flights_data=flightsDataTo,
type="to")
if not resultTo:
raise HTTPException(status_code=404, detail="No valid paths found")
return resultTo
@router.get("/negative")
async def get_class_names() -> List[str]:
@ -29,9 +38,9 @@ async def get_class_names() -> List[str]:
class_names = [line.strip() for line in file.readlines()]
return class_names
@router.get("/positive")
async def get_class_names() -> List[str]:
with open(".//neural_network/classification/class_names_positive.txt", "r", encoding="utf-8") as file:
class_names = [line.strip() for line in file.readlines()]
return class_names

View File

@ -36,5 +36,6 @@ class TripRequest(BaseModel):
countBusiness: int
countEconomic: int
departureDate: str
returnDate: str
flights: List[Flight]
returnDate: Optional[str] = None
flightsTo: List[Flight]
flightsBack: List[Flight]