AMPL integration with Python¶

[Model Colaboratory] [AMPL on Streamlit] [AMPL Community Edition]
AMPL and all solvers are now available as python packages for Windows, Linux (X86_64, aarch64, ppc64le), and macOS. For instance, to install AMPL with HiGHS, CBC and Gurobi, you just need the following:
# Install Python API for AMPL
$ python -m pip install amplpy --upgrade
# Install solver modules (e.g., HiGHS, CBC, Gurobi)
$ python -m amplpy.modules install highs cbc gurobi
# Activate your license (e.g., free https://ampl.com/ce license)
$ python -m amplpy.modules activate <license-uuid>
# Import in Python
$ python
>>> from amplpy import AMPL
>>> ampl = AMPL() # instantiate AMPL object
Note
You can use a free Community Edition license, which allows free and perpetual use of AMPL with Open-Source solvers.
# Minimal example:
from amplpy import AMPL
import pandas as pd
ampl = AMPL()
ampl.eval(r"""
set A ordered;
param S{A, A};
param lb default 0;
param ub default 1;
var w{A} >= lb <= ub;
minimize portfolio_variance:
sum {i in A, j in A} w[i] * S[i, j] * w[j];
s.t. portfolio_weights:
sum {i in A} w[i] = 1;
""")
tickers, cov_matrix = # ... pre-process data in Python
ampl.set["A"] = tickers
ampl.param["S"] = pd.DataFrame(
cov_matrix, index=tickers, columns=tickers
).unstack()
ampl.option["solver"] = "gurobi"
ampl.option["gurobi_options"] = "outlev=1"
ampl.solve()
assert ampl.get_value("solve_result") == "solved"
sigma = ampl.get_value("sqrt(sum {i in A, j in A} w[i] * S[i, j] * w[j])")
print(f"Volatility: {sigma*100:.1f}%")
# ... post-process solution in Python
[Python API] [GitHub]
On Google Colab¶
You can also install AMPL on Google Colab (where it is free by default) as follows:
# Install dependencies
!pip install -q amplpy
# Google Colab & Kaggle integration
from amplpy import AMPL, tools
ampl = tools.ampl_notebook(
modules=["coin", "highs", "gokestrel"], # modules to install
license_uuid="default", # license to use
g=globals()) # instantiate AMPL object and register magics
Note
On Google Colab there is a default AMPL Community Edition license that gives you unlimited access to AMPL with open-source solvers (e.g., HiGHS, CBC, Couenne, Ipopt, Bonmin) or with commercial solvers from the NEOS Server as described in Kestrel documentation.
In the list modules
you need to include
"gokestrel"
to use the kestrel driver;
"highs"
for the HiGHS solver;
"coin"
for the COIN-OR solvers.
To use other commercial solvers, your license needs to include the commercial solver (e.g., an AMPL CE commercial solver trial).
On Streamlit Cloud¶
AMPL can be used on Streamlit to produce interactive prescriptive analytics applications.