Добавление pyDOE3

This commit is contained in:
maksim 2024-11-05 20:57:07 +04:00
parent de0e04fb3a
commit a233bbf903
4 changed files with 91 additions and 1 deletions

50
main.py
View File

@ -1,4 +1,6 @@
import pandas as pd
from fastapi import FastAPI, HTTPException, BackgroundTasks from fastapi import FastAPI, HTTPException, BackgroundTasks
from pyDOE3 import pbdesign, lhs
from db.csv_to_db import csv_to_db from db.csv_to_db import csv_to_db
from network.routes import (ch_experimentdb_experiment_data_router, experiment_data_router, from network.routes import (ch_experimentdb_experiment_data_router, experiment_data_router,
@ -6,6 +8,7 @@ from network.routes import (ch_experimentdb_experiment_data_router, experiment_d
from network.routes import load_parameters_router, recycling_parameters_router from network.routes import load_parameters_router, recycling_parameters_router
from network.schemas import * from network.schemas import *
from new_experiment_planner import run_experiment from new_experiment_planner import run_experiment
from new_experiment_planner_pyDOE3 import scale_design, scale_design_lhs, round_by_index
app = FastAPI() app = FastAPI()
@ -56,3 +59,50 @@ async def init_db_data(background_tasks: BackgroundTasks):
except Exception as e: except Exception as e:
print(str(e.with_traceback())) print(str(e.with_traceback()))
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
# Пример запроса
# {
# "param_ranges": {
# "outer_blades_count": [12, 48],
# "outer_blades_length": [44, 107.5],
# "outer_blades_angle": [30, 75],
# "middle_blades_count": [9, 36],
# "load": [315, 465],
# "recycling_level": [0, 20],
# "oxidizer_temp": [471, 493]
# },
# "count_exp": 1440,
# "round_rules": [0, 1, 1, 0, 1, 1, 1]
# }
@app.post("/pyDOE3_screening_design")
def generate_screening_design(request: ExperimentParametersPyDOE3) -> List[Dict[str, float]]:
param_ranges = request.param_ranges
# Создаем screening design и масштабируем его
num_factors = len(param_ranges)
screening_design = pbdesign(num_factors)
scaled_screening_design = scale_design(screening_design, param_ranges)
# Преобразуем в DataFrame и возвращаем результат
df_screening = pd.DataFrame(scaled_screening_design, columns=param_ranges.keys())
return df_screening.to_dict(orient="records")
@app.post("/pyDOE3_lhs_design")
def generate_lhs_design(request: ExperimentParametersPyDOE3) -> List[Dict[str, float]]:
param_ranges = request.param_ranges
count_exp = request.count_exp
round_rules = request.round_rules
# Создаем lhs design и масштабируем его
num_factors = len(param_ranges)
lhs_samples = lhs(num_factors, samples=count_exp)
scaled_lhs_samples = scale_design_lhs(lhs_samples, param_ranges)
# Округляем значения
round_scaled_lhs_samples = round_by_index(scaled_lhs_samples, round_rules)
# Преобразуем в DataFrame и возвращаем результат
df_lhs = pd.DataFrame(round_scaled_lhs_samples, columns=param_ranges.keys())
return df_lhs.to_dict(orient="records")

View File

@ -1,7 +1,11 @@
from typing import Optional from typing import Optional, Dict, Tuple, List
from pydantic import BaseModel, ConfigDict from pydantic import BaseModel, ConfigDict
class ExperimentParametersPyDOE3(BaseModel):
param_ranges: Dict[str, Tuple[float, float]]
count_exp: int
round_rules: List[int]
class ExperimentParameters(BaseModel): class ExperimentParameters(BaseModel):
outer_blades_count: str outer_blades_count: str

View File

@ -0,0 +1,36 @@
import numpy as np
# Функция для масштабирования значений дизайна
def scale_design(design, param_ranges):
scaled_design = []
for row in design:
scaled_row = []
for i, val in enumerate(row):
min_val, max_val = param_ranges[list(param_ranges.keys())[i]]
scaled_val = (val + 1) / 2 * (max_val - min_val) + min_val
scaled_row.append(scaled_val)
scaled_design.append(scaled_row)
return np.array(scaled_design)
def scale_design_lhs(design, param_ranges):
scaled_design = []
for row in design:
scaled_row = []
for i, val in enumerate(row):
min_val, max_val = param_ranges[list(param_ranges.keys())[i]]
scaled_val = val * (max_val - min_val) + min_val
scaled_row.append(scaled_val)
scaled_design.append(scaled_row)
return np.array(scaled_design)
# Функция для округления значений
def round_by_index(array, rules):
rounded_array = np.zeros(array.shape)
for i in range(array.shape[0]):
for j in range(array.shape[1]):
rounded_array[i, j] = round(array[i, j], rules[j])
return rounded_array

Binary file not shown.