Try our new documentation site (beta).


feasopt.py


#!/usr/bin/env python3.7

# Copyright 2023, Gurobi Optimization, LLC

# This example reads a MIP model from a file, adds artificial
# variables to each constraint, and then minimizes the sum of the
# artificial variables.  A solution with objective zero corresponds
# to a feasible solution to the input model.
#
# We can also use FeasRelax feature to do it. In this example, we
# use minrelax=1, i.e. optimizing the returned model finds a solution
# that minimizes the original objective, but only from among those
# solutions that minimize the sum of the artificial variables.

import sys
import gurobipy as gp

if len(sys.argv) < 2:
    print('Usage: feasopt.py filename')
    sys.exit(0)

feasmodel = gp.read(sys.argv[1])

# create a copy to use FeasRelax feature later

feasmodel1 = feasmodel.copy()

# clear objective

feasmodel.setObjective(0.0)

# add slack variables

for c in feasmodel.getConstrs():
    sense = c.Sense
    if sense != '>':
        feasmodel.addVar(obj=1.0, name="ArtN_" + c.ConstrName,
                         column=gp.Column([-1], [c]))
    if sense != '<':
        feasmodel.addVar(obj=1.0, name="ArtP_" + c.ConstrName,
                         column=gp.Column([1], [c]))

# optimize modified model

feasmodel.optimize()

feasmodel.write('feasopt.lp')

# use FeasRelax feature

feasmodel1.feasRelaxS(0, True, False, True)

feasmodel1.write("feasopt1.lp")

feasmodel1.optimize()

Try Gurobi for Free

Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.

Evaluation License
Get a free, full-featured license of the Gurobi Optimizer to experience the performance, support, benchmarking and tuning services we provide as part of our product offering.
Academic License
Gurobi supports the teaching and use of optimization within academic institutions. We offer free, full-featured copies of Gurobi for use in class, and for research.
Cloud Trial

Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.

Search

Gurobi Optimization