资源简介
基于python的解线性规划问题程序代码,适用环境为python3.6
代码片段和文件信息
# encoding=utf-8
__author__ = ‘ysg‘
import numpy as np # python 矩阵操作lib
from openpyxl import Workbook
import xlwt
class Simplex():
def __init__(self):
self._A = ““ # 系数矩阵
self._b = ““ #
self._c = ‘‘ # 约束
self._B = ‘‘ # 基变量的下标集合
self.row = 0 # 约束个数
def solve(self filename):
# 读取文件内容,文件结构前两行分别为 变量数 和 约束条件个数
# 接下来是系数矩阵
# 然后是b数组
# 然后是约束条件c
# 假设线性规划形式是标准形式(都是等式)
A = []
b = []
c = []
with open(filename ‘r‘) as f:
self.var = int(f.readline())
self.row = int(f.readline())
for i in range(self.row):
x = list(map(int f.readline().strip().split(‘ ‘)))
A.append(x)
b = list(map(int list(f.readline().strip().split(‘ ‘))))
c = list(map(int list(f.readline().strip().split(‘ ‘))))
self._A = np.array(A dtype=float)
self._b = np.array(b dtype=float)
self._c = np.array(c dtype=float)
# self._A = np.array([[3-11-200][210110][-130-301]]dtype=float)
# self._b = np.array([-3412]dtype=float)
# self._c = np.array([-7 7 -2 -1 -6 0]dtype=float)
self._B = []
self.row = len(self._b)
self.var = len(self._c)
(x obj) = self.Simplex(self._A self._b self._c)
self.pprint(x obj A)
def pprint(self x obj A):
px = [‘x_%d = %f‘ % (i + 1 x[i]) for i in range(len(x))]
print(‘‘.join(px))
print(‘objective value is : %f‘ % obj)
print(‘------------------------------‘)
for i in range(len(A)):
print(‘%d-th line constraint value is : %f‘ % (i + 1 x.dot(A[i])))
def InitializeSimplex(self A b):
b_min min_pos = (np.min(b) np.argmin(b)) # 得到最小bi
# 将bi全部转化成正数
if (b_min < 0):
for i in range(self.row):
if i != min_pos:
A[i] = A[i] - A[min_pos]
b[i] = b[i] - b[min_pos]
A[min_pos] = A[min_pos] * -1
b[min_pos] = b[min_pos] * -1
# 添加松弛变量
slacks = np.eye(self.row)
A = np.concatenate((A slacks) axis=1)
c = np.concatenate((np.zeros(self.var) np.ones(self.row)) axis=0)
# 松弛变量全部加入基初始解为b
new_B = [i + self.var for i in range(self.row)]
# 辅助方程的目标函数值
obj = np.sum(b)
c = c[new_B].reshape(1 -1).dot(A) - c
c = c[0]
# entering basis
e = np.a
评论
共有 条评论