Сделал так, чтобы если 0 путей не крашилось

This commit is contained in:
maksim 2024-06-02 21:07:40 +04:00
parent eb2a74ae68
commit a216e0da45
3 changed files with 34 additions and 17 deletions

View File

@ -2,15 +2,17 @@ import json
from datetime import datetime, timedelta
import random
from typing import Dict, List
from fastapi import FastAPI, HTTPException, Request
app = FastAPI()
def load_graph_from_request(request) -> Dict[str, Dict[str, List]]:
graph = {}
# Загрузить данные о полетах из запроса
flights = request.flights
start_point = request.from_
end_point = request.to_
start_point = request.fromPoint
end_point = request.toPoint
# Добавить каждый полет в граф
for flight in flights:
@ -28,7 +30,7 @@ def load_graph_from_request(request) -> Dict[str, Dict[str, List]]:
# Добавление ребра в граф
graph[departure_point][destination_point] = [flight.distance, departure_time, destination_time]
return graph,start_point,end_point
return graph, start_point, end_point
# Функция для вычисления длины и времени пути с учетом минимального интервала времени
def path_length_and_time(path, graph):
@ -45,7 +47,6 @@ def path_length_and_time(path, graph):
end_time = graph[path[i]][path[i + 1]][2]
return length, start_time, end_time
# Функция для генерации начальной популяции
def generate_population(size, start, end, graph):
population = []
@ -59,14 +60,17 @@ def generate_population(size, start, end, graph):
path.append(next_node)
if path[-1] == end:
population.append(path)
if not population:
raise ValueError("Не удалось сгенерировать начальную популяцию с валидными путями.")
return population
# Функция для селекции родителей
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]
parents = sorted_population[:len(sorted_population) // 2]
if not parents:
raise ValueError("Популяция не содержит валидных путей для селекции родителей.")
return parents
# Функция для скрещивания (кроссинговера)
def crossover(parent1, parent2):
@ -77,7 +81,6 @@ def crossover(parent1, parent2):
child.append(gene)
return child
# Функция для мутации
def mutate(child):
if len(child) <= 2:
@ -87,11 +90,11 @@ def mutate(child):
child[index1], child[index2] = child[index2], child[index1]
return child
# Главная функция генетического алгоритма
def genetic_algorithm(start, end, graph, population_size=100, generations=100):
population = generate_population(population_size, start, end, graph)
for _ in range(generations):
for generation in range(generations):
print(f"Поколение {generation + 1}: {len(population)} путей")
parents = select_parents(population, graph)
new_population = parents[:]
while len(new_population) < population_size:
@ -104,5 +107,4 @@ def genetic_algorithm(start, end, graph, population_size=100, generations=100):
population = new_population
best_path = min(population, key=lambda p: path_length_and_time(p, graph)[0])
best_length, start_time, end_time = path_length_and_time(best_path, graph)
return best_path, best_length, start_time, end_time
return best_path, best_length, start_time, end_time

View File

@ -14,11 +14,26 @@ router = APIRouter(
tags=["Class"],
)
@router.post("/get_flight/")
async def get_flight(request: TripRequest):
graph, start_point, end_point = load_graph_from_request(request)
best_path, length, start_time, end_time = genetic_algorithm(start_point, end_point, graph)
return best_path, length, start_time, end_time
try:
graph, start_point, end_point = load_graph_from_request(request)
best_path, best_length, start_time, end_time = genetic_algorithm(start_point, end_point, graph)
return {
"best_path": best_path,
"best_length": best_length,
"start_time": start_time.isoformat(),
"end_time": end_time.isoformat()
}
except ValueError as e:
# Возвращаем значения по умолчанию
return {
"best_path": [],
"best_length": 0,
"start_time": None,
"end_time": None
}
@router.get("/negative")
async def get_class_names() -> List[str]:

View File

@ -31,8 +31,8 @@ class Flight(BaseModel):
countBusiness: int
class TripRequest(BaseModel):
from_: str
to_: str
fromPoint: str
toPoint: str
countBusiness: int
countEconomic: int
departureDate: str