AMPLPY: Jupyter Notebook Integration

Documentation: http://amplpy.readthedocs.io

GitHub Repository: https://github.com/ampl/amplpy

PyPI Repository: https://pypi.python.org/pypi/amplpy

Imports


In [1]:
from __future__ import print_function
from amplpy import AMPL, register_magics
import os, sys

Instantiate an ampl object and register jupyter magics


In [2]:
ampl = AMPL()
# Store %%ampl cells in the list _ampl_cells
# Evaluate %%ampl_eval cells with ampl.eval()
register_magics(store_name='_ampl_cells', ampl_object=ampl)

Use %%ampl_eval to pass the model to AMPL


In [3]:
%%ampl_eval
set SIZES;
param capacity >= 0;
param value {SIZES};
var Qty {SIZES} binary;
maximize TotVal: sum {s in SIZES} value[s] * Qty[s];
subject to Cap: sum {s in SIZES} s * Qty[s] <= capacity;

Set data


In [4]:
ampl.set['SIZES'] = [5, 4, 6, 3]
ampl.param['value'] = [10, 40, 30, 50]
ampl.param['capacity'] = 10

Use %%ampl_eval to display values


In [5]:
%%ampl_eval
display SIZES;
display value;
display capacity;


set SIZES := 5 4 6 3;

value [*] :=
3  50
4  40
5  10
6  30
;

capacity = 10

Use amplpy to retrive values


In [6]:
print('SIZES:', ampl.set['SIZES'].getValues().toList())
print('value:', ampl.param['value'].getValues().toDict())
print('capacity:', ampl.param['capacity'].value())


SIZES: [5.0, 4.0, 6.0, 3.0]
value: {3.0: 50.0, 4.0: 40.0, 5.0: 10.0, 6.0: 30.0}
capacity: 10.0

Use %%ampl_eval to solve the model


In [7]:
%%ampl_eval
option solver gurobi;
option gurobi_options 'outlev=1';
solve;


Gurobi 8.1.0: outlev=1
Optimize a model with 1 rows, 4 columns and 4 nonzeros
Variable types: 0 continuous, 4 integer (4 binary)
Coefficient statistics:
  Matrix range     [3e+00, 6e+00]
  Objective range  [1e+01, 5e+01]
  Bounds range     [1e+00, 1e+00]
  RHS range        [1e+01, 1e+01]
Found heuristic solution: objective 50.0000000
Presolve removed 1 rows and 4 columns
Presolve time: 0.00s
Presolve: All rows and columns removed

Explored 0 nodes (0 simplex iterations) in 0.00 seconds
Thread count was 1 (of 4 available processors)

Solution count 2: 90 50 

Optimal solution found (tolerance 1.00e-04)
Best objective 9.000000000000e+01, best bound 9.000000000000e+01, gap 0.0000%
Optimize a model with 1 rows, 4 columns and 4 nonzeros
Coefficient statistics:
  Matrix range     [3e+00, 6e+00]
  Objective range  [1e+01, 5e+01]
  Bounds range     [1e+00, 1e+00]
  RHS range        [1e+01, 1e+01]
Iteration    Objective       Primal Inf.    Dual Inf.      Time
       0    9.0000000e+01   0.000000e+00   0.000000e+00      0s

Solved in 0 iterations and 0.00 seconds
Optimal objective  9.000000000e+01
Gurobi 8.1.0: optimal solution; objective 90

In [ ]: