Python - error en metodo simples en python

 
Vista:
sin imagen de perfil

error en metodo simples en python

Publicado por vector (1 intervención) el 02/06/2023 17:07:18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
from scipy import linalg
from numpy import *
import numpy as np
from scipy.optimize import linprog
 
 
opcion1=None
opcion2=None
opcion0=None
print("-----------------------------")
print("Bienvenido a Calculator")
print("---------------------------------------------")
mostrarmenu=True
while mostrarmenu:
    print("-------------------")
    print("Menu de opciones")
    print("1.Maximizar")
    print("2.Minimizar")
    print("3.Salir del programa")
    opcionseleccionada=input("Por favor seleccione una opcion:")
 
    if opcionseleccionada in("1","2","3","4"):
 
 
        if opcionseleccionada=="1":
 
 
 
 
 
            def simplex_solver(c, A_ub, b_ub, A_eq=None, b_eq=None, minimize=True):
                if minimize:
                    c = [-coef for coef in c]  # Convertir minimización en maximización
 
                result = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, method='simplex')
 
                if result.success:
                    if minimize:
                        return result.fun, result.x
                    else:
                        return -result.fun, result.x
                else:
                    raise ValueError('No se pudo encontrar una solución óptima.')
 
            def get_coefficients(num_variables, name):
                coefficients = []
                for i in range(num_variables):
                    coef = float(input(f"Ingrese el coeficiente de la variable {name}{i + 1}: "))
                    coefficients.append(coef)
                return coefficients
 
            # Solicitar al usuario el número de variables
            num_variables = int(input("Ingrese el número de variables: "))
 
            # Solicitar al usuario los coeficientes de la función objetivo
            print("Ingrese los coeficientes de la función objetivo:")
            c = get_coefficients(num_variables, "X")
 
            # Solicitar al usuario el número de restricciones
            num_restricciones = int(input("Ingrese el número de restricciones: "))
 
            # Solicitar al usuario los coeficientes y el tipo de restricción de las restricciones
            A_ub = []
            b_ub = []
            A_eq = []
            b_eq = []
            for i in range(num_restricciones):
                print(f"\nRestricción {i + 1}")
                restriccion = get_coefficients(num_variables, "X")
                tipo_restriccion = input("Ingrese el tipo de restricción (<=, >=, <, >, =): ")
                valor_b = float(input("Ingrese el valor de la restricción: "))
 
                if tipo_restriccion == "<=":
                    A_ub.append(restriccion)  # Agregar los coeficientes a la matriz A_ub de desigualdad
                    b_ub.append(valor_b)  # Agregar el valor límite a la matriz b_ub de desigualdad
                elif tipo_restriccion == ">=":
                    A_ub.append([-coef for coef in restriccion])  # Agregar los coeficientes negados a la matriz A_ub de desigualdad
                    b_ub.append(-valor_b)  # Agregar el valor límite negado a la matriz b_ub de desigualdad
                elif tipo_restriccion == "<":
                    A_ub.append([-coef for coef in restriccion])  # Agregar los coeficientes negados a la matriz A_ub de desigualdad
                    b_ub.append(-valor_b)  # Agregar el valor límite negado a la matriz b_ub de desigualdad
                elif tipo_restriccion == ">":
                    A_ub.append(restriccion)  # Agregar los coeficientes a la matriz A_ub de desigualdad
                    b_ub.append(valor_b)  # Agregar el valor límite a la matriz b_ub de desigualdad
                elif tipo_restriccion == "=":
                    A_eq.append(restriccion)  # Agregar los coeficientes a la matriz A_eq de igualdad
                    b_eq.append(valor_b)  # Agregar el valor límite a la matriz b_eq de igualdad
                else:
                    raise ValueError("Tipo de restricción no válido. Debe ser '<=', '>=', '<', '>', o '='.")
 
            max_result, max_variables = simplex_solver(c, A_ub, b_ub, A_eq, b_eq, minimize=False)
            min_result, min_variables = simplex_solver(c, A_ub, b_ub, A_eq, b_eq, minimize=True)
 
            print("\nMaximización:")
            print("Valor óptimo:", max_result)
            print("Valores de las variables:")
            for i in range(num_variables):
                print(f"X{i + 1}:", max_variables[i])
 
            print("\nMinimización:")
            print("Valor óptimo:", min_result)
            print("Valores de las variables:")
            for i in range(num_variables):
                print(f"X{i + 1}:", min_variables[i])
 
 
 
        elif opcionseleccionada=="2":
            def simplex_solver(c, A_ub, b_ub, A_eq=None, b_eq=None, maximize=True):
                if not maximize:
                    c = [-coef for coef in c]  # Convertir minimización en maximización
 
                result = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, method='simplex')
 
                if result.success:
                    if maximize:
                        return result.fun, result.x
                    else:
                        return -result.fun, result.x
                else:
                    raise ValueError('No se pudo encontrar una solución óptima.')
 
            def get_coefficients(num_variables, name):
                coefficients = []
                for i in range(num_variables):
                    coef = float(input(f"Ingrese el coeficiente de la variable {name}{i + 1}: "))
                    coefficients.append(coef)
                return coefficients
 
            # Solicitar al usuario el número de variables
            num_variables = int(input("Ingrese el número de variables: "))
 
            # Solicitar al usuario los coeficientes de la función objetivo
            print("Ingrese los coeficientes de la función objetivo:")
            c = get_coefficients(num_variables, "X")
 
            # Solicitar al usuario el número de restricciones
            num_restricciones = int(input("Ingrese el número de restricciones: "))
 
            # Solicitar al usuario los coeficientes y el tipo de restricción de las restricciones
            A_ub = []
            b_ub = []
            A_eq = []
            b_eq = []
            for i in range(num_restricciones):
                print(f"\nRestricción {i + 1}")
                restriccion = get_coefficients(num_variables, "X")
                tipo_restriccion = input("Ingrese el tipo de restricción (<=, >=, <, >, =): ")
                valor_b = float(input("Ingrese el valor de la restricción: "))
 
                if tipo_restriccion == "<=":
                    A_ub.append(restriccion)  # Agregar los coeficientes a la matriz A_ub de desigualdad
                    b_ub.append(valor_b)  # Agregar el valor límite a la matriz b_ub de desigualdad
                elif tipo_restriccion == ">=":
                    A_ub.append([-coef for coef in restriccion])  # Agregar los coeficientes negados a la matriz A_ub de desigualdad
                    b_ub.append(-valor_b)  # Agregar el valor límite negado a la matriz b_ub de desigualdad
                elif tipo_restriccion == "<":
                    A_ub.append([-coef for coef in restriccion])  # Agregar los coeficientes negados a la matriz A_ub de desigualdad
                    b_ub.append(-valor_b)  # Agregar el valor límite negado a la matriz b_ub de desigualdad
                elif tipo_restriccion == ">":
                    A_ub.append(restriccion)  # Agregar los coeficientes a la matriz A_ub de desigualdad
                    b_ub.append(valor_b)  # Agregar el valor límite a la matriz b_ub de desigualdad
                elif tipo_restriccion == "=":
                    A_eq.append(restriccion)  # Agregar los coeficientes a la matriz A_eq de igualdad
                    b_eq.append(valor_b)  # Agregar el valor límite a la matriz b_eq de igualdad
                else:
                    raise ValueError("Tipo de restricción no válido. Debe ser '<=', '>=', '<', '>', o '='.")
 
            max_result, max_variables = simplex_solver(c, A_ub, b_ub, A_eq, b_eq, maximize=True)
            min_result, min_variables = simplex_solver(c, A_ub, b_ub, A_eq, b_eq, maximize=False)
 
            print("\nMaximización:")
            print("Valor óptimo:", max_result)
            print("Valores de las variables:")
            for i in range(num_variables):
                print(f"X{i + 1}:", max_variables[i])
 
            print("\nMinimización:")
            print("Valor óptimo:", min_result)
            print("Valores de las variables:")
            for i in range(num_variables):
                print(f"X{i + 1}:", min_variables[i])
        elif opcionseleccionada == "3":
            mostrarmenu = False
            print("---------------------------------")
            print("Gracias por preferir nuestro programa")
            print("-------------")

//errores
When I test the file I get the following error
Invalid input for linprog: A_eq must have exactly two "
"dimensions, and the number of columns in A_eq must be "
"equal to the size of c")
lp = _clean_inputs(lp._replace(A_ub=A_ub, A_eq=A_eq))
return lp, solver_options
lp, solver_options = _parse_linprog(lp, options, meth)
It should be noted that the program is made in python

[``your text`from scipy import linalg
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

error en metodo simples en python

Publicado por Costero (92 intervenciones) el 02/06/2023 20:54:30
Parece que tu A_ub no es un 2D array

La documention dice:

A_eq : 2-D array, optional
The equality constraint matrix. Each row of ``A_eq`` specifies the
coefficients of a linear equality constraint on ``x``.


Y aqui un ejemplo que copie de la documentation:

1
2
3
4
5
6
7
8
9
10
11
12
from scipy.optimize import linprog
c = [-1, 4]
A = [[-3, 1], [1, 2]]
b = [6, 4]
x0_bounds = (None, None)
x1_bounds = (-3, None)
res = linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds])
 
print(res.fun)
print(res.x)
print(res.message)
print(res.ineqlin)
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar