Ejemplo n.º 1
0
def buildVariableDefinitionList(df_criteria_list, df_criteria_bareme, with_scores, dict_boundaries):
    """
    Construction des variable du modèle
        
    Args:
        df_criteria_list: le dataFrame contenant les critères qualitatifs
        df_criteria_bareme: le dataFrame contenant les critères avec leurs bornes respectives
        with_scores: utilisation des notes ou non
        dict_boundaries: le min et le max des barèmes (0 et 20)
        
    
    Return: les listes de variables x et y
    """
    i=0
    variable_list_x = []
    variable_list_y = []
    for idx, row in df_criteria_bareme.iterrows():
        for criteria in df_criteria_list.iloc[:,1:]:
            i+=1
            var_x = Variable (f'x{i}', lb=row[f'Min_value_{criteria}'], ub = row[f'Max_value_{criteria}'])
            variable_list_x.append(var_x)
    #Mode sans les scores : on rajoute les variables de score       
    if not with_scores:
        for idx, row in df_criteria_bareme.iterrows():
            var_y = Variable (f'y{idx+1}', lb = dict_boundaries['min'], ub = dict_boundaries['max'])
            variable_list_y.append(var_y)
        
    return variable_list_x, variable_list_y
Ejemplo n.º 2
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
Ejemplo n.º 3
0
    def add_variable(self,
                     var_id,
                     lb=-inf,
                     ub=inf,
                     vartype=VarType.CONTINUOUS,
                     update=True):
        """ Add a variable to the current problem.

        Arguments:
            var_id (str): variable identifier
            lb (float): lower bound
            ub (float): upper bound
            vartype (VarType): variable type (default: CONTINUOUS)
            update (bool): update problem immediately (default: True)
        """

        if var_id in self.var_ids:
            var = self.problem.variables[var_id]
            var.lb = lb
            var.ub = ub
            var.type = vartype.value
        else:
            var = Variable(var_id, lb=lb, ub=ub, type=vartype.value)
            self.problem.add(var)
            self.var_ids.append(var_id)

        if update:
            self.problem.update()
Ejemplo n.º 4
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
Ejemplo n.º 5
0
def z(x: "SL", i: int):
    # TODO: come up with better function name
    cat = 'binary' if isinstance(x[0], stl.LinEq) else 'continuous'
    if isinstance(x[0], stl.LinEq):
        prefix = "q"
    else:
        prefix = "z"
    kwargs = {"name": "{}{}".format(prefix, i)}
    return Variable(type=cat, **kwargs)
Ejemplo n.º 6
0
def make_variables(S, flux_bounds):
    variables = []
    row_1 = S[0]
    for i in range(len(row_1)):
        v = Variable('v-' + str(i + 1),
                     lb=flux_bounds[0][i],
                     ub=flux_bounds[1][i])
        variables.append(v)
    print(variables)
    return variables
Ejemplo n.º 7
0
def z(x: "SL", g, i):
    # TODO: come up with better function name
    if isinstance(x[0], str) and isinstance(x[1], int):
        if x[0] in set(g.model.vars.input) | set(g.model.vars.env):
            lo, hi = -1, 1
        else:
            lo = hi = None

        kwargs = {'name': f"{x[0]}_{x[1]}", 'lb': lo, 'ub': hi}
        return (Variable(**kwargs), )

    r_var = Variable(name=f"r{i}")

    if not isinstance(x, (stl.And, stl.Or)):
        return (r_var, )

    bool_vars = {
        arg: Variable(type='binary', name=f"p{i}_{j}")
        for j, arg in enumerate(x.args)
    }
    return (r_var, tuple(bool_vars.items()))
def constrained_optimzation(objective_function, *variables, **constraints):
    # Objective function
    obj = Objective(objective_function, direction='max')

    # Symbolic variables
    variables = []
    for i in range(len(variables)):
        print('Variable {num}: '.format(i) + str(variables[i]))
        variable[i] = Variable(variables[i], lb=0)

    for key, value in constraints.items():
        print(key, value)

    # Constraints
    constraints = []
    for i in range(len(constraints)):
        print('Constraint {num}: '.format(i) + str(constraints[i]))
        constraint[i] = Constraint(constraints[i], lb=0)
Ejemplo n.º 9
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
        "New_York": 2.5,
        "Chicago": 1.8,
        "Topeka": 1.4
    }
}

freight_cost = 9  # Cost per case per thousand miles

# Define variables
variables = {}
for origin in supply:
    variables[origin] = {}
    for destination in demand:
        # Construct a variable with a name, bounds and type
        var = Variable(name="{}_to_{}".format(origin, destination),
                       lb=0,
                       type="integer")
        variables[origin][destination] = var

# Define constraints
constraints = []
for origin in supply:
    const = Constraint(sum(variables[origin].values()),
                       ub=supply[origin],
                       name="{}_supply".format(origin))
    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)
Ejemplo n.º 11
0
def main():
    #Pour lancer une nouvelle analyse portant sur d'autres classements il faut : 
        #mettre un fichier data valide (exemples dans le projet)
        #renseigner le nom du fichier d'export
        #Modifier les contraintes des variables update_model_Q3 l.59 et update_model_Q4 l.141
#------------------------------------------------------------  
#Q2.1 Programme Lineaire - Classement Couches-culottes avec notes
#------------------------------------------------------------
    #Initailisation des chemins de sources et d'export
   csv_name='../data/data_couches_original.xlsx'
   csv_export='./results/Couches_Analyse_Classement.xlsx'
    
   #nom d modèle
   model_name_1 = 'Programme Lineaire - Classement Couches-culottes avec notes' 
   #Solution du programme linéaire
   result_2_1 = checkAdditiveModel(csv_name=csv_name,
                      model_name=model_name_1,
                      eval_expr='x1',
                      direction='max',
                      with_scores=True)
   #Affichage console
   print(result_2_1)
   
   
   
#------------------------------------------------------------  
#Q2.2 'Programme Lineaire - Classement Couches-culottes sans note'
#------------------------------------------------------------  
   
   
   
   model_name_2 = 'Programme Lineaire - Classement Couches-culottes sans note'
   result_2_2 = checkAdditiveModel(csv_name=csv_name,
                      model_name=model_name_2,
                      eval_expr='x1',
                      direction='max')
   print(result_2_2)
   
   
   
#------------------------------------------------------------  
#Q3
#------------------------------------------------------------  
   
   #Récupération du Dataframe original issu de l'excel
   result_original = getOriginalData(csv_name) 
   #Dict correctement formé avec les Variables à mettre à jour et les contraintes à supprimer
   update_model_Q3 = createUpdateModel([Variable ('x6', ub = 20)], ['c16', 'c21'])
   
   
#------------------------------------------------------------  
#Q3.1 'Programme Lineaire - Meilleur score Joone' 'Programme Lineaire - Pire score Joone'
#------------------------------------------------------------  
   
   
   
   model_name_3 = 'Programme Lineaire - Meilleur score Joone'
   result_3_1_max = checkAdditiveModel(csv_name=csv_name,
                      model_name=model_name_3,
                      eval_expr='y1',
                      direction='max',
                      update_model=update_model_Q3)
   print(result_3_1_max)
   
    
  
   model_name_4 = 'Programme Lineaire - Pire score Joone'
   result_3_1_min = checkAdditiveModel(csv_name=csv_name,
                      model_name=model_name_4,
                      eval_expr='y1',
                      direction='min',
                      update_model=update_model_Q3)
   print(result_3_1_min)
   
   
   #------------------------------------------------------------ 
   #Q3.3 Calculs des indicateurs Spearman, Kendall et Moyenne des écarts
   #------------------------------------------------------------ 
  
   dict_max_y1 = compareRankings(result_original['Score'], result_3_1_max['Score'])
   dict_min_y1 = compareRankings(result_original['Score'], result_3_1_min['Score'])
   
   
   #export excel du Dataframe de résultats et des indicateurs
   exportInExcel(csv_export, 'Q3.1',#ficier d'export, nom du modèle
                 [result_original, result_3_1_max, result_3_1_min],#Dataframe à exporter
                 ['Modèle Original',model_name_3, model_name_4],#noms des dataframes
                 [dict_max_y1,dict_min_y1])#liste des dicts contenant les indicateurs pour chaque modèle
#------------------------------------------------------------  
#Q3.2 'Programme Lineaire - Meilleur score Lillydoo' 'Programme Lineaire - Pire score Lillydoo
#------------------------------------------------------------  
  
   model_name_5 = 'Programme Lineaire - Meilleur score Lillydoo'
   result_3_2_max = checkAdditiveModel(csv_name=csv_name,
                      model_name=model_name_5,
                      eval_expr='y12',
                      direction='max',
                      update_model=update_model_Q3)
   
   print(result_3_2_max)
   
 
   model_name_6 = 'Programme Lineaire - Pire score Lillydoo'
   result_3_2_min = checkAdditiveModel(csv_name=csv_name,
                      model_name='Programme Lineaire - Pire score Lillydoo',
                      eval_expr='y12',
                      direction='min',
                      update_model=update_model_Q3)
   
   print(result_3_2_min)
   
   
   #------------------------------------------------------------ 
   #Q3.3 Calculs des indicateurs Spearman, Kendall et Moyenne des écarts
   #------------------------------------------------------------ 
   dict_max_y12 = compareRankings(result_original['Score'], result_3_2_max['Score'])
   dict_min_y12 = compareRankings(result_original['Score'], result_3_2_min['Score'])
   
   
   
   exportInExcel(csv_export, 'Q3.2',
                 [result_original, result_3_2_max, result_3_2_min],
                 ['Modèle Original',model_name_5, model_name_6],
                 [dict_max_y12,dict_min_y12])

#------------------------------------------------------------  
#Q4 Calculs des Maximums pour chaque produit
#------------------------------------------------------------  
   
   update_model_Q4 = createUpdateModel([Variable ('x6', ub = 20)], ['c13', 'c14', 'c15', 
                                                                    'c16', 'c17', 'c18',
                                                                    'c19', 'c20', 'c21',
                                                                    'c22', 'c23'])
#------------------------------------------------------------  
#Q4.1 alculs des Maximums pour chaque produit
#------------------------------------------------------------
    
    
   model_name_7 = 'Programme Lineaire - Score global maximal pour chaque produit'
   result_4_1_all_max = checkAdditiveModel(csv_name=csv_name,
                      model_name=model_name_7,
                      eval_expr='all',
                      direction='max',
                      update_model=update_model_Q4)
   
   print(result_4_1_all_max)
   
#------------------------------------------------------------  
#Q4.2 Export des résultats
#------------------------------------------------------------
   dict_max_all = compareRankings(result_original['Score'], result_4_1_all_max['Score']) 
   exportInExcel(csv_export, 'Q4',
                 [result_original, result_4_1_all_max],
                 ['Modèle Original',model_name_7],
                 [dict_max_all])
Ejemplo n.º 12
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)
Ejemplo n.º 13
0
    def optimize_irrigation(self, zone, dt: object) -> tuple:
        """Apply Linear Programming to optimize irrigation water use.

        Results can be used to represent percentage mix
        e.g. if the field area is 100 ha, and the optimal area to be
             irrigated by a water source is

            `SW: 70 ha
            GW: 30 ha`

        and the required amount is 20mm

            `SW: 70 / 100 = 0.7 (irrigated area / total area, 70%)
            GW: 30 / 100 = 0.3 (30%)`
            
        Then the per hectare amount to be applied from each 
        water source is calculated as:

            `SW = 20mm * 0.7
               = 14mm

            GW = 20mm * 0.3
               = 6mm`
        
        Parameters
        ----------
        * zone : FarmZone
        * dt : datetime object, current datetime

        Returns
        ---------
        * Tuple : OrderedDict[str, float] : keys based on field and water source names
                                            values are hectare area
                  Float : $/ML cost of applying water
        """
        model = self.opt_model
        areas = []
        profit = []
        app_cost = OrderedDict()
        constraints = []

        zone_ws = zone.water_sources
        total_irrigated_area = sum(map(lambda f: f.irrigated_area 
                                    if f.irrigated_area is not None 
                                    else 0.0, zone.fields))
        field_area = {}
        possible_area = {}
        for f in zone.fields:
            f_name = f.name
            did = f"{f_name}__".replace(" ", "_")
            
            if f.irrigation.name == 'dryland':
                areas += [Variable(f"{did}{ws_name}", lb=0, ub=0) 
                            for ws_name in zone_ws]
                continue
            # End if

            # Disable this for now - estimated income includes variable costs
            # Will always incur maintenance costs and crop costs
            # total_pump_cost = sum([ws.pump.maintenance_cost(dt.year) for ws in zone_ws])
            # total_irrig_cost = f.irrigation.maintenance_cost(dt.year)
            # maintenance_cost = (total_pump_cost + total_irrig_cost)

            # estimated gross income - variable costs per ha
            crop_income_per_ha = f.crop.estimate_income_per_ha()
            req_water_ML_ha = f.calc_required_water(dt) / ML_to_mm

            if req_water_ML_ha == 0.0:
                field_area[f_name] = {
                    ws_name: Variable(f"{did}{ws_name}",
                                      lb=0.0,
                                      ub=0.0)
                    for ws_name in zone_ws
                }
            else:
                max_ws_area = zone.possible_area_by_allocation(f)

                field_area[f_name] = {
                    ws_name: Variable(f"{did}{ws_name}",
                                      lb=0, 
                                      ub=max_ws_area[ws_name])
                    for ws_name in zone_ws
                }
            # End if

            # Costs to pump needed water volume from each water source
            app_cost_per_ML = self.ML_water_application_cost(zone, f, req_water_ML_ha)

            app_cost.update({
                f"{did}{k}": v
                for k, v in app_cost_per_ML.items()
            })

            profit += [
                (crop_income_per_ha 
                - (app_cost_per_ML[ws_name] * req_water_ML_ha)
                ) * field_area[f_name][ws_name]
                for ws_name in zone_ws
            ]
        # End for

        # Total irrigation area cannot be more than available area
        constraints += [Constraint(sum(areas),
                                   lb=0.0,
                                   ub=min(total_irrigated_area, zone.total_area_ha))
                        ]

        # 0 <= field1*sw + field2*sw + field_n*sw <= possible area to be irrigated by sw
        for ws_name, w in zone_ws.items():
            alloc = w.allocation
            pos_area = zone.possible_irrigation_area(alloc)

            f_ws_var = []
            for f in zone.fields:
                f_ws_var += [field_area[f.name][ws_name]]
            # End for

            constraints += [Constraint(sum(f_ws_var),
                            lb=0.0,
                            ub=pos_area)]
        # End for

        # Generate appropriate OptLang model
        model = Model.clone(self.opt_model)
        model.objective = Objective(sum(profit), direction='max')
        model.add(constraints)
        model.optimize()

        return model.primal_values, app_cost
Ejemplo n.º 14
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)
Ejemplo n.º 15
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)
Ejemplo n.º 16
0
    def optimize_irrigated_area(self, zone) -> Dict:
        """Apply Linear Programming to naively optimize irrigated area.
        
        Occurs at start of season.

        Parameters
        ----------
        * zone : FarmZone object, representing a farm or a farming zone.
        """
        calc = []
        areas = []
        constraints = []
        zone_ws = zone.water_sources
        
        total_avail_water = zone.avail_allocation

        field_areas = {}
        for f in zone.fields:
            area_to_consider = f.total_area_ha
            did = f"{f.name}__".replace(" ", "_")

            naive_crop_income = f.crop.estimate_income_per_ha()
            naive_req_water = f.crop.water_use_ML_per_ha
            app_cost_per_ML = self.ML_water_application_cost(zone, f, naive_req_water)

            pos_field_area = [w.allocation / naive_req_water
                                for ws_name, w in zone_ws.items()
            ]
            pos_field_area = min(sum(pos_field_area), area_to_consider)
            
            field_areas[f.name] = {
                ws_name: Variable(f"{did}{ws_name}", 
                                  lb=0,
                                  ub=min(w.allocation / naive_req_water, area_to_consider))
                for ws_name, w in zone_ws.items()
            }

            # total_pump_cost = sum([ws.pump.maintenance_cost(year_step) for ws in zone_ws])
            profits = [field_areas[f.name][ws_name] * 
                       (naive_crop_income - app_cost_per_ML[ws_name])
                       for ws_name in zone_ws
            ]

            calc += profits
            curr_field_areas = list(field_areas[f.name].values())
            areas += curr_field_areas

            # Total irrigated area cannot be greater than field area
            # or area possible with available water
            constraints += [
                Constraint(sum(curr_field_areas), lb=0.0, ub=pos_field_area)
            ]
        # End for

        # for ws_name in zone_ws:
        #     total_f_ws = 0
        #     for f in zone.fields:
        #         total_f_ws += field_areas[f.name][ws_name]
        #     # End for
        # # End for

        # constraints += [Constraint(total_f_ws,
        #                     lb=0.0,
        #                     ub=zone.total_area_ha)]

        constraints += [Constraint(sum(areas),
                                   lb=0.0,
                                   ub=zone.total_area_ha)]

        # Generate appropriate OptLang model
        model = Model.clone(self.opt_model)
        model.objective = Objective(sum(calc), direction='max')
        model.add(constraints)
        model.optimize()

        if model.status != 'optimal':
            raise RuntimeError("Could not optimize!")

        return model.primal_values
Ejemplo n.º 17
0
from optlang import Model, Variable, Constraint, Objective

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
Ejemplo n.º 18
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')
        variable[i] = Variable(variables[i], lb=0)

    for key, value in constraints.items():
        print(key, value)

    # Constraints
    constraints = []
    for i in range(len(constraints)):
        print('Constraint {num}: '.format(i) + str(constraints[i]))
        constraint[i] = Constraint(constraints[i], lb=0)


constrained_optimzation(P**2, P, constraint=2)

# All the (symbolic) variables are declared, with a name and optionally a lower and/or upper bound.
x1 = Variable('x1', lb=0)
x2 = Variable('x2', lb=0)

# A constraint is constructed from an expression of variables and a lower and/or upper bound (lb and ub).
c1 = Constraint(P=1 - Q)
c2 = Constraint(10 * x1 + 4 * x2 + 5 * x3, ub=600)
c3 = Constraint(2 * x1 + 2 * x2 + 6 * x3, ub=300)

# An objective can be formulated
obj = Objective(10 * x1 + 6 * x2 + 4 * x3, 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])