回调cplex期间出现错误,我无法解决

时间:2019-12-04 15:55:46

标签: python cplex

我正在尝试开发一种算法来解决cplex中的特定混合整数问题。

当我尝试运行算法时,得到以下文本:

Traceback (most recent call last):
  Here the log shows the directory of the files of my algorithm for a few lines
.
.
.
.

and finally:
  File "/anaconda2/lib/python2.7/site-packages/cplex/__init__.py", line 1099, in solve
    _proc.mipopt(self._env._e, self._lp)
  File "/anaconda2/lib/python2.7/site-packages/cplex/_internal/_procedural.py", line 629, in mipopt
    check_status(env, status)
  File "/anaconda2/lib/python2.7/site-packages/cplex/_internal/_procedural.py", line 303, in __call__
    raise CplexSolverError(error_string, env, status)
cplex.exceptions.errors.CplexSolverError: CPLEX Error  1006: Error during callback.

您是否知道可能导致该文件错误的原因?

我有一些代码文件:

这是启动分辨率的文件,称为G_resoluciones:


import G_Callbacks
import G_Heuristica
import gc
import D2MIPpG
import cplex
import os   

def ResolvemosBC_q_C_norm(E,I,J,K,p,R,C):

    D2_C_DrBC_C_norm = open(os.path.abspath(os.path.join(os.getcwd(), '..'))+"/G_ResultsD2_C_DrBC_Cp_norm.txt", "a") 
    tiemposD2_C_DrBC_norm = {} 
    tiemposRelD2_C_DrBC_norm = {}
    nodosD2_C_DrBC_norm = {}
    CODD2_C_DrBC_norm={}
    ValObjD2_C_DrBC_norm = {}
    ValRelD2_C_DrBC_norm = {}
    MSJD2_C_DrBC_norm = {}
    MIPGAPD2_C_DrBC_norm = {}
    OptimalityGapD2_C_DrBC_norm = {}
    CutsD2_C_DrBC_norm = {}
    IterD2_C_DrBC_norm = {}
    BestBoundD2_C_DrBC_norm = {}
    IncD2_C_DrBC_norm = {}
    LP_GORDO_C_DrBC_norm = {}

    sH,thetaH,xH,qH,fobjH={},{},{},{},{} 
    m1 = D2MIPpG.solveD2(I,J,K,p,R,C) 
    sH,thetaH,xH,qH,fobjH=G_Heuristica.HeuristicaGeneral(p,I,K,J,R,C) 
    qHH={}
    indi=[]

    for k in range(K):
        for j in range(J):
            qHH[J*k+j]=qH[k,j]

    coefi=[]   
    for i in range(I):
        coefi.append(xH[i])
    for j in range(I,I+J*K,1):
        coefi.append(qHH[j-I])
    for j in range(I+J*K,I+J*K+K,1):
        coefi.append(sH[j-I-J*K])
    for j in range(I+J*K+K,I+J*K+K+K,1):
        coefi.append(thetaH[j-I-J*K-K])

    for i in range(len(coefi)):
        indi.append(i)

    m1.MIP_starts.add(cplex.SparsePair(ind=indi, val=coefi), m1.MIP_starts.effort_level.solve_fixed,"primera")   # primeros valores


    Nodos_cb = m1.register_callback(G_Callbacks.Nodos) 
    Nodos_cb.times_called = 0
    Inc=m1.register_callback(G_Callbacks.Incumbente) 

    G_Callbacks.Cplex_callback_D2BC_C_norm.model=m1   
    G_Callbacks.Cplex_callback_D2BC_C_norm.thetaVars=m1._data[3]
    G_Callbacks.Cplex_callback_D2BC_C_norm.qVars=m1._data[1]


    e=m1.register_callback(G_Callbacks.Cplex_callback_D2BC_C_norm)
    e.iterations=0
    e.iterationsR=0
    m1.parameters.mip.cuts.mircut.set(-1)
    m1.parameters.mip.cuts.gomory.set(-1)
    m1.parameters.mip.limits.treememory.set(50000)
    m1.parameters.mip.strategy.file.set(3)
    m1.parameters.workmem.set(10000)
    m1.parameters.timelimit.set(18000)
    m1.parameters.preprocessing.presolve.set(0)
    m1.parameters.preprocessing.numpass.set(0)
    m1.parameters.threads.set(1)
    m1.parameters.mip.strategy.fpheur.set(-1)
    m1.parameters.mip.strategy.heuristicfreq.set(-1)
    m1.parameters.mip.strategy.lbheur.set(0)
    m1.parameters.mip.strategy.rinsheur.set(-1)
    # m5._alpha=alpha
    ValorObjetivoMejorado={}
    Counter={}
    m1._Counter = Counter
    m1._ValorObjetivoMejorado = ValorObjetivoMejorado

    m1._qH=qH
    m1._thetaH=thetaH
    m1._fobjH=fobjH
    m1._K = K
    m1._J = J
    m1._p = p
    m1._I = I
    m1._R = R
    m1._C = C
    m1._FirstTime=1
    start = m1.get_time()
    m1.solve() #this is where the spyder says the error is
    end = m1.get_time()
    elapsed = end - start
    solrEC_D=m1.solution
    elapsedLP=e.stopic-start

    ValObjD2_C_DrBC_norm,tiemposD2_C_DrBC_norm, nodosD2_C_DrBC_norm, MSJD2_C_DrBC_norm, CODD2_C_DrBC_norm,ValRelD2_C_DrBC_norm, tiemposRelD2_C_DrBC_norm, MIPGAPD2_C_DrBC_norm,OptimalityGapD2_C_DrBC_norm, CutsD2_C_DrBC_norm,IterD2_C_DrBC_norm,BestBoundD2_C_DrBC_norm,LP_GORDO_C_DrBC_norm=Escribe_Resultados_CUTANDBRANCH(m1,Nodos_cb,e,elapsed,elapsedLP)

    D2_C_DrBC_C_norm.write('G_B&C_q_norm')
    D2_C_DrBC_C_norm.write(' %d %d %d %d ' % (E, I, J, K))
    D2_C_DrBC_C_norm.write(' %0.4f %0.4f %d %s %d %0.4f %0.4f %0.4f' % (float(ValObjD2_C_DrBC_norm), float(tiemposD2_C_DrBC_norm), nodosD2_C_DrBC_norm, MSJD2_C_DrBC_norm,CODD2_C_DrBC_norm, float(ValRelD2_C_DrBC_norm), float(tiemposRelD2_C_DrBC_norm), float(MIPGAPD2_C_DrBC_norm)))
    D2_C_DrBC_C_norm.write(' %0.4f %d %d %0.4f' % (float(OptimalityGapD2_C_DrBC_norm), CutsD2_C_DrBC_norm,IterD2_C_DrBC_norm,float(BestBoundD2_C_DrBC_norm)))                   
    D2_C_DrBC_C_norm.write(' %0.4f ' %(LP_GORDO_C_DrBC_norm))
    D2_C_DrBC_C_norm.write(' 1')
    D2_C_DrBC_C_norm.write("\n")   



    del m1
    gc.collect()


def Escribe_Resultados_CUTANDBRANCH(modelo, callback1, callback2, elapsed, elapsedLP):

    ValObj,tiempos,nodos, MSJ,COD,ValRel,tiemposRel,MIPGAP,OptimalityGap,Cuts,Iter,BestBound,LP_GORDO = {},{},{},{},{},{},{},{},{},{},{},{},{}

    solrEC_D=modelo.solution
#OPTIMAL INTEGER SOLUTION FOUND OR OPTIMAL SOLUTION WITH EPGAP OR EPAGAP TOLERANCE FOUND
    if solrEC_D.get_status()==101 or solrEC_D.get_status()==102:
        ValObj=solrEC_D.get_objective_value()
        tiempos=elapsed
        nodos=callback2.nodecnt
        MSJ=solrEC_D.status[solrEC_D.get_status()]
        COD=solrEC_D.get_status()
        ValRel=callback2.LPValueWithCuts
        tiemposRel=elapsedLP
        MIPGAP=((ValRel-ValObj)/ValObj)*100
        OptimalityGap=0
        Cuts=callback2.cuts+1
        Iter=callback2.iterationsR
        BestBound=callback2.mipnodeobjbnd
        LP_GORDO=callback2.TimeBetweenCalls
    #TIMELIMIT REACHED BUT INTEGER SOL EXISTS
    if solrEC_D.get_status()==107:
        ValObj=solrEC_D.get_objective_value()
        tiempos=elapsed
        nodos=-1
        MSJ=solrEC_D.status[solrEC_D.get_status()]
        COD=solrEC_D.get_status()
        ValRel=callback2.LPValueWithCuts
        tiemposRel=elapsedLP
        MIPGAP=-1                       
        OptimalityGap=callback1.MIP_relative_gap
        Cuts=callback2.cuts+1
        Iter=callback2.iterationsR
        BestBound=callback2.mipnodeobjbnd
        LP_GORDO=callback2.TimeBetweenCalls
     #TIMELIMIT REACHED BUT INTEGER SOL DOES NOT EXIST
    if solrEC_D.get_status()==108:
        ValObj=-1
        tiempos=elapsed
        nodos=-1
        MSJ=solrEC_D.status[solrEC_D.get_status()]
        COD=solrEC_D.get_status()
        ValRel=callback2.LPValueWithCuts
        tiemposRel=elapsedLP
        MIPGAP=-1                       
        OptimalityGap=-1
        Cuts=callback2.cuts+1
        Iter=callback2.iterationsR
        BestBound=callback2.mipnodeobjbnd
        LP_GORDO=callback2.TimeBetweenCalls                        
    #INFEASIBLE OR UNBOUNDED
    if solrEC_D.get_status()==119:
        ValObj=-1
        tiempos=elapsed
        nodos=-1
        MSJ=solrEC_D.status[solrEC_D.get_status()]
        COD=solrEC_D.get_status()
        ValRel=-1
        tiemposRel=-1
        MIPGAP=-1                       
        OptimalityGap=-1
        Cuts=-1
        Iter=-1 
        BestBound=-1
        LP_GORDO=0

    return ValObj,tiempos,nodos, MSJ,COD,ValRel,tiemposRel,MIPGAP,OptimalityGap,Cuts,Iter,BestBound,LP_GORDO

现在,第一个调用的其他代码文件:

G_callbacks:

from __future__ import division
import cplex.callbacks
from cplex.callbacks import MIPInfoCallback
import G_SeparationProblems
import numpy
import operator

#MIPInfoCallback
class Nodos(MIPInfoCallback):
    num_nodes=-1
    best_OBJ=-1
    MIP_relative_gap=-1
    times_called =0
    LPSol= -1
    FirstT = 1
    stopinc=0
    #These values are set in case the problem is solved at the first iteration of the root, because if that happens I guess
    #we never even get to call the callback. In any case, that never happens for my instances.
    def __call__(self):
        self.times_called += 1
        self.num_nodes=self.get_num_nodes()
        self.best_OBJ=self.get_best_objective_value()
        self.MIP_relative_gap=self.get_MIP_relative_gap()
        if self.times_called==1 and self.FirstT == 1:
            self.LPSol=self.get_best_objective_value()
            self.stopinc=self.get_time()
            self.FirstT = 0

#IncumbentCallback
class Incumbente(cplex.callbacks.IncumbentCallback):
    def __call__(self):
        print "El callback Incumbente dice: "
        print self.get_solution_source()




class Cplex_callback_D2BC_C_norm(cplex.callbacks.UserCutCallback):
    def __init__(self,env):
        cplex.callbacks.UserCutCallback.__init__(self,env)
        self.env=env
    LPValueWithCuts=-1
    cuts=-1 
    iterations=0
    lb=-cplex.infinity
    ub=cplex.infinity
    lbPrimal=-cplex.infinity
    iterationsR=0
    times_called=0
    BeenOptimal=0
    alpha = 0

    q_sep={}
    theta_sep={}

    q_in={}
    theta_in={}
    cbasis={}
    vbasis={}
    te,ue,ve={},{},{}
    tr,ur,vr={},{},{}
    startic={}
    RepDif= 0
    Dif=0
    DifAnterior=0
    HaHabidoCortes=0
    TimeBetweenCalls=-1
    UES={}
    max_index={}
    max_value={}
    q_puedeser={}
    theta_puedeser={}
    fobj_puedeser={}
    cambio={}
    def __call__(self):

        if self.model._Counter == 1:
            print "EN EL USER CUT CALLBACK : %s" %self.model._ValorObjetivoMejorado
            Vars=sorted(self.thetaVars.values())
            coeffs = {}
            for k in range(self.model._K):
                if not self.thetaVars[k] in coeffs:
                    coeffs[self.thetaVars[k]]=0
                coeffs[self.thetaVars[k]]+=self.model._p[k]
            self.add(cut=cplex.SparsePair(ind=coeffs.keys(),val=coeffs.values()),sense="L", rhs=self.model._ValorObjetivoMejorado,use=0)

        self.model._Counter = 0

        self.ub=self.get_objective_value()
        print "ITERACION %s" %(self.times_called)
        self.nodecnt=self.get_num_nodes()
        print "Callback called %s times" %self.times_called
        if self.times_called==0:
            for k in range(self.model._K):
                for j in range(self.model._J):
                    self.q_in[k,j]=self.model._qH[k,j]


            for k in range(self.model._K):
                self.theta_in[k]=self.model._thetaH[k]

        self.DifAnterior=self.ub-self.lb

        if self.RepDif >= 30:
            print "SALTANDO QUE ES GERUNDIO!"
            self.lb=self.ub

        self.times_called+=1

        self.startic[self.times_called] = self.model.get_time()
        if self.nodecnt == 0 and self.times_called>=2:
            self.TimeBetweenCalls=self.startic[self.times_called]-self.startic[self.times_called-1]

        r=1
        self.mipnodeobjbnd = self.get_objective_value()

        if self.nodecnt == 1 and self.model._FirstTime == 1:
            self.stopic = self.model.get_time()
            self.model._FirstTime=0
        if self.nodecnt >= 0:
            self.stopic = self.model.get_time()


            Vars2=sorted(self.thetaVars.values())
            theta=self.get_values(Vars2)
            Vars=sorted(self.qVars.values())
            a=self.get_values(Vars)
            data=numpy.array(a)
            shape=(self.model._K, self.model._J)
            q=data.reshape(shape)

            sub={}



            self.lbPrimal=self.get_incumbent_objective_value()

            tr,ur,vr={},{},{}
            self.CurrentBestObjBound=self.get_best_objective_value()
            self.CurrentBestObj=self.get_incumbent_objective_value()

            if self.ub-self.lbPrimal > 1e-4*self.ub:

                self.alpha = 1


                for k in range(self.model._K):
                    for j in range(self.model._J):
                        self.q_sep[k,j]=self.alpha*q[k,j]+(1-self.alpha)*self.q_in[k,j]
                for k in range(self.model._K):
                    self.theta_sep[k]=self.alpha*theta[k]+(1-self.alpha)*self.theta_in[k]
            print self.ub
            print self.lb
            if self.ub-self.lb > 1e-4*self.ub:
                self.HaHabidoCortes=0
                for k in range(self.model._K):
                    h=0

                    sub=G_SeparationProblems.SeparationProblem_q_C_norm(self.model._p,self.q_sep,self.theta_sep,self.model._I,self.model._J,self.model._K,self.model._R,self.model._C)
                    sub.set_problem_type(sub.problem_type.LP)
                    print "El Problema es un %s: %s" %(sub.get_problem_type(),sub.problem_type[sub.get_problem_type()])

                    sub.parameters.preprocessing.presolve.set(sub.parameters.preprocessing.presolve.values.off)
                    sub.parameters.lpmethod.set(sub.parameters.lpmethod.values.primal)
                    sub.solve()


                    if sub.solution.get_status()==sub.solution.status.optimal:
                        print "Estamos dentro para recuperar vertice" 
                        a,aa={},{}
                        verticealpha={}
                        a=sub.solution.get_values(range(0,self.model._K*self.model._I,1))
                        data=numpy.array(a)
                        shape=(self.model._K,self.model._I)
                        aa=data.reshape(shape)
                        for k in range(self.model._K):
                            for i in range(self.model._I):
                                verticealpha[k,g,i]=aa[k,i]

                        b,bb={},{}
                        verticebeta={}
                        b=sub.solution.get_values(range(self.model._K*self.model._I, self.model._K*self.model._I+self.model._K*self.model._J,1))
                        data=numpy.array(b)
                        shape=(self.model._K,self.model._J)
                        bb=data.reshape(shape)
                        for k in range(self.model._K):
                            for j in range(self.model._J):
                                verticebeta[k,g,j]=bb[k,j]

                        c,cc={},{}
                        verticegamma={}
                        c=sub.solution.get_values(range(self.model._K*self.model._I+self.model._K*self.model._J, self.model._K*self.model._I+self.model._K*self.model._J+self.model._K*self.model._J*self.model._J,1))
                        data=numpy.array(c)
                        shape=(self.model._K, self.model._J, self.model._J)
                        cc=data.reshape(shape)
                        for k in range (self.model._K):
                            for l in range (self.model._J):
                                for j in range (self.model._J):
                                    verticegamma[k,g,l,j]=cc[k,l,j]

                        ll={}
                        verticelamb={}
                        ll=sub.solution.get_values(range(self.model._K*self.model._I+self.model._K*self.model._J+self.model._K*self.model._J*self.model._J,self.model._K*self.model._I+self.model._K*self.model._J+self.model._K*self.model._J*self.model._J+self.model._K,1))
                        for k in range(self.model._K):
                            verticelamb[k,g]=ll[k]


                        h=h+1

                    self.iterations=self.iterations+1
                    print "h=%s" %h

                    if h!=0:
                        for a in range(h-1,h,1):
                            if(sum(self.theta_sep[k]*(1+self.model._p[k]*verticelamb[k,a]) for k in range(self.model._K))-1e-4> sum(self.q_sep[k,j]*verticebeta[k,a,j] for k in range(self.model._K) for j in range(self.model._J))):
                                self.HaHabidoCortes=1
                                r=r+1
                                coeffs={} 
                                for k in range(self.model._K): 
                                    if not self.thetaVars[k] in coeffs: 
                                        coeffs[self.thetaVars[k]]=0 
                                    coeffs[self.thetaVars[k]]+=(1+self.model._p[k]*verticelamb[k,a]) 
                                for k in range(self.model._K):
                                    for j in range(self.model._J):
                                        if not self.qVars[k,j] in coeffs:
                                            coeffs[self.qVars[k,j]]=0
                                        coeffs[self.qVars[k,j]]-=verticebeta[k,a,j] #0 mas eso
                                self.add(cut=cplex.SparsePair(ind=coeffs.keys(),val=coeffs.values()), sense="L", rhs=0, use=self.use_cut.force)
                                print "CORTE DE OPTIMALIDAD AÑADIDO"

                    self.iterationsR += 1
                    self.lb=sub.solution.get_objective_value()

                    print "HAHABIDOCORTES: %s" %self.HaHabidoCortes
                    if self.HaHabidoCortes==0:
                        for k in range(self.model._K):
                            for j in range(self.model._J):
                                self.q_in[k,j]=self.q_sep[k,j]
                        for k in range(self.model._K):
                            self.theta_in[k]=self.theta_sep[k]

                    self.Dif=self.ub-self.lb
                    if self.DifAnterior-self.Dif==0:
                        self.RepDif+=1
                    print "DifAnterior:= %s -- Dif:= %s" %(self.DifAnterior, self.Dif)
            else:
                self.lb = -cplex.infinity


            print "**************************"
            print "NODE: %s" %self.nodecnt
            print "UPPER BOUND: %s" %self.ub
            print "LOWER BOUND D: %s" %self.lb
            print "LOWER BOUND P: %s" %self.lbPrimal
            print "**************************"

            self.cuts=self.get_num_cuts(134) #134 is user cuts
            self.startic[self.times_called] = self.model.get_time()

            if self.nodecnt>=0:
                self.LPValueWithCuts=sum(self.model._p[k]*theta[k] for k in range(self.model._K))
                self.model._LPValueWithCuts=self.LPValueWithCuts

G_heuristica

import operator
import RANDUtilidades
import random

def HeuristicaGeneral(p,I,K,J,R,C):
    x={}
    q={}
    UES={}
    max_index={}
    max_value={}
    d={}
    s={}
    fobj={}

    for i in range(I):
        x[i]=float(1)
    for i in range(I):
        x[i]=x[i]/I

    for k in range(K):
        for j in range(J):
            UES[k,j]=sum(C[k,i,j]*x[i] for i in range(I))

    for k in range(K):
        max_index[k], max_value[k] = max(enumerate(UES[k,j] for j in range(J)), key=operator.itemgetter(1))

    for k in range(K):
        for j in range(J):
            if j == max_index[k]:
                q[k,j]=1
            else:
                q[k,j]=0

    for k in range(K):
        d[k]=sum(R[k,i,max_index[k]]*x[i] for i in range(I))

    for k in range(K):
        s[k]=sum(C[k,i,max_index[k]]*x[i] for i in range(I))
    fobj=sum(p[k]*d[k] for k in range(K))

    return s,d,x,q,fobj

D2MIPG:


import cplex

def solveMIPpG(I,J,K,p,R,C):
    model = cplex.Cplex()
    #Definition of the variables
    x, q, z = {},{},{}
    for i in range(I):
        x[i]=model.variables.add(obj=[0],lb=[0],ub=[1],types=["C"], names=["x[%s]" %i])[0]
    for k in range(K):
        for j in range(J):
            q[k,j]=model.variables.add(obj=[0],lb=[0], types=["B"], names=["q[%s,%s]" %(k,j)])[0]
    for k in range(K):
        for j in range(J):
            for i in range(I):
                z[k,i,j]=model.variables.add(obj=[p[k]*R[k,i,j]], lb=[0], types=["C"], names=["z[%s,%s,%s]" %(k,i,j)])[0]


    model.objective.set_sense(model.objective.sense.maximize)

    #Model constraints
    #Suma qjs igual a 1.
    for k in range(K):
        model.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=[q[k,j] for j in range(J)],val=[1.0]*J)], senses=["E"], rhs=[1], names=['SumaProbs[%s]' %k])[0]
    for k in range(K):
        for j in range(J):
            coef=[]
            for i in range(I):
                coef.append(1)
            coef.append(-1)
            var=[]
            for i in range(I):
                var.append(z[k,i,j])
            var.append(q[k,j])
            model.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=var, val=coef)], senses=["E"], rhs=[0], names=['sumazsq[%s,%s]'%(k,j)])[0]
    for k in range(K):
        for i in range(I):
            coef2=[]
            for j in range(J):
                coef2.append(1)
            coef2.append(-1)
            var2=[]
            for j in range(J):
                var2.append(z[k,i,j])
            var2.append(x[i])
            model.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=var2, val=coef2)], senses=["E"], rhs=[0], names=['sumazsx[%s,%s]'%(k,i)])[0]
    for k in range(K):
        for j in range(J):
            for l in range(J):
                if j!=l:
                    coef3=[]
                    for i in range(I):
                        coef3.append(C[k,i,l]-C[k,i,j])
                    var3=[]
                    for i in range(I):
                        var3.append(z[k,i,j])
                    model.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=var3, val=coef3)], senses=["L"], rhs=[0], names=['bestresp[%s,%s,%s]'%(k,l,j)])[0]

    model._data = x, q, z
    # model.write("MIPpGHAHA.lp")
    return model

#This is the weak formulation D2  #Generador inicial del modelo  
def solveD2(I,J,K,p,R,C): 
    model = cplex.Cplex()
    #Definition of the variables
    theta, s ,q, x = {},{},{},{}
    for i in range(I):
        x[i]=model.variables.add(obj=[0],lb=[0],ub=[1],types=["C"], names=["x[%s]" %i])[0]
    for k in range(K):
        for j in range(J):
            q[k,j]=model.variables.add(obj=[0],lb=[0], types=["B"], names=["q[%s,%s]" %(k,j)])[0]
    for k in range(K):
        s[k] = model.variables.add(obj=[0], types=["C"], names=["s[%s]" % k])[0]
    for k in range(K):
        theta[k] = model.variables.add(obj=[p[k]], types=["C"], names=["theta[%s]" % k])[0]

    model.objective.set_sense(model.objective.sense.maximize)

    M1, M2= {}, {}
    M1 = 2 * max(R.values()) + 1
    M2 = 2 * max(C.values()) + 1

    #Constraints of the model
    #Suma qjs igual a 1.
    for k in range(K):
        model.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=[q[k,j] for j in range(J)],val=[1.0]*J)], senses=["E"], rhs=[1], names=['SumaProbs[%s]' %k])[0]
    model.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=[x[i] for i in range(I)],val=[1.0]*I)], senses=["E"], rhs=[1], names=['Sumaxs'])[0]

    for k in range(K):
        for j in range(J):
            coef=[]
            coef.append(1)
            for i in range(I):
                coef.append(-R[k,i,j])
            coef.append(M1)
            vars=[]
            vars.append(theta[k])
            for i in range(I):
                vars.append(x[i])
            vars.append(q[k,j])

            model.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=vars, val=coef)], senses=["L"], rhs=[M1], names=['Bound_d[%s,%s]' %(k,j)])[0]
    for k in range(K):
        for j in range(J):
            coef2=[]
            coef2.append(1)
            for i in range(I):
                coef2.append(-C[k,i,j])
            coef2.append(M2)
            vars2=[]
            vars2.append(s[k])
            for i in range(I):
                vars2.append(x[i])
            vars2.append(q[k,j])
            coef3=[]
            coef3.append(1)
            for i in range(I):
                coef3.append(-C[k,i,j])
            vars3=[]
            vars3.append(s[k])
            for i in range(I):
                vars3.append(x[i])
            model.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=vars2,val=coef2)],senses=["L"], rhs=[M2], names=['bound_s1[%s,%s]' %(k,j)])[0]
            model.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=vars3, val=coef3)], senses=["G"], rhs=[0], names=['bound_s2[%s,%s]' %(k,j)])[0]    

    model._data = x, q, s, theta
    # model.write("D2HAHA.lp")
    return model

G_Separation问题


def SeparationProblem_q_C_norm(p,q,theta,I,J,K,R,C):
    model=cplex.Cplex()
    alpha,beta,gamma,lamb={},{},{},{}
    for k in range(K):
        for i in range(I):
            alpha[k,i]=model.variables.add(obj=[0], lb=[-cplex.infinity], ub=[cplex.infinity], types=["C"], names=["alpha[%s,%s]"%(k,i)])[0]
    for k in range(K):
        for j in range(J):
            beta[k,j]=model.variables.add(obj=[q[k,j]], lb=[-cplex.infinity], ub=[cplex.infinity], types=["C"], names=["beta[%s,%s]"%(k,j)])[0]
    for k in range(K):
        for l in range(J):
            for j in range(J):
                gamma[k,l,j]=model.variables.add(obj=[0], lb=[0], ub=[cplex.infinity], types=["C"], names=["gamma[%s,%s,%s]"%(k,l,j)])[0]
    for k in range(K):
        lamb[k]=model.variables.add(obj=[p[k]*theta[k]], lb=[0], ub=[cplex.infinity], types=["C"], names=["lambda[%s]"%(k)])[0]            

    model.objective.set_sense(model.objective.sense.minimize)
    #Restricciones
    for k in range(K):
        for i in range(I):
            for j in range(J):
                var=[]
                var.append(alpha[k,i])
                var.append(beta[k,j])
                var.apend(lamb[k])
                for l in range(J):
                    if l!=j:
                        var.append(gamma[k,l,j])
                coef=[]
                coef.append(1)
                coef.append(1)
                coef.append(p[k]*R[k,i,j])
                for l in range(J):
                    if l!=j:
                        coef.append(C[k,i,l]-C[k,i,j])
                model.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=var,val=coef)], senses=["G"], rhs=[0], names=['1era[%s,%s,%s]'%(k,i,j)])[0]

    for i in range(I):
        var=[]
        for k in range(K):
            var.append(alpha[k,i])
        coef=[]
        for k in range(K):
            coef.append(-1)
        model.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=var,val=coef)], senses=["G"], rhs=[0], names=['2a[%s]'%(i)])[0]

    var=[]
    for k in range(K):
        var.append(lamb[k])
    for j in range(J):
        for k in range(K):
            var.append(beta[k,j])
    coef=[]
    for k in range(K):
        coef.append(-1)
    for j in range(J):
        for k in range(K):
            coef.append(1)
    model.linear_constraints.add(lin_expr=[cplex.SparsePair(ind=var,val=coef)], senses=["E"], rhs=[-1], names=['norm'])[0]


    model._data = alpha,beta,gamma,lamb
    return model

我的实例还可以,并且可以与其他算法一起运行而没有问题。

1 个答案:

答案 0 :(得分:1)

调试回调错误的最好方法是将回调代码包装到try/except块中,从中打印出实际的异常,然后重新引发它:

try:
  # callback code here
  ...
except:
  print(sys.exc_info()[0])
  raise

这将告诉您到底出了什么问题。