I would like to make some experiments in Python
with constraint satisfaction problems from this database: all of the examples there are given in both the AMPL
and GAMS
file format. Is there a tool to convert these equations to simple python functions that looks like
def quadratic(X):
return (X[0]**2 - X[1]**2, 2*X[0]*X[1])
and similar?
I have started reading this manual but am not sure if that's the right direction. (I'm not very strong at programming.) I will be grateful for possible hints.
I've recently written a parser for a subset of AMPL in Python which is available here. It is incomplete but can already handle many AMPL expressions and can be easily extended.
Here's an example of converting an objective function from AMPL into Python:
import ampl, sys
class AMPLToPythonConverter:
def __init__(self, stream):
self.stream = stream
def visit_reference(self, expr):
self.stream.write(expr.name)
def visit_binary(self, expr):
expr.lhs.accept(self)
self.stream.write(' {} '.format(expr.op))
expr.rhs.accept(self)
def visit_decl(self, decl):
if decl.kind == 'minimize':
self.stream.write("def {}(x):\n".format(decl.name))
self.stream.write(" return ");
decl.body.accept(self)
self.stream.write('\n')
compound_stmt = ampl.parse(
"""
var x;
minimize f: x * x;
""", "input")
for node in compound_stmt.nodes:
node.accept(AMPLToPythonConverter(sys.stdout))
Running this code prints:
def f(x):
return x * x
To keep things simple the example hardcodes argument name x
, but it is possible to derive it from the AST.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With