AMPL integration with Python

AMPL' All-New Python ecosystem

[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 for personal, academic, or commercial prototyping purposes using AMPL APIs.

# 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)
ampl.option["gurobi_options"] = "outlev=1"
ampl.solve(solver="gurobi")
assert ampl.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, ampl_notebook
ampl = ampl_notebook(
    modules=["gurobi", "coin", "highs", "gokestrel"], # modules to install
    license_uuid="default") # license to use

Note

On Google Colab there is a default AMPL Community Edition license that gives you access to AMPL with open-source solvers for personal, academic or commercial prototyping use (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).

[Model Colaboratory]

On Streamlit Cloud

AMPL can be used on Streamlit to produce interactive prescriptive analytics applications.

Check it out on Streamlit Cloud: RunOnStreamlit

[AMPL on Streamlit]

See more