
import logging
import sys
import os
import math
import numpy as np
sys.path.append(os.path.dirname(os.getcwd()))
print(sys.path)
from smac.facade.func_facade import fmin_smac
from ConfigSpace.hyperparameters import UniformFloatHyperparameter

# Import ConfigSpace and different types of parameters
from smac.configspace import ConfigurationSpace
from smac.facade.smac_bo_facade import SMAC4BO
# Import SMAC-utilities
from smac.scenario.scenario import Scenario

def branin_function(configs):
    
    """
    Compute the branin function.
    :param X: dictionary containing the input points.
    :return: the value of the branin function
    """
    x1, x2 = configs["x0"] * 15 - 5, 2.275

    a = 1.0
    b = 5.1 / (4.0 * math.pi * math.pi)
    c = 5.0 / math.pi
    r = 6.0
    s = 10.0
    t = 1.0 / (8.0 * math.pi)

    y_value = a * (x2 - b * x1 * x1 + c * x1 - r) ** 2 + s * (1 - t) * np.cos(x1) + s
    #print(f'BRANIN PRINT: X: {X} ----- Y: {y_value}' )
    # restructure to get the same return value structure as the other funtions
    print(f'Function value of {y_value} \n configuration {configs}')

    return y_value


# debug output
logging.basicConfig(level=20)
logger = logging.getLogger("Optimizer")  # Enable to show Debug outputs

# Build Configuration Space which defines all parameters and their ranges
cs = ConfigurationSpace()
x0 = UniformFloatHyperparameter("x0", 0, 1, default_value=0)

cs.add_hyperparameters([x0])

# Scenario object
scenario = Scenario({"run_obj": "quality",  # we optimize quality (alternatively runtime)
                     "runcount-limit": 50,  # max. number of function evaluations; for this example set to a low number
                     "cs": cs,  # configuration space
                     "deterministic": "true"
                     })
init_kwargs = {'init_budget': 2}
# fmin_smac assumes that the function is deterministic
# and uses under the hood the SMAC4HPO
# Optimize, using a SMAC-object
print("Optimizing! Depending on your machine, this might take a few minutes.")
smac = SMAC4BO(scenario=scenario,
               initial_design_kwargs=init_kwargs,
               rng=np.random.RandomState(42),
               tae_runner=branin_function,
               )

smac.optimize()
