【问题标题】:How to export docplex solutions in Python?如何在 Python 中导出 docplex 解决方案?
【发布时间】:2021-11-11 21:15:02
【问题描述】:

我使用docplex.model.print_solution() 在控制台中获取解决方案。如何将所有解决方案导出到文件中?

谢谢

【问题讨论】:

    标签: python cplex docplex


    【解决方案1】:

    您可以使用 python 文件。

    让我使用zoo example

    from docplex.mp.model import Model
    
    mdl = Model(name='buses')
    nbbus40 = mdl.integer_var(name='nbBus40')
    nbbus30 = mdl.integer_var(name='nbBus30')
    mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
    mdl.minimize(nbbus40*500 + nbbus30*400)
    mdl.solve(log_output=True,)
    
    #display solution
    for v in mdl.iter_integer_vars():
        print(v," = ",v.solution_value)
    
    #write solution to a file
    f= open("c://temp//sol.txt", "w")
    for v in mdl.iter_integer_vars():
        f.write(str(v)+" = "+str(v.solution_value)+'\n')
    f.close()
    
    """
    
    which gives
    
    nbBus40  =  6.0
    nbBus30  =  2.0
    
    in the display and in the file
    
    """
    

    来自https://github.com/AlexFleischerParis/zoodocplex/blob/master/zoowritesolutioninafile.py

    【讨论】:

      【解决方案2】:

      导出方法会创建一个详细的json文件:

      mdl.solution.export("solution.json")
      

      如果您只想存储在docplex.model.print_solution() 中看到的结果,您可以使用:

      with open("solution.txt", "w") as solfile:
          solfile.write(mdl.solution.to_string())
      

      【讨论】:

        猜你喜欢
        • 2019-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多