我想用来自 this database 的约束满足问题在 Python
中做一些实验:所有示例均以 AMPL
和 GAMS
文件格式给出。有没有一种工具可以将这些方程式转换为简单的 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/