import openpyxl
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
import optuna
from scipy.optimize import minimize_scalar

# Функция загрузки данных из Excel
def load_data_from_excel(excel_file, columns_to_check):
    workbook = openpyxl.load_workbook(excel_file, data_only=True)
    sheet = workbook.active

    numeric_data = []

    for row in sheet.iter_rows(min_row=1):
        row_values = []
        is_full_numeric = True

        for col in columns_to_check:
            cell_value = row[col - 1].value
            if isinstance(cell_value, (int, float)):
                row_values.append(cell_value)
            else:
                is_full_numeric = False
                break

        if is_full_numeric:
            numeric_data.append(row_values)

    df = pd.DataFrame(numeric_data)
    # Удаление первой строки
    df = df.drop(index=0).reset_index(drop=True)
    return df

# Функция сортировки данных по температуре и расходу
def sort_data_by_temperature_and_flow_rate(df, temperature_index, flow_rate_index):
    return df.sort_values(by=[temperature_index, flow_rate_index])

# Функция получения уникальных значений температуры
def get_unique_temperatures(df, temperature_index):
    return df.iloc[:, temperature_index].unique()

# Функция поиска номинального значения температуры
def find_nominal_temperature(unique_temperatures):
    print(f"Уникальные значения температуры: {unique_temperatures}")
    nominal_temperature = float(input("Введите номинальное значение температуры обратной сетевой воды (например, 70): "))
    return nominal_temperature

# Функция расчета дельт
def calculate_deltas(df, temperature_index, power_index, nominal_temperature):
    df['Дельта'] = 0.0
    nominal_subset = df[df.iloc[:, temperature_index] == nominal_temperature]

    unique_temperatures = get_unique_temperatures(df, temperature_index)

    for temp in unique_temperatures:
        if temp == nominal_temperature:
            continue

        subset = df[df.iloc[:, temperature_index] == temp]
        if len(subset) != len(nominal_subset):
            print(f"Warning: Length mismatch between Tоб={temp} и Tоб={nominal_temperature}. Skipping this segment.")
            continue

        df.loc[subset.index, 'Дельта'] = subset.iloc[:, power_index].values - nominal_subset.iloc[:, power_index].values

    filtered_df = df[df.iloc[:, temperature_index] != nominal_temperature]

    return filtered_df

# Измененная функция нормализации дельт для поддержки индивидуальных целевых значений
def normalize_deltas(df, temperature_index, delta_index, target_values, tolerance=1e-6):
    unique_temperatures = get_unique_temperatures(df, temperature_index)
    first_deltas = {}

    for temp in unique_temperatures:
        subset = df[df.iloc[:, temperature_index] == temp]
        if not subset.empty:
            first_delta = subset.iloc[0, delta_index]
            first_deltas[temp] = first_delta

    df['Модифицированное значение'] = 0.0
    for temp in unique_temperatures:
        first_delta = first_deltas[temp]
        target_value = target_values.get(temp, None)
        if target_value is None:
            print(f"Целевое значение для температуры {temp} не задано.")
            continue

        if abs(first_delta) < tolerance:
            k = 0.0
        else:
            k = target_value / first_delta

        df.loc[df.iloc[:, temperature_index] == temp, 'Модифицированное значение'] = df.loc[df.iloc[:, temperature_index] == temp, 'Дельта'] * k

    return df

# Новая функция для получения коэффициентов регрессии для каждой температуры
def get_regression_coefficients(df, temperature_index):
    temp_to_coef = {}
    unique_temperatures = get_unique_temperatures(df, temperature_index)

    for temp in unique_temperatures:
        subset = df[df.iloc[:, temperature_index] == temp]
        X = subset['Дельта'].values.reshape(-1, 1)
        y = subset['Модифицированное значение'].values

        # Проверяем, что у нас достаточно данных для построения модели
        if len(X) > 1:
            model = LinearRegression()
            model.fit(X, y)
            slope = model.coef_[0]
            temp_to_coef[temp] = slope
        else:
            print(f"Недостаточно данных для построения модели для температуры {temp}")

    return temp_to_coef

# Функция оптимизации целевого значения для достижения требуемого коэффициента регрессии
def optimize_target_value(temp_match, df, temperature_index, delta_index, coef_base, tolerance=1e-6):
    subset = df[df.iloc[:, temperature_index] == temp_match].copy()
    if subset.empty:
        print(f"Данные для температуры {temp_match} не найдены.")
        return None, None

    first_delta = subset.iloc[0, delta_index]
    if abs(first_delta) < tolerance:
        print(f"Первое значение 'Дельта' для температуры {temp_match} слишком мало.")
        return None, None

    # Определяем целевую функцию для оптимизации
    def objective(target_value):
        k = target_value / first_delta
        subset['Модифицированное значение'] = subset['Дельта'] * k
        X = subset['Дельта'].values.reshape(-1, 1)
        y = subset['Модифицированное значение'].values

        if len(X) < 2:
            return float('inf')

        model = LinearRegression()
        model.fit(X, y)
        coef_match = model.coef_[0]
        return abs(coef_match - coef_base)

    # Выполняем оптимизацию
    res = minimize_scalar(objective, bounds=(0.01, 10), method='bounded')
    optimal_target_value = res.x
    k = optimal_target_value / first_delta

    # Обновляем 'Модифицированное значение' в основном датафрейме
    df.loc[df.iloc[:, temperature_index] == temp_match, 'Модифицированное значение'] = df.loc[df.iloc[:, temperature_index] == temp_match, 'Дельта'] * k

    return optimal_target_value, k

# Функция сохранения данных
def save_data(df, output_file):
    df.to_csv(output_file, index=False)

# Целевая функция для Optuna
def objective(trial, Gt_train, Gt_test, mod_train, mod_test):
    degree = trial.suggest_int('degree', 1, 5)  # Ограничиваем степень полинома для стабильности

    poly = PolynomialFeatures(degree=degree)
    Gt_train_poly = poly.fit_transform(Gt_train)
    Gt_test_poly = poly.transform(Gt_test)

    model = LinearRegression()
    model.fit(Gt_train_poly, mod_train)

    mod_pred = model.predict(Gt_test_poly)

    r2 = r2_score(mod_test, mod_pred)

    return -r2

# Обновленная функция построения графиков с учетом разных давлений
def main_plot(data_list, pt_values):
    fig, (ax_gt, ax_delta) = plt.subplots(1, 2, figsize=(14, 6), gridspec_kw={'width_ratios': [1, 1]})

    for idx, (data, pt) in enumerate(zip(data_list, pt_values)):
        print(f"Обработка давления Pt = {pt}")

        # График зависимости модифицированного значения от Gт
        Gt = data['Gт'].values.reshape(-1, 1)
        mod_value = data['Модифицированное значение'].values

        # Нормировка данных
        scaler = StandardScaler()
        Gt_scaled = scaler.fit_transform(Gt)

        Gt_train, Gt_test, mod_train, mod_test = train_test_split(Gt_scaled, mod_value, test_size=0.2, random_state=42)

        study = optuna.create_study(direction='minimize')
        study.optimize(lambda trial: objective(trial, Gt_train, Gt_test, mod_train, mod_test), n_trials=50)

        best_degree = study.best_params['degree']
        best_r2 = -study.best_value

        poly = PolynomialFeatures(degree=best_degree)
        Gt_poly = poly.fit_transform(Gt_scaled)

        model = LinearRegression()
        model.fit(Gt_poly, mod_value)

        mod_value_pred = model.predict(Gt_poly)

        # Преобразуем обратно для построения графика
        Gt_original = scaler.inverse_transform(Gt_scaled)
        order = np.argsort(Gt_original.flatten())

        ax_gt.scatter(data['Gт'], data['Модифицированное значение'], label=f'Исходные данные Pt={pt}', color=plt.cm.tab10(idx % 10), alpha=0.6)
        ax_gt.plot(Gt_original[order].flatten(), mod_value_pred[order], '-', label=f'Poly deg {best_degree}, R²: {best_r2:.2f}, Pt={pt}', color=plt.cm.tab10(idx % 10))

        # Вывод уравнения полиномиальной регрессии
        coef = model.coef_[::-1]
        intercept = model.intercept_
        equation = f"y = {intercept:.4f} "
        for i, c in enumerate(coef[1:], start=1):
            equation += f"+ ({c:.15f}) * x^{i} "
        print(f"Уравнение полинома для графика 'Модифицированное значение' от 'Gт' (степень {best_degree}), Pt={pt}:")
        print(equation)

        # График зависимости модифицированного значения от Дельта
        unique_tob_values = data['Tоб'].unique()

        for tob_value in unique_tob_values:
            df_filtered = data[data['Tоб'] == tob_value]
            df_filtered = df_filtered.sort_values(by='Gт')

            X = df_filtered['Дельта'].values.reshape(-1, 1)
            y = df_filtered['Модифицированное значение'].values

            if len(X) > 1:
                model = LinearRegression()
                model.fit(X, y)

                slope = model.coef_[0]
                intercept = model.intercept_

                ax_delta.plot(df_filtered['Дельта'], df_filtered['Модифицированное значение'], label=f'Tоб: {tob_value}, Pt={pt}')

                print(f"Уравнение для Tоб {tob_value}, Pt={pt}: y = {slope:.4f} * x + {intercept:.10f}")
            else:
                print(f"Недостаточно данных для построения модели для Tоб {tob_value}, Pt={pt}")

    ax_gt.set_title('Зависимость f(Pот, Gтурб)')
    ax_gt.set_xlabel('Gт')
    ax_gt.set_ylabel('Модифицированное значение')
    ax_gt.legend()
    ax_gt.grid(True)  # Добавляем сетку

    ax_delta.set_title('Зависимость f(dNe, dtоб)')
    ax_delta.set_xlabel('Дельта')
    ax_delta.set_ylabel('Модифицированное значение')
    ax_delta.legend()
    ax_delta.grid(True)  # Добавляем сетку

    plt.tight_layout()
    plt.show()

def remove_outliers_iqr(df, column_name):
    Q1 = df[column_name].quantile(0.25)
    Q3 = df[column_name].quantile(0.75)
    IQR = Q3 - Q1

    lower_bound = Q1 - 1.5 * IQR
    upper_bound = Q3 + 1.5 * IQR

    return df[(df[column_name] >= lower_bound) & (df[column_name] <= upper_bound)]

def find_temperature_pairs(pressure_temp_data):
    """
    Находит соответствующие пары температур для одинаковых дельт между разными давлениями.

    :param pressure_temp_data: словарь, где ключ — давление, значение — словарь с номинальной температурой и списком температур
    :return: словарь, где ключ — дельта, значение — список кортежей (давление, температура)
    """
    # Словарь для хранения температур по дельтам
    delta_to_temps = {}

    # Вычисляем дельты и собираем температуры по дельтам
    for pressure, data in pressure_temp_data.items():
        nominal = data['nominal']
        temperatures = data['temperatures']
        deltas = [int(round(temp - nominal)) for temp in temperatures]
        data['deltas'] = deltas  # Сохраняем дельты обратно в данные

        for delta, temp in zip(deltas, temperatures):
            if delta not in delta_to_temps:
                delta_to_temps[delta] = []
            delta_to_temps[delta].append((pressure, temp))

    # Ищем дельты, которые присутствуют в нескольких давлениях
    result = {}
    for delta, temps in delta_to_temps.items():
        if len(temps) > 1:
            result[delta] = temps

    # Сортируем результаты по дельтам
    sorted_result = {delta: result[delta] for delta in sorted(result)}

    # Выводим результат
    print("Соответствующие пары температур для общих дельт:")
    for delta, temps in sorted_result.items():
        print(f"{delta}: {temps}")

    return sorted_result

if __name__ == "__main__":
    excel_file = '/content/drive/MyDrive/Final_test_data.xlsx'
    final_output_file = 'final_output_with_delta.csv'

    temperature_index = 9  # Индекс колонки 'Tоб'
    flow_rate_index = 0    # Индекс колонки 'Gт'
    power_index = 2        # Индекс колонки 'Ne'
    pressure_index = 11    # Индекс колонки 'Pt'

    # Загрузка данных из Excel файла
    df = load_data_from_excel(excel_file, [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
                                           13, 14, 15, 16, 17, 18, 19, 20, 21,
                                           22, 23, 24, 25, 26, 27, 28])

    # Округление давления до десятых долей
    df['Pt_rounded'] = df.iloc[:, pressure_index].round(1)

    # Получение уникальных значений давления
    unique_pt_values = df['Pt_rounded'].unique()
    print(f"Уникальные значения давления: {unique_pt_values}")

    data_list = []
    pt_values = []
    pressure_temp_data = {}  # Для хранения температур и номинальных температур

    for pt in unique_pt_values:
        print(f"\nОбработка давления Pt = {pt}")
        df_pt = df[df['Pt_rounded'] == pt].copy().drop(columns=['Pt_rounded'])

        # Сортировка данных
        sorted_df = sort_data_by_temperature_and_flow_rate(df_pt, temperature_index, flow_rate_index)

        # Находжение уникальных значений температуры
        unique_temperatures = get_unique_temperatures(sorted_df, temperature_index)

        # Поиск номинального значения температуры
        nominal_temperature = find_nominal_temperature(unique_temperatures)

        # Сохраняем данные для функции поиска пар температур
        pressure_temp_data[pt] = {
            'nominal': nominal_temperature,
            'temperatures': sorted(unique_temperatures.tolist())
        }

        # Расчет дельты
        result_df = calculate_deltas(sorted_df, temperature_index, power_index, nominal_temperature)

        # Запрос целевых значений для первого давления
        if len(data_list) == 0:
            target_values = {}
            for temp in get_unique_temperatures(result_df, temperature_index):
                target_value = float(input(f"Введите целевое значение для температуры {temp} (например, 1.0): "))
                target_values[temp] = target_value

            # Нормализация дельты
            normalized_df = normalize_deltas(result_df, temperature_index, result_df.columns.get_loc('Дельта'), target_values)
            # Удаление выбросов по столбцу 'Модифицированное значение'
            cleaned_df = remove_outliers_iqr(normalized_df, 'Модифицированное значение')

            # Автоматическое переименование столбцов после создания новых столбцов
            column_names = [
                'Gт', 'Qт', 'Ne', 'qe', 'Gcн', 'Ipв', 'Toхл', 'Qот', 'w',
                'Tоб', 'Tпр', 'Pt', 'Pдиаф', 'Psн', 'Pk', 'Gк',
                'G:Д03', 'G:С29', 'T:Д03', 'P:Д03', 'P:Ч13', 'T:Ч13',
                'P:Ч17', 'P:Ч20', 'P:Ч29', 'T:Р27', 'T:ДФ', 'Дельта', 'Модифицированное значение'
            ]

            # Проверяем, совпадает ли количество столбцов
            if len(column_names) == cleaned_df.shape[1]:
                cleaned_df.columns = column_names
            else:
                print(f"Количество столбцов в DataFrame ({cleaned_df.shape[1]}) не соответствует ожидаемому ({len(column_names)}). Автоматическое переименование невозможно.")
                continue

            # Сохранение результата
            output_file = f'final_output_with_delta_Pt_{pt}.csv'
            save_data(cleaned_df, output_file)
            print(f"Обработка давления Pt = {pt} завершена.")

            data_list.append(cleaned_df)
            pt_values.append(pt)

            # Получаем коэффициенты регрессии для первого давления
            temp_base_to_coef = get_regression_coefficients(cleaned_df, temperature_index)

        else:
            # Для остальных давлений
            # Расчет дельты уже выполнен выше

            # Инициализируем столбец 'Модифицированное значение'
            result_df['Модифицированное значение'] = 0.0
            delta_index = result_df.columns.get_loc('Дельта')
            tolerance = 1e-6

            # Получаем пары температур для общих дельт
            delta_to_temps_pressures = find_temperature_pairs(pressure_temp_data)

            # Словарь целевых значений для температур
            target_values = {}

            for delta, temp_pressure_list in delta_to_temps_pressures.items():
                # Ищем соответствующие температуры для текущего давления и первого давления
                temp_base = None
                temp_match = None
                for pressure, temp in temp_pressure_list:
                    if pressure == pt:
                        temp_match = temp
                    elif pressure == pt_values[0]:
                        temp_base = temp

                if temp_base and temp_match:
                    coef_base = temp_base_to_coef.get(temp_base, None)
                    if coef_base is None:
                        print(f"Коэффициент регрессии для температуры {temp_base} не найден.")
                        continue

                    # Оптимизируем целевое значение для temp_match
                    optimal_target_value, k = optimize_target_value(
                        temp_match, result_df, temperature_index, delta_index, coef_base, tolerance
                    )
                    if optimal_target_value is not None:
                        target_values[temp_match] = optimal_target_value
                        print(f"Оптимальное целевое значение для температуры {temp_match} при Pt={pt}: {optimal_target_value:.4f}, коэффициент k: {k:.4f}")
                    else:
                        print(f"Не удалось оптимизировать целевое значение для температуры {temp_match} при Pt={pt}")
                else:
                    print(f"Нет соответствующей температуры для дельты {delta} при давлении {pt}")

            # Нормализуем дельты с найденными целевыми значениями
            normalized_df = normalize_deltas(result_df, temperature_index, delta_index, target_values)
            # Удаление выбросов по столбцу 'Модифицированное значение'
            cleaned_df = remove_outliers_iqr(normalized_df, 'Модифицированное значение')

            # Автоматическое переименование столбцов после создания новых столбцов
            column_names = [
                'Gт', 'Qт', 'Ne', 'qe', 'Gcн', 'Ipв', 'Toхл', 'Qот', 'w',
                'Tоб', 'Tпр', 'Pt', 'Pдиаф', 'Psн', 'Pk', 'Gк',
                'G:Д03', 'G:С29', 'T:Д03', 'P:Д03', 'P:Ч13', 'T:Ч13',
                'P:Ч17', 'P:Ч20', 'P:Ч29', 'T:Р27', 'T:ДФ', 'Дельта', 'Модифицированное значение'
            ]

            # Проверяем, совпадает ли количество столбцов
            if len(column_names) == cleaned_df.shape[1]:
                cleaned_df.columns = column_names
            else:
                print(f"Количество столбцов в DataFrame ({cleaned_df.shape[1]}) не соответствует ожидаемому ({len(column_names)}). Автоматическое переименование невозможно.")
                continue

            # Сохранение результата
            output_file = f'final_output_with_delta_Pt_{pt}.csv'
            save_data(cleaned_df, output_file)
            print(f"Обработка давления Pt = {pt} завершена.")

            data_list.append(cleaned_df)
            pt_values.append(pt)

    # Вызов функции для поиска пар температур
    find_temperature_pairs(pressure_temp_data)

    # Построение графиков
    main_plot(data_list, pt_values)
Код возвращает:
Уникальные значения давления: [1.2 1.5]

Обработка давления Pt = 1.2
Уникальные значения температуры: [38 43 48 53 58 63 68]
Введите номинальное значение температуры обратной сетевой воды (например, 70): 53
Введите целевое значение для температуры 38 (например, 1.0): 0.05
Введите целевое значение для температуры 43 (например, 1.0): 0.05
Введите целевое значение для температуры 48 (например, 1.0): 0.05
Введите целевое значение для температуры 58 (например, 1.0): 0.05
Введите целевое значение для температуры 63 (например, 1.0): 0.05
Введите целевое значение для температуры 68 (например, 1.0): 0.05
<ipython-input-4-8ca4627d3feb>:86: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df['Модифицированное значение'] = 0.0
Обработка давления Pt = 1.2 завершена.

Обработка давления Pt = 1.5
Уникальные значения температуры: [50 55 60 65 70]
Введите номинальное значение температуры обратной сетевой воды (например, 70): 70
<ipython-input-4-8ca4627d3feb>:405: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  result_df['Модифицированное значение'] = 0.0
<ipython-input-4-8ca4627d3feb>:86: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df['Модифицированное значение'] = 0.0
Соответствующие пары температур для общих дельт:
-15: [(1.2, 38), (1.5, 55)]
-10: [(1.2, 43), (1.5, 60)]
-5: [(1.2, 48), (1.5, 65)]
0: [(1.2, 53), (1.5, 70)]
Оптимальное целевое значение для температуры 55 при Pt=1.5: 0.0571, коэффициент k: 0.1786
Оптимальное целевое значение для температуры 60 при Pt=1.5: 0.0565, коэффициент k: 0.2174
Оптимальное целевое значение для температуры 65 при Pt=1.5: 0.0682, коэффициент k: 0.4545
Коэффициент регрессии для температуры 53 не найден.
Целевое значение для температуры 50 не задано.
Обработка давления Pt = 1.5 завершена.
Соответствующие пары температур для общих дельт:
-15: [(1.2, 38), (1.5, 55)]
-10: [(1.2, 43), (1.5, 60)]
-5: [(1.2, 48), (1.5, 65)]
0: [(1.2, 53), (1.5, 70)]
[I 2024-12-01 16:24:00,356] A new study created in memory with name: no-name-715de29d-6b54-4ab1-a3db-8230596ad16a
[I 2024-12-01 16:24:00,363] Trial 0 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,370] Trial 1 finished with value: -0.9250701650474981 and parameters: {'degree': 1}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,377] Trial 2 finished with value: -0.9333863839137906 and parameters: {'degree': 2}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,383] Trial 3 finished with value: -0.9333863839137906 and parameters: {'degree': 2}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,395] Trial 4 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,403] Trial 5 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,411] Trial 6 finished with value: -0.9333863839137906 and parameters: {'degree': 2}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,426] Trial 7 finished with value: -0.9333805529648781 and parameters: {'degree': 3}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,435] Trial 8 finished with value: -0.9333863839137906 and parameters: {'degree': 2}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,443] Trial 9 finished with value: -0.9333863839137906 and parameters: {'degree': 2}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,460] Trial 10 finished with value: -0.9332533314015535 and parameters: {'degree': 4}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,479] Trial 11 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,498] Trial 12 finished with value: -0.9332533314015535 and parameters: {'degree': 4}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,516] Trial 13 finished with value: -0.9332533314015535 and parameters: {'degree': 4}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,533] Trial 14 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,549] Trial 15 finished with value: -0.9332533314015535 and parameters: {'degree': 4}. Best is trial 0 with value: -0.9334174302934306.
Обработка давления Pt = 1.2
[I 2024-12-01 16:24:00,568] Trial 16 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,590] Trial 17 finished with value: -0.9333805529648781 and parameters: {'degree': 3}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,614] Trial 18 finished with value: -0.9333805529648781 and parameters: {'degree': 3}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,633] Trial 19 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,655] Trial 20 finished with value: -0.9332533314015535 and parameters: {'degree': 4}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,680] Trial 21 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,706] Trial 22 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,731] Trial 23 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,757] Trial 24 finished with value: -0.9332533314015535 and parameters: {'degree': 4}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,781] Trial 25 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,807] Trial 26 finished with value: -0.9332533314015535 and parameters: {'degree': 4}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,834] Trial 27 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,856] Trial 28 finished with value: -0.9333805529648781 and parameters: {'degree': 3}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,874] Trial 29 finished with value: -0.9250701650474981 and parameters: {'degree': 1}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,896] Trial 30 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,918] Trial 31 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,934] Trial 32 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,951] Trial 33 finished with value: -0.9332533314015535 and parameters: {'degree': 4}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,969] Trial 34 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:00,988] Trial 35 finished with value: -0.9250701650474981 and parameters: {'degree': 1}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,011] Trial 36 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,033] Trial 37 finished with value: -0.9332533314015535 and parameters: {'degree': 4}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,053] Trial 38 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,069] Trial 39 finished with value: -0.9332533314015535 and parameters: {'degree': 4}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,090] Trial 40 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,107] Trial 41 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,124] Trial 42 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,140] Trial 43 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,157] Trial 44 finished with value: -0.9332533314015535 and parameters: {'degree': 4}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,175] Trial 45 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,194] Trial 46 finished with value: -0.9332533314015535 and parameters: {'degree': 4}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,210] Trial 47 finished with value: -0.9334174302934306 and parameters: {'degree': 5}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,226] Trial 48 finished with value: -0.9333805529648781 and parameters: {'degree': 3}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,243] Trial 49 finished with value: -0.9333863839137906 and parameters: {'degree': 2}. Best is trial 0 with value: -0.9334174302934306.
[I 2024-12-01 16:24:01,279] A new study created in memory with name: no-name-beadb4ee-84f3-4cab-adc5-b70acd797cb7
[I 2024-12-01 16:24:01,286] Trial 0 finished with value: -0.16520896830950949 and parameters: {'degree': 4}. Best is trial 0 with value: -0.16520896830950949.
[I 2024-12-01 16:24:01,292] Trial 1 finished with value: -0.16117374314125132 and parameters: {'degree': 1}. Best is trial 0 with value: -0.16520896830950949.
[I 2024-12-01 16:24:01,298] Trial 2 finished with value: -0.16117374314125132 and parameters: {'degree': 1}. Best is trial 0 with value: -0.16520896830950949.
[I 2024-12-01 16:24:01,304] Trial 3 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,311] Trial 4 finished with value: -0.16520896830950949 and parameters: {'degree': 4}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,317] Trial 5 finished with value: -0.1669575798547055 and parameters: {'degree': 3}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,323] Trial 6 finished with value: -0.16768690812633924 and parameters: {'degree': 5}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,329] Trial 7 finished with value: -0.16768690812633924 and parameters: {'degree': 5}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,335] Trial 8 finished with value: -0.1669575798547055 and parameters: {'degree': 3}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,342] Trial 9 finished with value: -0.16768690812633924 and parameters: {'degree': 5}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,357] Trial 10 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,376] Trial 11 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,399] Trial 12 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,426] Trial 13 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
Уравнение полинома для графика 'Модифицированное значение' от 'Gт' (степень 5), Pt=1.2:
y = 0.0975 + (0.000065387994208) * x^1 + (-0.001644694602162) * x^2 + (0.003248404921449) * x^3 + (0.034656644759113) * x^4 + (0.000000000000000) * x^5 
Уравнение для Tоб 38, Pt=1.2: y = 0.1786 * x + 0.0000000000
Уравнение для Tоб 43, Pt=1.2: y = 0.2174 * x + -0.0000000000
Уравнение для Tоб 48, Pt=1.2: y = 0.4545 * x + 0.0000000000
Уравнение для Tоб 58, Pt=1.2: y = -0.4167 * x + 0.0000000000
Уравнение для Tоб 63, Pt=1.2: y = -0.2000 * x + 0.0000000000
Уравнение для Tоб 68, Pt=1.2: y = -0.1220 * x + 0.0000000000
Обработка давления Pt = 1.5
[I 2024-12-01 16:24:01,452] Trial 14 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,476] Trial 15 finished with value: -0.16117374314125132 and parameters: {'degree': 1}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,508] Trial 16 finished with value: -0.1669575798547055 and parameters: {'degree': 3}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,528] Trial 17 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,550] Trial 18 finished with value: -0.16520896830950949 and parameters: {'degree': 4}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,568] Trial 19 finished with value: -0.16117374314125132 and parameters: {'degree': 1}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,587] Trial 20 finished with value: -0.1669575798547055 and parameters: {'degree': 3}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,606] Trial 21 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,628] Trial 22 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,651] Trial 23 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,671] Trial 24 finished with value: -0.1669575798547055 and parameters: {'degree': 3}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,695] Trial 25 finished with value: -0.16117374314125132 and parameters: {'degree': 1}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,719] Trial 26 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,745] Trial 27 finished with value: -0.1669575798547055 and parameters: {'degree': 3}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,769] Trial 28 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,791] Trial 29 finished with value: -0.16117374314125132 and parameters: {'degree': 1}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,819] Trial 30 finished with value: -0.1669575798547055 and parameters: {'degree': 3}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,847] Trial 31 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,869] Trial 32 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,885] Trial 33 finished with value: -0.16117374314125132 and parameters: {'degree': 1}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,905] Trial 34 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,922] Trial 35 finished with value: -0.16117374314125132 and parameters: {'degree': 1}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,939] Trial 36 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,957] Trial 37 finished with value: -0.1669575798547055 and parameters: {'degree': 3}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,973] Trial 38 finished with value: -0.16520896830950949 and parameters: {'degree': 4}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:01,988] Trial 39 finished with value: -0.16117374314125132 and parameters: {'degree': 1}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:02,004] Trial 40 finished with value: -0.1669575798547055 and parameters: {'degree': 3}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:02,020] Trial 41 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:02,035] Trial 42 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:02,052] Trial 43 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:02,069] Trial 44 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:02,085] Trial 45 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:02,102] Trial 46 finished with value: -0.16117374314125132 and parameters: {'degree': 1}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:02,119] Trial 47 finished with value: -0.1669575798547055 and parameters: {'degree': 3}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:02,136] Trial 48 finished with value: -0.1753961027067762 and parameters: {'degree': 2}. Best is trial 3 with value: -0.1753961027067762.
[I 2024-12-01 16:24:02,152] Trial 49 finished with value: -0.1669575798547055 and parameters: {'degree': 3}. Best is trial 3 with value: -0.1753961027067762.
Уравнение полинома для графика 'Модифицированное значение' от 'Gт' (степень 2), Pt=1.5:
y = 0.0571 + (0.012538372035580) * x^1 + (0.000000000000000) * x^2 
Уравнение для Tоб 50, Pt=1.5: y = 0.0000 * x + 0.0000000000
Уравнение для Tоб 55, Pt=1.5: y = 0.1786 * x + -0.0000000000
Уравнение для Tоб 60, Pt=1.5: y = 0.2174 * x + -0.0000000000
Уравнение для Tоб 65, Pt=1.5: y = 0.4545 * x + 0.0000000000
Я бы хотел измменить кд так, чтобы для всех последующих давлений после первого для температур у которых нет соответствия из первого давления не строились бы графики. Пример для давления 1.5 температура 50 не имеет соответствия из первого давления и модель возвращается с коэфиициентом 0 Уравнение для Tоб 50, Pt=1.5: y = 0.0000 * x + 0.0000000000, что портит вид графиков