Фух, я сделал апи для ген.алгоритма, супер каллово, надо расскидать нормально и будет бомба

This commit is contained in:
maksim 2024-06-02 19:27:25 +04:00
parent 1e3a2f3efa
commit eb2a74ae68
3 changed files with 50 additions and 29 deletions

View File

@ -1,32 +1,35 @@
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)
# Добавление ребра в граф
graph[departure_point][destination_point] = [flight.distance, departure_time, destination_time]
return graph,start_point,end_point
# Функция для вычисления длины и времени пути с учетом минимального интервала времени
def path_length_and_time(path, graph):
length = 0
@ -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"))

View File

@ -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:

View File

@ -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]