Skip to content

Commit

Permalink
Update examples
Browse files Browse the repository at this point in the history
  • Loading branch information
fdabrandao committed Jun 23, 2022
1 parent a98faa8 commit 0d4f50f
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 51 deletions.
5 changes: 2 additions & 3 deletions examples/asyncexample.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
import sys
import os


def main(argc, argv):
from amplpy import AMPL, DataFrame
# You can install amplpy with "python -m pip install amplpy"
from amplpy import AMPL
import amplpy
from time import time

Expand Down
6 changes: 4 additions & 2 deletions examples/dataframeexample.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
import sys
import os


def main(argc, argv):
# You can install amplpy with "python -m pip install amplpy"
from amplpy import AMPL, DataFrame

os.chdir(os.path.dirname(__file__) or os.curdir)

# Note: If you want to perform data transformations use pandas dataframes.
# amplpy dataframes are simple dataframes for data communication only.

# Create first dataframe (for data indexed over NUTR)
# Add data row by row
df1 = DataFrame("NUTR", ("n_min", "n_max"))
Expand Down
55 changes: 31 additions & 24 deletions examples/dietmodel.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
import sys
import os
import pandas as pd


def main(argc, argv):
from amplpy import AMPL, DataFrame
# You can install amplpy with "python -m pip install amplpy"
from amplpy import AMPL

os.chdir(os.path.dirname(__file__) or os.curdir)

# Create an AMPL instance
ampl = AMPL()

"""
# If the AMPL installation directory is not in the system search path:
from amplpy import Environment
Expand All @@ -27,27 +27,31 @@ def main(argc, argv):
model_directory = argv[2] if argc == 3 else os.path.join("..", "models")
ampl.read(os.path.join(model_directory, "diet/diet.mod"))

# Create a pandas dataframe with data for cost, f_min, f_max
foods = ["BEEF", "CHK", "FISH", "HAM", "MCH", "MTL", "SPG", "TUR"]
costs = [3.59, 2.59, 2.29, 2.89, 1.89, 1.99, 1.99, 2.49]

fmin = [2, 2, 2, 2, 2, 2, 2, 2]
fmax = [10, 10, 10, 10, 10, 10, 10, 10]

df = DataFrame("FOOD")
df.set_column("FOOD", foods)
df.add_column("cost", costs)
df.add_column("f_min", fmin)
df.add_column("f_max", fmax)
df = pd.DataFrame(
list(zip(foods, costs, fmin, fmax)),
columns=["FOOD", "cost", "f_min", "f_max"],
).set_index("FOOD")

# Send the data to AMPL and initialize the indexing set "FOOD"
ampl.set_data(df, "FOOD")

# Create a pandas dataframe with data for n_min, n_max
nutrients = ["A", "C", "B1", "B2", "NA", "CAL"]
nmin = [700, 700, 700, 700, 0, 16000]
nmax = [20000, 20000, 20000, 20000, 50000, 24000]

df = DataFrame("NUTR")
df.setColumn("NUTR", nutrients)
df.add_column("n_min", nmin)
df.add_column("n_max", nmax)
df = pd.DataFrame(
list(zip(nutrients, nmin, nmax)),
columns=["NUTR", "n_min", "n_max"],
).set_index("NUTR")

# Send the data to AMPL and initialize the indexing set "NUTR"
ampl.set_data(df, "NUTR")

amounts = [
Expand All @@ -59,19 +63,22 @@ def main(argc, argv):
[295, 770, 440, 430, 315, 400, 379, 450],
]

df = DataFrame(("NUTR", "FOOD"), "amt")
df.setValues(
{
(nutrient, food): amounts[i][j]
for i, nutrient in enumerate(nutrients)
for j, food in enumerate(foods)
}
)
ampl.set_data(df)
# Set the values for the parameter "amt"
ampl.param["amt"] = {
(nutrient, food): amounts[i][j]
for i, nutrient in enumerate(nutrients)
for j, food in enumerate(foods)
}

# Solve the problem
ampl.solve()

print("Objective: {}".format(ampl.get_objective("Total_Cost").value()))
# Check if the problem was solved successfully
solve_result = ampl.get_value("solve_result")
if solve_result != "solved":
raise Exception("Failed to solve (solve_result: {})".format(solve_result))

print("Objective: {}".format(ampl.obj["Total_Cost"].value()))


if __name__ == "__main__":
Expand Down
13 changes: 8 additions & 5 deletions examples/efficientfrontier.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
import sys
import os


def main(argc, argv):
# You can install amplpy with "python -m pip install amplpy"
from amplpy import AMPL

os.chdir(os.path.dirname(__file__) or os.curdir)
Expand All @@ -16,7 +15,6 @@ def main(argc, argv):

# Create an AMPL instance
ampl = AMPL()

"""
# If the AMPL installation directory is not in the system search path:
from amplpy import Environment
Expand Down Expand Up @@ -62,9 +60,9 @@ def main(argc, argv):
returns = [None] * steps
variances = [None] * steps
for i in range(steps):
print("Solving for return = {:g}".format(maxret - (i - 1) * stepsize))
print("Solving for return = {:g}".format(maxret - i * stepsize))
# Set target return to the desired point
target_return.set(maxret - (i - 1) * stepsize)
target_return.set(maxret - i * stepsize)
ampl.eval("let stockopall:={};let stockrun:=stockall;")
# Relax integrality
ampl.set_option("relax_integrality", True)
Expand All @@ -75,7 +73,12 @@ def main(argc, argv):
ampl.eval("let stockopall:={i in stockrun:weights[i]>0.5};")
# Set integrality back
ampl.set_option("relax_integrality", False)
# Solve the problem
ampl.solve()
# Check if the problem was solved successfully
solve_result = ampl.get_value("solve_result")
if solve_result != "solved":
raise Exception("Failed to solve (solve_result: {})".format(solve_result))
print("QMIP result = {:g}".format(variance.value()))
# Store data of corrent frontier point
returns[i] = maxret - (i - 1) * stepsize
Expand Down
21 changes: 14 additions & 7 deletions examples/firstexample.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
import sys
import os


def main(argc, argv):
# You can install amplpy with "python -m pip install amplpy"
from amplpy import AMPL

os.chdir(os.path.dirname(__file__) or os.curdir)

# Create an AMPL instance
ampl = AMPL()

"""
# If the AMPL installation directory is not in the system search path:
from amplpy import Environment
Expand All @@ -31,6 +29,9 @@ def main(argc, argv):

# Solve
ampl.solve()
solve_result = ampl.get_value("solve_result")
if solve_result != "solved":
raise Exception("Failed to solve (solve_result: {})".format(solve_result))

# Get objective entity by AMPL name
totalcost = ampl.get_objective("Total_Cost")
Expand All @@ -44,6 +45,9 @@ def main(argc, argv):

# Resolve and display objective
ampl.solve()
solve_result = ampl.get_value("solve_result")
if solve_result != "solved":
raise Exception("Failed to solve (solve_result: {})".format(solve_result))
print("New objective value:", totalcost.value())

# Reassign data - all instances
Expand All @@ -53,18 +57,21 @@ def main(argc, argv):

# Resolve and display objective
ampl.solve()
solve_result = ampl.get_value("solve_result")
if solve_result != "solved":
raise Exception("Failed to solve (solve_result: {})".format(solve_result))
print("New objective value:", totalcost.value())

# Get the values of the variable Buy in a dataframe object
buy = ampl.get_variable("Buy")
df = buy.get_values()
# Print them
print(df)
# Print as pandas dataframe
print(df.to_pandas())

# Get the values of an expression into a DataFrame object
df2 = ampl.get_data("{j in FOOD} 100*Buy[j]/Buy[j].ub")
# Print them
print(df2)
# Print as pandas dataframe
print(df2.to_pandas())


if __name__ == "__main__":
Expand Down
8 changes: 5 additions & 3 deletions examples/locationtransportation.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
import sys
import os


def main(argc, argv):
# You can install amplpy with "python -m pip install amplpy"
from amplpy import AMPL

os.chdir(os.path.dirname(__file__) or os.curdir)
Expand Down Expand Up @@ -62,7 +61,7 @@ def main(argc, argv):
# Solve the subproblem.
ampl.eval("solve Sub;")
result = ship_cost.result()
if result.find("infeasible") != -1:
if result == "infeasible":
# Add a feasibility cut.
num_cut_param.set(num_cuts)
cut_type.set(num_cuts, "ray")
Expand All @@ -85,6 +84,9 @@ def main(argc, argv):
# Re-solve the master problem.
print("RE-SOLVING MASTER PROBLEM")
ampl.eval("solve Master;")
solve_result = ampl.get_value("solve_result")
if solve_result != "solved":
raise Exception("Failed to solve (solve_result: {})".format(solve_result))
# Copy the data from the Build variable used in the master problem
# to the build parameter used in the subproblem.
build_param.set_values(build_var.get_values())
Expand Down
16 changes: 14 additions & 2 deletions examples/multidimensionalexample.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
import sys
import os
import pandas as pd


def main(argc, argv):
Expand All @@ -29,6 +28,7 @@ def main(argc, argv):
links_from = ["PITT", "PITT", "NE", "NE", "NE", "SE", "SE", "SE", "SE"]
links_to = ["NE", "SE", "BOS", "EWR", "BWI", "EWR", "BWI", "ATL", "MCO"]

# Using amplpy.DataFrame
df = DataFrame(("LINKSFrom", "LINKSTo"), ("cost", "capacity"))
df.set_column("LINKSFrom", links_from)
df.set_column("LINKSTo", links_to)
Expand All @@ -37,6 +37,18 @@ def main(argc, argv):
print(df)

ampl.set_data(df, "LINKS")
ampl.display("LINKS")

# Using pandas.DataFrame (recommended)
df = pd.DataFrame(
list(zip(links_from, links_to, cost, capacity)),
columns=["LINKSFrom", "LINKSTo", "cost", "capacity"],
).set_index(["LINKSFrom", "LINKSTo"])
print(df)

ampl.eval("reset data LINKS;")
ampl.set_data(df, "LINKS")
ampl.display("LINKS")


if __name__ == "__main__":
Expand Down
4 changes: 1 addition & 3 deletions examples/optionsexample.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
import sys
import os


def main(argc, argv):
# You can install amplpy with "python -m pip install amplpy"
from amplpy import AMPL

os.chdir(os.path.dirname(__file__) or os.curdir)

# Create an AMPL instance
ampl = AMPL()

"""
# If the AMPL installation directory is not in the system search path:
from amplpy import Environment
Expand Down
13 changes: 11 additions & 2 deletions examples/trackingmodel.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
import sys
import os


def main(argc, argv):
# You can install amplpy with "python -m pip install amplpy"
from amplpy import AMPL

os.chdir(os.path.dirname(__file__) or os.curdir)
Expand Down Expand Up @@ -44,8 +43,13 @@ def main(argc, argv):

# Relax the integrality
ampl.set_option("relax_integrality", True)

# Solve the problem
ampl.solve()
solve_result = ampl.get_value("solve_result")
if solve_result != "solved":
raise Exception("Failed to solve (solve_result: {})".format(solve_result))

objectives = list(obj for name, obj in ampl.get_objectives())
assert objectives[0].value() == ampl.get_objective("cst").value()
print("QP objective value", ampl.get_objective("cst").value())
Expand All @@ -71,8 +75,13 @@ def main(argc, argv):

# Get back to the integer problem
ampl.set_option("relax_integrality", False)

# Solve the (integer) problem
ampl.solve()
solve_result = ampl.get_value("solve_result")
if solve_result != "solved":
raise Exception("Failed to solve (solve_result: {})".format(solve_result))

print("QMIP objective value", ampl.get_objective("cst").value())


Expand Down

0 comments on commit 0d4f50f

Please sign in to comment.