From eb2a74ae68ff3474a903dd7c29b6cf2b754c2403 Mon Sep 17 00:00:00 2001 From: maksim Date: Sun, 2 Jun 2024 19:27:25 +0400 Subject: [PATCH] =?UTF-8?q?=D0=A4=D1=83=D1=85,=20=D1=8F=20=D1=81=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D0=B0=D0=BB=20=D0=B0=D0=BF=D0=B8=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20=D0=B3=D0=B5=D0=BD.=D0=B0=D0=BB=D0=B3=D0=BE=D1=80?= =?UTF-8?q?=D0=B8=D1=82=D0=BC=D0=B0,=20=D1=81=D1=83=D0=BF=D0=B5=D1=80=20?= =?UTF-8?q?=D0=BA=D0=B0=D0=BB=D0=BB=D0=BE=D0=B2=D0=BE,=20=D0=BD=D0=B0?= =?UTF-8?q?=D0=B4=D0=BE=20=D1=80=D0=B0=D1=81=D1=81=D0=BA=D0=B8=D0=B4=D0=B0?= =?UTF-8?q?=D1=82=D1=8C=20=D0=BD=D0=BE=D1=80=D0=BC=D0=B0=D0=BB=D1=8C=D0=BD?= =?UTF-8?q?=D0=BE=20=D0=B8=20=D0=B1=D1=83=D0=B4=D0=B5=D1=82=20=D0=B1=D0=BE?= =?UTF-8?q?=D0=BC=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- genetic_algorithm/genetic_algorithm.py | 45 +++++++++++--------------- router_class.py | 13 ++++++-- schemas.py | 21 +++++++++++- 3 files changed, 50 insertions(+), 29 deletions(-) diff --git a/genetic_algorithm/genetic_algorithm.py b/genetic_algorithm/genetic_algorithm.py index 0e20f6a..93be5c2 100644 --- a/genetic_algorithm/genetic_algorithm.py +++ b/genetic_algorithm/genetic_algorithm.py @@ -1,31 +1,34 @@ import json from datetime import datetime, timedelta import random +from typing import Dict, List -# Функция для загрузки данных из JSON-файла и преобразования в граф -def load_graph_from_json(file_path): - with open(file_path, 'r', encoding='utf-8') as file: - data = json.load(file) - +def load_graph_from_request(request) -> Dict[str, Dict[str, List]]: graph = {} - start_point = data['from'] - end_point = data['to'] - for flight in data['flights']: - departure_point = flight['departurePoint'] - destination_point = flight['destinationPoint'] - distance = flight['distance'] - departure_time = datetime.fromisoformat(flight['departureTime']) - destination_time = datetime.fromisoformat(flight['destinationTime']) + # Загрузить данные о полетах из запроса + flights = request.flights + start_point = request.from_ + end_point = request.to_ + # Добавить каждый полет в граф + for flight in flights: + departure_point = flight.departurePoint + destination_point = flight.destinationPoint + departure_time = datetime.fromisoformat(flight.departureTime) + destination_time = datetime.fromisoformat(flight.destinationTime) + + # Проверка наличия вершин в графе и их создание при необходимости if departure_point not in graph: graph[departure_point] = {} + if destination_point not in graph: + graph[destination_point] = {} - graph[departure_point][destination_point] = (distance, departure_time, destination_time) - - return graph, start_point, end_point + # Добавление ребра в граф + graph[departure_point][destination_point] = [flight.distance, departure_time, destination_time] + return graph,start_point,end_point # Функция для вычисления длины и времени пути с учетом минимального интервала времени def path_length_and_time(path, graph): @@ -103,13 +106,3 @@ def genetic_algorithm(start, end, graph, population_size=100, generations=100): best_length, start_time, end_time = path_length_and_time(best_path, graph) return best_path, best_length, start_time, end_time - -# Пример использования -file_path = './/data_ga.json' -graph, start_point, end_point = load_graph_from_json(file_path) - -best_path, length, start_time, end_time = genetic_algorithm(start_point, end_point, graph) -print("Наиболее короткий путь от", start_point, "до", end_point, ":", best_path) -print("Длина пути:", length) -print("Начальное время:", start_time.strftime("%d %B %Y %H:%M")) -print("Конечное время:", end_time.strftime("%d %B %Y %H:%M")) diff --git a/router_class.py b/router_class.py index 9e9c1c5..153902b 100644 --- a/router_class.py +++ b/router_class.py @@ -1,16 +1,25 @@ from typing import Annotated -from fastapi import APIRouter, Depends +from fastapi import APIRouter, Depends, HTTPException from typing import List +from pydantic import ValidationError + from enums import TypeMood, TypeModel +from genetic_algorithm.genetic_algorithm import genetic_algorithm, load_graph_from_request from repository import QuestionRepository -from schemas import SQuestionAdd, SQuestion, SQuestionId +from schemas import SQuestionAdd, SQuestion, SQuestionId, Flight, TripRequest router = APIRouter( prefix="/class", 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 + @router.get("/negative") async def get_class_names() -> List[str]: with open(".//neural_network/classification/class_names_negative.txt", "r", encoding="utf-8") as file: diff --git a/schemas.py b/schemas.py index 20aa121..bde840e 100644 --- a/schemas.py +++ b/schemas.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Optional, List from pydantic import BaseModel, ConfigDict from datetime import datetime from enums import TypeMood, TypeModel @@ -19,3 +19,22 @@ class SQuestion(SQuestionAdd): class SQuestionId(BaseModel): ok: bool = True question_id: int + +class Flight(BaseModel): + id: int + departurePoint: str + destinationPoint: str + destinationTime: str + departureTime: str + distance: float + countEconomic: int + countBusiness: int + +class TripRequest(BaseModel): + from_: str + to_: str + countBusiness: int + countEconomic: int + departureDate: str + returnDate: str + flights: List[Flight] \ No newline at end of file