Comment je peux faire une interface graphique pour ce code sur python

Signaler
-
 wahida98 -
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

class PL:

def __init__(self, A = np.empty([0,0]), b = np.empty([0,0]), c = np.empty([0,0]), minmax = "MAX"):
self.A = A
self.b = b
self.c = c
self.x = [float(0)] * len(c)
self.minmax = minmax
self.printIter = False
self.optimalValue = None
self.transform = False

def addA(self, A):
self.A = A

def addB(self, b):
self.b = b

def addC(self, c):
self.c = c
self.transform = False

def setObj(self, minmax):
if(minmax == "MIN" or minmax == "MAX"):
self.minmax = minmax
else:
print("Objectif invalide.")
self.transform = False

def setPrintIter(self, printIter):
self.printIter = printIter

def printSoln(self):
print("La solution optimal du PL:\n\n X* =", end=" ",sep="")
print(self.x)
print("\n")
print("La cardinalité du transversal minimum :\n\n Z* = ", end=" ",sep="")
print(int(self.optimalValue))
print("\n")
def printTableau(self, tableau):

print("ind \t\t", end = "")
for j in range(0, len(c)):
print("x_" + str(j), end = "\t")
for j in range(0, (len(tableau[0]) - len(c) - 2)):
print("s_" + str(j), end = "\t")

print()
for j in range(0, len(tableau)):
for i in range(0, len(tableau[0])):
if(not np.isnan(tableau[j, i])):
if(i == 0):
print(int(tableau[j, i]), end = "\t")
else:
print(round(tableau[j, i], 2), end = "\t")
else:
print(end = "\t")
print()

def getTableau(self):
# construct starting tableau

if(self.minmax == "MIN" and self.transform == False):
self.c[0:len(c)] = 1 * self.c[0:len(c)]
self.transform = False

t1 = np.array([None, 0])
numVar = len(self.c)
numSlack = len(self.A)

t1 = np.hstack(([None], [0], self.c, [0] * numSlack))

basis = np.array([0] * numSlack)

for i in range(0, len(basis)):
basis[i] = numVar + i

A = self.A

if(not ((numSlack + numVar) == len(self.A[0]))):
B = np.identity(numSlack)
A = np.hstack((self.A, B))

t2 = np.hstack((np.transpose([basis]), np.transpose([self.b]), A))

tableau = np.vstack((t1, t2))

tableau = np.array(tableau, dtype ='float')

return tableau

def optimize(self):

if(self.minmax == "MIN" and self.transform == False):
for i in range(len(self.c)):
self.c[i] = -1 * self.c[i]
transform = False

tableau = self.getTableau()

if(self.printIter == True):
print("Tableau de départ:")
self.printTableau(tableau)

# assume initial basis is not optimal
optimal = False

# keep track of iterations for display
iter = 1

while(True):

if(self.printIter == True):
print("----------------------------------")
print("Itération :", iter)
self.printTableau(tableau)

if(self.minmax == "MAX"):
for profit in tableau[0, 2:]:
if profit > 0:
optimal = False
break
optimal = True
else:
for cost in tableau[0, 2:]:
if cost < 0:
optimal = False
break
optimal = True

# if all directions result in decreased profit or increased cost
if optimal == True:
break

# nth variable enters basis, account for tableau indexing
if (self.minmax == "MAX"):
n = tableau[0, 2:].tolist().index(np.amax(tableau[0, 2:])) + 2
else:
n = tableau[0, 2:].tolist().index(np.amin(tableau[0, 2:])) + 2

# minimum ratio test, rth variable leaves basis
minimum = 99999
r = -1

for i in range(1, len(tableau)):
if(tableau[i, n] > 0):
val = tableau[i, 1]/tableau[i, n]
if val<minimum:
minimum = val
r = i

pivot = tableau[r, n]



# perform row operations
# divide the pivot row with the pivot element
tableau[r, 1:] = tableau[r, 1:] / pivot



# pivot other rows
for i in range(0, len(tableau)):
if i != r:
mult = tableau[i, n] / tableau[r, n]
tableau[i, 1:] = tableau[i, 1:] - mult * tableau[r, 1:]


# new basic variable
tableau[r, 0] = n - 2

iter += 1


if(self.printIter == True):
print("----------------------------------")
print("Le tableau final parvenu en", iter, "itérations")
self.printTableau(tableau)
else:
print('\n\n' + '\033[32m' + ' >>> Résolu! <<<' + '\x1b[0m')

self.x = np.array([0] * len(c), dtype = int)
# save coefficients
for key in range(1, (len(tableau))):
if(tableau[key, 0] < len(c)):

self.x[int(tableau[key, 0])] = tableau[key, 1]

for i in range(0,len(self.x)):
if(self.x[i]==0):
self.x[i]=1
else:
self.x[i]=0



self.optimalValue = len(c) - 1 * tableau[0,1]

a = 0

class b():
global a
a = self.x


model = PL()
A = np.array([ [1,0,1,0],[1,1,0,0],[0,1,0,1],[0,0,1,1] ])
B = A.transpose()
n = len(B)
m = len(B[1])

b=np.ones(n,dtype=int)
c=np.ones(m,dtype=int)
model.addA(B)
model.addB(b)
model.addC(c)
model.setObj("MIN")

C = np.zeros([m,m], dtype = int)

for i in range(0,n):
h =-1
k =-1
for j in range(0,m):
if(B[i][j]==1):
if(h==-1):
h=j
else:
k=j
C[h][k]=1
C[k][h]=1


print("La matrice d'incidence :\n\nM1 =\n", A, "\n")
print("La matrice d'adjacence :\n\nM2 =\n", C, "\n")
print("Le graphe correspondant :\n\nG >>\n")

G=nx.from_numpy_matrix(C)

nx.draw(G,with_labels=1,node_color='c',font_size=12)
plt.show()

print("Le PL correspondant:\n\n(P) >>\n")
objf = "( Min(Z) = "
for i in range(0,m):
objf += "X" + str(i) + " + "
d = len(objf)
y = slice(d-2)
objf = objf[y]
print(objf)
print("|")
for i in range(0,n):
st = "| "
for j in range(0,m):
if(B[i][j]==1):
st += "X" + str(j) + " + "


x = slice(10)
st = st[x]
st += " >= 1"
print(st)
print("|")
print("( xᵢ >= 0, ∀ i ∈ {0,...," + str(m-1) + "}")
model.optimize()
print("\n")

model.printSoln()
print("Le transversal minimum est:\n\n T* = ", end=" ",sep="")
v = len(a)

Tm = "{"
for i in range(0,v):
if(a[i]==1):
Tm += "X" + str(i) + ", "
p = len(Tm)
z = slice(p-2)
Tm = Tm[z]
Tm += "}"
print(Tm)

3 réponses

Bonjour,

import bonjour
import s'il vous plaît
import merci

:-)
Messages postés
363
Date d'inscription
lundi 23 mars 2020
Statut
Membre
Dernière intervention
18 septembre 2020
57
Bonjour wahida98,

Les indentations étant importantes en Python, pourrais-tu reposter ton code en utilisant les balises de code ?

Mode d'emploi:
https://codes-sources.commentcamarche.net/faq/11288-les-balises-de-code

On y verrait plus clair ...
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

class PL:
    
    def __init__(self, A = np.empty([0,0]), b = np.empty([0,0]), c = np.empty([0,0]), minmax = "MAX"):
        self.A = A
        self.b = b
        self.c = c
        self.x = [float(0)] * len(c)
        self.minmax = minmax
        self.printIter = False
        self.optimalValue = None
        self.transform = False
        
    def addA(self, A):
        self.A = A
        
    def addB(self, b):
        self.b = b
        
    def addC(self, c):
        self.c = c
        self.transform = False
    
    def setObj(self, minmax):
        if(minmax == "MIN" or minmax == "MAX"):
            self.minmax = minmax
        else:
            print("Objectif invalide.")
        self.transform = False
            
    def setPrintIter(self, printIter):
        self.printIter = printIter
            
    def printSoln(self):
        print("La solution optimal du PL:\n\n  X* =", end=" ",sep="")
        print(self.x)
        print("\n")
        print("La cardinalité du transversal minimum :\n\n  Z* = ", end=" ",sep="")
        print(int(self.optimalValue))
        print("\n")
    def printTableau(self, tableau):
        
        print("ind \t\t", end = "")
        for j in range(0, len(c)):
            print("x_" + str(j), end = "\t")
        for j in range(0, (len(tableau[0]) - len(c) - 2)):
            print("s_" + str(j), end = "\t")
        
        print()
        for j in range(0, len(tableau)):
            for i in range(0, len(tableau[0])):
                if(not np.isnan(tableau[j, i])):
                    if(i == 0):
                        print(int(tableau[j, i]), end = "\t")
                    else:
                        print(round(tableau[j, i], 2), end = "\t")
                else:
                    print(end = "\t")
            print()
            
    def getTableau(self):
        # construct starting tableau
        
        if(self.minmax == "MIN" and self.transform == False):
            self.c[0:len(c)] = 1 * self.c[0:len(c)]
            self.transform = False
        
        t1 = np.array([None, 0])
        numVar = len(self.c)
        numSlack = len(self.A)
        
        t1 = np.hstack(([None], [0], self.c, [0] * numSlack))
        
        basis = np.array([0] * numSlack)
        
        for i in range(0, len(basis)):
            basis[i] = numVar + i
        
        A = self.A
        
        if(not ((numSlack + numVar) == len(self.A[0]))):
            B = np.identity(numSlack)
            A = np.hstack((self.A, B))
            
        t2 = np.hstack((np.transpose([basis]), np.transpose([self.b]), A))
        
        tableau = np.vstack((t1, t2))
        
        tableau = np.array(tableau, dtype ='float')
        
        return tableau
            
    def optimize(self):
        
        if(self.minmax == "MIN" and self.transform == False):
            for i in range(len(self.c)):
                self.c[i] = -1 * self.c[i]
                transform = False
        
        tableau = self.getTableau()
         
        if(self.printIter == True):
            print("Tableau de départ:")
            self.printTableau(tableau)
        
        # assume initial basis is not optimal
        optimal = False

        # keep track of iterations for display
        iter = 1

        while(True):
            
            if(self.printIter == True):
                print("----------------------------------")
                print("Itération :", iter)
                self.printTableau(tableau)
                
            if(self.minmax == "MAX"):
                for profit in tableau[0, 2:]:
                    if profit > 0:
                        optimal = False
                        break
                    optimal = True
            else:
                for cost in tableau[0, 2:]:
                    if cost < 0:
                        optimal = False
                        break
                    optimal = True

            # if all directions result in decreased profit or increased cost
            if optimal == True: 
                 break
            
            # nth variable enters basis, account for tableau indexing
            if (self.minmax == "MAX"):
                n = tableau[0, 2:].tolist().index(np.amax(tableau[0, 2:])) + 2
            else:
                n = tableau[0, 2:].tolist().index(np.amin(tableau[0, 2:])) + 2

            # minimum ratio test, rth variable leaves basis 
            minimum = 99999
            r = -1

            for i in range(1, len(tableau)): 
                if(tableau[i, n] > 0):
                    val = tableau[i, 1]/tableau[i, n]
                    if val<minimum: 
                        minimum = val 
                        r = i
                            
            pivot = tableau[r, n] 
            
           

            # perform row operations 
            # divide the pivot row with the pivot element 
            tableau[r, 1:] = tableau[r, 1:] / pivot 
            
            

            # pivot other rows
            for i in range(0, len(tableau)): 
                if i != r:
                    mult = tableau[i, n] / tableau[r, n]
                    tableau[i, 1:] = tableau[i, 1:] - mult * tableau[r, 1:] 


            # new basic variable 
            tableau[r, 0] = n - 2
            
            iter += 1
            
        
        if(self.printIter == True):
            print("----------------------------------")
            print("Le tableau final parvenu en", iter, "itérations")
            self.printTableau(tableau)
        else:
            print('\n\n' + '\033[32m' + '      >>> Résolu! <<<' + '\x1b[0m')
            
        self.x = np.array([0] * len(c), dtype = int)
        # save coefficients
        for key in range(1, (len(tableau))):
            if(tableau[key, 0] < len(c)):

                self.x[int(tableau[key, 0])] = tableau[key, 1] 
       
        for i in range(0,len(self.x)):
            if(self.x[i]==0):
                self.x[i]=1
            else:
                self.x[i]=0
        

        
        self.optimalValue = len(c) - 1 * tableau[0,1]           
        
        a = 0

        class b():
            global a
            a = self.x
    

model = PL()
A = np.array([ [1,0,1,0],[1,1,0,0],[0,1,0,1],[0,0,1,1] ])
B = A.transpose()
n = len(B)
m = len(B[1])

b=np.ones(n,dtype=int)
c=np.ones(m,dtype=int)
model.addA(B)
model.addB(b)
model.addC(c)
model.setObj("MIN")

C = np.zeros([m,m], dtype = int)

for i in range(0,n):
    h =-1
    k =-1
    for j in range(0,m):
        if(B[i][j]==1):
            if(h==-1):
                h=j
            else:
                k=j
    C[h][k]=1
    C[k][h]=1
            

print("La matrice d'incidence :\n\nM1 =\n", A, "\n")
print("La matrice d'adjacence :\n\nM2 =\n", C, "\n")
print("Le graphe correspondant :\n\nG >>\n")

G=nx.from_numpy_matrix(C)

nx.draw(G,with_labels=1,node_color='c',font_size=12)
plt.show()

print("Le PL correspondant:\n\n(P) >>\n")
objf = "( Min(Z) = "
for i in range(0,m):
    objf += "X" + str(i) + " + "
d = len(objf)
y = slice(d-2)
objf = objf[y]
print(objf)
print("|")    
for i in range(0,n):
    st = "| "
    for j in range(0,m):
        if(B[i][j]==1):
            st += "X" + str(j) + " + "
    

    x = slice(10)
    st = st[x]
    st += " >= 1"            
    print(st)   
print("|")
print("( xᵢ >= 0, ∀ i ∈ {0,...," + str(m-1) + "}")
model.optimize()
print("\n")

model.printSoln()
print("Le transversal minimum est:\n\n  T* = ", end=" ",sep="")
v = len(a)

Tm = "{"
for i in range(0,v):
    if(a[i]==1):
        Tm += "X" + str(i) + ", "
p = len(Tm)
z = slice(p-2)
Tm = Tm[z]
Tm += "}"        
print(Tm)  
Messages postés
363
Date d'inscription
lundi 23 mars 2020
Statut
Membre
Dernière intervention
18 septembre 2020
57