本文整理匯總了Python中pulp.lpSum方法的典型用法代碼示例。如果您正苦於以下問題:Python pulp.lpSum方法的具體用法?Python pulp.lpSum怎麽用?Python pulp.lpSum使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pulp
的用法示例。
在下文中一共展示了pulp.lpSum方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_objective_function
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [as 別名]
def get_objective_function(self, input_data, dmu_code, input_variables,
output_variables):
''' Generates objective function of input-oriented multiplier 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.
Returns:
pulp.LpSum: objective function.
'''
return pulp.lpSum([input_data.coefficients[dmu_code, category] *
output_variables[category]
for category in input_data.output_categories])
示例2: get_equality_constraint
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [as 別名]
def get_equality_constraint(self, input_data, dmu_code, input_variables,
output_variables):
''' Generates equality constraint of input-oriented multiplier 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.
Returns:
pulp.LpConstraint: equality constraint.
'''
return pulp.lpSum([input_data.coefficients[dmu_code, category] *
input_variables[category]
for category in input_data.input_categories]) == 1
示例3: _get_equality_constraint
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [as 別名]
def _get_equality_constraint(self, dmu_code):
''' Returns equality constraint.
Args:
dmu_code (str): DMU code.
Returns:
pulp.LpConstraint: equality constraint.
'''
coeffs = self._model_to_decorate.input_data.coefficients
variables = self._get_variables()
sum_vars = pulp.lpSum([coeffs[dmu_code, category] * value
for category, value in variables.items()
if category not in self.categories])
assert(sum_vars)
return sum_vars == 1
示例4: define_lp
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [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
示例5: label_prop
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [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)
示例6: get_minima
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [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
示例7: set_objective
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [as 別名]
def set_objective(self, variables, coefficients):
self.prob += lpSum([variable * coefficient for variable, coefficient in zip(variables, coefficients)])
示例8: add_constraint
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [as 別名]
def add_constraint(self, variables, coefficients, sign, rhs):
if coefficients:
lhs = [variable * coefficient for variable, coefficient in zip(variables, coefficients)]
else:
lhs = variables
if sign == SolverSign.EQ:
self.prob += lpSum(lhs) == rhs
elif sign == SolverSign.NOT_EQ:
self.prob += lpSum(lhs) != rhs
elif sign == SolverSign.GTE:
self.prob += lpSum(lhs) >= rhs
elif sign == SolverSign.LTE:
self.prob += lpSum(lhs) <= rhs
else:
raise SolverException('Incorrect constraint sign')
示例9: _set_objective_function
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [as 別名]
def _set_objective_function(self):
# Similar to constraints, saving the costs expressions as attributes
# can give you the chance to retrieve their values at the end of the optimization
self.total_holding_cost = self.input_params['holding_cost'] * pulp.lpSum(self.inventory_variables)
self.total_production_cost = pulp.lpSum(row['production_cost'] * self.production_variables[index]
for index, row in self.input_data.iterrows())
objective = self.total_holding_cost + self.total_production_cost
self.model.setObjective(objective)
# ================== Optimization ==================
示例10: create_model
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [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)
示例11: create_model
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [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)
示例12: create_model
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [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)
示例13: _gclp
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [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
示例14: _create_lp
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [as 別名]
def _create_lp(self):
''' Creates initial LP.
'''
self._model_to_decorate._create_lp()
self.lp_model = self._model_to_decorate.lp_model
variables = [self._model_to_decorate._variables[dmu_code] for dmu_code
in self.input_data.DMU_codes]
self._model_to_decorate.lp_model += (pulp.lpSum(variables) == 1,
'VRS_constraint')
self.lp_model = self._model_to_decorate.lp_model
示例15: _add_constraints_for_outputs
# 需要導入模塊: import pulp [as 別名]
# 或者: from pulp import lpSum [as 別名]
def _add_constraints_for_outputs(self, variables, dmu_code,
obj_variable):
''' Adds constraints for outputs to linear program.
Args:
variables (dict of str to pulp.LpVariable): a dictionary
that maps DMU codes to pulp.LpVariable, created with
pulp.LpVariable.dicts.
dmu_code (str): DMU code for which LP is being created.
obj_variable (pulp.LpVariable): LP variable that is optimised
(either efficiency score or inverse of efficiency score).
'''
for (count, output_category) in enumerate(
self.input_data.output_categories):
current_output = self.input_data.coefficients[(dmu_code,
output_category)]
output_coeff = self._concrete_model.get_output_variable_coefficient(
obj_variable, output_category)
sum_all_outputs = pulp.lpSum([variables[dmu] *
self.input_data.coefficients
[(dmu, output_category)]
for dmu in self.input_data.DMU_codes])
name = 'constraint_output_{count}'.format(count=count)
self.lp_model += (self._constraint_creator.create(
-output_coeff * current_output +
sum_all_outputs, 0, output_category), name)
self._constraints[output_category] = name