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

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,31 +1,34 @@
import json import json
from datetime import datetime, timedelta from datetime import datetime, timedelta
import random import random
from typing import Dict, List
# Функция для загрузки данных из JSON-файла и преобразования в граф def load_graph_from_request(request) -> Dict[str, Dict[str, List]]:
def load_graph_from_json(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
graph = {} graph = {}
start_point = data['from']
end_point = data['to']
for flight in data['flights']: # Загрузить данные о полетах из запроса
departure_point = flight['departurePoint'] flights = request.flights
destination_point = flight['destinationPoint'] start_point = request.from_
distance = flight['distance'] end_point = request.to_
departure_time = datetime.fromisoformat(flight['departureTime'])
destination_time = datetime.fromisoformat(flight['destinationTime'])
# Добавить каждый полет в граф
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: if departure_point not in graph:
graph[departure_point] = {} 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
return graph,start_point,end_point
# Функция для вычисления длины и времени пути с учетом минимального интервала времени # Функция для вычисления длины и времени пути с учетом минимального интервала времени
def path_length_and_time(path, graph): 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) 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
# Пример использования
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 typing import Annotated
from fastapi import APIRouter, Depends from fastapi import APIRouter, Depends, HTTPException
from typing import List from typing import List
from pydantic import ValidationError
from enums import TypeMood, TypeModel from enums import TypeMood, TypeModel
from genetic_algorithm.genetic_algorithm import genetic_algorithm, load_graph_from_request
from repository import QuestionRepository from repository import QuestionRepository
from schemas import SQuestionAdd, SQuestion, SQuestionId from schemas import SQuestionAdd, SQuestion, SQuestionId, Flight, TripRequest
router = APIRouter( router = APIRouter(
prefix="/class", prefix="/class",
tags=["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") @router.get("/negative")
async def get_class_names() -> List[str]: async def get_class_names() -> List[str]:
with open(".//neural_network/classification/class_names_negative.txt", "r", encoding="utf-8") as file: 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 pydantic import BaseModel, ConfigDict
from datetime import datetime from datetime import datetime
from enums import TypeMood, TypeModel from enums import TypeMood, TypeModel
@ -19,3 +19,22 @@ class SQuestion(SQuestionAdd):
class SQuestionId(BaseModel): class SQuestionId(BaseModel):
ok: bool = True ok: bool = True
question_id: int 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]