I new using Cplex in python. I already know how to code a mathematical optimization problem correctly and create a function to show the solution friendly (F1). Currently, I want to modify some features of the model without creating a new model. My idea is solving a model P, then a model P1 (changing the decision variables domain), P2 (relaxing some set o constraints), and so on. I would like to have the solution of those models using my function F1.
My code is the following:
import time
import numpy as np
import cplex
from cplex import Cplex
from cplex.exceptions import CplexError
import sys
from openpyxl import Workbook
import xlrd
def GAP_RL(I,J,data):
#TIEMPO INICIAL
inicio=time.process_time() #------------------------------- INICIO DEL CONTEO DE TIEMPO
#CONJUNTOS
maquinas=range(I) #CONJUNTO DE TRABAJOS
trabajos=range(J) #CONJUNTO DE MÁQUINAS
#print("MÁQUINAS={} | TRABAJOS= {} |\n".format(list(maquinas),list(trabajos)))
print("\n")
#PARÁMETROS
wb = Workbook()
ws = wb.active
book = xlrd.open_workbook(data+'.xlsx')
sheet = book.sheet_by_name("c")
c_a=[[int(sheet.cell_value(r,c)) for c in range(sheet.ncols)] for r in range(sheet.nrows)]
c_a=np.matrix(c_a)
print("COSTO DE ASIGNACIÓN")
print("")
print(c_a) # ------------------------------------------------ COSTO DE ASIGNACIÓN
print("\n")
sheet = book.sheet_by_name("a")
a=[[int(sheet.cell_value(r,c)) for c in range(sheet.ncols)] for r in range(sheet.nrows)]
a=np.matrix(a)
print("UTILIZACIÓN")
print("")
print(a) #---------------------------------------------------- REQUERIMIENTOS
print("\n")
sheet = book.sheet_by_name("b")
b=[[int(sheet.cell_value(r,c)) for c in range(sheet.ncols)] for r in range(sheet.nrows)]
b=np.matrix(b)
print("DISPONIBILIDAD")
print("")
print(b) #---------------------------------------------------- CAPACIDAD MÁXIMA DE PROCESO
print("\n")
Model=cplex.Cplex() #CREACIÓN DEL MODELO.
Model.parameters.mip.tolerances.integrality.set(0) #ESPECIFICA LA CANTIDAD POR LA CUAL UNA
#VARIABLE ENTERA PUEDE SER DIFERENTE DE UN
#ENTERO Y AÚN ASÍ CONSIDERASE FACTIBLE
Model.objective.set_sense(Model.objective.sense.minimize) #SENTIDO DE OPTIMIZACIÓN.
#Model.parameters.timelimit.set(float(7200)) #TIEMPO MÁXIMO DE EJECUCIÓN [SEGUNDOS].
#Model.parameters.mip.tolerances.mipgap.set(float(0.1)) #GAP DE TÉRMINO.
#VARIABLES DE DECISIÓN
x_vars=np.array([["x("+str(i)+","+str(j)+")" for j in trabajos] for i in maquinas])
x_varnames = x_vars.flatten()
x_vartypes='B'*I*J
x_varlb = [0.0]*len(x_varnames)
x_varub = [1.0]*len(x_varnames)
x_varobj = []
for i in maquinas:
for j in trabajos:
x_varobj.append(float(c_a[i,j]))
Model.variables.add(obj = x_varobj, lb = x_varlb, ub = x_varub, types = x_vartypes, names = x_varnames)
#RESTRICCIONES
#PRIMER CONJUNTO DE RESTRICCIONES: CADA TRABAJO ES ASIGNADO A UNA ÚNICA MÁQUINA.
for j in trabajos:
row1=[]
val1=[]
for i in maquinas:
row1.append(x_vars[i,j])
val1.append(float(1.0))
Model.linear_constraints.add(lin_expr = [cplex.SparsePair(ind = row1, val= val1)], senses = 'E', rhs = [float(1.0)])
#SEGUNDO CONJUNTO DE RESTRICCIONES: LAS ASIGNACIONES DE TRABAJOS CONSIDERAN LA CAPACIDAD MÁXIMA DE PROCESAMIENTO DE LAS MÁQUINAS
for i in maquinas:
row2=[]
val2=[]
for j in trabajos:
row2.append(x_vars[i,j])
val2.append(float(a[i,j]))
Model.linear_constraints.add(lin_expr = [cplex.SparsePair(ind = row2, val= val2)], senses = 'L', rhs = [float(b[i])])
#RESOLVER MODELO Y EXPANDIR
solution=Model.solve()
Model.write('modelo_GAP.lp')
#MOSTRAR SOLUCION
def show_solution():
print("--------------------------------------------------------------------------------------------------------------")
print("\nVALOR FUNCIÓN OBJETIVO - COSTO TOTAL DE ASIGNACIÓN = {}".format(Model.solution.get_objective_value()))
print("--------------------------------------------------------------------------------------------------------------")
for i in maquinas:
for j in trabajos:
if(Model.solution.get_values("x("+str(i)+","+str(j)+")")!=0.0):
print("x("+str(i+1)+","+str(j+1)+")"+" = "+str(Model.solution.get_values("x("+str(i)+","+str(j)+")")))
fin=time.process_time()
tiempo=float(fin)-float(inicio)
print("")
print("TIEMPO DE CÓMPUTO [s]= ", float(tiempo))
show_solution()
GAP_RL(I=2,J=7,data='data')
The data file is the following:
The matrix c_a is the following:

The matrix a is the following:

The matrix b is the following:

So I would like to know how to make those changes in my model which is written in that way. Thanks in advance.