python 线性规划问题(pulp库的blend) 1.1

版权声明:转载请告知征得同意。 https://blog.csdn.net/qq_42731466/article/details/82049501

python解决线性规划问题

引用部分

http://www.gnu.org/software/glpk/glpk.html

http://www.coin-or.org/

http://www.cplex.com/

http://www.gurobi.com/

目前这是第一篇
目前我所知道到线性模块有pulp库,scipy下的linprog,pymprog库
lingrog举例:

https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html

pymprog库:

https://blog.csdn.net/jacke121/article/details/79954541?tdsourcetag=s_pcqq_aiomsg

这里说pulp库
help(pulp)可以找到一些文档,逼着我要发挥有限的英文水平。
为了解决线性代数的问题也是拼了。

上次依赖的是scipy.optimize下的linprog,偶然得知还有pulp库可以做,而且更符合书写习惯,果断研究一下。
以上闲聊结束。
注意: PuLP requires Python >= 2.5.

先用文档的一个例子
目标函数
Min z = -4x + y
0<=x<=3
0<=y<=1

from pulp import *
prob = LpProblem('myProblem',sense = LpMinimize)
x = LpVariable('x',0,3)
y = LpVariable('y',0,1)
prob += x + y <= 2
prob += -4*x + y 
status = prob.solve(GLPK(msg=0))
#LpStatus[status]
print(value(x))

一下是详细展开,借用官方文档,顺带少量翻译。
按照习惯先把官方原文贴出来,然后我再以简单的形式表达出来。

https://pythonhosted.org/PuLP/CaseStudies/a_blending_problem.html

目标函数:
LpProblem():
LpProblem(name = 'z',sense = LpMinimize)

A variable called prob (although its name is not important) is created
using the LpProblem function. It has two parameters, the first being
the arbitrary name of this problem (as a string), and the second
parameter being either LpMinimize or LpMaximize depending on the type of LP you are trying to solve:
LpProblem():
sense的参数:
LpMaximize
LpMinimize

变量名的命名
LpVariable():
LpVariable(name,lowbound=None,upbound=None,cat =LpContinuous,e=None)

The problem variables x1 and x2 are created using the LpVariable
class. It has four parameters, the first is the arbitrary name of what
this variable represents, the second is the lower bound on this
variable, the third is the upper bound, and the fourth is essentially
the type of data (discrete or continuous). The options for the fourth
parameter are LpContinuous or LpInteger, with the default as
LpContinuous. If we were modelling the number of cans to produce, we
would need to input LpInteger since it is discrete data. The bounds
can be entered directly as a number, or None to represent no bound
(i.e. positive or negative infinity), with None as the default. If the
first few parameters are entered and the rest are ignored (as shown),
they take their default values. However, if you wish to specify the
third parameter, but you want the second to be the default value, you
will need to specifically set the second parameter as it’s default
value. i.e you cannot leave a parameter entry blank.
e.g:
LpVariable("example", None, 100)
这个例子设置了上下限
.
LpVariable("example", upBound = 100)
这个例子的下限缺省,必须注明上限upBound=
.
x1=LpVariable("ChickenPercent",0,None,LpInteger)
这个例子中设置了离散参数,如果不设置LpContinuous成为默认参数
.
.

The constraints are now entered (Note: any “non-negative” constraints
were already included when defining the variables). This is done with
the ‘+=’ operator again, since we are adding more data to the prob
variable. The constraint is logically entered after this, with a comma
at the end of the constraint equation and a brief description of the
cause of that constraint:
#The five constraints are entered
逗号后面是可以直接加注释的,很舒服的书写习惯
prob += x1 + x2 == 100, “PercentagesSum” #这里是允许等号的
prob += 0.100*x1 + 0.200*x2 >= 8.0, “ProteinRequirement”
prob += 0.080*x1 + 0.100*x2 >= 6.0, “FatRequirement”
prob += 0.001*x1 + 0.005*x2 <= 2.0, “FibreRequirement”
prob += 0.002*x1 + 0.005*x2 <= 0.4, “SaltRequirement”

过程保存
writeLP()

Now that all the problem data is entered, the writeLP() function can be used to copy this information into a .lp file into the directory that your code-block is running from. Once your code runs successfully, you can open this .lp file with a text editor to see what the above steps were doing. You will notice that there is no assignment operator (such as an equals sign) on this line. This is because the function/method called writeLP() is being performed to the variable/object prob (and the string “WhiskasModel.lp” is an additional parameter). The dot . between the variable/object and the function/method is important and is seen frequently in Object Oriented software (such as this):
prob.writeLP("WhiskasModel.lp")
这个我没看懂,似乎保存成了文件

结果求解
prob.solve()

The LP is solved using the solver that PuLP chooses. The input
brackets after solve() are left empty in this case, however they can
be used to specify which solver to use (e.g prob.solve(CPLEX()) ):
.#The problem is solved using PuLP’s choice of Solver
.#空参数
prob.solve()

求解状态
LpStatus[prob.status]

Now the results of the solver call can be displayed as output to us.
Firstly, we request the status of the solution, which can be one of
“Not Solved”, “Infeasible”, “Unbounded”, “Undefined” or “Optimal”. The
value of prob (pulp.pulp.LpProblem.status) is returned as an integer,
which must be converted to its significant text meaning using the
LpStatus dictionary. Since LpStatus is a dictionary(dict), its input
must be in square brackets:
.# The status of the solution is printed to the screen
print("Status:", LpStatus[prob.status])
可以返回五种求解状态
“Not Solved”, “Infeasible”, “Unbounded”, “Undefined” or “Optimal”

解的输出

The variables and their resolved optimum values can now be printed to
the screen. The for loop makes variable cycle through all the
problem variable names . Then it prints each variable name, followed
by an equals sign, followed by its optimum value. name and varValue
are properties of the object variable.

for v in prob.variables():
    print(v.name, "=", v.varValue)

The optimised objective function value is printed to the screen, using
the value function. This ensures that the number is in the right
format to be displayed. objective is an attribute of the object prob:
.# The optimised objective function value is printed to the screen
print("Total Cost of Ingredients per can = ", value(prob.objective))
value()
返回求解值

更多的例子:

https://pythonhosted.org/PuLP/CaseStudies/a_blending_problem.html

.

PuLP is an LP modeler written in python. PuLP can generate MPS or LP
files
and call GLPK[1], COIN CLP/CBC[2], CPLEX[3], and GUROBI[4] to solve linear
problems.

See the examples directory for examples.

PuLP requires Python >= 2.5.

The examples require at least a solver in your PATH or a shared library file.

Documentation is found on https://www.coin-or.org/PuLP/.
A comprehensive wiki can be found at https://www.coin-or.org/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 and 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

Choose a solver and solve the problem. ex:
>>> 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.
[email protected]

References:
[1] http://www.gnu.org/software/glpk/glpk.html
[2] http://www.coin-or.org/
[3] http://www.cplex.com/
[4] http://www.gurobi.com/

PACKAGE CONTENTS
amply
constants
pulp
solverdir (package)
solvers
sparse
tests

FUNCTIONS
clock(…)
clock() -> floating point number

    Return the CPU time or real time since the start of the process or since
    the first call to clock().  This has as much precision as the system
    records.

maketrans(x, y=None, z=None, /)
    Return a translation table usable for str.translate().

    If there is only one argument, it must be a dictionary mapping Unicode
    ordinals (integers) or characters to Unicode ordinals, strings or None.
    Character keys will be then converted to ordinals.
    If there are two arguments, they must be strings of equal length, and
    in the resulting dictionary, each character in x will be mapped to the
    character at the same position in y. If there is a third argument, it
    must be a string, whose characters will be mapped to None in the result.

DATA
DIRNAME = r’D:\Ana\lib\site-packages\pulp’
EPS = 1e-07
LpBinary = ‘Binary’
LpCategories = {‘Binary’: ‘Binary’, ‘Continuous’: ‘Continuous’, ‘Integ…
LpConstraintEQ = 0
LpConstraintGE = 1
LpConstraintLE = -1
LpConstraintSenses = {-1: ‘<=’, 0: ‘=’, 1: ‘>=’}
LpContinuous = ‘Continuous’
LpCplexLPLineSize = 78
LpInteger = ‘Integer’
LpMaximize = -1
LpMinimize = 1
LpSenses = {-1: ‘Maximize’, 1: ‘Minimize’}
LpSolverDefault = pulp.solvers.PULP_CBC_CMD object
LpStatus = {-3: ‘Undefined’, -2: ‘Unbounded’, -1: ‘Infeasible’, 0: ‘No…
LpStatusInfeasible = -1
LpStatusNotSolved = 0
LpStatusOptimal = 1
LpStatusUnbounded = -2
LpStatusUndefined = -3
PULPCFGFILE = ‘pulp.cfg.win’
VERSION = ‘1.6.8’
arch = ‘64’
cbc_path = ‘cbc’
coinMP_path = [r’D:\Ana\lib\site-packages\pulp\libCoinMP.so’]
config_filename = r’D:\Ana\lib\site-packages\pulp\pulp.cfg.win’
cplex_dll_path = ‘cplex100.dll’
glpk = None
glpk_path = ‘glpsol’
gurobi_path = r’C:\gurobi10\win32\python2.5\lib’
gurobipy = None
ilm_cplex_license = r’LICENSE your-enterprise\nRUNTIME NEVER …’
ilm_cplex_license_signature = 0
is_64bits = True
log = Logger pulp.pulp (WARNING)
operating_system = ‘win’
pulp_cbc_path = r’D:\Ana\lib\site-packages\pulp\solverdir\cbc\win\64\c…
scip_path = ‘scip’
yaposib = None

猜你喜欢

转载自blog.csdn.net/qq_42731466/article/details/82049501