4

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.

Peter Franek
  • 577
  • 3
  • 8
  • 25

2 Answers2

4

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.

vitaut
  • 49,672
  • 25
  • 199
  • 336
1

The following connection between GAMS and Pyomo might be of use:

Pyomo is a Python-based open-source software package that supports a diverse set of optimization capabilities for formulating, solving, and analyzing optimization models.

The convert function provided by GAMS allows you to generate a Pyomo Concrete scalar model from a GAMS-model.

Hence, you should be able to convert the GAMS model to a Pyomo model and then access its functions via the capabilities provided by Pyomo.

  • [convert function](https://www.gams.com/latest/docs/S_CONVERT.html) says "CONVERT comes free of charge with any *licensed* GAMS". Would you know of an opensource GAMS parser / reader that can handle the models in http://www.gamsworld.org/performance/princetonlib/princetonlib.htm ? Thanks – denis Oct 25 '18 at 13:34
  • Thank you for pointing this out. Unfortunately, I do not know an opensource parser. – Christoph Neumann Oct 29 '18 at 10:04