ampl = AMPL()
ampl.read(os.path.join(model_directory, "test.mod"))
ampl.read_data(os.path.join(model_directory, "test.dat"))AMPLPY tutorial in Quarto
Meet AMPLPY
Here we are importing some packages that you will use in your Quarto file to run AMPL directly from python, solve it from here and also see the results generated from AMPL here
We are making sure that the directory is properly set for python to see the ampl mod, dat and run files. We are creating an instance of AMPL and reading the mod files we want to solve.
We can set the solver for AMPL and solving it like so. I’m using gurobi here. But CBC or Highs should also work since this is a linear problem in this particular case. If you are solving a non-linear problem, pay attention to which solver would work for that case!
# Set the solver to use
solver = "gurobi"
ampl.set_option("solver", solver)
ampl.solve()
if ampl.solve_result != "solved":
raise Exception(f"Failed to solve (solve_result: {ampl.solve_result}")
else:
print("wow,it works!")Gurobi 9.1.1: optimal solution; objective 1200
wow,it works!
okay, we have solved. Good news! but we have no idea what we solved. So, we have to see the value of our objective function.
totalcost = ampl.get_objective("TotalUsage")
print("Objective is:", totalcost.value())Objective is: 1200.0
And the variables we just calculated for arriving at this optimal solution.
import pandas
variables = ampl.get_variable("Select")
df = variables.get_values()
df =df.to_pandas()
print(df.index)
plot = df.plot(title="DataFrame Plot")Index(['basketball', 'park', 'pool', 'rec'], dtype='object')

what if someone suddenly tells you, they will build you a pool basically for free but has a hidden agenda for not building a park and makes it very expensive?
No worries, we calcuate the new optimimum by directly updating the input data from python to get the new optimal solution
cost = ampl.get_parameter("cost")
cost.set_values({"park": 1000, "pool": 0})
print("Park is made ridiculously expensive and pool is made basically free here!")Park is made ridiculously expensive and pool is made basically free here!
We solve again…
ampl.solve()
if ampl.solve_result != "solved":
raise Exception(f"Failed to solve (solve_result: {ampl.solve_result})")
print("New objective value:", totalcost.value())Gurobi 9.1.1: optimal solution; objective 800
New objective value: 800.0
we see the new solution again. Congratulations on learning this!
import pandas
variables = ampl.get_variable("Select")
df = variables.get_values()
df =df.to_pandas()
print(df)
plot = df.plot.bar(title="DataFrame Plot") Select.val
basketball 0
park 0
pool 1
rec 1
