Pulp之二:Pulp中几个重要的概念
- LpProblem类
LpProblem(name='NoName', sense=LpMinimize)
构造函数,用来构造一个LP问题实例,其中name指定问题名(输出信息用),
sense值是LpMinimize或LpMaximize中的一个,用来指定目标函数是求极大值还是极小值。
solve(solver=None, **kwargs)
在对LpProblem添加完约束条件后,调用该函数进行求解,如果不是求解特定的整数规划问题,solver一般使用默认即可。
- LpVariable类
LpVariable(name, lowBound=None, upBound=None, cat='Continuous', e=None)
构造函数,用来构造LP问题中的变量,name指定变量名,lowBound和upBound是下界和上界,
默认分别是负无穷到正无穷,cat用来指定变量是离散(Integer,Binary)还是连续(Continuous)。
dicts(name, indexs, lowBound=None, upBound=None, cat='Continuous', indexStart=[])
用来构造变量字典,可以让我们不用一个个地创建Lp变量实例。name指定所有变量的前缀,
index是列表,其中的元素会被用来构成变量名,后面三个参数和LbVariable中的一样。
-
lpSum(vector)
计算一个序列的值,使用lpSum求解比普通的sum函数要快得多。 -
pulp.allcombinations()方法
allcombinations(list, k): 返回list的所有元素组合,元素个数不超过k
Examples
See the examples directory for examples. PuLP requires Python 2.7 or Python >= 3.4.
The examples use the default solver (CBC). To use other solvers they must be available (installed and accessible). For more information on how to do that, see the guide on configuring solvers.
Documentation is found on https://coin-or.github.io/pulp/.
Use LpVariable() to create new variables. To create a variable 0 <= x <= 3:
x = LpVariable("x", 0, 3)
To create a variable 0 <= y <= 1:
y = LpVariable("y", 0, 1)
Use LpProblem() to create new problems. Create "myProblem":
prob = LpProblem("myProblem", LpMinimize)
Combine variables to create expressions and constraints, then add them to the problem:
prob += x + y <= 2
If you add an expression (not a constraint), it will become the objective:
prob += -4*x + y
To solve with the default included solver:
status = prob.solve()
To use another sovler to solve the problem:
status = prob.solve(GLPK(msg = 0))
Display the status of the solution:
LpStatus[status]
'Optimal'
You can get the value of the variables using value(). ex:
value(x)
2.0
Exported Classes:
LpProblem -- Container class for a Linear programming problem
LpVariable -- Variables that are added to constraints in the LP
LpConstraint -- A constraint of the general form
a1x1+a2x2 ...anxn (<=, =, >=) b
LpConstraintVar -- Used to construct a column of the model in column-wise modelling
Exported Functions:
value() -- Finds the value of a variable or expression
lpSum() -- given a list of the form [a1*x1, a2x2, ..., anxn] will construct a linear expression to be used as a constraint or variable
lpDot() --given two lists of the form [a1, a2, ..., an] and [ x1, x2, ..., xn] will construct a linear epression to be used as a constraint or variable
Comments, bug reports, patches and suggestions are welcome.
Comments and suggestions: https://github.com/coin-or/pulp/discussions
Bug reports: https://github.com/coin-or/pulp/issues
Patches: https://github.com/coin-or/pulp/pulls
Copyright J.S. Roy (js@jeannot.org), 2003-2005 Copyright Stuart A. Mitchell (stu@stuartmitchell.com) See the LICENSE file for copyright information.