added new attribute and one method for new experiments

This commit is contained in:
AnnZhimol 2024-11-28 20:52:42 +03:00
parent f394139d35
commit 8cbe236fcf
3 changed files with 105 additions and 25 deletions

View File

@ -19,6 +19,7 @@ class ExperimentParameters(Base):
recycling_id: Mapped[Optional[int]] = mapped_column(ForeignKey('recycling_parameters.id', ondelete='SET NULL')) recycling_id: Mapped[Optional[int]] = mapped_column(ForeignKey('recycling_parameters.id', ondelete='SET NULL'))
experiment_hash: Mapped[str] = mapped_column(unique=True) experiment_hash: Mapped[str] = mapped_column(unique=True)
experiment_category_id: Mapped[Optional[int]] = mapped_column(ForeignKey('experiment_category.id', ondelete='SET NULL'), nullable=True) experiment_category_id: Mapped[Optional[int]] = mapped_column(ForeignKey('experiment_category.id', ondelete='SET NULL'), nullable=True)
oxidizer_temp: Mapped[float] = mapped_column(nullable=True)
def __repr__(self): def __repr__(self):
return f"<ExperimentParameters>" return f"<ExperimentParameters>"

View File

@ -2,12 +2,15 @@ import hashlib
from typing import Sequence from typing import Sequence
import pandas as pd import pandas as pd
import yaml
from fastapi import HTTPException from fastapi import HTTPException
from sqlalchemy.future import select from sqlalchemy.future import select
from db.crud import create from db.crud import create, update, get_by_id, update_exp
from db.models import LoadParameters, RecyclingParameters
from db.models.experiment_parameters_model import ExperimentParameters from db.models.experiment_parameters_model import ExperimentParameters
from db.postgres_db_connection import async_session_postgres from db.postgres_db_connection import async_session_postgres
from macros_generator import load_calculation, recycling_calculation
async def get_exp_parameters_by_category(category_id: int) -> Sequence[ExperimentParameters]: async def get_exp_parameters_by_category(category_id: int) -> Sequence[ExperimentParameters]:
@ -35,13 +38,13 @@ async def save_experiment_to_db(df: pd.DataFrame):
for _, row in df.iterrows(): for _, row in df.iterrows():
try: try:
# Преобразуем load и recycling_level в соответствующие id # Преобразуем load и recycling_level в соответствующие id
load_id = int(row['load']) load = int(row['load'])
recycling_id = int(row['recycling_level']) recycling = int(row['recycling_level'])
# Генерация хеша для experiment_hash # Генерация хеша для experiment_hash
experiment_hash = generate_experiment_hash(row) experiment_hash = generate_experiment_hash(row)
await create( exp = await create(
ExperimentParameters, ExperimentParameters,
outer_blades_count=int(row['outer_blades_count']), outer_blades_count=int(row['outer_blades_count']),
outer_blades_length=float(row['outer_blades_length']), outer_blades_length=float(row['outer_blades_length']),
@ -49,9 +52,76 @@ async def save_experiment_to_db(df: pd.DataFrame):
middle_blades_count=int(row['middle_blades_count']), middle_blades_count=int(row['middle_blades_count']),
load_id= None, load_id= None,
recycling_id=None, recycling_id=None,
experiment_hash=experiment_hash experiment_hash=experiment_hash,
oxidizer_temp=float(row['oxidizer_temp'])
) )
await process_and_save_experiment_data(exp.id, load, recycling)
except Exception as e: except Exception as e:
print(f"Ошибка при сохранении данных: {e}") print(f"Ошибка при сохранении данных: {e}")
raise HTTPException(status_code=500, detail=f"Ошибка при сохранении данных: {e}") raise HTTPException(status_code=500, detail=f"Ошибка при сохранении данных: {e}")
async def process_and_save_experiment_data(id: int, load: float, recycling_level: float) -> dict:
try:
experiment = await get_by_id(ExperimentParameters, id)
if experiment is None:
raise HTTPException(status_code=404, detail=f"ExperimentParameters с id {id} не найден.")
yaml_file_path = "config.yaml"
with open(yaml_file_path, "r", encoding="utf-8") as file:
data = yaml.safe_load(file)
diameters = data["parameters"]["diameters"]
dict_load = load_calculation(load, diameters, None)
primary_air_consumption = dict_load["primary_air_consumption"]
secondary_air_consumption = dict_load["secondary_air_consumption"]
gas_inlet_consumption = dict_load["gas_inlet_consumption"]
alpha = dict_load["alpha"]
gas_consumption = dict_load["gas_consumption"]
air_consumption = dict_load["air_consumption"]
dict_recycling = recycling_calculation(alpha, gas_consumption, air_consumption, recycling_level)
co2 = dict_recycling["CO2"]
n2 = dict_recycling["N2"]
h2o = dict_recycling["H2O"]
o2 = dict_recycling["O2"]
load_params = await create(
LoadParameters,
load=int(load),
primary_air_consumption=primary_air_consumption,
secondary_air_consumption=secondary_air_consumption,
gas_inlet_consumption=gas_inlet_consumption
)
recycling_params = await create(
RecyclingParameters,
load_id=load_params.id,
recycling_level=int(recycling_level),
co2=co2,
n2=n2,
h2o=h2o,
o2=o2
)
await update_exp(
ExperimentParameters,
id=experiment.id,
updated_data={
"load_id": load_params.id,
"recycling_id": recycling_params.id
}
)
return {
"message": "Данные успешно обработаны и сохранены.",
"load_parameters": load_params,
"recycling_parameters": recycling_params
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")

View File

@ -1,8 +1,11 @@
import yaml
from fastapi import APIRouter, HTTPException from fastapi import APIRouter, HTTPException
from scipy.stats import alpha
from db.crud import * from db.crud import *
from db.models import LoadParameters from db.models import LoadParameters
from db.repositories import get_exp_parameters_by_category, get_exp_parameters_by_exp_hash from db.repositories import get_exp_parameters_by_category, get_exp_parameters_by_exp_hash
from macros_generator import load_calculation, recycling_calculation
from network.schemas import ExperimentParametersBody from network.schemas import ExperimentParametersBody
router = APIRouter() router = APIRouter()
@ -90,36 +93,44 @@ async def delete_experiment_parameters(id: int):
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@router.post('/process_and_save/{id}') # @router.post('/process_and_save/{id}') было нужно для проверки
async def process_and_save_experiment_data(id: int): async def process_and_save_experiment_data(id: int, load: float, recycling_level: float) -> dict:
try: try:
# Получаем данные из ExperimentParameters по id
experiment = await get_by_id(ExperimentParameters, id) experiment = await get_by_id(ExperimentParameters, id)
if experiment is None: if experiment is None:
raise HTTPException(status_code=404, detail=f"ExperimentParameters с id {id} не найден.") raise HTTPException(status_code=404, detail=f"ExperimentParameters с id {id} не найден.")
# Пример обработки данных yaml_file_path = "config.yaml"
load_value = experiment.outer_blades_length * experiment.middle_blades_count
primary_air_consumption = load_value * 0.1 # Условный коэффициент
secondary_air_consumption = load_value * 0.05
gas_inlet_consumption = load_value * 0.03
recycling_level = experiment.outer_blades_count * 0.5 with open(yaml_file_path, "r", encoding="utf-8") as file:
co2 = recycling_level * 0.02 data = yaml.safe_load(file)
n2 = recycling_level * 0.01
h2o = recycling_level * 0.005 diameters = data["parameters"]["diameters"]
o2 = recycling_level * 0.015
dict_load = load_calculation(load, diameters, None)
primary_air_consumption = dict_load["primary_air_consumption"]
secondary_air_consumption = dict_load["secondary_air_consumption"]
gas_inlet_consumption = dict_load["gas_inlet_consumption"]
alpha = dict_load["alpha"]
gas_consumption = dict_load["gas_consumption"]
air_consumption = dict_load["air_consumption"]
dict_recycling = recycling_calculation(alpha, gas_consumption, air_consumption, recycling_level)
co2 = dict_recycling["CO2"]
n2 = dict_recycling["N2"]
h2o = dict_recycling["H2O"]
o2 = dict_recycling["O2"]
# Сохраняем данные в LoadParameters
load_params = await create( load_params = await create(
LoadParameters, LoadParameters,
load=int(load_value), load=int(load),
primary_air_consumption=primary_air_consumption, primary_air_consumption=primary_air_consumption,
secondary_air_consumption=secondary_air_consumption, secondary_air_consumption=secondary_air_consumption,
gas_inlet_consumption=gas_inlet_consumption gas_inlet_consumption=gas_inlet_consumption
) )
# Сохраняем данные в RecyclingParameters
recycling_params = await create( recycling_params = await create(
RecyclingParameters, RecyclingParameters,
load_id=load_params.id, load_id=load_params.id,
@ -130,8 +141,7 @@ async def process_and_save_experiment_data(id: int):
o2=o2 o2=o2
) )
# Обновляем ExperimentParameters await update_exp(
experiment = await update_exp(
ExperimentParameters, ExperimentParameters,
id=experiment.id, id=experiment.id,
updated_data={ updated_data={
@ -143,8 +153,7 @@ async def process_and_save_experiment_data(id: int):
return { return {
"message": "Данные успешно обработаны и сохранены.", "message": "Данные успешно обработаны и сохранены.",
"load_parameters": load_params, "load_parameters": load_params,
"recycling_parameters": recycling_params, "recycling_parameters": recycling_params
"updated_experiment_parameters": experiment
} }
except Exception as e: except Exception as e: