本文整理汇总了Python中pulp.LpProblem方法的典型用法代码示例。如果您正苦于以下问题:Python pulp.LpProblem方法的具体用法?Python pulp.LpProblem怎么用?Python pulp.LpProblem使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pulp
的用法示例。
在下文中一共展示了pulp.LpProblem方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_objective
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def update_objective(self, input_data, dmu_code, input_variables,
output_variables, lp_model):
''' Updates coefficients of the objective function of a given model.
Args:
input_data (InputData): object that stores input data.
dmu_code (str): DMU code.
input_variables (dict of str to pulp.LpVariable): dictionary
that maps variable name to pulp variable corresponding
to input categories.
output_variables (dict of str to pulp.LpVariable): dictionary
that maps variable name to pulp variable corresponding
to output categories.
lp_model (pulp.LpProblem): linear programming model.
'''
for category in input_data.output_categories:
lp_model.objective[output_variables[category]] = input_data.coefficients[
dmu_code, category]
示例2: update_equality_constraint
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def update_equality_constraint(self, input_data, dmu_code, input_variables,
output_variables, lp_model):
''' Updates coefficients of the equality constraint of a given model.
Args:
input_data (InputData): object that stores input data.
dmu_code (str): DMU code.
input_variables (dict of str to pulp.LpVariable): dictionary
that maps variable name to pulp variable corresponding
to input categories.
output_variables (dict of str to pulp.LpVariable): dictionary
that maps variable name to pulp variable corresponding
to output categories.
lp_model (pulp.LpProblem): linear programming model.
'''
for category, var in input_variables.items():
lp_model.constraints['equality_constraint'][var] = input_data.coefficients[
dmu_code, category]
示例3: define_lp
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def define_lp(fares, product_names):
"""Set up LP.
Parameters
----------
fares: 2D np array
contains fares for products, size n_classes*n_products
products_names: list
product names (typically relation/class combinations)
Returns
-------
tuple of the form (LP problem, decision variables)
"""
prob = pulp.LpProblem('network_RM', pulp.LpMaximize)
# decision variables: available seats per product
x = pulp.LpVariable.dicts('x', product_names, lowBound=0)
# objective function
revenue = pulp.lpSum([x[it]*fares.ravel()[i] for i, it in
enumerate(product_names)])
prob += revenue
return prob, x
示例4: label_prop
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def label_prop(C, nt, Dct, lp="linear"):
#Inputs:
# C : Number of share classes between src and tar
# nt : Number of target domain samples
# Dct : All d_ct in matrix form, nt * C
# lp : Type of linear programming: linear (default) | binary
#Outputs:
# Mcj : all M_ct in matrix form, m * C
Dct = abs(Dct)
model = pulp.LpProblem("Cost minimising problem", pulp.LpMinimize)
Mcj = pulp.LpVariable.dicts("Probability",
((i, j) for i in range(C) for j in range(nt)),
lowBound=0,
upBound=1,
cat='Continuous')
# Objective Function
model += (
pulp.lpSum([Dct[j, i]*Mcj[(i, j)] for i in range(C) for j in range(nt)])
)
# Constraints
for j in range(nt):
model += pulp.lpSum([Mcj[(i, j)] for i in range(C)]) == 1
for i in range(C):
model += pulp.lpSum([Mcj[(i, j)] for j in range(nt)]) >= 1
# Solve our problem
model.solve()
pulp.LpStatus[model.status]
Output = [[Mcj[i, j].varValue for i in range(C)] for j in range(nt)]
return np.array(Output)
示例5: __init__
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def __init__(self):
self.prob = LpProblem('Daily Fantasy Sports', LpMaximize)
示例6: __init__
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def __init__(self, input_data, input_params):
self.input_data = input_data
self.input_params = input_params
self.model = pulp.LpProblem(name='prod_planning', sense=pulp.LpMinimize)
self._create_decision_variables()
self._create_main_constraints()
self._set_objective_function()
# ================== Decision variables ==================
示例7: create_model
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def create_model(self):
def distances(assignment):
return l2_distance(self.data[assignment[0]], self.centroids[assignment[1]])
clusters = list(range(self.k))
assignments = [(i, j)for i in range(self.n) for j in range(self.k)]
# outflow variables for data nodes
self.y = pulp.LpVariable.dicts('data-to-cluster assignments',
assignments,
lowBound=0,
upBound=1,
cat=pulp.LpInteger)
# outflow variables for cluster nodes
self.b = pulp.LpVariable.dicts('cluster outflows',
clusters,
lowBound=0,
upBound=self.n-self.min_size,
cat=pulp.LpContinuous)
# create the model
self.model = pulp.LpProblem("Model for assignment subproblem", pulp.LpMinimize)
# objective function
self.model += pulp.lpSum(distances(assignment) * self.y[assignment] for assignment in assignments)
# flow balance constraints for data nodes
for i in range(self.n):
self.model += pulp.lpSum(self.y[(i, j)] for j in range(self.k)) == 1
# flow balance constraints for cluster nodes
for j in range(self.k):
self.model += pulp.lpSum(self.y[(i, j)] for i in range(self.n)) - self.min_size == self.b[j]
# flow balance constraint for the sink node
self.model += pulp.lpSum(self.b[j] for j in range(self.k)) == self.n - (self.k * self.min_size)
示例8: create_model
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def create_model(self):
def distances(assignment):
return l2_distance(self.data[assignment[0]], self.centroids[assignment[1]])
clusters = list(range(self.k))
assignments = [(i, j)for i in range(self.n) for j in range(self.k)]
# outflow variables for data nodes
self.y = pulp.LpVariable.dicts('data-to-cluster assignments',
assignments,
lowBound=0,
upBound=1,
cat=pulp.LpInteger)
# outflow variables for cluster nodes
self.b = pulp.LpVariable.dicts('cluster outflows',
clusters,
lowBound=0,
upBound=self.n-self.min_size,
cat=pulp.LpContinuous)
# create the model
self.model = pulp.LpProblem("Model for assignment subproblem", pulp.LpMinimize)
# objective function
self.model += pulp.lpSum([distances(assignment) * self.y[assignment] for assignment in assignments])
# flow balance constraints for data nodes
for i in range(self.n):
self.model += pulp.lpSum(self.y[(i, j)] for j in range(self.k)) == 1
# flow balance constraints for cluster nodes
for j in range(self.k):
self.model += pulp.lpSum(self.y[(i, j)] for i in range(self.n)) - self.min_size == self.b[j]
# capacity constraint on outflow of cluster nodes
for j in range(self.k):
self.model += self.b[j] <= self.max_size - self.min_size
# flow balance constraint for the sink node
self.model += pulp.lpSum(self.b[j] for j in range(self.k)) == self.n - (self.k * self.min_size)
示例9: create_model
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def create_model(self):
def distances(assignment):
return l2_distance(self.data[assignment[0]], self.centroids[assignment[1]])
assignments = [(i, j) for i in range(self.n) for j in range(self.k)]
# assignment variables
self.y = pulp.LpVariable.dicts('data-to-cluster assignments',
assignments,
lowBound=0,
upBound=1,
cat=pulp.LpInteger)
# create the model
self.model = pulp.LpProblem("Model for assignment subproblem", pulp.LpMinimize)
# objective function
self.model += pulp.lpSum([distances(assignment) * self.weights[assignment[0]] * self.y[assignment] for assignment in assignments]), 'Objective Function - sum weighted squared distances to assigned centroid'
# this is also weighted, otherwise the weighted centroid computation don't make sense.
# constraints on the total weights of clusters
for j in range(self.k):
self.model += pulp.lpSum([self.weights[i] * self.y[(i, j)] for i in range(self.n)]) >= self.min_weight, "minimum weight for cluster {}".format(j)
self.model += pulp.lpSum([self.weights[i] * self.y[(i, j)] for i in range(self.n)]) <= self.max_weight, "maximum weight for cluster {}".format(j)
# make sure each point is assigned at least once, and only once
for i in range(self.n):
self.model += pulp.lpSum([self.y[(i, j)] for j in range(self.k)]) == 1, "must assign point {}".format(i)
示例10: _gclp
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def _gclp(self, composition={}, mus={}, phases=[]):
if not qmpy.FOUND_PULP:
raise Exception('Cannot do GCLP without installing PuLP and an LP',
'solver')
prob = pulp.LpProblem('GibbsEnergyMin', pulp.LpMinimize)
phase_vars = pulp.LpVariable.dicts('lib', phases, 0.0)
prob += pulp.lpSum([ (p.energy -
sum([ p.unit_comp.get(elt,0)*mu
for elt, mu in mus.items() ])) * phase_vars[p]
for p in phases]),\
"Free Energy"
for elt, constraint in composition.items():
prob += pulp.lpSum([
p.unit_comp.get(elt,0)*phase_vars[p]
for p in phases ]) == float(constraint),\
'Conservation of '+elt
##[vh]
##print prob
if pulp.GUROBI().available():
prob.solve(pulp.GUROBI(msg=False))
elif pulp.COIN_CMD().available():
prob.solve(pulp.COIN_CMD())
else:
prob.solve()
phase_comp = dict([ (p, phase_vars[p].varValue)
for p in phases if phase_vars[p].varValue > 1e-5])
energy = sum( p.energy*amt for p, amt in phase_comp.items() )
energy -= sum([ a*composition.get(e, 0) for e,a in mus.items()])
return energy, phase_comp
示例11: get_minima
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def get_minima(self, phases, bounds):
"""
Given a set of Phases, get_minima will determine the minimum
free energy elemental composition as a weighted sum of these
compounds
"""
prob = pulp.LpProblem('GibbsEnergyMin', pulp.LpMinimize)
pvars = pulp.LpVariable.dicts('phase', phases, 0)
bvars = pulp.LpVariable.dicts('bound', bounds, 0.0, 1.0)
prob += pulp.lpSum( self.phase_energy(p)*pvars[p] for p in phases ) - \
pulp.lpSum( self.phase_energy(bound)*bvars[bound] for bound in bounds ), \
"Free Energy"
for elt in self.bound_space:
prob += sum([ p.unit_comp.get(elt,0)*pvars[p] for p in phases ])\
== \
sum([ b.unit_comp.get(elt, 0)*bvars[b] for b in bounds ]),\
'Contraint to the proper range of'+elt
prob += sum([ bvars[b] for b in bounds ]) == 1, \
'sum of bounds must be 1'
if pulp.GUROBI().available():
prob.solve(pulp.GUROBI(msg=False))
elif pulp.COIN_CMD().available():
prob.solve(pulp.COIN_CMD())
elif pulp.COINMP_DLL().available():
prob.solve(pulp.COINMP_DLL())
else:
prob.solve()
E = pulp.value(prob.objective)
xsoln = defaultdict(float,
[(p, pvars[p].varValue) for p in phases if
abs(pvars[p].varValue) > 1e-4])
return xsoln, E
示例12: _create_lp
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def _create_lp(self):
''' Creates initial linear program.
'''
assert len(self.input_data.DMU_codes) != 0
self._variables.clear()
self._constraints.clear()
# create LP for the first DMU - it is the easiest way to
# adapt current code
for elem in self.input_data.DMU_codes:
dmu_code = elem
break
orientation = self._concrete_model.get_orientation()
obj_type = self._concrete_model.get_objective_type()
self.lp_model = pulp.LpProblem('Envelopment model: {0}-'
'oriented'.format(orientation),
obj_type)
ub_obj = self._concrete_model.get_upper_bound_for_objective_variable()
obj_variable = pulp.LpVariable('Variable in objective function',
self._concrete_model.
get_lower_bound_for_objective_variable(),
ub_obj,
pulp.LpContinuous)
self._variables['obj_var'] = obj_variable
self.lp_model += (obj_variable,
'Efficiency score or inverse of efficiency score')
lambda_variables = pulp.LpVariable.dicts('lambda',
self.input_data.DMU_codes,
0, None, pulp.LpContinuous)
self._variables.update(lambda_variables)
self._add_constraints_for_outputs(lambda_variables, dmu_code,
obj_variable)
self._add_constraints_for_inputs(lambda_variables, dmu_code,
obj_variable)
示例13: solve
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def solve(g):
el = g.get_edge_list()
nl = g.get_node_list()
p = LpProblem('min_cost', LpMinimize)
capacity = {}
cost = {}
demand = {}
x = {}
for e in el:
capacity[e] = g.get_edge_attr(e[0], e[1], 'capacity')
cost[e] = g.get_edge_attr(e[0], e[1], 'cost')
for i in nl:
demand[i] = g.get_node_attr(i, 'demand')
for e in el:
x[e] = LpVariable("x"+str(e), 0, capacity[e])
# add obj
objective = lpSum (cost[e]*x[e] for e in el)
p += objective
# add constraints
for i in nl:
out_neig = g.get_out_neighbors(i)
in_neig = g.get_in_neighbors(i)
p += lpSum(x[(i,j)] for j in out_neig) -\
lpSum(x[(j,i)] for j in in_neig)==demand[i]
p.solve()
return x, value(objective)
示例14: add_capacity_constraints
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def add_capacity_constraints(prob, x, A, product_names, capacities,
leg_names=None):
"""Add capacity contraints as upper bound on the segments/legs.
Parameters
----------
prob: pulp.LpProblem
the LP problem
x: dict
contains decision variables (each of which has type pulp.pulp.LpVariable)
A: 2D np array
incidence matrix, size n_relations*n_legs
products_names: list
list of product names (e.g. relation/class combinations)
capacities: Iterable
list of capacity on each leg/segment
leg_names: list
list of leg names
Returns
-------
list of tuples of the form (constraint, constraint_name)
where `constraint` is of type pulp.LpConstraint
and `constraint_name` is of type str
"""
n_trips, n_legs = A.shape
n_classes = int(len(product_names) / n_trips)
A_ = np.tile(A, (n_classes, 1))
capacity_constraints = []
for leg, leg_name in enumerate(leg_names):
leg_load = pulp.lpSum([x[it]*A_[i, leg] for i, it
in enumerate(product_names)])
capacity_constraint = (leg_load <= capacities[leg],
"cap_{}".format(leg_name))
prob += capacity_constraint
capacity_constraints.append(capacity_constraint)
return capacity_constraints
示例15: _solve_balancing_ilp_pulp
# 需要导入模块: import pulp [as 别名]
# 或者: from pulp import LpProblem [as 别名]
def _solve_balancing_ilp_pulp(A):
import pulp
x = [pulp.LpVariable('x%d' % i, lowBound=1, cat='Integer') for i in range(A.shape[1])]
prob = pulp.LpProblem("chempy balancing problem", pulp.LpMinimize)
prob += reduce(add, x)
for expr in [pulp.lpSum([x[i]*e for i, e in enumerate(row)]) for row in A.tolist()]:
prob += expr == 0
prob.solve()
return [pulp.value(_) for _ in x]