本文整理汇总了Python中pulp.lpSum函数的典型用法代码示例。如果您正苦于以下问题:Python lpSum函数的具体用法?Python lpSum怎么用?Python lpSum使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了lpSum函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: solve_jiang_guan_lp
def solve_jiang_guan_lp(return_samples, targets, asset_partition):
n = return_samples.shape[1]
prob = pulp.LpProblem('Jiang Guan DCCP Sample Approximation', pulp.LpMinimize)
x = [pulp.LpVariable('Asset {0:d} Weight'.format(i), 0.0, 1.0) for i in range(n)]
mu = calc_first_moment(return_samples)
prob += pulp.lpDot(mu, x), 'Sample Mean Return'
i = 0
for sample in return_samples:
prob += (pulp.lpDot(sample, x) >= targets[0],
'Global return target for sample {0:d}'.format(i))
i += 1
i = 0
j = 1
for assets in asset_partition:
for sample in return_samples:
prob += (pulp.lpSum([sample[k] * x[k] for k in range(n)]) >= targets[j],
'Return target for segment {0:d} for sample {1:d}'.format(j, i))
i += 1
j += 1
prob += (pulp.lpSum(x) == 1.0, 'Fully invested portfolio requirement')
prob.writeLP('JiangGuanDccp.lp')
prob.solve()
status = pulp.LpStatus[prob.status]
print 'Status: {0:s}'.format(status)
return np.array([v.varValue for v in prob.variables()]), status
示例2: solve
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)
示例3: _GetTotalEnergyProblem
def _GetTotalEnergyProblem(self, min_driving_force=0, objective=pulp.LpMinimize):
# Define and apply the constraints on the concentrations
ln_conc_lb, ln_conc_ub = self._MakeLnConcentratonBounds()
# Create the driving force variable and add the relevant constraints
A, b, _c = self._MakeDrivingForceConstraints(ln_conc_lb, ln_conc_ub)
lp = pulp.LpProblem("OBD", objective)
# ln-concentration variables
l = pulp.LpVariable.dicts("l", ["%d" % i for i in xrange(self.Nc)])
x = [l["%d" % i] for i in xrange(self.Nc)] + [min_driving_force]
total_g = pulp.LpVariable("g_tot")
for j in xrange(A.shape[0]):
row = [A[j, i] * x[i] for i in xrange(A.shape[1])]
lp += (pulp.lpSum(row) <= b[j, 0]), "energy_%02d" % j
total_g0 = float(self.dG0_r_prime * self.fluxes.T)
total_reaction = self.S * self.fluxes.T
row = [total_reaction[i, 0] * x[i] for i in xrange(self.Nc)]
lp += (total_g == total_g0 + pulp.lpSum(row)), "Total G"
lp.setObjective(total_g)
#lp.writeLP("../res/total_g.lp")
return lp, total_g
示例4: K_dominnace_check_2
def K_dominnace_check_2(self, u_d, v_d, _inequalities):
"""
:param u_d: a d-dimensional vector(list) like [ 8.53149891 3.36436796]
:param v_d: tha same list like u_d
:param _inequalities: list of constraints on d-dimensional Lambda Polytope like
[[0, 1, 0], [1, -1, 0], [0, 0, 1], [1, 0, -1], [0.0, 1.4770889, -3.1250839]]
:return: True if u is Kdominance to v regarding given _inequalities otherwise False
"""
_d = len(u_d)
prob = LpProblem("Kdominance", LpMinimize)
lambda_variables = LpVariable.dicts("l", range(_d), 0)
for inequ in _inequalities:
prob += lpSum([inequ[j + 1] * lambda_variables[j] for j in range(0, _d)]) + inequ[0] >= 0
prob += lpSum([lambda_variables[i] * (u_d[i]-v_d[i]) for i in range(_d)])
#prob.writeLP("show-Ldominance.lp")
status = prob.solve()
LpStatus[status]
result = value(prob.objective)
if result < 0:
return False
return True
示例5: _MakeMDFProblem
def _MakeMDFProblem(self):
"""Create a CVXOPT problem for finding the Maximal Thermodynamic
Driving Force (MDF).
Does not set the objective function... leaves that to the caller.
Returns:
the linear problem object, and the three types of variables as arrays
"""
A, b, c, y, l = self._GetPrimalVariablesAndConstants()
B = pulp.LpVariable("mdf")
x = y + l + [B]
lp = pulp.LpProblem("MDF_PRIMAL", pulp.LpMaximize)
cnstr_names = ["driving_force_%02d" % j for j in xrange(self.Nr_active)] + \
["covariance_var_ub_%02d" % j for j in xrange(self.Nr)] + \
["covariance_var_lb_%02d" % j for j in xrange(self.Nr)] + \
["log_conc_ub_%02d" % j for j in xrange(self.Nc)] + \
["log_conc_lb_%02d" % j for j in xrange(self.Nc)]
for j in xrange(A.shape[0]):
row = [A[j, i] * x[i] for i in xrange(A.shape[1])]
lp += (pulp.lpSum(row) <= b[j, 0]), cnstr_names[j]
objective = pulp.lpSum([c[i] * x[i] for i in xrange(A.shape[1])])
lp.setObjective(objective)
lp.writeLP("res/mdf_primal.lp")
return lp, objective, y, l, B
示例6: good_annotation_locations
def good_annotation_locations(item, annotate_first=True):
"""Find the minimum number of annotations necessary to extract all the fields
Since annotations can be reviewed and modified later by the user we want to keep
just the minimum number of them.
Parameters
----------
item : Item
annotate_first : book
If true always annotate the first instance of the item in the page
Returns
-------
List[ItemLocation]
"""
# x[i] = 1 iff i-th item is representative
# A[i, j] = 1 iff i-th item contains the j-th field
#
# Solve:
# min np.sum(x)
# Subject to:
# np.all(np.dot(A.T, x) >= np.repeat(1, len(fields)))
index_locations = {location: i for i, location in enumerate(item.locations)}
P = pulp.LpProblem("good_annotation_locations", pulp.LpMinimize)
X = [pulp.LpVariable("x{0}".format(i), cat="Binary") for i in range(len(index_locations))]
if annotate_first:
P += X[0] == 1
P += pulp.lpSum(X)
for field in item.fields:
P += pulp.lpSum([X[index_locations[location.item]] for location in field.locations]) >= 1
P.solve()
return [i for (i, x) in enumerate(X) if x.value() == 1]
示例7: _MakeMDFProblemDual
def _MakeMDFProblemDual(self):
"""Create a CVXOPT problem for finding the Maximal Thermodynamic
Driving Force (MDF).
Does not set the objective function... leaves that to the caller.
Returns:
the linear problem object, and the four types of variables as arrays
"""
A, b, c, w, g, z, u = self._GetDualVariablesAndConstants()
x = w + g + z + u
lp = pulp.LpProblem("MDF_DUAL", pulp.LpMinimize)
cnstr_names = ["y_%02d" % j for j in xrange(self.Nr)] + \
["l_%02d" % j for j in xrange(self.Nc)] + \
["MDF"]
for i in xrange(A.shape[1]):
row = [A[j, i] * x[j] for j in xrange(A.shape[0])]
lp += (pulp.lpSum(row) == c[i, 0]), cnstr_names[i]
objective = pulp.lpSum([b[i] * x[i] for i in xrange(A.shape[0])])
lp.setObjective(objective)
lp.writeLP("res/mdf_dual.lp")
return lp, objective, w, g, z, u
示例8: min_one_norm
def min_one_norm(B,initial_seed,seed):
weight_initial = 1 / float(len(initial_seed))
weight_later_added = weight_initial / float(0.5)
difference = len(seed) - len(initial_seed)
[r,c] = B.shape
prob = pulp.LpProblem("Minimum one norm", pulp.LpMinimize)
indices_y = range(0,r)
y = pulp.LpVariable.dicts("y_s", indices_y, 0)
indices_x = range(0,c)
x = pulp.LpVariable.dicts("x_s", indices_x)
f = dict(zip(indices_y, [1.0]*r))
prob += pulp.lpSum(f[i] * y[i] for i in indices_y) # objective function
prob += pulp.lpSum(y[s] for s in initial_seed) >= 1
prob += pulp.lpSum(y[r] for r in seed) >= 1 + weight_later_added * difference
for j in range(r):
temp = dict(zip(indices_x, list(B[j,:])))
prob += pulp.lpSum(y[j] + (temp[k] * x[k] for k in indices_x)) == 0
prob.solve()
print "Status:", pulp.LpStatus[prob.status]
result = []
for var in indices_y:
result.append(y[var].value())
return result
示例9: opt
def opt(C, X):
orderNum = len(X)
routeNum = len(C)
routeIdx = range(routeNum)
orderIdx = range(orderNum)
# print routeIdx,orderIdx
eps = 1.0 / 10 ** 7
print eps
var_choice = lp.LpVariable.dicts('route', routeIdx, cat='Binary')
# var_choice=lp.LpVariable.dicts('route',routeIdx,lowBound=0)#尝试松弛掉01变量
exceed_labor = lp.LpVariable('Number of routes exceed 1000', 0)
prob = lp.LpProblem("lastMile", lp.LpMinimize)
prob += exceed_labor * 100000 + lp.lpSum(var_choice[i] * C[i] for i in routeIdx)
prob += lp.lpSum(var_choice[i] for i in routeIdx) <= 1000 + exceed_labor + eps
for i in orderIdx:
prob += lp.lpSum(var_choice[j] for j in X[i]) >= (1 - eps)
prob.solve(lp.CPLEX(msg=0))
print "\n\nstatus:", lp.LpStatus[prob.status]
if lp.LpStatus[prob.status] != 'Infeasible':
obj = lp.value(prob.objective)
print "\n\nobjective:", obj
sol_list = [var_choice[i].varValue for i in routeIdx]
print "\n\nroutes:", (sum(sol_list))
# print "\n\noriginal problem:\n",prob
return obj, sol_list, lp.LpStatus[prob.status]
else:
return None, None, lp.LpStatus[prob.status]
示例10: fit
def fit(self, x, y):
classifiers = []
classifier_weights = []
clf = self.base_estimator
# get predictions of one classifer
clf.fit(x, y)
y_predict = clf.predict(x)
u = (y_predict == y).astype(int)
u[u == 0] = -1
for index, value in enumerate(u):
if value == -1:
print index
# solving linear programming
d = pp.LpVariable.dicts("d", range(len(y)), 0, 1)
prob = pp.LpProblem("LPboost", pp.LpMinimize)
prob += pp.lpSum(d) == 1 # constraint for sum of weights to be 1
# objective function
objective_vector = []
for index in range(len(y)):
objective_vector.append(d[index] * u[index])
prob += pp.lpSum(objective_vector)
print pp.LpStatus[prob.solve()]
for v in prob.variables():
if v.varValue > 0:
print v.name + "=" + str(v.varValue)
示例11: setup
def setup():
# ... declare variables
x = ilp.LpVariable.dicts('x', nodes_vars.keys(), 0, 1, ilp.LpBinary)
y = ilp.LpVariable.dicts('y',
[(i, j) for i, j in edges] + [(j, i) for i, j in edges],
0, 1, ilp.LpBinary)
limits = defaultdict(int)
for i, j in edges:
limits[i] += 1
limits[j] += 1
# ... define the problem
prob = ilp.LpProblem("Factorizer", ilp.LpMinimize)
# ... define the constraints
for i in nodes_vars:
prob += ilp.lpSum(y[(i, j)] for j in nodes_vars if (i, j) in y) <= limits[i]*x[i]
for i, j in edges:
prob += y[(i, j)] + y[(j, i)] == 1
# ... define the objective function (min number of factorizations)
prob += ilp.lpSum(x[i] for i in nodes_vars)
return x, prob
示例12: K_dominance_check
def K_dominance_check(self, _V_best_d, Q_d):
"""
:param _V_best_d: a list of d-dimension
:param Q_d: a list of d-dimension
:return: True if _V_best_d is prefered to Q_d regarding self.Lambda_inequalities and using Kdominance
other wise it returns False
"""
_d = len(_V_best_d)
prob = LpProblem("Ldominance", LpMinimize)
lambda_variables = LpVariable.dicts("l", range(_d), 0)
for inequ in self.Lambda_ineqalities:
prob += lpSum([inequ[j + 1] * lambda_variables[j] for j in range(0, _d)]) + inequ[0] >= 0
prob += lpSum([lambda_variables[i] * (_V_best_d[i]-Q_d[i]) for i in range(_d)])
#prob.writeLP("show-Ldominance.lp")
status = prob.solve()
LpStatus[status]
result = value(prob.objective)
if result < 0:
return False
return True
示例13: _create_lp
def _create_lp(self):
''' See base class.
'''
self.model._create_lp()
self.lp_model_max_slack = self.model.lp_model.deepcopy()
input_slack_vars = pulp.LpVariable.dicts(
'input_slack', self.strongly_disposal_input_categories,
0, None, pulp.LpContinuous)
output_slack_vars = pulp.LpVariable.dicts(
'output_slack', self.strongly_disposal_output_categories,
0, None, pulp.LpContinuous)
# change objective function
self.lp_model_max_slack.sense = pulp.LpMaximize
self.lp_model_max_slack.objective = (
pulp.lpSum(list(input_slack_vars.values())) +
pulp.lpSum(list(output_slack_vars.values())))
# change constraints
for input_category in self.strongly_disposal_input_categories:
name = self.model._constraints[input_category]
self.lp_model_max_slack.constraints[name].addterm(
input_slack_vars[input_category], 1)
self.lp_model_max_slack.constraints[name].sense = pulp.LpConstraintEQ
for output_category in self.strongly_disposal_output_categories:
name = self.model._constraints[output_category]
self.lp_model_max_slack.constraints[name].addterm(
output_slack_vars[output_category], -1)
self.lp_model_max_slack.constraints[name].sense = pulp.LpConstraintEQ
示例14: get_linear_program_solution
def get_linear_program_solution(self, c, b, A, x):
prob = LpProblem("myProblem", LpMinimize)
prob += lpSum([xp*cp for xp, cp in zip(x, c)]), "Total Cost of Ingredients per can"
for row, cell in zip(A, b):
prob += lpSum(ap*xp for ap, xp in zip(row, x)) <= cell
solved = prob.solve()
return prob
示例15: def_problem
def def_problem(self, queue_a):
"""define lp problem"""
n = self.n
tn = self.tn
tl = self.tl
b = self.b
iIdx = range(n)
tIdx = range(tn)
ti = range(n)
si = range(n)
Ti = range(n)
Si = range(n)
for i in xrange(n):
ti[i] = queue_a[i].at
si[i] = queue_a[i].tsize
Ti[i] = queue_a[i].ft
Si[i] = queue_a[i].size
iIdx[i] = str(i)
for t in xrange(tn):
tIdx[t] = str(t)
"""-----------------------------------
PuLP variable definition
varb--bi(t)
prob--objective and constraints
objective:
max:[0~n-1][0~ti-1])sigma bi(t)
constraints:
1.any t,[0~n-1] sigma bi(t) <= B
2.any i,[0-Ti] sigma bi(t)*tl>= si
3.any i,[0~T-1] sigma bi(t)*tl<= Si
------------------------------------"""
print "\ndefine lp variables"
self.varb = pulp.LpVariable.dicts('b',(iIdx,tIdx),0,b,cat='Integer')
print "define lp problem"
self.prob = pulp.LpProblem('Prefetching Schedule',pulp.LpMaximize)
print "define lp objective"
self.prob += pulp.lpSum([tl*self.varb[i][t] for i in iIdx for t in tIdx if int(t)<ti[int(i)]])
print "define constraints on B"
for t in tIdx:
self.prob += pulp.lpSum([self.varb[i][t] for i in iIdx]) <= b
print "define constraints on si"
for i in iIdx:
self.prob += pulp.lpSum([tl*self.varb[i][t] for t in tIdx if int(t)<=Ti[int(i)]]) >= si[int(i)]
print "define constraints on Si"
for i in iIdx:
self.prob += pulp.lpSum([tl*self.varb[i][t] for t in tIdx]) <= Si[int(i)]