Programming to Realize Linear Programming-Simplex Method

Keywords: Python Programming

Programming Realization of Simplex Method (Part 2)


Previously: https://blog.csdn.net/nanashi_F/article/details/95891827

3. python Programming of Dual Simplex Method (Basically Simplex Method)

Step1: Simplex table class (shared with simplex method, abbreviated)

Step2: Iterative Function

	def Iteration2(self):    	#Iterative function
        lim=100		#Maximum number of iterations (to prevent infinite iterations without solutions)
        while(lim>0):
            self.check=[]
            for i in range(self.X_num):     #Calculate the number of tests
                temp=0
                for j in range(self.B_num):
                    temp+=self.bound[j][i]*self.z0[self.Xbase[j]]
                self.check.append(self.z0[i]-temp)
            self.IsEnd()		#Judging whether the iteration is over
            if self.flag>0:		#If there is a solution, the iteration ends.
                break
            else:				#Otherwise, base transformation is performed.
                self.BaseChange(2)
                lim-=1

Step3: Judging Iterative Termination Function

	def IsEnd2(self):
        self.flag=1
        for i in range(self.B_num):
            if self.bound[i][self.X_num]<0:		#If the constrained right-hand constant is negative, continue iterating
                self.flag=0
                break

Step4: BaseChange Function and Simplex Method

    def FindMain2(self):    #Finding the Main Element
        iB=[]
        for i in range(self.B_num):
            iB.append(self.bound[i][self.X_num])
        iout=iB.index(min(iB)) #Get the minimum value ordinal number in b
        theta=[]
        for j in range(self.X_num):
            if self.bound[iout][j]>=0:
                th=1000
            elif self.check[j]==0:
                th=1000
            else:
                th=self.check[j]/self.bound[iout][j]
            theta.append(th)
        iin=theta.index(min(theta))           #Get the minimum value serial number in the number of tests
        main=self.bound[iout][iin]        
        return [iout,iin,main]

IV. Input-python Form Program

Code

#!/usr/bin/python
# -*- coding: utf-8 -*-

import LPTable
from tkinter import *
from tkinter import ttk

def Start():
    model=comboxlis.get()      #Getting Simplex Types
    if model=="simplex method":
        model1()
    elif model=="Dual Simplex Method":
        model2()
    else:
        text31.insert("end","Choose a computing model")

def model2():
    Table=ReadData2()
    Table.Iteration2()   #Enter Iteration
    if Table.flag>0:    #Determine whether the optimal solution is obtained by iteration
        z=0                 #optimal value
        Best=[]             #optimum solution
        for j in range(Table.X_num-Table.B_num):
            Best.append(0)
        for i in range(Table.B_num):
            X=Table.Xbase[i]
            c=Table.z0[X]
            num=Table.bound[i][Table.X_num]
            Best[Table.Xbase[i]]=num    #Recording Optimal Solution
            z+=num*c                    #Arrange the Optimum Value
        text41.insert("end",Best)
        z=-z    #Minimum conversion
        text51.insert("end",str(z))
        if Table.flag==1:
            text52.insert("end","<Unique Optimal Solution>")
        else:
            text52.insert("end","<Alternative optimal solution>")
    else:
        text52.insert("end","<No Optimal Solution>")
    
    

def model1():
    [Table,Mtype]=ReadData()    #Obtaining data
    Table.Iteration()   #Enter Iteration
    if Table.flag>0:    #Determine whether the optimal solution is obtained by iteration
        z=0                 #optimal value
        Best=[]             #optimum solution
        for j in range(Table.X_num-Table.B_num):
            Best.append(0)
        for i in range(Table.B_num):
            X=Table.Xbase[i]
            c=Table.z0[X]
            num=Table.bound[i][Table.X_num]
            Best[Table.Xbase[i]]=num    #Recording Optimal Solution
            z+=num*c                    #Arrange the Optimum Value
        text41.insert("end",Best)
        if Mtype=="min":    #Minimum conversion
            z=-z
        text51.insert("end",str(z))
        if Table.flag==1:
            text52.insert("end","<Unique Optimal Solution>")
        else:
            text52.insert("end","<Alternative optimal solution>")
    else:
        text52.insert("end","<No Optimal Solution>")

def StrChange(sstr):    #Converting strings to list storage
    lst=sstr.split(' ')
    new=[]
    length=len(lst)
    for i in range(length):
        new.append(float(lst[i]))
    return [new,length]

def ReadData2():    #Read data
    text41.delete("1.0","end")
    text51.delete("1.0","end")
    text52.delete("1.0","end")
    [z0,X_num]=StrChange(entry21.get())
    for i in range(X_num):  #Transform objective function
        z0[i]=-z0[i]
    IB=text31.get("1.0","end").split('\n')
    B_num=len(IB)-1
    bound=[]            #constraint condition
    for i in range(B_num):
        bound.append(StrChange(IB[i])[0])
        for j in range(X_num+1):
            bound[i][j]=-bound[i][j]
    Xbase=[]
    for i in range(B_num):     #Add artificial variables
        Xbase.append(X_num+i)
        z0.append(0)
        b=bound[i].pop(-1)
        for k in range(B_num):
            if k==i:
                bound[i].append(1.0)
            else:
                bound[i].append(0.0)
        bound[i].append(b)
    X_num+=B_num
    Itable=LPTable.Table(X_num,B_num,z0,Xbase,bound)
    return Itable

def ReadData():    #Read data
    text41.delete("1.0","end")
    text51.delete("1.0","end")
    text52.delete("1.0","end")
    [z0,X_num]=StrChange(entry21.get())
    Mtype=comboxlist.get()
    if Mtype=="min":        #Minimum calculation
        for j in range(X_num):
            z0[j]=-z0[j]
    IB=text31.get("1.0","end").split('\n')
    B_num=len(IB)-1
    bound=[]            #constraint condition
    for i in range(B_num):
        bound.append(StrChange(IB[i])[0])
    Xbase=[]
    for i in range(B_num):  #Add artificial variables
        Xbase.append(X_num+i)
        z0.append(-1000)
        b=bound[i].pop(-1)
        for k in range(B_num):
            if k==i:
                bound[i].append(1.0)
            else:
                bound[i].append(0.0)
        bound[i].append(b)
    X_num+=B_num
    Itable=LPTable.Table(X_num,B_num,z0,Xbase,bound)
    return [Itable,Mtype]

if __name__ == "__main__":
    root = Tk()  
    root.geometry('300x320')  
    root.title("Linear Programming Experiment 1")
    between='- - - - - - - - - - - - - - - - - - - - - - - - - - -'

    Btn1 = Button(root, text="Start the calculation", width=6,command=Start)
    Btn1.grid(row=0, column=0)

    comvalue=StringVar()#Form's own text, create a new value
    comboxlis=ttk.Combobox(root,textvariable=comvalue,width=15) #Initialization
    comboxlis["values"]=("simplex method","Dual Simplex Method")
    comboxlis.current(0)  #Choose the first
    comboxlis.grid(row=0, column=1,columnspan=2)

    label21 = Label(root, text="objective function:")
    label21.grid(row=1, column=0)

    comvalue=StringVar()#Form's own text, create a new value
    comboxlist=ttk.Combobox(root,textvariable=comvalue,width=4) #Initialization
    comboxlist["values"]=("max","min")
    comboxlist.current(0)  #Choose the first
    comboxlist.grid(row=1, column=1)

    entry21 = Entry(root,width=14)
    entry21.grid(row=1, column=2,columnspan=2)

    label31 = Label(root, text="constraint condition:")
    label31.grid(row=2, column=0)

    text31=Text(root,width=28,height=8)
    text31.grid(row=2, column=1,columnspan=3)

    be1=Label(root,text=between)
    be1.grid(row=3,column=0,columnspan=4)

    label41 = Label(root, text="optimum solution:")
    label41.grid(row=4, column=0)

    text41 = Text(root,width=31,height=1)
    text41.grid(row=4, column=1,columnspan=3)

    label51 = Label(root, text="optimal value:")
    label51.grid(row=5, column=0)

    text51 = Text(root,width=10,height=1)
    text51.grid(row=5, column=1)

    text52 = Text(root,width=13,height=1)
    text52.grid(row=5, column=2)

    root.mainloop() 

Actual interface

Posted by designerguy on Wed, 31 Jul 2019 02:09:18 -0700