Skip to main content

Running Gurobi model in python function

Answered

Comments

3 comments

  • Maliheh Aramon
    Gurobi Staff Gurobi Staff

    Hi Aryaman,

    In every function call, you are not changing Gurobi parameters, you are changing the problem input that results in a new model object. You can remove the model.reset(1) from the end and just have model.dispose() to delete the model object. In the next function call, when you initialize the model, you create a new model object for the new problem input. 

    In case you are calling the function \(\texttt{run_gurobi_model}\) in parallel, it is important to create a separate environment object for each parallel job too. Please check the article How do I use multiprocessing in Python with Gurobi?

    Best regards,

    Maliheh

    0
  • Aryaman Shaan
    Gurobi-versary
    First Comment
    First Question

    Hi Maliheh,

    Thank you so much for your response. I have two follow up questions. 

    1. Would keeping model.reset(1) instead of model.dispose() lead to an incorrect solution? 

    2. If I run the function run_gurobi_model in multiple Jupyter notebook files at the same time do I need to explicitly change the environment? I am asking since I think each Jupyter notebook has its own ipykernel, a new gurobi environment should be created in each notebook. Is this thinking correct? 

    Again, thanks a lot for your help.

    Shaan

    0
  • Maliheh Aramon
    Gurobi Staff Gurobi Staff

    Hi Shaan, 

    1. Would keeping model.reset(1) instead of model.dispose() lead to an incorrect solution? 

    Not necessarily. The model.reset(1) essentially does not have any impact because you have already queried the results you need and a new model will be created in the next function call. The best practice is to free all resources as soon as you do not need the object. Therefore, it is highly recommended to call model.dispose() at the end and delete model.reset(1) as it does not do anything in your setup.

    2. If I run the function run_gurobi_model in multiple Jupyter notebook files at the same time do I need to explicitly change the environment? I am asking since I think each Jupyter notebook has its own ipykernel, a new gurobi environment should be created in each notebook. Is this thinking correct? 

    I think you are right that each notebook will use a different environment. Following the best practice advice above, when you rely on the default environment, you can call disposeDefaultEnv() to release all the resources as soon as you do not need the environment. And this is even more important in a Jupyter notebook which is a long-running Python session and the Gurobi environment would exist for the entire duration unless it is explicitly freed.

    Best regards,

    Maliheh 

    0

Please sign in to leave a comment.