Esempio n. 1
0
    def get_elastic_constraints(self):
        """Instance method
        
        This method creates an instance of the class LinearConstraints where elastic/slack variables are added.
        
        Returns
        -------
        E_linear_constraints : :class:`.LinearConstraints`
          Linear constraints with added pair of elastic (slack) variables to each constraint.
        """
        E_linear_constraints = lc.LinearConstraints(
            self._linear_constraints.D_sites_modtypes,
            self._linear_constraints.specifications)

        L_econstraints = []  # initializing list of elastic constraints
        L_PuLP_econstraints = []
        D_variables_modforms_ex = {}
        D_PuLP_variables_ex = {}  # initializing extended dictionary

        # initializing extended dictionary for Modform objects
        D_variables_modforms_ex.update(
            self._linear_constraints.modform_space.D_variables_modforms)

        # initializing extended dictionary for LpVariable objects
        D_PuLP_variables_ex.update(
            self._linear_constraints.modform_space.D_PuLP_variables)

        for i in range(1,
                       len(self._linear_constraints.L_linear_constraints) + 1):

            lhs = self._linear_constraints.L_linear_constraints[i - 1][0]

            elastic_variable1 = "e_%s" % (2 * i - 1)
            elastic_variable2 = "e_%s" % (2 * i)
            evariables_diff = " + " + elastic_variable1 + " - " + elastic_variable2

            PuLP_evariable1 = pulp.LpVariable(elastic_variable1, lowBound=0)
            PuLP_evariable2 = pulp.LpVariable(elastic_variable2, lowBound=0)

            D_variables_modforms_ex[elastic_variable1] = modform.Modform(
                elastic_variable1)
            D_variables_modforms_ex[elastic_variable2] = modform.Modform(
                elastic_variable2)

            D_PuLP_variables_ex[elastic_variable1] = PuLP_evariable1
            D_PuLP_variables_ex[elastic_variable2] = PuLP_evariable2

            lhs_new = lhs + evariables_diff

            L_econstraints.append(
                (lhs_new,
                 self._linear_constraints.L_linear_constraints[i - 1][1]))

            #
            lhs_PuLP = sum([
                v[0] * v[1] for v in
                self._linear_constraints.L_PuLP_constraints[i - 1].items()
            ])
            LHS = lhs_PuLP + PuLP_evariable1 - PuLP_evariable2

            L_PuLP_econstraints.append(
                pulp.LpConstraint(
                    LHS,
                    rhs=float(
                        self._linear_constraints.L_linear_constraints[i -
                                                                      1][1])))

        E_linear_constraints.L_linear_constraints = L_econstraints
        E_linear_constraints.L_PuLP_constraints = L_PuLP_econstraints

        E_linear_constraints.modform_space.D_variables_modforms = D_variables_modforms_ex
        E_linear_constraints.modform_space.D_PuLP_variables = D_PuLP_variables_ex

        return E_linear_constraints
def truncate(n, decimals=0):
    multiplier = 10**decimals
    return int(n * multiplier) / multiplier


def round_up(n, decimals=0):
    multiplier = 10**decimals
    return math.ceil(n * multiplier) / multiplier


# Create a LP Maximization problem
Lp_copy = p.LpProblem('Problem', p.LpMaximize)

# Knapsack problem
x1 = p.LpVariable("x1", lowBound=0, upBound=1)
x2 = p.LpVariable("x2", lowBound=0, upBound=1)
x3 = p.LpVariable("x3", lowBound=0, upBound=1)
x4 = p.LpVariable("x4", lowBound=0, upBound=1)
x5 = p.LpVariable("x5", lowBound=0, upBound=1)
x6 = p.LpVariable("x6", lowBound=0, upBound=1)
x7 = p.LpVariable("x7", lowBound=0, upBound=1)
x8 = p.LpVariable("x8", lowBound=0, upBound=1)
x9 = p.LpVariable("x9", lowBound=0, upBound=1)
x10 = p.LpVariable("x10", lowBound=0, upBound=1)
x11 = p.LpVariable("x11", lowBound=0, upBound=1)

x = [x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11]

# Funkcja celu
Lp_copy += 10 * x1 + 7 * x2 + 2 * x3 + 1 * x4 + 2 * x5 + 4 * x6 + 3 * x7 + 6 * x8 + 3 * x9 + 7 * x10 + 6 * x11
def create_thermal_plant_lp( pb,name):

    lp = pulp.LpProblem(name+".lp", pulp.LpMinimize)
    lp.setSolver()
    prod_vars = {}
    in_use_vars ={}
    turn_on_vars={}
    defaillance={}
    cout_proportionnel_defaillance=3000 #euros/MWh
    for t in pb.time_steps:
        prod_vars[t] = {}
        in_use_vars[t] = {}
        turn_on_vars[t] = {}
        defaillance[t]=pulp.LpVariable("defailance_"+str(t), 0.0,None )

        for thermal_plant in pb.thermal_plants :
            #creation des variables
            ###########################################################
            var_name = "prod_"+str(t)+"_"+str(thermal_plant.name)
            prod_vars[t][thermal_plant] = pulp.LpVariable(var_name, 0.0, thermal_plant.pmax(t) )

            var_name = "inUse_"+str(t)+"_"+str(thermal_plant.name)
            in_use_vars[t][thermal_plant] = pulp.LpVariable(var_name, cat="Binary")

            var_name = "turnon_"+str(t)+"_"+str(thermal_plant.name)
            turn_on_vars[t][thermal_plant] = pulp.LpVariable(var_name, cat="Binary")
           
            #creation des contraintes
            ###########################################################
                  
            if thermal_plant.pmax(t)<=0.001:
                 lp+=in_use_vars[t][thermal_plant]==0,"imposition_arret_"+str(t)+"_"+str(thermal_plant.name)
 
            


        constraint_name = "balance_"+ str(t)
        lp += pulp.lpSum([ prod_vars[t][thermal_plant] for thermal_plant in pb.thermal_plants ])+defaillance[t] == pb.demand[t], constraint_name
        for thermal_plant in pb.thermal_plants :
            constraint_name = "prod_min_" + str(thermal_plant) + "_" + str(t)
            lp += prod_vars[t][thermal_plant] >= in_use_vars[t][thermal_plant] * thermal_plant.pmin(t), constraint_name
            constraint_name = "prod_max_" + str(thermal_plant) + "_" + str(t)
            lp += prod_vars[t][thermal_plant] <= in_use_vars[t][thermal_plant] * thermal_plant.pmax(t), constraint_name
            if t != 0 :
                constraint_name = "demarrage_" + str(thermal_plant) + "_" + str(t)
                lp += in_use_vars[t][thermal_plant] - in_use_vars[t-1][thermal_plant] <= turn_on_vars[t][thermal_plant], constraint_name
            if t == 0 :
                constraint_name = "demarrage_" + str(thermal_plant) + "_" + str(t)
                lp += turn_on_vars[t][thermal_plant] >= in_use_vars[t][thermal_plant], constraint_name


    #creation de la fonction objectif
    ###########################################################

    lp.setObjective( pulp.lpSum([defaillance[t] for t in pb.time_steps])* pb.time_step_duration/60.0*cout_proportionnel_defaillance\
                   +pulp.lpSum([ turn_on_vars[t][thermal_plant]*thermal_plant.startup_cost+prod_vars[t][thermal_plant] * (thermal_plant.proportionnal_cost* pb.time_step_duration/60.0)
        for thermal_plant in pb.thermal_plants for t in pb.time_steps]))
                    
    model=Model(lp,prod_vars)

    return model
import pulp

# init linear optimization problem object
LO_problem = pulp.LpProblem("knapsack_ILO", pulp.LpMaximize)

# data (parameters)
sizes = [5, 10, 2, 3, 5]
weights = [4, 1, 2, 3, 4]
rewards = [5, 8, 3, 2, 7]
size_capacity = 20
weight_capacity = 10
n = len(sizes)  # number of items

# decision variables
x = [pulp.LpVariable(f'x_{i}', cat='Binary') for i in range(n)]

# objective function
LO_problem += pulp.lpDot(x, rewards), "total_reward"

# constraints
LO_problem += pulp.lpDot(x, sizes) <= size_capacity, "size_capacity_constraint"
LO_problem += pulp.lpDot(
    x, weights) <= weight_capacity, "weight_capacity_constraint"

print(LO_problem)
LO_problem.solve()
print("Status:", pulp.LpStatus[LO_problem.status])

# each of the variables is printed with it's resolved optimum value
for v in LO_problem.variables():
Esempio n. 5
0
Imin = Imin * MW_H2 / density_H2  # m^3
Fmax_booster = Fmax_booster * MW_H2 / density_H2  # m^3
Fmax_prestorage = Fmax_prestorage * MW_H2 / density_H2  # m^3

ECF_booster = ECF_booster / MW_H2 * density_H2  #kWh/m^3
ECF_prestorage = ECF_prestorage / MW_H2 * density_H2  #kWh/m^3

#number of electrolyzer max
N_electrolyzer_max = int(3510)

# LP objective variable for transportation model
LP_eps_3 = pulp.LpProblem('LP_eps_3', pulp.LpMaximize)
LP_cost_3 = pulp.LpProblem('LP_cost_3', pulp.LpMinimize)

N_electrolyzer_3 = pulp.LpVariable('N_electrolyzer_3',
                                   lowBound=0,
                                   cat='Integer')

N_booster_3 = pulp.LpVariable('N_booster_3', lowBound=0, cat='Integer')

N_prestorage_3 = pulp.LpVariable('N_prestorage_3', lowBound=0, cat='Integer')

N_tank_3 = pulp.LpVariable('N_tank_3', lowBound=0, cat='Integer')

alpha_3 = pulp.LpVariable.dicts(
    'alpha_3', [str(i) for i in range(1, N_electrolyzer_max + 1)],
    cat='Binary')

E_3 = pulp.LpVariable.dicts('E_3', [str(i) for i in input_df.index],
                            lowBound=0,
                            cat='Continuous')
Esempio n. 6
0
Imin = Imin * MW_H2 / density_H2  # m^3

Fmax_prestorage = Fmax_prestorage * MW_H2 / density_H2  # m^3
ECF_prestorage = ECF_prestorage / MW_H2 * density_H2  #kWh/m^3

EMF_SMR = EMF_SMR * 0.001 / MW_H2 * density_H2  #tonne CO2/m^3 of H2

#number of electrolyzer max
N_electrolyzer_max = int(3510)

# Transportation model
LP_eps_4 = pulp.LpProblem('LP_eps_4', pulp.LpMaximize)
LP_cost_4 = pulp.LpProblem('LP_cost_4', pulp.LpMinimize)

N_electrolyzer_4 = pulp.LpVariable('N_electrolyzer_4',
                                   lowBound=0,
                                   cat='Integer')

N_prestorage_4 = pulp.LpVariable('N_prestorage_4', lowBound=0, cat='Integer')

N_tank_4 = pulp.LpVariable('N_tank_4', lowBound=0, cat='Integer')

alpha_4 = pulp.LpVariable.dicts(
    'alpha_4', [str(i) for i in range(1, N_electrolyzer_max + 1)],
    cat='Binary')

E_4 = pulp.LpVariable.dicts('E_4', [str(i) for i in input_df.index],
                            lowBound=0,
                            cat='Continuous')

H2_4 = pulp.LpVariable.dicts('H2_4', [str(i) for i in input_df.index],
Esempio n. 7
0
def runBikeShareMatchingLP(bikes,
                           empty,
                           valuations,
                           tol,
                           print_solution=False):
    # Get the number of stations and riders
    num_stations = len(bikes)
    num_riders = len(valuations)

    # Initialize LP
    prob = plp.LpProblem("Bike-Share Matching Problem", plp.LpMaximize)

    # Float variables x_ij \in [0,1]
    variables = [[[
        plp.LpVariable("x_" + str(i) + "_" + str(s) + "_" + str(t),
                       lowBound=0,
                       upBound=1,
                       cat='Integer') for t in range(0, num_stations)
    ] for s in range(0, num_stations)] for i in range(0, num_riders)]
    #variables = [[[plp.LpVariable("x_" + str(i) + "_" + str(s) + "_" + str(t), lowBound = 0 , upBound = 1, cat = 'Continuous') for t in range(0, num_stations)] for s in range(0, num_stations)] for i in range(0, num_riders)]

    # Welfare-maximizing objective funciton
    prob += sum(valuations[i][s][t] * variables[i][s][t]
                for t in range(0, num_stations)
                for s in range(0, num_stations) for i in range(0, num_riders))

    # Each bidder is assigned at most one source-sink pair
    for i in range(0, num_riders):
        prob += sum(variables[i][s][t] for t in range(0, num_stations)
                    for s in range(0, num_stations)) <= 1.0

    # Each station s can only provide at most b_s bikes
    for k in range(0, num_riders):
        range_bidders = [i for i in range(0, num_riders) if i != k]
        for s in range(0, num_stations):
            for t in range(0, num_stations):
                prob += variables[k][s][t] + sum(
                    variables[i][s][t_prime]
                    for t_prime in range(0, num_stations)
                    for i in range_bidders) <= bikes[s]

    # Each station t can only receive at most e_s bikes plus the number of bikes leaving the station
    for k in range(0, num_riders):
        range_bidders = [i for i in range(0, num_riders) if i != k]
        for s in range(0, num_stations):
            for t in range(0, num_stations):
                prob += variables[k][s][t] + sum(
                    variables[i][s_prime][t] - variables[i][t][s_prime]
                    for s_prime in range(0, num_stations)
                    for i in range_bidders) <= empty[t]
    '''
    # Each station s can only provide at most b_s bikes
    for s in range(0, num_stations):    
        prob += sum(variables[i][s][t] for t in range(0, num_stations) for i in range(0, num_riders)) <= bikes[s]
    
    # Each station t can only receive at most e_s bikes plus the number of bikes leaving the station
    for t in range(0, num_stations):    
        prob += sum(variables[i][s][t] - variables[i][t][s] for s in range(0, num_stations) for i in range(0, num_riders)) <= empty[t] 
        
    # A constraint to avoid a user making space on its own
    for t in range(0, num_stations):
        prob += sum(variables[i][s][t] - variables[i][t][s] for s in range(0, num_stations) for i in range(0, num_riders)) <= empty[t]
                
    '''
    # Save model
    prob.writeLP("BikeShareMatching.lp")

    # Solve
    prob.solve()

    print("program value", plp.value(prob.objective))
    if (print_solution):
        printSolution(prob)

    return check_integer_values(plp, prob, tol)
Esempio n. 8
0
    def __init__(self,
                 multi_circuit: MultiCircuit,
                 verbose=False,
                 allow_load_shedding=False,
                 allow_generation_shedding=False):
        """
        DC OPF problem
        :param multi_circuit: multi circuit instance
        :param verbose: verbose?
        :param allow_load_shedding: Allow load shedding?
        :param allow_generation_shedding: Allow generation shedding?
        """

        # list of OP object islands
        self.opf_islands = list()

        # list of opf islands to solve apart (this allows to split the problem and only assign loads on a series)
        self.opf_islands_to_solve = list()

        # flags
        self.verbose = verbose
        self.allow_load_shedding = allow_load_shedding
        self.allow_generation_shedding = allow_generation_shedding

        # circuit compilation
        self.multi_circuit = multi_circuit
        self.numerical_circuit = self.multi_circuit.compile()
        self.islands = self.numerical_circuit.compute()

        # compile the indices
        # indices of generators that contribute to the static power vector 'S'
        self.gen_s_idx = np.where(
            (np.logical_not(self.numerical_circuit.controlled_gen_dispatchable)
             * self.numerical_circuit.controlled_gen_enabled) == True)[0]

        self.bat_s_idx = np.where(
            (np.logical_not(self.numerical_circuit.battery_dispatchable) *
             self.numerical_circuit.battery_enabled) == True)[0]

        # indices of generators that are to be optimized via the solution vector 'x'
        self.gen_x_idx = np.where(
            (self.numerical_circuit.controlled_gen_dispatchable *
             self.numerical_circuit.controlled_gen_enabled) == True)[0]

        self.bat_x_idx = np.where(
            (self.numerical_circuit.battery_dispatchable *
             self.numerical_circuit.battery_enabled) == True)[0]

        # get the devices
        self.controlled_generators = self.multi_circuit.get_controlled_generators(
        )
        self.batteries = self.multi_circuit.get_batteries()
        self.loads = self.multi_circuit.get_loads()

        # shortcuts...
        nbus = self.numerical_circuit.nbus
        nbr = self.numerical_circuit.nbr
        ngen = len(self.controlled_generators)
        nbat = len(self.batteries)
        Sbase = self.multi_circuit.Sbase

        # bus angles
        self.theta = np.array([
            pulp.LpVariable("Theta_" + str(i), -0.5, 0.5) for i in range(nbus)
        ])

        # Generator variables (P and P shedding)
        self.controlled_generators_P = np.empty(ngen, dtype=object)
        self.controlled_generators_cost = np.zeros(ngen)
        self.generation_shedding = np.empty(ngen, dtype=object)

        for i, gen in enumerate(self.controlled_generators):
            name = 'GEN_' + gen.name + '_' + str(i)
            pmin = gen.Pmin / Sbase
            pmax = gen.Pmax / Sbase
            self.controlled_generators_P[i] = pulp.LpVariable(
                name + '_P', pmin, pmax)
            self.generation_shedding[i] = pulp.LpVariable(
                name + '_SHEDDING', 0.0, 1e20)
            self.controlled_generators_cost[i] = gen.Cost

        # Batteries
        self.battery_P = np.empty(nbat, dtype=object)
        self.battery_cost = np.zeros(nbat)
        self.battery_lower_bound = np.zeros(nbat)
        self.numerical_circuit.C_batt_bus = csc_matrix(
            self.numerical_circuit.C_batt_bus)
        for i, battery in enumerate(self.batteries):
            name = 'BAT_' + battery.name + '_' + str(i)
            pmin = battery.Pmin / Sbase
            pmax = battery.Pmax / Sbase
            self.battery_lower_bound[i] = pmin
            self.battery_P[i] = pulp.LpVariable(name + '_P', pmin, pmax)
            self.battery_cost[i] = battery.Cost

        # load shedding
        self.load_shedding = np.array([
            pulp.LpVariable("LoadShed_" + load.name + '_' + str(i), 0.0, 1e20)
            for i, load in enumerate(self.loads)
        ])

        # declare the loading slack vars
        self.slack_loading_ij_p = np.empty(nbr, dtype=object)
        self.slack_loading_ji_p = np.empty(nbr, dtype=object)
        self.slack_loading_ij_n = np.empty(nbr, dtype=object)
        self.slack_loading_ji_n = np.empty(nbr, dtype=object)
        for i in range(nbr):
            self.slack_loading_ij_p[i] = pulp.LpVariable(
                "LoadingSlack_ij_p_" + str(i), 0, 1e20)
            self.slack_loading_ji_p[i] = pulp.LpVariable(
                "LoadingSlack_ji_p_" + str(i), 0, 1e20)
            self.slack_loading_ij_n[i] = pulp.LpVariable(
                "LoadingSlack_ij_n_" + str(i), 0, 1e20)
            self.slack_loading_ji_n[i] = pulp.LpVariable(
                "LoadingSlack_ji_n_" + str(i), 0, 1e20)

        self.branch_flows_ij = np.empty(nbr, dtype=object)
        self.branch_flows_ji = np.empty(nbr, dtype=object)

        self.converged = False
Esempio n. 9
0
    def lp_solve(self, weight_of_corner=1):
        '''
        Use linear programming to solve min cost flow problem, make it possible to define constrains.

        Alert: pulp will automatically transfer node's name into str and repalce some special
        chars into '_', and will throw a error if there are variables' name duplicated.
        '''

        prob = pulp.LpProblem()  # minimize

        var_dict = {}
        varname2tuple = {}
        for u, v, he_id in self.flow_network.edges:
            var_dict[u, v, he_id] = pulp.LpVariable(
                f'{u}{v}{he_id}', self.flow_network[u][v][he_id]['lowerbound'],
                self.flow_network[u][v][he_id]['capacity'], pulp.LpInteger)
            # pulp will replace ' ' with '_' automatically
            varname2tuple[f'{u}{v}{he_id}'.replace(' ', "_")] = (u, v, he_id)

        objs = []
        for he in self.planar.dcel.half_edges.values():
            lf, rf = he.twin.inc.id, he.inc.id
            objs.append(self.flow_network[lf][rf][he.id]['weight'] *
                        var_dict[lf, rf, he.id])

        # bend points' cost
        if weight_of_corner != 0:
            for v in self.planar.G:
                if self.planar.G.degree(v) == 2:
                    (f1, he1_id), (f2, he2_id) = [
                        (f, key)
                        for f, keys in self.flow_network.adj[v].items()
                        for key in keys
                    ]
                    x = var_dict[v, f1, he1_id]
                    y = var_dict[v, f2, he2_id]
                    p = pulp.LpVariable(x.name + "temp", None, None,
                                        pulp.LpInteger)
                    prob.addConstraint(x - y <= p)
                    prob.addConstraint(y - x <= p)
                    objs.append(weight_of_corner * p)

        prob += pulp.lpSum(objs)  # number of bends in graph

        for f in self.planar.dcel.faces:
            prob += self.flow_network.nodes[f]['demand'] == pulp.lpSum([
                var_dict[v, f, he_id]
                for v, _, he_id in self.flow_network.in_edges(f, keys=True)
            ])
        for v in self.planar.G:
            prob += -self.flow_network.nodes[v]['demand'] == pulp.lpSum([
                var_dict[v, f, he_id]
                for _, f, he_id in self.flow_network.out_edges(v, keys=True)
            ])

        state = prob.solve()
        res = defaultdict(lambda: defaultdict(dict))
        if state == 1:  # update flow_dict
            self.flow_network.cost = pulp.value(prob.objective)
            for var in prob.variables():
                if var.name in varname2tuple:
                    u, v, he_id = varname2tuple[var.name]
                    res[u][v][he_id] = int(var.varValue)
        else:
            raise Exception("Problem can't be solved by linear programming")
        return res
Esempio n. 10
0
    'discount': 0.04
}, {
    'base': 8,
    'discount': 0.07
}]

banana_shopping = pulp.LpProblem('Banana Shopping', pulp.LpMaximize)

banana_price = [[
    round(banana_price(scheme['base'], scheme['discount'], b), 2)
    for b in range(total_bananas_per_vendor + 1)
] for scheme in vendor_schema]

bananas = [range(total_bananas_per_vendor + 1) for i in range(total_vendors)]
selected_bananas = [[
    pulp.LpVariable('vendor_' + str(i) + '_' + str(j) + '_bananas',
                    cat='Binary') for j in range(total_bananas_per_vendor + 1)
] for i in range(1, total_vendors + 1)]

for i in range(total_vendors):
    banana_shopping += pulp.lpSum([
        selected_bananas[i][j] for j in range(total_bananas_per_vendor + 1)
    ]) == 1, 'SOS constraint ' + str(i)

total_bananas = flatten([[
    selected_bananas[i][j] * bananas[i][j]
    for j in range(total_bananas_per_vendor + 1)
] for i in range(total_vendors)])

banana_shopping += pulp.lpSum(
    total_bananas
) <= total_vendors * total_bananas_per_vendor, 'Total available bananas'
Esempio n. 11
0
#!/usr/bin/python3
# import sys !{sys.executable} -m pip install pulp
# import the library pulp as p
import pulp as p

# Create a LP Minimization problem
Lp_prob = p.LpProblem('Problem', p.LpMaximize)

# Create problem Variables
x1 = p.LpVariable("x1", lowBound=0)  # Create a variable x1 >= 0
x2 = p.LpVariable("x2", lowBound=0)  # Create a variable x2 >= 0

# Objective Function
Lp_prob += 40 * x1 + 30 * x2

# Constraints:
x3 = p.LpVariable("x3", lowBound=0)
Lp_prob += 16 - x1 - 2 * x2 == x3
x4 = p.LpVariable("x4", lowBound=0)
Lp_prob += 9 - x1 - x2 == x4
x5 = p.LpVariable("x5", lowBound=0)
Lp_prob += 24 - 3 * x1 - 2 * x2 == x5

# Display the problem
print(Lp_prob)

status = Lp_prob.solve()  # Solver
print(p.LpStatus[status])  # The solution status

# Printing the final solution
print(p.value(x1), p.value(x2), p.value(Lp_prob.objective))
Esempio n. 12
0
#souce https://www.geeksforgeeks.org/python-linear-programming-in-pulp/
# import the library pulp as p 
import pulp as p 
  
# Create problem Variables  
bin1 = p.LpVariable("bin1", 0, 10)
bin2 = p.LpVariable("bin2",0, 10)
bin3 = p.LpVariable("bin3",0, 10)
bin4 = p.LpVariable("bin4",0,10)
bin5 = p.LpVariable("bin5",0,10)
bin6 = p.LpVariable("bin6",0,10)

Y1 = p.LpVariable("Y1",0,1)
Y2 = p.LpVariable("Y2",0,1)
Y3 = p.LpVariable("Y3",0,1)
Y4 = p.LpVariable("Y4",0,1)
Y5 = p.LpVariable("Y5",0,1)
Y6 = p.LpVariable("Y6",0,1)

X11 = p.LpVariable("X1-1",0,1)
X12 = p.LpVariable("X1-2",0,1)
X13 = p.LpVariable("X1-3",0,1)
X14 = p.LpVariable("X1-4",0,1)
X15 = p.LpVariable("X1-5",0,1)
X16 = p.LpVariable("X1-6",0,1)

X21 = p.LpVariable("X2-1",0,1)
X22 = p.LpVariable("X2-2",0,1)
X23 = p.LpVariable("X2-3",0,1)
X24 = p.LpVariable("X2-4",0,1)
X25 = p.LpVariable("X2-5",0,1)
Esempio n. 13
0
# define objective function(projected points) and constraints
objectiveFunction = ''
numPlayersConstraint = ''
costConstraint = ''

df['temp_index'] = df.index

# create pulp variables for each player's row and build constraints
for uniqueColumn in df[teamColumn].unique():
    tempConstraint = ''

    for index, row in df.loc[df[teamColumn] == uniqueColumn].iterrows():
        varName = 'p' + str(row['temp_index'])
        variable = pulp.LpVariable(
            varName, lowBound=0, upBound=1, cat=pulp.LpInteger
        )  #make binary player variable(0 for not in lineup, 1 for in lineup)

        #update constraints with player's projections and cost
        objectiveFunction += row[projectionsColumn] * variable
        numPlayersConstraint += variable
        costConstraint += row[budgetColumn] * variable
        tempConstraint += variable

    prob += (tempConstraint <= maxSameTeam)

# add objective function(projected points), the number of players chosen constraint, cost constraint, position constraints, and team constraints to problem
prob += objectiveFunction
prob += (numPlayersConstraint == numPlayers)
prob += (costConstraint <= budget)
Esempio n. 14
0
    def get_feasible_linear_constraints(self):
        """Instance method
        
        * This method obtains set of feasible linear constraints and populated the instance attribute, ``feasible_linear_constraints``.
        * Linear programming algorithm is employed with slack variables
        """
        E_constraints = self.get_elastic_constraints()

        # trying something new
        ###############################################
        # additional constraints

        L_evariables_sorted = sorted([
            k
            for k, v in E_constraints.modform_space.D_PuLP_variables.iteritems(
            ) if k[0] == 'e'
        ],
                                     key=natural_keys)
        L_PuLP_evariables_sorted = [
            E_constraints.modform_space.D_PuLP_variables[k]
            for k in L_evariables_sorted
        ]

        L_extra_PuLP_constraints = []  # e.g., -t <= e_1-e_2 <= t
        t_var = pulp.LpVariable('t', lowBound=0)

        for ii in xrange(0, len(L_PuLP_evariables_sorted), 2):

            e1 = L_evariables_sorted[ii]
            e2 = L_evariables_sorted[ii + 1]

            #e1_e2 - t <= 0; sense=-1 sets LE-- less than equal to inequality
            LHS_1 = E_constraints.modform_space.D_PuLP_variables[
                e1] - E_constraints.modform_space.D_PuLP_variables[e2] - t_var
            L_extra_PuLP_constraints.append(
                pulp.LpConstraint(LHS_1, rhs=0, sense=-1))

            # e1-e2 +t >= 0; sense=1 sets GE-- greater than equal to inequality
            LHS_2 = E_constraints.modform_space.D_PuLP_variables[
                e1] - E_constraints.modform_space.D_PuLP_variables[e2] + t_var
            L_extra_PuLP_constraints.append(
                pulp.LpConstraint(LHS_2, rhs=0, sense=1))
        #end for ii in xrange(0, len(L_PuLP_evariables_sorted), 2)

        #L_PuLP_constraints_extended = list(E_constraints.L_PuLP_constraints)
        E_constraints.L_PuLP_constraints.extend(L_extra_PuLP_constraints)

        #objective_function_PuLP_extended   = t_var + pulp.lpSum(L_PuLP_evariables_sorted)

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

        lp_solver = lps.LinearProgrammingSolver(E_constraints)

        #L_variables_sorted = sorted([k for k,v in E_constraints.D_PuLP_variables.iteritems() if k[0]=='e'], key=natural_keys)
        #L_PuLP_evariables_sorted = [E_constraints.D_PuLP_variables[k] for k in L_variables_sorted]

        objective_function_PuLP = pulp.lpSum(L_PuLP_evariables_sorted) + t_var

        lp_minimize_solution = lp_solver.linear_programming_solver(
            objective_function_PuLP, pulp.LpMinimize)

        #print(lp_minimize_solution)
        #print("status: ", LpStatus[lp_minimize_solution.status])

        #for v in lp_minimize_solution.variables():
        #    print(v, pulp.value(v))

        for i in range(1,
                       len(self._linear_constraints.L_linear_constraints) + 1):

            elastic_variable1 = "e_%s" % (2 * i - 1)
            elastic_variable2 = "e_%s" % (2 * i)

            value_PuLP_evariable1 = pulp.value(
                E_constraints.modform_space.D_PuLP_variables[elastic_variable1]
            )

            value_PuLP_evariable2 = pulp.value(
                E_constraints.modform_space.D_PuLP_variables[elastic_variable2]
            )
            diff = value_PuLP_evariable1 - value_PuLP_evariable2
            adjusted_rhs = float(
                self._linear_constraints.L_linear_constraints[i - 1][1]) - diff

            self._feasible_linear_constraints.L_linear_constraints.append(
                (self._linear_constraints.L_linear_constraints[i - 1][0],
                 adjusted_rhs))

            lhs_PuLP = sum([
                v[0] * v[1] for v in
                self._linear_constraints.L_PuLP_constraints[i - 1].items()
            ])
            self._feasible_linear_constraints.L_PuLP_constraints.append(
                pulp.LpConstraint(lhs_PuLP, rhs=float(adjusted_rhs)))
Esempio n. 15
0
import numpy as np

# Исходные данные (прямой задачи).
# Первые 2 элемента - коэффициенты в ограничениях прямой задачи.
# Третий элемент - коэффициенты целевой функции.
initial_data = np.array([[-2, -1, 6], [-1, 3, 9], [1, 1, 0]])

# Начинаем процесс перехода к двойственной задаче.
b = initial_data.transpose()

# Создаем задачу минимизации LP (т. к. для прямой задачи была максимизация).
task = pl.LpProblem("problem", pl.LpMinimize)

# Каждое ограничение прямой задачи становится двойственной переменной.
# Первый агрумент - имя переменной, второй и третий - ограничения слева и справа соответсвенно.
y1 = pl.LpVariable('y1', None, 0)
y2 = pl.LpVariable('y2', 0, None)

# Целевая функция двойственной задачи.
task += (b[2, 0] * y1 + b[2, 1] * y2)

# Каждая переменная прямой задачи становится двойственным ограничением.
# Коэффициент двойственной переменной в двойственных ограничениях равен коэффициенту переменной из ограничения прямой задачи.
task += (b[0, 0] * y1 + b[0, 1] * y2 >= b[0, 2])
task += (b[1, 0] * y1 + b[1, 1] * y2 >= b[1, 2])

# Решаем двойственную задачу.
status = task.solve()

# Вывод результатов.
print("Results:")
Esempio n. 16
0
def main():
    # 変数
    # タイムスロット 6*n * 教科 5

    total_slot = sum(subjects.values())

    v = {}
    for s in subjects.keys():
        v[s] = {}
        for x in days:
            v[s][x] = {}
            for y in timeslot:
                v[s][x][y] = {}
                for r in rooms:
                    v[s][x][y][r] = pulp.LpVariable(f'var_{s}_{x}_{y}_{r}',
                                                    lowBound=0,
                                                    upBound=1,
                                                    cat=pulp.LpInteger)

    problem = pulp.LpProblem("時間割", pulp.LpMinimize)

    problem += pulp.lpSum([
        v[s][x][y][r] * x for s in subjects.keys() for x in days
        for y in timeslot for r in rooms
    ])

    # 各教科は必要コマ数実施
    for s in subjects.keys():
        for r in rooms:
            problem += pulp.lpSum(
                [v[s][x][y][r] for x in days for y in timeslot]) == subjects[s]

    # 同一教科は同一コマに先生の数未満
    for s in subjects.keys():
        for x in days:
            for y in timeslot:
                problem += pulp.lpSum([v[s][x][y][r]
                                       for r in rooms]) <= teachers[s]
# 同一コマ+同一クラスは1教科のみ
    for x in days:
        for y in timeslot:
            for r in rooms:
                problem += pulp.lpSum([v[s][x][y][r]
                                       for s in subjects.keys()]) <= 1

# クラスの一日の同一教科は2まで
    for s in subjects.keys():
        for x in days:
            for r in rooms:
                problem += pulp.lpSum([v[s][x][y][r] for y in timeslot]) <= 2

    solver = pulp.PULP_CBC_CMD(msg=False)
    result = problem.solve(solver)

    print(pulp.LpStatus[result])
    # print(pulp.value(problem.objective))

    if result == pulp.LpStatusOptimal:
        for x in days:
            print(x, end=": ")
            for y in timeslot:
                print(y, end="(")
                for r in rooms:
                    for s in subjects.keys():
                        if pulp.value(v[s][x][y][r]) == 1:
                            print(r, s, end=",")
                print(")", end=', ')
            print()
Esempio n. 17
0
def get_underapprox_box(activation_pattern, weights, biases, min_val, max_val,
                        additional_constraints, epsilon):
    def get_w_t_x(weight_vector, pulpInputs):
        w_t_x = []
        num_inputs = len(weight_vector)
        for i in range(num_inputs):
            coeff = weight_vector[i]
            if coeff >= 0:
                w_t_x.append(coeff * pulpInputs[i][1])
            else:
                w_t_x.append(coeff * pulpInputs[i][0])
        return w_t_x

    num_inputs = weights[0].shape[1]
    pulpInputs = []
    for i in range(num_inputs):
        var_name = 'x' + str(i)
        hi = var_name + '_hi'
        lo = var_name + '_low'
        d_hi = pulp.LpVariable(hi,
                               lowBound=min_val,
                               upBound=max_val,
                               cat='Continuous')
        d_lo = pulp.LpVariable(lo,
                               lowBound=min_val,
                               upBound=max_val,
                               cat='Continuous')
        pulpInputs.append((d_lo, d_hi))
    prob = pulp.LpProblem("Box", pulp.LpMaximize)
    prob += pulp.lpSum([
        (pulpInputs[i][1] - pulpInputs[i][0]) for i in range(num_inputs)
    ]), "Total Range is Maximized"
    for i in range(num_inputs):
        prob += (pulpInputs[i][1] - pulpInputs[i][0]
                 ) >= 0, "High > Low Constraint for x_" + str(i)
    for layer_id, layer in enumerate(activation_pattern):
        weight_matrix = weights[layer_id]
        bias_vector = biases[layer_id]
        for neuron_id, neuron in enumerate(layer):
            if neuron == 2:
                continue
            weight_vector = weight_matrix[neuron_id]
            b = bias_vector[neuron_id]
            constraint_name = "activation constraint for neuron" + str(
                layer_id) + "_" + str(neuron_id)
            if neuron == 0:
                w_t_x = get_w_t_x(weight_vector, pulpInputs)
                prob += pulp.lpSum(w_t_x) <= -1 * b, constraint_name
            elif neuron == 1:
                w_t_x = get_w_t_x(-1 * weight_vector, pulpInputs)
                prob += pulp.lpSum(w_t_x) <= (b -
                                              UPPER_THRESH), constraint_name
    for constraint_id, constraint in enumerate(additional_constraints):
        diff_weight, diff_bias = constraint
        w_t_x = get_w_t_x(-1 * diff_weight, pulpInputs)
        constraint_name = "additinal property constraint " + str(constraint_id)
        rhs = -1 * epsilon + diff_bias - UPPER_THRESH
        prob += pulp.lpSum(w_t_x) <= rhs, constraint_name
    # print (prob)
    status = prob.solve()
    result = pulp.LpStatus[status]
    print(result)
    under_approx_box = []
    if result == 'Infeasible':
        for i in range(num_inputs):
            under_approx_box.append((0, 0))
        return under_approx_box, 0, 0
    assert result == 'Optimal', "The under-approximate constraint problem fails to give optimal solution"
    for i in range(num_inputs):
        under_approx_box.append(
            (pulp.value(pulpInputs[i][0]), pulp.value(pulpInputs[i][1])))
    perimeter = 0.0
    volume = 1.0
    for i in range(num_inputs):
        volume *= (pulp.value(pulpInputs[i][1]) - pulp.value(pulpInputs[i][0]))
        perimeter += pulp.value(pulpInputs[i][1]) - pulp.value(
            pulpInputs[i][0])
    return under_approx_box, volume, perimeter
Esempio n. 18
0
    return STOCK


if __name__ == '__main__':

        file_path = '../data/truck_instance_base.data'
        graph, p, start, n_clientsuppr, n_depsuppr, Entity = extract_donnes(file_path)
        file_path = '../data/truck_instance_base.data'
        graph, p, start, n_clientsuppr, n_depsuppr, Entity = extract_donnes(file_path)

        prob,COUTSTAUXDOU = set_model_cout_net(graph, p, start, n_clientsuppr, n_depsuppr,Entity)

        #prob.solve(pl.PULP_CBC_CMD(logPath='./output_file/CBC_max_flow.log'))
        prob.solve()

        qr  = pl.LpVariable("qr", LpInteger)
        gpu = pl.LpVariable("QteGPU", LpInteger)
        coutsTotal = pl.LpVariable("coutsTotal", LpInteger)
        Benefice = pl.LpVariable("Benefice", LpInteger)
        Route_utilises=0
        #Optimal
        print("Status:", pl.LpStatus[prob.status])



        nx.write_graphml(graph, "graph_routes.graphml")
        # ------------------------------------------------------------------------ #
        # Print the solver output
        # ------------------------------------------------------------------------ #
        print(f'Status:\n{pl.LpStatus[prob.status]}')
Esempio n. 19
0
    def optimize(self):
        """
        Run the optimization.
        set solution in self.X
        set state STATE_SOLVED_OK if solved,
        otherwise STATE_SOLVED_BAD
        """
        assert self.state != self.STATE_UNDEFINED,\
               "set_data() must be called before optimize()!"
        self.atm = self.models['ATM']
        self.lnd = self.models['LND']
        self.ice = self.models['ICE']
        self.ocn = self.models['OCN']
        self.real_variables = [
            'TotalTime', 'T1', 'Tice', 'Tlnd', 'Tatm', 'Tocn'
        ]
        self.integer_variables = [
            'NBice', 'NBlnd', 'NBatm', 'NBocn', 'Nice', 'Nlnd', 'Natm', 'Nocn'
        ]
        self.X = {}
        X = self.X
        self.prob = pulp.LpProblem("Minimize ACME time cost", pulp.LpMinimize)
        for rv in self.real_variables:
            X[rv] = pulp.LpVariable(rv, lowBound=0)

        for iv in self.integer_variables:
            X[iv] = pulp.LpVariable(iv, lowBound=1, cat=pulp.LpInteger)

        # cost function
        self.prob += X['TotalTime']

        #constraints
        self.constraints = []
        # Layout-dependent constraints. Choosing another layout to model
        # will require editing these constraints
        self.constraints.append([X['Tice'] - X['T1'] <= 0, "Tice - T1 == 0"])
        self.constraints.append([X['Tlnd'] - X['T1'] <= 0, "Tlnd - T1 == 0"])
        self.constraints.append([
            X['T1'] + X['Tatm'] - X['TotalTime'] <= 0,
            "T1 + Tatm - TotalTime <= 0"
        ])
        self.constraints.append(
            [X['Tocn'] - X['TotalTime'] <= 0, "Tocn - TotalTime == 0"])
        self.constraints.append([
            X['Nice'] + X['Nlnd'] - X['Natm'] == 0, "Nice + Nlnd - Natm == 0"
        ])
        self.constraints.append([
            X['Natm'] + X['Nocn'] == self.maxtasks,
            "Natm + Nocn <= %d" % (self.maxtasks)
        ])
        self.constraints.append([
            self.atm.blocksize * X['NBatm'] - X['Natm'] == 0,
            "Natm = %d * NBatm" % self.atm.blocksize
        ])
        self.constraints.append([
            self.ice.blocksize * X['NBice'] - X['Nice'] == 0,
            "Nice = %d * NBice" % self.ice.blocksize
        ])
        self.constraints.append([
            self.lnd.blocksize * X['NBlnd'] - X['Nlnd'] == 0,
            "Nlnd = %d * NBlnd" % self.lnd.blocksize
        ])
        self.constraints.append([
            self.ocn.blocksize * X['NBocn'] - X['Nocn'] == 0,
            "Nocn = %d * NBocn" % self.ocn.blocksize
        ])

        # These are the constraints based on the timing data.
        # They should be the same no matter what the layout of the components.
        self.add_model_constraints()

        for c, s in self.constraints:
            self.prob += c, s

        # Write the program to file and solve (using coin-cbc)
        self.prob.writeLP("IceLndAtmOcn_model.lp")
        self.prob.solve()
        self.set_state(self.prob.status)
        return self.state
def process(G, bound, root, kappa='tree', c=None, reduction=False, margin=8):
    depths = {x: float('inf') for x in G.nodes()}
    current_level = deque([root])
    next_level = deque()

    parent = {}
    depth = 0
    res = nx.DiGraph()

    count = 0

    while True:
        for n in current_level:
            depths[n] = depth
            count += 1

            for (u, v, d) in G.edges([n], data=True):
                assert (n == u)
                if d['weight'] <= bound:
                    found_in_current_level = v in next_level
                    in_current_level = v in current_level

                    if in_current_level:
                        # v on same level
                        pass
                    elif depths[v] != float('inf'):
                        # back edge
                        res.add_edge(
                            v, n)  # other direction to enable removing leafs
                    else:
                        # forward edge
                        if not found_in_current_level:
                            # check if weak link to lower nodes exists (current level is ok!)
                            avoid = False
                            for (w, y, e) in G.edges([v], data=True):
                                assert (w == v)
                                if e['weight'] <= bound + margin:
                                    if depths[y] < depth:
                                        # avoid nodes with weak edges to lower nodes!
                                        avoid = True
                                        break

                            if not avoid:
                                next_level.append(v)
                                if reduction:
                                    parent[v] = u

        if len(next_level) >= kappa_fun(
                kappa, depth + 1):  # depth for next level, so +1
            current_level = next_level
            next_level = deque()
            depth += 1
        else:
            break

    if reduction:
        K = res.to_undirected()
        prob = pulp.LpProblem("NodeReduction", pulp.LpMinimize)
        x = {
            n: pulp.LpVariable("Node_" + str(n), 0, 1, pulp.LpInteger)
            for n in K.nodes()
        }

        prob += sum(x.values())  # minimize objective function

        for j in range(1, depth + 1):
            prob += sum([v for k, v in x.items() if depths[k] == j
                         ]) >= kappa_fun(kappa, j)

        for n in K.nodes():
            if n == root:
                continue
            potential_parents = [
                x[v] for (u, v) in K.edges([n]) if depths[u] > depths[v]
            ]
            prob += x[n] <= sum(potential_parents)

        prob.solve()

        for n in K.nodes():
            if not x[n].varValue == 1:
                res.remove_node(n)
        count = len(res.nodes())

    dat = [{
        'bound': bound,
        'root': root,
        'depth': depth,
        'allnodes': len(G.nodes()),
        'nodes': count
    }]

    if res is not None:
        if len(res.edges()) > 1:
            dat[0]['maxweight'] = max(
                [G[u][v]['weight'] for (u, v) in res.edges()])
        else:
            dat[0]['maxweight'] = 0

    return dat, res
Esempio n. 21
0
def addVar(name):
    varname = 'targetVariable[' + str(len(targetVariable)) + ']'
    var = pulp.LpVariable(varname, lowBound=parameter.activeThreshold)
    weightIndex[name] = var
    targetVariable.append(var)
    return varname
Esempio n. 22
0
 def _init_var(self):
     self._var = pulp.LpVariable(self.name,
                                 lowBound=self.min,
                                 upBound=self.max,
                                 cat="Integer")
Esempio n. 23
0
list_values = []
for x in range(len(a)):
    c.append((-2) ** x)




print(c)
multi_output = [v * s for v, s in zip(a, c)]
total = sum(multi_output)
c_val = math.ceil(total/2)
b = []
for x in range(c_val):
    b.append((-2) ** x)

x = p.LpVariable("x", dicts=b)
y = p.LpVariable("y", lowBound = 0)



list_values = []
for x in range(len(A)):
    list_values.append((-2) ** x)

multi_output = [v * s for v, s in zip(A, list_values)]
c_val = math.ceil(total/2)
possible_vals = []
for x in range(c_val):
    possible_vals.append((-2) ** x)

all_ones = []
Esempio n. 24
0
path_to_cplex = r'C:/Program Files/IBM/ILOG/CPLEX_Studio_Community201/cplex/bin/x64_win64/cplex.exe'

import pulp as pl


model = pl.LpProblem("Example", pl.LpMinimize)
solver = pl.CPLEX_CMD(path=path_to_cplex)
_var = pl.LpVariable('a')
_var2 = pl.LpVariable('a2')
model += _var + _var2 == 1
print("test")
result = model.solve(solver)


"""
facc58cf08ee0-pulp.sol


Minimize
OBJ: __dummy
Subject To
_C1: a + a2 = 1
Bounds
__dummy = 0
a free
a2 free
End

 """

print(result)
Esempio n. 25
0
 def solve_lp(self, x, y):
     y = y.detach().numpy()
     x = x.view(-1, 28 * 28)
     #xp = F.relu(self.fc1(x))
     #xp.sum().backward() #make sure grad is there
     #xp= xp.detach().numpy()
     #xp = self.fc1(x).detach().numpy()
     #print(xp.shape) # 64 x 10
     w = self.fc1.weight.detach().numpy()
     b = self.fc1.bias.detach().numpy()
     xpp = np.matmul(x, w.T) + b
     lp_vars_w = []
     for ii in range(10):
         lp_vars_w.append([])
         for i in range(28 * 28):
             lp_vars_w[-1].append(
                 pulp.LpVariable('w%d_%d' % (ii, i),
                                 lowBound=w[ii][i] - 1,
                                 upBound=w[ii][i] + 1,
                                 cat='Continuous'))
     lp_vars_b = []
     for i in range(10):
         lp_vars_b.append(
             pulp.LpVariable('b%d' % i,
                             lowBound=b[i] - 1,
                             upBound=b[1] + 1,
                             cat='Continuous'))
     problem = []
     constraints = []
     for target_idx in range(len(y)):
         target = y[target_idx]
         for idx in range(10):
             if xpp[target_idx][idx] < 0:
                 #S w_i * x_i + b  <= 0
                 #constraints.append(sum([ lp_vars_w[j] * x[target_idx][j].item() for j in range(28*28)]) <= 0)
                 constraints.append(
                     sum([
                         lp_vars_w[idx][j] * x[target_idx][j].item()
                         for j in range(28 * 28)
                     ] + lp_vars_b[idx]) <= 0.1)
             else:
                 #S w_i * x_i + b  <= 0
                 #constraints.append(sum([ lp_vars_w[j] * x[target_idx][j].item() for j in range(28*28)]) >= 0)
                 constraints.append(
                     sum([
                         lp_vars_w[idx][j] * x[target_idx][j].item()
                         for j in range(28 * 28)
                     ] + lp_vars_b[idx]) >= -0.1)
             if target == idx:
                 problem.append(
                     sum([
                         lp_vars_w[idx][j] * x[target_idx][j].item()
                         for j in range(28 * 28)
                     ] + lp_vars_b[idx]))
                 #problem.append(sum([ lp_vars_w[j] for j in range(28*28)]))
             else:
                 problem.append(
                     sum([
                         -lp_vars_w[idx][j] * x[target_idx][j].item()
                         for j in range(28 * 28)
                     ] + lp_vars_b[idx]))
                 #problem.append(sum([ - lp_vars_w[j]  for j in range(28*28)]))
     lp_max = pulp.LpProblem("nn", pulp.LpMaximize)
     lp_max += sum(problem), "Z"
     for constraint in constraints:
         lp_max += constraint
     lp_max.solve()
     print(pulp.LpStatus[lp_max.status])
     #zero the grad
     #self.fc1.bias.grad.data.fill_(0)
     #self.fc1.weight.grad.data.fill_(1)
     for variable in lp_max.variables():
         if variable.name[0] == 'w':
             ii, i = map(int, variable.name[1:].split('_'))
             self.fc1.weight[ii][i] = float(variable.varValue)
         elif variable.name[0] == 'b':
             i = int(variable.name[1:])
             self.fc1.bias[i] = float(variable.varValue)
Esempio n. 26
0
    def add_adjacent_variables_constraints_m1(self) -> None:
        """Method to create LP variables for each pair of adjacent geometries (using mode 1).

        """
        logging.debug("method add_adjacent_variables_constraints_m1 called")
        combinations = set()

        for i in tqdm(range(self.gdf.shape[0]), desc="Construction LP"):
            for j in range(self.gdf.shape[0]):
                if j == i:
                    # We don't check the adjacency with itself.
                    continue
                if (i, j) in combinations or (j, i) in combinations:
                    # If the combination already exists we skip it.
                    continue

                # Create a set with all possible combinations to optimize.
                combinations.add((i, j))

        for i, j in combinations:
            # Create the variables for the optimal horizontal en vertical length between p_i en p_j
            h = p.LpVariable(f"h_{i}_{j}")
            v = p.LpVariable(f"v_{i}_{j}")
            self.problem += h >= 0
            self.problem += v >= 0

            # Calculate the minimum length between i en j based on their width
            w = self.gdf.at[i, "geom_size"] + self.gdf.at[j, "geom_size"]

            # Add a gap if they are non-adjacent
            perimeters = [
                np for np in self.gdf.iloc[i, :]["_neighbors"].split(",")
            ]
            neighbors = [
                n for n in self.gdf.iloc[i, :]["_neighbors"].split(",")
            ]
            if str(j) in neighbors or True:
                gap = 0
                # if float(perimeters[neighbors.index(str(j))]) > 0.1 or True:
                if True:
                    self._distances.append(h)
                    self._distances.append(v)
            else:
                gap = self.gap_size

            # Check whether the neighbors should be connected horizontally or vertically.
            geom_dist_x = self.gdf.at[j,
                                      "geometry"].x - self.gdf.at[i,
                                                                  "geometry"].x
            geom_dist_y = self.gdf.at[j,
                                      "geometry"].y - self.gdf.at[i,
                                                                  "geometry"].y

            # Depending on whether x_i - x_j yields a positive or negative result we decide the order
            # in which they are presented in the constraints.
            if geom_dist_x > 0:
                if abs(geom_dist_x) > abs(geom_dist_y):
                    # Add constraint 1
                    self.problem += (self._coord_dict[j]["x"] -
                                     self._coord_dict[i]["x"] >= w + gap)
                # Add constraint 3
                self.problem += (h >= self._coord_dict[j]["x"] -
                                 self._coord_dict[i]["x"] - w)
            else:
                if abs(geom_dist_x) > abs(geom_dist_y):
                    # Add constraint 1
                    self.problem += (self._coord_dict[i]["x"] -
                                     self._coord_dict[j]["x"] >= w + gap)
                # Add constraint 3
                self.problem += (h >= self._coord_dict[i]["x"] -
                                 self._coord_dict[j]["x"] - w)

            # Depending on whether y_i - y_j yields a positive or negative result we decide the order
            # in which they are presented in the constraints.
            if geom_dist_y > 0:
                if not abs(geom_dist_x) > abs(geom_dist_y):
                    # Add constraint 2
                    self.problem += (self._coord_dict[j]["y"] -
                                     self._coord_dict[i]["y"] >= w + gap)
                # Add constraint 4
                self.problem += (v >= self._coord_dict[j]["y"] -
                                 self._coord_dict[i]["y"] - w)
            else:
                if not abs(geom_dist_x) > abs(geom_dist_y):
                    # Add constraint 2
                    self.problem += (self._coord_dict[i]["y"] -
                                     self._coord_dict[j]["y"] >= w + gap)
                # Add constraint 4
                self.problem += (v >= self._coord_dict[i]["y"] -
                                 self._coord_dict[j]["y"] - w)

            # Define the objective
        self.problem += p.lpSum(self._distances)
Esempio n. 27
0
def V1G_optimization(): #this is the function for managed charging

    # initiate the problem statement
    model=lp.LpProblem('Minimize_Distribution_level_Peak_Valley_Difference', lp.LpMinimize)

    #define optimization variables
    veh_V1G=range(n_V1G_Veh)
    time_Interval=range(24)

    chargeprofiles=lp.LpVariable.dicts('charging_profiles', ((i,j) for i in veh_V1G for j in time_Interval), lowBound=0.1, upBound=power_V1GUppper)
    chargestates=lp.LpVariable.dicts('charging_states', ((i,j) for i in veh_V1G for j in time_Interval), cat='Binary')
    total_load=lp.LpVariable.dicts('total_load', time_Interval,lowBound=0.1)
    max_load=lp.LpVariable('max_load', lowBound=0)
    min_load=lp.LpVariable('min_load', lowBound=0)

    # define objective function
    model += max_load - min_load
    #model += max_load

    # define constraints
    for t in time_Interval: # constraint 1 & 2: to identify the max and min loads
        model += total_load[t] <= max_load
        model += total_load[t] >= min_load

    for t in time_Interval: # constraint 3: calculate the total load at each time interval t
        if opt_includeSolar == 0:
            model += lp.lpSum( [chargeprofiles[i,t]] for i in veh_V1G) + base_Load[t] + unmanaged_Load[t] == total_load[t]
        else:
            model += lp.lpSum([chargeprofiles[i, t]] for i in veh_V1G) + base_Load[t] + unmanaged_Load[t] - solarCurve[t] == total_load[t]

    for i in veh_V1G: # constraint 4: constraint on charging powers for each EV: only optimize the charge profile between start and end charging time
        temp_start=v1g_startingTime[i]
        temp_end=v1g_endingTime[i]
        if temp_start >= temp_end:
            for t in range (temp_end):
                model += chargeprofiles[i,t] <= chargestates[i,t] * power_V1GUppper
                model += chargeprofiles[i,t] >= chargestates[i,t] * power_V1GLower
            for t in range(temp_end, temp_start, 1):
                model += chargeprofiles[i,t] == 0
                model += chargestates[i,t] == 0
            for t in range(temp_start, 24, 1):
                model += chargeprofiles[i,t] <= chargestates[i,t] * power_V1GUppper
                model += chargeprofiles[i,t] >= chargestates[i,t] * power_V1GLower
        if temp_start < temp_end:
            for t in range(temp_start):
                model += chargeprofiles[i,t] == 0
                model += chargestates[i,t] ==0
            for t in range(temp_start, temp_end, 1):
                model += chargeprofiles[i,t] <= chargestates[i,t] * power_V1GUppper
                model += chargeprofiles[i,t] >= chargestates[i,t] * power_V1GLower
            for t in range(temp_end, 24, 1):
                model += chargeprofiles[i,t] == 0
                model += chargestates[i,t]==0

    for i in veh_V1G: # constraint 5: SOC constraint, cannot be greater than 1, end_SOC must be above certain levels
        temp_start=v1g_startingTime[i]
        temp_end=v1g_endingTime[i]
        temp_startSOC=v1g_startingSOC[i]
        if temp_start >= temp_end:
            for t in range(temp_start+1, 24, 1):
                temp_timer = range (temp_start, t, 1)
                model += temp_startSOC + lp.lpSum( [chargeprofiles[i,tn] *charge_efficiency/batteryCapacity] for tn in temp_timer) <=1
            for t in range (0, temp_end+1, 1):
                temp_timer = range (0, t, 1)
                model += temp_startSOC + lp.lpSum( [chargeprofiles[i,tn] *charge_efficiency/batteryCapacity] for tn in range(temp_start, 24,1)) \
                         + lp.lpSum( [chargeprofiles[i,tn] *charge_efficiency/batteryCapacity] for tn in temp_timer) <=1
            #if end_SOC == 1:
            #    incrementSOC=v1g_distance[i]/batteryRange
            #    model += lp.lpSum([chargeprofiles[i, tn] * charge_efficiency / batteryCapacity] for tn in  range(temp_start, 24, 1)) \
            #             + lp.lpSum([chargeprofiles[i, tn] * charge_efficiency / batteryCapacity] for tn in temp_timer) >= incrementSOC  # need to divide 4
            if end_SOC ==2:
                model += temp_startSOC + lp.lpSum([chargeprofiles[i, tn] *charge_efficiency / batteryCapacity] for tn in range(temp_start, 24, 1)) + lp.lpSum([chargeprofiles[i, tn] *charge_efficiency / batteryCapacity] for tn in range(0, temp_end)) ==1
        if temp_start < temp_end:
             for t in range (temp_start+1, temp_end+1, 1):
                temp_timer = range (temp_start, t, 1)
                model += temp_startSOC + lp.lpSum( [chargeprofiles[i,tn] *charge_efficiency/batteryCapacity] for tn in temp_timer) <=1
             #if end_SOC == 1:
             #   incrementSOC=v1g_distance[i]/batteryRange
             #   model += lp.lpSum( [chargeprofiles[i,tn] * charge_efficiency/batteryCapacity] for tn in temp_timer) >= incrementSOC
             if end_SOC ==2:
                #model += temp_startSOC + lp.lpSum([chargeprofiles[i, tn] *(1/charge_efficiency / batteryCapacity)] for tn in range(temp_start, 24, 1)) + lp.lpSum([chargeprofiles[i, tn] *(1/charge_efficiency / batteryCapacity)] for tn in temp_timer) ==1
                model += temp_startSOC + lp.lpSum([chargeprofiles[i, tn] * charge_efficiency / batteryCapacity] for tn in range(temp_start, temp_end, 1)) ==1

                #for t in time_Interval:  # constraint 6: number of chargers available at time interval t
        #model += lp.lpSum([chargestates[i, t]] for i in veh_V1G) <= 400

    #print(model)
    status=model.solve()
    if isManaged==1:
        print(lp.LpStatus[status])
        #print(lp.value(max_load), lp.value(min_load))

    return chargeprofiles, total_load
Esempio n. 28
0
    def add_adjacent_variables_constraints_m4(self, s_dict) -> None:
        """Method to create LP variables for each pair of adjacent geometries (using mode 4).

        """
        logging.debug("method add_adjacent_variables_constraints_m4 called")
        combinations = set()

        for i in tqdm(range(self.gdf.shape[0]), desc="Construction LP"):
            for j in range(self.gdf.shape[0]):
                if j == i:
                    # We don't check the adjacency with itself.
                    continue
                if (i, j) in combinations or (j, i) in combinations:
                    # If the combination already exists we skip it.
                    continue

                # Create a set with all possible combinations to optimize.
                combinations.add((i, j))

        for i, j in combinations:
            # Create the variables for the optimal horizontal en vertical length between p_i en p_j
            h = p.LpVariable(f"h_{i}_{j}")
            v = p.LpVariable(f"v_{i}_{j}")
            self.problem += h >= 0
            self.problem += v >= 0

            # Calculate the minimum length between i en j based on their width
            w = self.gdf.at[i, "geom_size"] + self.gdf.at[j, "geom_size"]

            # Add a gap if they are non-adjacent
            if str(j) in self.gdf.iloc[i, :]["_neighbors"].split(","):
                gap = 0
                self._distances.append(h)
                self._distances.append(v)

            else:
                gap = self.gap_size

            # Create the S constant based on the results in the first iteration to determine horizontal or vertical adjacency in the cartogram.
            if s_dict[i][j] and str(j) in self.gdf.iloc[
                    i, :]["_neighbors"].split(","):
                s = w
                one_minus_s = 0
            elif not s_dict[i][j] and str(j) in self.gdf.iloc[
                    i, :]["_neighbors"].split(","):
                s = 0
                one_minus_s = w
            else:
                s = 0
                one_minus_s = 0

            # Check the distance between j en i to determine in which order to place the coordinates
            geom_dist_x = self.gdf.at[j,
                                      "geometry"].x - self.gdf.at[i,
                                                                  "geometry"].x
            geom_dist_y = self.gdf.at[j,
                                      "geometry"].y - self.gdf.at[i,
                                                                  "geometry"].y

            # Depending on whether x_i - x_j yields a positive or negative result we decide the order
            # in which they are presented in the constraints.
            if geom_dist_x > 0:
                if s > 0:
                    # Add constraint 1
                    self.problem += (self._coord_dict[j]["x"] -
                                     self._coord_dict[i]["x"] >= s)

                # Add constraint 3
                self.problem += (h >= self._coord_dict[j]["x"] -
                                 self._coord_dict[i]["x"] - w)
            else:
                if s > 0:
                    # Add constraint 1
                    self.problem += (self._coord_dict[i]["x"] -
                                     self._coord_dict[j]["x"] >= s)

                # Add constraint 3
                self.problem += (h >= self._coord_dict[i]["x"] -
                                 self._coord_dict[j]["x"] - w)

            # Depending on whether y_i - y_j yields a positive or negative result we decide the order
            # in which they are presented in the constraints.
            if geom_dist_y > 0:
                if one_minus_s > 0:
                    # Add constraint 2
                    self.problem += (self._coord_dict[j]["y"] -
                                     self._coord_dict[i]["y"] >= one_minus_s)
                # Add constraint 4
                self.problem += (v >= self._coord_dict[j]["y"] -
                                 self._coord_dict[i]["y"] - w)
            else:
                if one_minus_s > 0:
                    # Add constraint 2
                    self.problem += (self._coord_dict[i]["y"] -
                                     self._coord_dict[j]["y"] >= one_minus_s)
                # Add constraint 4
                self.problem += (v >= self._coord_dict[i]["y"] -
                                 self._coord_dict[j]["y"] - w)

            # Define the objective
        self.problem += p.lpSum(self._distances)
Esempio n. 29
0
        params = (f.read()).split('\n')
        params = [e for e in params if e != ""]
    BUS_COUNT = int(params[0])  # k
    BUS_SIZE = int(params[1])  # s
    rowdies = [eval(e) for e in params[2:]]

    # Define the linear programming problem
    lp_problem = pulp.LpProblem("Optimizing_Bus_Assignments", pulp.LpMinimize)

    # Initialize the variables bi(u)
    variables = {}
    for i in range(BUS_COUNT):
        for u in range(n):
            varname = 'b' + str(i) + '_' + str(u)
            keyname = 'b[' + str(i) + '][' + str(u) + ']'
            x = pulp.LpVariable(varname, lowBound=0, upBound=1, cat='Integer')
            variables[keyname] = x

    # Initialize the variables zi(u, v)+ and zi(u, v)-
    for i in range(BUS_COUNT):
        for edge in edges:
            u = str(node2hash[edge[0]])
            v = str(node2hash[edge[1]])
            varname1 = 'z_' + str(i) + '_' + u + '_' + v + '_' + 'plus'
            keyname1 = 'z' + str(i) + '[' + u + '][' + v + ']+'
            varname2 = 'z_' + str(i) + '_' + u + '_' + v + '_' + 'minus'
            keyname2 = 'z' + str(i) + '[' + u + '][' + v + ']-'
            x = pulp.LpVariable(varname1, cat='Continuous')
            y = pulp.LpVariable(varname2, cat='Continuous')
            variables[keyname1] = x
            variables[keyname2] = y
# 线性规划2

import pulp

profit = pulp.LpProblem("My LP Problem", pulp.LpMaximize)

x = pulp.LpVariable('x', lowBound=0, cat='Integer')  #Integer---不连续的整数
y = pulp.LpVariable('y', lowBound=2, cat='Integer')  #Continuous--连续的

# Objective function目标函数
profit += 72 * x + 64 * y

# Constraints约束
profit += 3 * x <= 100
profit += 12 * x + 8 * y <= 480
profit += x + y <= 50

print(profit)

profit.solve()
print(pulp.LpStatus[profit.status])

for variable in profit.variables():
    print('{} = {}'.format(variable.name, variable.varValue))

print(pulp.value(profit.objective))