Исправил бесконечный цикл и сейвлю это
This commit is contained in:
parent
a216e0da45
commit
0c55d4912a
@ -1,240 +0,0 @@
|
||||
{
|
||||
"from": "Барнаул, Михайловка, BAX",
|
||||
"to": "Анапа, Витязево, AAQ",
|
||||
"countBusiness": 2,
|
||||
"countEconomic": 2,
|
||||
"departureDate": "2024-06-14",
|
||||
"returnDate": "2024-09-04",
|
||||
"flights": [
|
||||
{
|
||||
"id": 61,
|
||||
"departurePoint": "Казань, Казань, KZN",
|
||||
"destinationPoint": "Санкт-Петербург, Пулково, LED",
|
||||
"destinationTime": "2024-08-20T13:07:00",
|
||||
"departureTime": "2024-08-20T10:24:00",
|
||||
"distance": 1220.6400474973418,
|
||||
"countEconomic": 265,
|
||||
"countBusiness": 36
|
||||
},
|
||||
{
|
||||
"id": 62,
|
||||
"departurePoint": "Иркутск, Иркутск, IKT",
|
||||
"destinationPoint": "Братск, Братск, BTK",
|
||||
"destinationTime": "2024-07-11T10:28:00",
|
||||
"departureTime": "2024-07-11T09:23:00",
|
||||
"distance": 487.9816774502034,
|
||||
"countEconomic": 120,
|
||||
"countBusiness": 20
|
||||
},
|
||||
{
|
||||
"id": 63,
|
||||
"departurePoint": "Краснодар, Пашковский, KRR",
|
||||
"destinationPoint": "Махачкала, Уйташ, MCX",
|
||||
"destinationTime": "2024-08-13T00:14:00",
|
||||
"departureTime": "2024-08-12T22:38:00",
|
||||
"distance": 722.9657315613899,
|
||||
"countEconomic": 265,
|
||||
"countBusiness": 36
|
||||
},
|
||||
{
|
||||
"id": 64,
|
||||
"departurePoint": "Нарьян-Мар, Нарьян-Мар, NNM",
|
||||
"destinationPoint": "Ульяновск, Баратаевка, ULY",
|
||||
"destinationTime": "2024-08-26T13:27:00",
|
||||
"departureTime": "2024-08-26T09:06:00",
|
||||
"distance": 1507.5398828540344,
|
||||
"countEconomic": 265,
|
||||
"countBusiness": 36
|
||||
},
|
||||
{
|
||||
"id": 65,
|
||||
"departurePoint": "Сургут, Сургут, SGC",
|
||||
"destinationPoint": "Оренбург, Оренбург, REN",
|
||||
"destinationTime": "2024-06-26T19:15:00",
|
||||
"departureTime": "2024-06-26T15:52:00",
|
||||
"distance": 1519.299200422927,
|
||||
"countEconomic": 265,
|
||||
"countBusiness": 36
|
||||
},
|
||||
{
|
||||
"id": 66,
|
||||
"departurePoint": "Махачкала, Уйташ, MCX",
|
||||
"destinationPoint": "Норильск, Алыкель, NSK",
|
||||
"destinationTime": "2024-07-21T06:10:00",
|
||||
"departureTime": "2024-07-20T17:56:00",
|
||||
"distance": 3703.9000546114958,
|
||||
"countEconomic": 265,
|
||||
"countBusiness": 36
|
||||
},
|
||||
{
|
||||
"id": 67,
|
||||
"departurePoint": "Барнаул, Михайловка, BAX",
|
||||
"destinationPoint": "Белгород, им. В.Г. Шухова, EGO",
|
||||
"destinationTime": "2024-06-14T10:24:00",
|
||||
"departureTime": "2024-06-14T07:14:00",
|
||||
"distance": 3228.5554208976832,
|
||||
"countEconomic": 120,
|
||||
"countBusiness": 20
|
||||
},
|
||||
{
|
||||
"id": 68,
|
||||
"departurePoint": "Краснодар, Пашковский, KRR",
|
||||
"destinationPoint": "Норильск, Алыкель, NSK",
|
||||
"destinationTime": "2024-09-09T11:24:00",
|
||||
"departureTime": "2024-09-08T22:57:00",
|
||||
"distance": 3801.082681475355,
|
||||
"countEconomic": 265,
|
||||
"countBusiness": 36
|
||||
},
|
||||
{
|
||||
"id": 69,
|
||||
"departurePoint": "Нижний Новгород, Стригино, GOJ",
|
||||
"destinationPoint": "Казань, Казань, KZN",
|
||||
"destinationTime": "2024-06-18T12:06:00",
|
||||
"departureTime": "2024-06-18T11:19:00",
|
||||
"distance": 349.6277459879821,
|
||||
"countEconomic": 120,
|
||||
"countBusiness": 20
|
||||
},
|
||||
{
|
||||
"id": 70,
|
||||
"departurePoint": "Благовещенск, Игнатьево, BQS",
|
||||
"destinationPoint": "Набережные Челны, Бегишево, NBC",
|
||||
"destinationTime": "2024-07-22T18:59:00",
|
||||
"departureTime": "2024-07-22T13:44:00",
|
||||
"distance": 5063.878359107013,
|
||||
"countEconomic": 265,
|
||||
"countBusiness": 36
|
||||
},
|
||||
{
|
||||
"id": 71,
|
||||
"departurePoint": "Иркутск, Иркутск, IKT",
|
||||
"destinationPoint": "Барнаул, Михайловка, BAX",
|
||||
"destinationTime": "2024-06-15T09:29:00",
|
||||
"departureTime": "2024-06-15T07:21:00",
|
||||
"distance": 1407.5882508285608,
|
||||
"countEconomic": 120,
|
||||
"countBusiness": 20
|
||||
},
|
||||
{
|
||||
"id": 1,
|
||||
"departurePoint": "Ноябрьск, Ноябрьск, NOJ",
|
||||
"destinationPoint": "Челябинск, Баландино, CEK",
|
||||
"destinationTime": "2024-09-16T06:17:00",
|
||||
"departureTime": "2024-09-16T03:42:00",
|
||||
"distance": 1160.5033298370313,
|
||||
"countEconomic": 65,
|
||||
"countBusiness": 10
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"departurePoint": "Москва, Внуково, VKO",
|
||||
"destinationPoint": "Ростов-на-Дону, Платов, ROV",
|
||||
"destinationTime": "2024-09-12T18:07:00",
|
||||
"departureTime": "2024-09-12T16:05:00",
|
||||
"distance": 918.091611352077,
|
||||
"countEconomic": 74,
|
||||
"countBusiness": 11
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"departurePoint": "Владивосток, Кневичи, VVO",
|
||||
"destinationPoint": "Барнаул, Михайловка, BAX",
|
||||
"destinationTime": "2024-08-15T16:18:00",
|
||||
"departureTime": "2024-08-15T11:01:00",
|
||||
"distance": 3730.5081332082163,
|
||||
"countEconomic": 79,
|
||||
"countBusiness": 12
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"departurePoint": "Петрозаводск, Бесовец, PES",
|
||||
"destinationPoint": "Сургут, Сургут, SGC",
|
||||
"destinationTime": "2024-09-01T11:50:00",
|
||||
"departureTime": "2024-09-01T05:13:00",
|
||||
"distance": 2077.379976088868,
|
||||
"countEconomic": 169,
|
||||
"countBusiness": 18
|
||||
},
|
||||
{
|
||||
"id": 53,
|
||||
"departurePoint": "Уфа, Уфа, UFA",
|
||||
"destinationPoint": "Москва, Домодедово, DME",
|
||||
"destinationTime": "2024-09-20T09:46:00",
|
||||
"departureTime": "2024-09-20T09:12:00",
|
||||
"distance": 1151.602690782937,
|
||||
"countEconomic": 265,
|
||||
"countBusiness": 36
|
||||
},
|
||||
{
|
||||
"id": 54,
|
||||
"departurePoint": "Нижний Новгород, Стригино, GOJ",
|
||||
"destinationPoint": "Красноярск, Емельяново, KJA",
|
||||
"destinationTime": "2024-08-04T23:35:00",
|
||||
"departureTime": "2024-08-04T12:53:00",
|
||||
"distance": 3015.7580421346734,
|
||||
"countEconomic": 265,
|
||||
"countBusiness": 36
|
||||
},
|
||||
{
|
||||
"id": 55,
|
||||
"departurePoint": "Краснодар, Пашковский, KRR",
|
||||
"destinationPoint": "Омск, Центральный, OMS",
|
||||
"destinationTime": "2024-07-28T19:22:00",
|
||||
"departureTime": "2024-07-28T10:27:00",
|
||||
"distance": 2659.8366524460557,
|
||||
"countEconomic": 265,
|
||||
"countBusiness": 36
|
||||
},
|
||||
{
|
||||
"id": 56,
|
||||
"departurePoint": "Полярный, Полярный, PYJ",
|
||||
"destinationPoint": "Благовещенск, Игнатьево, BQS",
|
||||
"destinationTime": "2024-09-04T06:44:00",
|
||||
"departureTime": "2024-09-04T02:21:00",
|
||||
"distance": 1974.1571330162965,
|
||||
"countEconomic": 120,
|
||||
"countBusiness": 20
|
||||
},
|
||||
{
|
||||
"id": 57,
|
||||
"departurePoint": "Братск, Братск, BTK",
|
||||
"destinationPoint": "Тюмень, Рощино, THX",
|
||||
"destinationTime": "2024-07-21T18:08:00",
|
||||
"departureTime": "2024-07-21T16:12:00",
|
||||
"distance": 2219.622819604269,
|
||||
"countEconomic": 265,
|
||||
"countBusiness": 36
|
||||
},
|
||||
{
|
||||
"id": 58,
|
||||
"departurePoint": "Белгород, им. В.Г. Шухова, EGO",
|
||||
"destinationPoint": "Анапа, Витязево, AAQ",
|
||||
"destinationTime": "2024-08-15T13:44:00",
|
||||
"departureTime": "2024-08-15T12:20:00",
|
||||
"distance": 629.2506997536557,
|
||||
"countEconomic": 120,
|
||||
"countBusiness": 20
|
||||
},
|
||||
{
|
||||
"id": 59,
|
||||
"departurePoint": "Белгород, им. В.Г. Шухова, EGO",
|
||||
"destinationPoint": "Казань, Казань, KZN",
|
||||
"destinationTime": "2024-08-24T22:45:00",
|
||||
"departureTime": "2024-08-24T20:30:00",
|
||||
"distance": 1009.1424941120106,
|
||||
"countEconomic": 265,
|
||||
"countBusiness": 36
|
||||
},
|
||||
{
|
||||
"id": 60,
|
||||
"departurePoint": "Москва, Внуково, VKO",
|
||||
"destinationPoint": "Нижний Новгород, Стригино, GOJ",
|
||||
"destinationTime": "2024-09-04T19:53:00",
|
||||
"departureTime": "2024-09-04T18:58:00",
|
||||
"distance": 413.0044473319829,
|
||||
"countEconomic": 120,
|
||||
"countBusiness": 20
|
||||
}
|
||||
]
|
||||
}
|
@ -4,8 +4,6 @@ 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 = {}
|
||||
|
||||
@ -35,8 +33,12 @@ def load_graph_from_request(request) -> Dict[str, Dict[str, List]]:
|
||||
# Функция для вычисления длины и времени пути с учетом минимального интервала времени
|
||||
def path_length_and_time(path, graph):
|
||||
length = 0
|
||||
if path[0] not in graph or path[1] not in graph[path[0]]:
|
||||
return float('inf'), None, None
|
||||
|
||||
start_time = graph[path[0]][path[1]][1]
|
||||
end_time = start_time
|
||||
|
||||
for i in range(len(path) - 1):
|
||||
if path[i] not in graph or path[i + 1] not in graph[path[i]]:
|
||||
return float('inf'), start_time, end_time
|
||||
@ -48,29 +50,35 @@ def path_length_and_time(path, graph):
|
||||
return length, start_time, end_time
|
||||
|
||||
# Функция для генерации начальной популяции
|
||||
def generate_population(size, start, end, graph):
|
||||
def generate_population(size, start, end, graph, max_attempts=100):
|
||||
population = []
|
||||
for _ in range(size):
|
||||
path = [start]
|
||||
while path[-1] != end:
|
||||
if path[-1] not in graph or not graph[path[-1]]:
|
||||
break
|
||||
next_node = random.choice(list(graph[path[-1]].keys()))
|
||||
if next_node not in path:
|
||||
for i in range(size):
|
||||
attempts = 0
|
||||
while attempts < max_attempts:
|
||||
path = [start]
|
||||
visited = set(path)
|
||||
while path[-1] != end:
|
||||
if path[-1] not in graph or not graph[path[-1]]:
|
||||
break
|
||||
next_node = random.choice(list(graph[path[-1]].keys()))
|
||||
if next_node in visited:
|
||||
break
|
||||
path.append(next_node)
|
||||
if path[-1] == end:
|
||||
population.append(path)
|
||||
if not population:
|
||||
raise ValueError("Не удалось сгенерировать начальную популяцию с валидными путями.")
|
||||
visited.add(next_node)
|
||||
# Если длина пути превышает количество узлов в графе, выйти из цикла
|
||||
if len(path) > len(graph):
|
||||
break
|
||||
if path[-1] == end:
|
||||
population.append(path)
|
||||
break
|
||||
attempts += 1
|
||||
return population
|
||||
|
||||
# Функция для селекции родителей
|
||||
def select_parents(population, graph):
|
||||
sorted_population = sorted(population, key=lambda p: path_length_and_time(p, graph)[0])
|
||||
parents = sorted_population[:len(sorted_population) // 2]
|
||||
if not parents:
|
||||
raise ValueError("Популяция не содержит валидных путей для селекции родителей.")
|
||||
return parents
|
||||
return sorted_population[:len(sorted_population) // 2]
|
||||
|
||||
|
||||
# Функция для скрещивания (кроссинговера)
|
||||
def crossover(parent1, parent2):
|
||||
@ -81,6 +89,7 @@ def crossover(parent1, parent2):
|
||||
child.append(gene)
|
||||
return child
|
||||
|
||||
|
||||
# Функция для мутации
|
||||
def mutate(child):
|
||||
if len(child) <= 2:
|
||||
@ -90,11 +99,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 generation in range(generations):
|
||||
print(f"Поколение {generation + 1}: {len(population)} путей")
|
||||
parents = select_parents(population, graph)
|
||||
new_population = parents[:]
|
||||
while len(new_population) < population_size:
|
||||
|
@ -17,23 +17,9 @@ router = APIRouter(
|
||||
|
||||
@router.post("/get_flight/")
|
||||
async def get_flight(request: TripRequest):
|
||||
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
|
||||
}
|
||||
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_length, start_time, end_time
|
||||
|
||||
@router.get("/negative")
|
||||
async def get_class_names() -> List[str]:
|
||||
|
Loading…
x
Reference in New Issue
Block a user