python - 将 `AMPL` 或 `GAMS` 文件转换为 `Python`

标签 python converters type-conversion ampl gams-math

我想用来自 this database 的约束满足问题在 Python 中做一些实验:所有示例均以 AMPLGAMS 文件格式给出。有没有一种工具可以将这些方程式转换为简单的 python 函数,看起来像

def quadratic(X):

 return (X[0]**2 - X[1]**2, 2*X[0]*X[1])

和类似的?

我已经开始阅读this manual但我不确定这是否是正确的方向。 (我不是很擅长编程。)如果有可能的提示,我将不胜感激。

最佳答案

我最近用 Python 为 AMPL 的一个子集编写了一个解析器,可用 here .它不完整,但已经可以处理许多 AMPL 表达式并且可以轻松扩展。

这是一个将目标函数从 AMPL 转换为 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))

运行这段代码打印:

def f(x):
  return x * x

为了简单起见,示例硬编码参数名称 x,但可以从 AST 派生它。

关于python - 将 `AMPL` 或 `GAMS` 文件转换为 `Python`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30666785/

相关文章:

c - 用整数计算 float 的标准化方法是怎样的?

python - 如何相对于引用系移动蛋白质坐标

java - 将 XML 转换为 Avro 并生成 AVRO 架构

javascript - 如何对数字进行零填充?

c++ - 相关模板类之间函数参数的自动转换

Javascript 隐式数字转换

python - python 中的内置 .count 是什么?

python - 为什么权重不会改变 sci-kit 学习包中的 K 均值聚类中心位置?

python - Flask 和 AngularJs

c++ - 如何将 SHA1 转换为无符号长整型数组 [5]?