Generic Examples

These examples use the generic interface, which allow the same set of functions to be called on all supported solvers.

Example: load

This example shows how to load a model, solve it and display basic information.

from tsp_helpers import tsp_model

import amplpy_gurobi 
#import amplpy_cplex
ampls = amplpy_gurobi



def doStuff(a):
    '''
    Generic function doing the optimization and reading the results
    '''
    # Optimize with default settings
    a.optimize()
    print("Model status:", a.get_status())
    # Print the objective function
    print("Objective:", a.get_obj())
    # Get the solution vector
    d = a.get_solution_vector()
    # Print the non-zeroes, by getting a map
    # Note that this will only work if the col file has been generated
    map = a.get_var_map_inverse()
    nonzeroes = [(map[index], d[index]) for index in map if d[index] != 0]
    for (name, value) in nonzeroes:
        print("{} = {}".format(name, value))
    return cm.get_solution_dict()


ampl = tsp_model('tsp_51_1.txt')

#cm = ampl.export_cplex_model()
#print(doStuff(cm))

gm = ampl.export_gurobi_model()
print(doStuff(gm))

Example: info callback

This example shows how to monitor the progress of the solution process by registering a callback.

import sys
from tsp_helpers import tsp_model
import amplpy_gurobi as ampls_gurobi
import amplpy_cplex as ampls_cplex
ampls = ampls_gurobi

# Define my generic callback function


class MyCallback(ampls.GenericCallback):
    def __init__(self):
        super(MyCallback, self).__init__()
        self.nMIPnodes = 0

    def run(self):
        t = self.getAMPLWhere()
        print("AMPL Phase: {}, from solver: {}".format(
            t, self.getWhereString()))
        if t == ampls.Where.MSG:
            # print(self.getMessage())
            return 0
        if t == ampls.Where.LPSOLVE:
            print("LP solve, {} iterations".format(
                self.getValue(ampls.Value.ITERATIONS).integer))
            return 0
        if t == ampls.Where.PRESOLVE:
            print("Presolve, eliminated {} rows and {} columns.".format(
                self.getValue(ampls.Value.PRE_DELROWS).integer,
                self.getValue(ampls.Value.PRE_DELCOLS).integer))
            return 0
        if t == ampls.Where.MIPNODE:
            self.nMIPnodes += 1
            print("New MIP node, count {}".format(self.nMIPnodes))
        if t == ampls.Where.MIPSOL:
            print("MIP Solution = {}".format(self.getObj()))
        return 0


class MyCplexCallback(ampls_cplex.CPLEXCallback):
    def run(self):
        try:
            print('>>', dir(self))
            w = self.getWhere()
            # where = self.getWhereText()
            print(w)
            return 0
        except Exception as e:
            print(e)


class MyGurobiCallback(ampls_gurobi.GurobiCallback):
    def run(self):
        print(dir(self))
        w = self.getWhere()
        # where = self.getWhereText()
        print(w)
        return 0


def doStuff(a, cb):
    cb = MyCallback()
    a.setCallback(cb)
    a.optimize()
    print(a.getObj())


ampl = tsp_model('tsp_51_1.txt')

print('Cplex with generic callback:')
cm = ampl.exportCplexModel()
doStuff(cm, MyCallback())

print('Cplex with cplex callback:')
cm = ampl.exportCplexModel()
doStuff(cm, MyCplexCallback())

print('Gurobi with generic callback:')
gm = ampl.exportGurobiModel()
doStuff(gm, MyCallback())

print('Gurobi with gurobi callback:')
gm = ampl.exportGurobiModel()
doStuff(gm, MyGurobiCallback())

Solver specific examples

Example: simple callback

from amplpy import AMPL
import amplpy_gurobi as ampls

ampl = AMPL()

ampl.eval('''
set A:=1..10;
param n{a in A} := a*2;
var x{A} >=0 integer;
maximize z: sum{a in A} x[a]/2;
c{a in A}: x[a] <= n[a];
''')

CALL_COUNT_MIP = 0
CALL_COUNT_MIPSOL = 0


class MyCallback(ampls.GurobiCallback):
    def run(self):
        try:
            where = self.getAMPLWhere()
            global CALL_COUNT_MIP, CALL_COUNT_MIPSOL
            if where == ampls.GRB_CB_MIPSOL:
                CALL_COUNT_MIPSOL += 1
                print(self.getSolutionVector())
                print("GRB_CB_MIP_SOL #{}!".format(CALL_COUNT_MIPSOL))
            elif where == ampls.GRB_CB_MIP:
                CALL_COUNT_MIP += 1
                print("GRB_CB_MIP #{}!".format(CALL_COUNT_MIP))
                print(self.getSolutionVector())
                if CALL_COUNT_MIP >= 10:
                    return 1
        except Exception as e:
            print(e)
        return 0


m = ampl.exportGurobiModel()
cb = MyCallback()
m.setCallback(cb)
m.optimize()
obj = m.getObj()
nvars = m.getNumVars()
err = m.writeSol()

ampl.importSolution(m)
o = ampl.getObjective('z')

print("Obj values - AMPL={} Gurobi={}".format(o.value(), obj))