Python-Gurobi:检索MIP线性算法的解

2024-10-03 17:20:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个MIP,我试图通过回调恢复线性松弛的解,但我做不到。我使用下面的代码来提取变量Z,就在重新释放MIP的线性松弛之后。在

# Definition de la fonction callback
def mycallback(model, where):
    if where == GRB.Callback.MIPNODE:
        if model.cbGet(GRB.Callback.MIPNODE_STATUS) == GRB.Status.OPTIMAL:
            sol_Z=model.cbGetNodeRel(model.getAttr('x', vZ))
            FTe=range(1,FT+1)
            for cb in FCBloc: 
                for e in FOpEq:
                    for t in FTe:
                        Bl_ZDonnees.update({(cb,e,t):sol_Z[cb[0],cb[1],t,e]})
            NomFichier="M_1_Relax.csv"
            fichier = open(NomFichier, 'w')
            cw = csv.writer(fichier, delimiter=';')
            for bl1 in Bl_ZDonnees:
                cw.writerow([bl1,Blst_Donnees[bl1]])
            fichier.close()
            model.terminate()

Tags: informodelifcallback线性wherecb
2条回答

函数Model.cbGetNodeRel()takes a Var object or a list of Var objects。所以你需要写一些类似sol_Z=model.cbGetNodeRel(vZ)的东西。在

我测试这个方法,没问题。在

    #**********************************************************************
# Optimise relaxation, then recover the values that are near to 1   
    def M_Relax(model,FF,Fb0,Fb1,FBlocs,FBlocsR,FBlocs_FOP,FCBloc,FT,FOp_,FOpEq,FVarOrdProd):
        FTe=range(1,FT+1)
        Fbif=[Fb0,Fb1]
        N=len(FBlocs)
        mr=model.copy()
        mr.setParam('OutputFlag',0)
        # Create variables déplacements des équipements
        vZ={}
        for Cb in FCBloc:
            for t in FTe:
                for e in FOpEq:
                    vZ[Cb[0],Cb[1],t,e]= model.getVarByName(name="vZ_{}_{}_{}_{}".format(Cb[0],Cb[1],t,e))
        EntVars=[]
        for var in mr.getVars():
            if var.vType !=GRB.CONTINUOUS:
                EntVars+=[var]
                var.vType=GRB.CONTINUOUS

        mr.optimize()
        Blst_Donnees={}
        status = mr.status
        if mr.SolCount>0 or status == GRB.Status.OPTIMAL:
            sol_Z=mr.getAttr('x', vZ)
            for bl in FBlocsR:
                 for e in [e1 for e1 in FOpEq if e1[0]==op]:                            
                     for cb in [cb1 for cb1 in FCBloc if cb1[1]==bl]:
                          if len([t for t in FTe if sol_Z[cb[0],bl,t,e]>0.8])>=1:
                              t1=min([t for t in FTe if sol_Z[cb[0],bl,t,e]>0.8])                                            
                                    Blst_Donnees.update({('Z',cb[0],cb[1],e):t1})
            NomFichier="M_Relaxation.csv"
            fichier = open(NomFichier, 'w')
            cw = csv.writer(fichier, delimiter=';')
            for bl1 in Blst_Donnees:
                cw.writerow([bl1,Blst_Donnees[bl1]])
            fichier.close()
            return Blst_Donnees
        elif status == GRB.Status.INFEASIBLE:
            return [0,0]

相关问题 更多 >