Пример #1
0
def game_to_milp(g: Game, robust=True, counter_examples=None):
    # TODO: implement counter_example encoding
    if not counter_examples:
        counter_examples = [{}]

    model = Model()
    store = keydefaultdict(lambda x: rob_encode.z(x, g))
    # Add counter examples to store
    for i, ce in enumerate(counter_examples):
        store.update(counter_example_store(g, ce, i))

    # Encode each scenario.
    scenarios = [
        create_scenario(g, i) for i, ce in enumerate(counter_examples)
    ]
    constraints, objs = zip(*(encode_game(g2, store) for g2 in scenarios))

    # Objective is to maximize the minimum robustness of the scenarios.
    if len(objs) > 1:
        obj = stl.andf(*objs)
        constraints = chain(rob_encode.encode(obj, store, 0),
                            fn.cat(constraints))
    else:
        obj = objs[0]
        constraints = fn.cat(constraints)

    for i, (constr, kind) in enumerate(constraints):
        if constr is True:
            continue
        add_constr(model, constr, kind, i)

    # TODO: support alternative objective functions
    J = store[obj][0] if isinstance(store[obj], tuple) else store[obj]
    model.objective = Objective(J, direction='max')
    return model, store
Пример #2
0
def game_to_milp(g: Game, robust=True, counter_examples=None):
    # TODO: implement counter_example encoding
    if not counter_examples:
        counter_examples = [{}]

    model = Model()
    store = keydefaultdict(lambda x: rob_encode.z(x, g))
    # Add counter examples to store
    for i, ce in enumerate(counter_examples):
        store.update(counter_example_store(g, ce, i))

    # Encode each scenario.
    scenarios = [
        create_scenario(g, i) for i, ce in enumerate(counter_examples)
    ]
    constraints, objs = zip(*(encode_game(g2, store) for g2 in scenarios))

    # Objective is to maximize the minimum robustness of the scenarios.
    if len(objs) > 1:
        obj = stl.andf(*objs)
        constraints = chain(
            rob_encode.encode(obj, store, 0), fn.cat(constraints))
    else:
        obj = objs[0]
        constraints = fn.cat(constraints)

    for i, (constr, kind) in enumerate(constraints):
        if constr is True:
            continue
        add_constr(model, constr, kind, i)

    # TODO: support alternative objective functions
    J = store[obj][0] if isinstance(store[obj], tuple) else store[obj]
    model.objective = Objective(J, direction='max')
    return model, store
Пример #3
0
def fact(meta, plazo, DD, Gm, F):
    # All the (symbolic) variables are declared, with a name and optionally a lower and/or upper bound.
    a = Variable('%ahorro', lb=0, ub=1)
    g = Variable('%otrosgastos', lb=0, ub=1)
    f = Variable('%fondoemergencia', lb=0, ub=1)

    # A constraint is constructed from an expression of variables and a lower and/or upper bound (lb and ub).
    c1 = Constraint(a + g + f, lb=1, ub=1)
    c2 = Constraint(g * DD, lb=Gm)
    #El % de ahorro * dinero disponible * el plazo debe ser estrictamente igual a la meta
    c3 = Constraint(a * DD * plazo, lb=meta, ub=meta)
    c4 = Constraint(f * DD, lb=F, ub=F)

    # An objective can be formulated
    obj = Objective(a * DD * plazo, direction='max')

    # Variables, constraints and objective are combined in a Model object, which can subsequently be optimized.
    model = Model(name='Simple model')
    model.objective = obj
    model.add([c1, c2, c3, c4])

    status = model.optimize()
    #print("status:", model.status)
    #print("objective value:", model.objective.value)
    #print("----------")
    resultados = {
        '%ahorro': 0,
        '%otrosgastos': 0,
        '%fondoemergencia': 0,
        'status': status,
        'months': plazo
    }
    for var_name, var in model.variables.iteritems():
        resultados[var_name] = round(var.primal * DD)
    if model.status == 'optimal':
        print('Opcion 1:')
        print('Ahorrando mensual', resultados['%ahorro'], ', lograras ahorrar',
              resultados['%ahorro'] * plazo)
        print('Para otros gastos tendrías disponible mensual',
              resultados['%otrosgastos'])
        print('En', plazo, 'meses')
    else:
        print('La meta no es factible con las condiciones dadas:')
        print('Con', DD, 'disponible, ahorrar', meta, 'en', plazo,
              'meses, con', Gm, 'mínimo para otros gastos.')
    resultados['saving'] = resultados['%ahorro']
    resultados['other'] = resultados['%otrosgastos']
    resultados['emergency'] = resultados['%fondoemergencia']
    resultados['total'] = resultados['%ahorro'] * plazo
    resultados['msg'] = "Ahorrando mensual $ " + '{:,}'.format(resultados['saving']).replace(",",".") \
        + " , lograrás ahorrar $ " + '{:,}'.format(resultados['total']).replace(",",".") \
        + ". Para otros gastos tendrías disponible mensual $ " \
        + '{:,}'.format(resultados['other']).replace(",",".") + " en "+str(resultados['months']) + " meses."
    return resultados
Пример #4
0
def stoichiomatrix_solution(S, flux_bounds, objective_index,
                            objective_direction):

    #We make a variable 'v-(index)' for each reaction (column) in the matrix:
    variables = make_variables(S, flux_bounds)
    constraints = make_constraints(S, variables)
    obj = make_objective(objective_index, objective_direction, variables)

    model = Model(name='Stoichiomatrix')
    model.objective = obj
    model.add(constraints)
    status = model.optimize()

    return [status, model]
Пример #5
0
def tiempo(meta, DD, Gm, F):
    plazo = 0
    while plazo <= 60:
        a = Variable('%ahorro', lb=0, ub=1)
        g = Variable('%otrosgastos', lb=0, ub=1)
        f = Variable('%fondoemergencia', lb=0, ub=1)

        # A constraint is constructed from an expression of variables and a lower and/or upper bound (lb and ub).
        c1 = Constraint(a + g + f, lb=1, ub=1)
        c2 = Constraint(g * DD, lb=Gm)
        #El % de ahorro * dinero disponible * el plazo debe ser estrictamente igual a la meta
        c3 = Constraint(a * DD * plazo, lb=meta, ub=meta)
        c4 = Constraint(f * DD, lb=F, ub=F)
        # An objective can be formulated
        obj = Objective(a * DD * plazo, direction='max')
        # Variables, constraints and objective are combined in a Model object, which can subsequently be optimized.
        model = Model(name='Simple model')
        model.objective = obj
        model.add([c1, c2, c3, c4])
        resultados = dict()
        status = model.optimize()
        for var_name, var in model.variables.iteritems():
            #print(var_name, "=", round(var.primal * DD))
            resultados[var_name] = round(var.primal * DD)
        if model.status == 'optimal':
            print('Opción 2:')
            print('Ahorrando mensual', resultados['%ahorro'],
                  ', lograras ahorrar', resultados['%ahorro'] * plazo)
            print('Para otros gastos tendrías disponible mensual',
                  resultados['%otrosgastos'])
            print('En', plazo, 'meses')
            break
        plazo += 1
    if plazo > 60:
        status = 'overtime'
    resultados.update({'status': status, 'months': plazo})
    resultados['months'] = plazo
    resultados['saving'] = resultados['%ahorro']
    resultados['other'] = resultados['%otrosgastos']
    resultados['emergency'] = resultados['%fondoemergencia']
    resultados['total'] = resultados['%ahorro'] * plazo
    resultados['msg'] = "Ahorrando mensual $ " + '{:,}'.format(resultados['saving']).replace(",",".") \
        + " , lograrás ahorrar $ " + '{:,}'.format(resultados['total']).replace(",",".") \
        + ". Para otros gastos tendrías disponible mensual $ " \
        + '{:,}'.format(resultados['other']).replace(",",".") + " en "+str(resultados['months']) + " meses."
    return resultados
Пример #6
0
def solveBIP(affinity):
    m = len(affinity)
    n = len(affinity[0])
    variables = {}
    for i in range(0, m):
        variables[i] = {}
        for j in range(0, n):
            var = Variable(name="{}_{}".format(i, j),
                           lb=0,
                           ub=1,
                           type="integer")
            variables[i][j] = var

    constraints = []
    for i in range(0, m):
        const = Constraint(sum(variables[i].values()), ub=1)
        constraints.append(const)

    for j in range(0, n):
        const = Constraint(sum(row[j] for row in variables.values()), ub=1)
        constraints.append(const)

    obj = Objective(
        sum(affinity[i][j] * variables[i][j] for i in range(0, m)
            for j in range(0, n)))

    model = Model(name="BIP Solved")
    model.add(constraints)
    model.objective = obj

    status = model.optimize()
    # for var in model.variables:
    # 	print var.name, " : ", var.primal

    mat = np.zeros((m, n))
    #print mat
    for ind in model.variables:
        i, j = ind.name.split("_")
        i = int(i)
        j = int(j)
        mat[i, j] = ind.primal

    return mat
Пример #7
0
def buildModel(constraint_list, obj, model_name):
    """
    Construit le model et l'excute pour le résoudre
    En décommentant les lignes, il est possible d'afficher les élements constitutifs d'un modèle (debug)
        
    Args:
        constraint_list : listes contraintes existantes
        obj: fonction objectif
        model_name: nom du model

    Return: l'objet modèle
    """
    model = Model(name = model_name)
    model.objective = obj
    model.add(constraint_list)
    model.optimize() 
    #Print du modèle pour débug
#    for cons in model.constraints.items():
#        print(cons[1])
#    for var in model.variables.items():
#        print(var)
    return model
    constraints.append(const)
for destination in demand:
    const = Constraint(sum(row[destination] for row in variables.values()),
                       lb=demand[destination],
                       name="{}_demand".format(destination))
    constraints.append(const)

# Define the objective
obj = Objective(sum(freight_cost * distances[ori][dest] * variables[ori][dest]
                    for ori in supply for dest in demand),
                direction="min")
# We can print the objective and constraints
print(obj)
print("")
for const in constraints:
    print(const)

print("")

# Put everything together in a Model
model = Model()
model.add(constraints)  # Variables are added implicitly
model.objective = obj

# Optimize and print the solution
status = model.optimize()
print("Status:", status)
print("Objective value:", model.objective.value)
print("")
for var in model.variables:
    print(var.name, ":", var.primal)
Пример #9
0
def result():
    if request.method == 'POST':
        fields = [k for k in request.form]
        values = [request.form[k] for k in request.form]
        data = dict(zip(fields, values))
        animal_name = data['animal']
        animal_type = data['animal_type']
        weight = data['weight']
        ingredients = {
            k: v
            for k, v in data.items()
            if k != 'animal' and k != 'animal_type' and k != 'weight'
        }
        selected_ingredients = [*ingredients]
        print(selected_ingredients)

        ################################################
        variable_objects = []  # stores all the contraints for the formulation
        """The feed size is the amount in kilogram (kg) the buyer wants to get from the feed formulator, this should be collected from the client side"""
        feed_size = weight
        animal_selected = animal_name
        #################################
        selected_animal_stage = animal_type

        variable_objects = []  # stores all the contraints for the formulation

        variable_sum = None
        for i in range(1, len(selected_ingredients) + 1):
            ing = Variable('x{0}'.format(i), lb=0)
            if i == 1:
                variable_sum = ing
            elif i > 1:
                variable_sum += ing
            variable_objects.append(ing)
        print("THE VARIABLE SUM FOR THE CONSTRAINT =>>>>>", variable_sum)

        #the next step is to build the constraints for the formulation
        #we will build the contraints using the value of the ingredients respective nutrients compositions for the the particular animal maximum and minimum nutrient value
        #let's build the first contraint for the formulation

        #but before then, the demand reqirement will be the variable_sum, so all we need to do is to assign the variable_sum to the first contraint
        # contraint_sum = None

        #this should be constants to solve the formulation
        #do not change
        c1 = Constraint(variable_sum, lb=feed_size)
        # c2 = Constraint(variable_sum,ub = feed_size )
        contraints_list = []
        #append the fisrt two constraints into the contraints_list.
        contraints_list.append(c1)
        # contraints_list.append(c2)

        # the temp sum to hold the temporary sum of all the varible for the formulation
        temp_var_sum = None

        # print(animal_db[animal_selected][selected_animal_stage])
        # if the user selects finisher broiler

        #This will return the keys in the finisher's feed contraints
        # This will return the keys in the finisher's feed contraints
        for nutrient in animal_db[animal_selected][selected_animal_stage]:
            """now we will iterate through the returned nutrient compositions for the finisher broiler"""
            for bound in animal_db[animal_selected][selected_animal_stage][
                    nutrient]:
                count = 0
                # print("BOUND=>",bound)

                for ing_name in selected_ingredients:
                    # print("\nIngredient ====>",ing_name,"\n")
                    if count == 0:
                        # print("\n\n--------------Another contraints goes from here-----------------------------")
                        if nutrient != "Energy":
                            temp_var_sum = (
                                ingredient_db[ing_name]["ing"][nutrient] /
                                100) * variable_objects[count]
                            # print(temp_var_sum,end=" ")
                            count = count + 1
                        else:
                            temp_var_sum = ingredient_db[ing_name]["ing"][
                                nutrient] * variable_objects[count]
                            # print(temp_var_sum,end=" ")
                            count = count + 1

                        # print(count)
                    elif count > 0:
                        # print("\n\n--------------Another contraints goes from here-----------------------------")
                        if nutrient != "Energy":
                            temp_var_sum += (
                                ingredient_db[ing_name]["ing"][nutrient] /
                                100) * variable_objects[count]
                            # print(temp_var_sum,end=" ")
                            count = count + 1
                        else:
                            temp_var_sum += ingredient_db[ing_name]["ing"][
                                nutrient] * variable_objects[count]
                            # print(temp_var_sum,end=" ")
                            count = count + 1

                ############################Then we build the contraints from here after the sum of the constraints has been generated##############################

                # print("\n\n--------------Another contraints goes from here-----------------------------")
                # print("NUTRIENT ===> ",nutrient)
                # print(temp_var_sum, end=" ")
                # print("BOUND=>",bound, end=" ")
                # print("=",animal_db[animal_selected][selected_animal_stage][nutrient][bound])

                if bound == "Min":
                    contraints_list.append(
                        Constraint(temp_var_sum,
                                   lb=animal_db[animal_selected]
                                   [selected_animal_stage][nutrient][bound]))
                    print(
                        temp_var_sum, ">=", animal_db[animal_selected]
                        [selected_animal_stage][nutrient][bound])

                elif bound == "Max":
                    contraints_list.append(
                        Constraint(temp_var_sum,
                                   ub=animal_db[animal_selected]
                                   [selected_animal_stage][nutrient][bound]))
                    print(
                        temp_var_sum, "<=", animal_db[animal_selected]
                        [selected_animal_stage][nutrient][bound])

                elif bound == "Equal":
                    contraints_list.append(
                        Constraint(temp_var_sum,
                                   lb=animal_db[animal_selected]
                                   [selected_animal_stage][nutrient][bound]))
                    contraints_list.append(
                        Constraint(temp_var_sum,
                                   ub=animal_db[animal_selected]
                                   [selected_animal_stage][nutrient][bound]))
                    print(
                        temp_var_sum, ">=", animal_db[animal_selected]
                        [selected_animal_stage][nutrient][bound])
                    print(
                        temp_var_sum, "<=", animal_db[animal_selected]
                        [selected_animal_stage][nutrient][bound])

                # all_const+=temp_var_sum

        ####################################################################################################################################################

        print("\nCONTRAINTS===>", contraints_list, end="\n\n\n")

        #constructing the object function from here
        objective_sum = None
        for i in range(0, len(selected_ingredients)):
            if i == 0:
                objective_sum = ingredient_db[
                    selected_ingredients[i]]["Price"] * variable_objects[i]
            elif i > 0:
                objective_sum += ingredient_db[
                    selected_ingredients[i]]["Price"] * variable_objects[i]
            print(objective_sum)
        print("OBJECTIVE FUNCTION ====> ", objective_sum, end="\n\n\n\n")

        obj = Objective(objective_sum, direction='min')
        # Variables, constraints and objectives are combined in a Model object, which can subsequently be optimized.
        model = Model(name='Simple model')
        model.objective = obj
        model.add(contraints_list)
        status = model.optimize()

        print("status:", status)
        print("objective value:", model.objective.value)
        print(
            "---------------------------------------------------------------------"
        )
        variable_quantity = model.variables
        objValue = round(model.objective.value, 2)

        variables = []
        for a, n in variable_quantity.items():
            value = a, round(n.primal, 2)
            variables.append(value)

        price = []
        for i in selected_ingredients:
            value = i, ingredient_db[i]["Price"]
            price.append(value)
        collection = dict(zip(variables, price))

    return render_template("result.html",
                           collection=collection,
                           animal_type=animal_type,
                           objValue=objValue)
Пример #10
0
def result():
    if request.method == 'POST':
        result = request.form
        fields = [k for k in request.form]
        values = [request.form[k] for k in request.form]
        data = dict(zip(fields, values))
        animal_name = data['animal']
        animal_type = data['animal_type']
        weight = data['weight']
        selected_ingredients = {k: v for k, v in data.items() if k != 'animal' and k != 'animal_type' and k != 'weight'}
        ingredient_names = [*selected_ingredients]
        # for k in ingredient_names:
        #     ration = INGREDIENT_DB[k]
        # print(ration)

        # Computation starts here---

    # animal ration(nutrient requirement)
    animal_ration = ANIMAL_FEED_REQUIREMENT_DB[animal_type]

    # Define variables
    # variables = {}
    # variable_object = {}
    # for i in range(1, len(ingredient_names)+1):
    #     variable_object[ingredient_names[i-1]] = 'x'+str(i)
    # for ration in animal_ration:
    #     variables[ration] = {}
    #     for k, v in variable_object.items():
    #         for name in ingredient_names:
    #             var = Variable(v, lb=0)
    #             variables[ration][name] = var
    variables = {}
    
    for ration in animal_ration:
        variables[ration] = {}
        for name in ingredient_names:
            var = Variable("{}".format(name), lb=0)
            variables[ration][name] = var
    print(variables)
    print(len(variables))

    # Get nutrient level of feed ingredients
    # for name in ingredient_names:
    #     for ration in animal_ration:
    #         # if (INGREDIENT_DB[name] != ration):
    #         #     a.append(animal_ration[ration])
    #         # else:
    #         try:
    #             a.append(INGREDIENT_DB[name][ration])
    #         except Exception as e:
    #             print(e)
    # print(a)

    # Define constraints
    constraints = []

    for ration in animal_ration:
        try:
            const = Constraint(
                sum((INGREDIENT_DB[name][ration]/100) * variables[name][ration]
                    if ration in INGREDIENT_DB[name]
                    else animal_ration[ration] * variables[name][ration]
                    for name in ingredient_names 
                ),
                    lb=animal_ration[ration]
            )
            # print(const)
            constraints.append(const)
        except Exception as e:
            print(e)
    # print(len(constraints))
    {{ ingredient_db[selected_ingredients[i]]["Price"] }}
    {% for i in range( 0, lengthOfIngredients): %}


    # for name in ingredient_names:
    #     print(name)
    #     print("-" * 10)
    # for k, v in variable_object.items():
    #     print(v)

    # Objective function
    for ration in animal_ration:
        obj = Objective(
            sum(INGREDIENT_PRICE[name] * variables[name][ration] for name in ingredient_names),
                direction='min'
    )
    # Objective( 58*x1+150*x2+60*x3+15*x4+50*x5+90*x6+700*x7+1300*x8+550*x9)

    # print(obj)
    # Solve
    model = Model()
    model.objective = obj
    model.add(constraints)
    status = model.optimize()
    print("status:", status)
    print("objective value:", model.objective.value)
    print("-------------")
    for var_name , var in model.variables.items():
        print(var_name, "=", var.primal)
    # result = model.objective.value
        
    return render_template("result.html", animal_type = animal_type)
Пример #11
0
import numpy as np
from optlang import Model, Variable, Constraint, Objective

# All the (symbolic) variables are declared, with a name and optionally a lower
# and/or upper bound.
x = np.array([Variable('x{}'.format(i), lb=0) for i in range(1, 4)])

bounds = [100, 600, 300]

A = np.array([[1, 1, 1],
              [10, 4, 5],
              [2, 2, 6]])

w = np.array([10, 6, 4])

obj = Objective(w.dot(x), direction='max')

c = np.array([Constraint(row, ub=bound) for row, bound in zip(A.dot(x), bounds)])

model = Model(name='Numpy model')
model.objective = obj
model.add(c)

status = model.optimize()

print("status:", model.status)
print("objective value:", model.objective.value)
print("----------")
for var_name, var in model.variables.iteritems():
    print(var_name, "=", var.primal)
Пример #12
0
model = Model(name='optlang model')

### Decision variables, positive (lb is lower bound)
#   x is real, y is interger
x = Variable('x',lb=0,type='continuous')
y = Variable('y',lb=0,type='integer')

### Constraints, x+2*y<=4, 5*x-y>=8
model.add([
    Constraint(x+2*y, ub=4),
    Constraint(5*x-y, lb=8)
])

### Objetive function to be maximixed
model.objective = Objective(x+2*y-2, direction='max')

### Solve
status = model.optimize()

### status can be "optimal", "infeasible", "unbounded"
#   or "undefined", if the solver decides there is no
#   optimal value, but cannot decide why
print("status:", model.status)

### optimal value
#   (only acceptable if status is "optimal")
print("objective value:", model.objective.value)
### print the value of each decision variable
#   for the optimal solution
#   (only acceptable if status is "optimal")
Пример #13
0
    def optimization_problem(self):

        """This method is to build the mathematical optimization problem for the generator"""

        print('Building the problem - Please wait')
        print('Variables')
        # Parameters abbreviation
        N = self.Horizon
        efficiency = self.Efficiency
        power = self.Power
        energy = self.Energy
        mode = self.N_mode
        alpha = self.Startup_cold_time
        beta = self.Minimum_downtime
        price_elec = self.Commodity_Price.electricity_price
        price_carbon = self.Commodity_Price.carbon_price
        price_fuel = self.Commodity_Price.fuel_price
        price_fossil = self.Commodity_Price.fossil_price

        # Variable Registration
        # -----------------------------------------------------------------------------------
        model = Model(name=self.Name)
        X = [[]]*mode   # list of lists, representing state variables for each mode of operation
        S = [Variable(name='start_' + str(t), type='binary') for t in range(N)]
        F = [Variable(name='shutdown_' + str(t), type='binary') for t in range(N)]

        for m in range(mode):

            X[m] = [Variable(name='state_mode_' + str(m) + '_' + str(t), type='binary') for t in range(N)]

            for t in range(alpha):
                X[m][t].set_bounds(0, 0)

        print('Constraints')
        # Constraints Registration
        # -----------------------------------------------------------------------------------
        # ctr_initial_states = [[]]*mode
        ctr_unique_mode = [[]]*N
        ctr_start_shut = [[]]*N
        ctr_init_state = [[]]*mode
        ctr_start_01 = [[]]*(N-alpha-1)
        ctr_start_02 = [[]]*(N-alpha)

        # Initial States Constraints
        for m in range(mode):

            ctr_init_state[m] = [[]]*(alpha+1)

            for t in range(alpha+1):
                ctr_init_state[m][t] = Constraint(X[m][t], lb=0, ub=0, name='ctr_initial_states_m_' + str(m) + str(t))

        # Listed constraints
        for t in range(N):

            # 1.1 Unique mode constraint:
            ctr_unique_mode[t] = Constraint(sum(X[m][t] for m in range(mode)), ub=1, name='ctr_unique_mode_' + str(t))

            # 1.2 Startup - shutdown constraint:
            ctr_start_shut[t] = Constraint(S[t] + F[t], ub=1, name='ctr_start_shut_' + str(t))

        for i, t in enumerate(range(alpha, N-1)):     # 2, 21

            # 1.3 Startup - shutdown constraint 2 :
            ctr_start_01[i] = Constraint(S[t - alpha] - F[t] - sum(X[m][t+1] - X[m][t] for m in range(mode)), lb=0, ub=0, name='ctr_start_01_' + str(t))

            # 1.4 Minimum startup time :
            ctr_start_02[i] = Constraint(sum(sum(X[m][t - k] for k in range(1, alpha)) for m in range(mode)) + alpha*S[t-alpha],
                                         ub=alpha, name='ctr_start_02_' + str(t))

        ctr_start_02[N-alpha-1] = Constraint(sum(sum(X[m][N - 1 - k] for k in range(1, alpha)) for m in range(mode)) + alpha*S[N - 1 - alpha],
                                             ub=alpha, name='ctr_start_02_' + str(N - 1))

        # 1.5 Capacity Factor constraint : will be done below

        # 1.6 Minimum shutdown time : will be done below

        # Objective function :
        # -----------------------------------------------------------------------------------

        print('Objective')
        obj_list = [[]]*(mode+1)
        obj_func = Objective(0, direction='max')
        obj_coeff_dict = {}

        obj_coeff_start = dict(zip(S, [-self.Power[0]*(self.Startup_dep_cost + self.Startup_fuel*price_fossil[t]) for t in range(N)]))
        obj_coeff_dict.update(obj_coeff_start)

        for m in range(mode):

            # obj_list[m] = Objective(energy[m]*sum(price_elec[t]*X[m][t] - price_fuel[m].values[t]*X[m][t] - price_carbon[t]*self.Emission_Intensity[m]*X[m][t]
            #                                        - X[m][t]*self.Cost_var_OM for t in range(N)), direction='max')

            obj_coeff_rev = dict(zip(X[m], [energy[m]*(price_elec[t] - price_fuel[m].values[t] - price_carbon[t]*self.Emission_Intensity[m]
                                                       - self.Cost_var_OM) for t in range(N)]))
            obj_coeff_dict.update(obj_coeff_rev)

        # for elem in obj_list:
        #
        #     obj_func += elem.expression

        # Add variables and constraints to the model :

        var_list = []
        cons_list = []

        for m in range(mode):
            var_list.extend(X[m])
            cons_list.extend(ctr_init_state[m])

        var_list.extend(S)
        var_list.extend(F)

        cons_list.extend(ctr_unique_mode)
        cons_list.extend(ctr_start_shut)
        cons_list.extend(ctr_start_01)
        cons_list.extend(ctr_start_02)

        # 1.6 Minimum shutdown time :
        if self.Minimum_downtime is not None:

            ctr_min_time = [[]] * (N - beta)

            for i, t in enumerate(range(N - beta)):
                ctr_min_time[i] = Constraint(
                    sum(sum(X[m][t + k] for k in range(1, beta + 1)) for m in range(mode)) + beta * F[t],
                    lb=0, ub=beta, name='ctr_min_time_' + str(t))

            cons_list.extend(ctr_min_time)
            self._cons['ctr_min_time'] = ctr_min_time

        model.add(var_list)

        # 1.5 Capacity Factor Constraint :
        # ------------------------------------------------------------------------------------------------

        index = self.input_price.index
        time_interval = (index[-1] - index[0]).days

        if time_interval >= self.CF * 365:

            coeff_capacity_factor_dict = {}
            print('Capacity Factor Constraint Activated ')
            for m in range(mode):
                dict_tempo = dict(zip(X[m], [1]*N))
                coeff_capacity_factor_dict.update(dict_tempo)

            ctr_capacity_factor = Constraint(0, name='ctr_capacity_factor')
            model.add(ctr_capacity_factor)
            model.constraints['ctr_capacity_factor'].ub = self.CF*365*24
            ctr_capacity_factor.set_linear_coefficients(coeff_capacity_factor_dict)
            self._cons['ctr_capacity_factor'] = ctr_capacity_factor

        # 1.6 Minimum shutdown time :

        # for i, t in enumerate(range(N-beta)):

        # ctr_min_time[i] = Constraint(sum(sum(X[m][t + k] for k in range(1, beta + 1)) for m in range(mode)) + beta * F[t],
        #     lb=0, ub=beta, name='ctr_min_time_' + str(t))

        # ctr_min_time[i] = Constraint(0, lb=0, name='ctr_min_time_' + str(t))
        # model.add(ctr_min_time[i])
        # model.constraints['ctr_min_time_' + str(t)].ub = beta
        # dict_tempo = {F[t]: beta}
        #
        # for m in range(mode):
        #
        #     dict_tempo_1 = dict(zip(X[m][t:(t+beta+1)], [1]*beta))
        #     dict_tempo.update(dict_tempo_1)
        #
        # ctr_min_time[i].set_linear_coefficients(dict_tempo)

        # Add other constraints and objective function
        # ------------------------------------------------------------------------------------------------

        model.add(cons_list)
        model.objective = obj_func
        obj_func.set_linear_coefficients(obj_coeff_dict)

        self.optim_model = model

        for m in range(mode):
            self._var['state_mode_' + str(m)] = X[m]

        self._var['Start'] = S
        self._var['Shut'] = F
        self._cons.update({'ctr_init_state': ctr_init_state, 'ctr_unique_mode': ctr_unique_mode, 'ctr_start_shut': ctr_start_shut,
                          'ctr_start_01': ctr_start_01, 'ctr_start_02': ctr_start_02})
        print('Object Creation Finished')