import numpy as np

import optuna

from BO_Objective import Objective


def normalize_trials(trials):
    value_list = np.array([t.values for t in trials])
    mu = np.mean(value_list, axis=0)
    std = np.std(value_list, axis=0)
    return (value_list - mu) / (std + 1e-9)


def radar_area_matrix(values):
    """
    Computes the radar-chart polygon area for each row in 'values'
    using the shoelace formula (vectorized).

    Parameters
    ----------
    values : 2D np.ndarray of shape (m, n)
        - m: number of rows (models/configurations)
        - n: number of radar dimensions (objectives)
        Each row is one set of radial distances for the radar chart.

    Returns
    -------
    areas : 1D np.ndarray of shape (m,)
        The polygon area for each row.
    """
    values = np.asarray(values)
    m, n = values.shape

    # Angles equally spaced
    angles = np.linspace(0, 2 * np.pi, n, endpoint=False)

    x = values * np.cos(angles)
    y = values * np.sin(angles)

    # Shoelace formula
    cross_term = x * np.roll(y, -1, axis=1) - y * np.roll(x, -1, axis=1)
    areas = 0.5 * np.abs(np.sum(cross_term, axis=1))

    return areas




if __name__ == "__main__":
    datasets = [
        # 'arrhythmia', 'wine', 'lympho', 'glass', 'vertebral', 'wbc', 'ecoli', 'ionosphere', 'breastw', 'pima',
        # 'vowels',
        #
        # 'letter',
        # 'cardio',
        'seismic',
        'musk', 'speech', 'abalone', 'pendigits', 'mammography',
        'mulcross',
        'forest_cover'
                ]

    for dataset in datasets:
        objective = Objective(dataset, method='tsne', save_path='res-2')

        # algo = optuna.samplers.TPESampler(n_startup_trials=10, n_ei_candidates=24)
        algo = optuna.samplers.NSGAIISampler()
        # algo = optuna.samplers.GPSampler(n_startup_trials=10)
        study = optuna.create_study(sampler=algo, directions=['maximize']*9, storage="sqlite:///record/ocsvm2.db")
        study.optimize(objective.tsne_search, n_trials=500, show_progress_bar=True)
        print(study.best_trials)

        # objective.plot_results('OCSVM', root='./res-ocsvm-large_data')
        objective.save_result('TSNE')