改变方程的ast.NodeTransformer的示例

tar*_*sch 19 python genetic-programming abstract-syntax-tree

这是我上一个问题的延续.我想解析一个方程式并按照我得到的方式工作.我想要做的基本上是随机加扰它,所以我得到一个新的等式,它必须也是一个有效的函数.这将用于遗传算法.

这是我开始的地方:

class Py2do(ast.NodeTransformer):
def __init__(self):
  self.tree=[]
def generic_visit(self, node):
    print type(node).__name__
    self.tree.append(type(node).__name__)
    ast.NodeVisitor.generic_visit(self, node)
    depth=3
    s = node.__dict__.items()
    s = "    ".join("%s %r" % x for x in sorted(node.__dict__.items()))
    print( "%s%s\t%s" % (depth, str(type(node)), s) )
    for x in ast.iter_child_nodes(node):
      print (x, depth)

def visit_Name(self, node):
    # print 'Name :', node.id
    pass

def visit_Num(self, node):
    print 'Num :', node.__dict__['n']

def visit_Str(self, node):
    print "Str :", node.s

def visit_Print(self, node):
    print "Print :"
    ast.NodeVisitor.generic_visit(self, node)

def visit_Assign(self, node):
    print "Assign :"
    ast.NodeVisitor.generic_visit(self, node)

def visit_Expr(self, node):
    print "Expr :"
    ast.NodeVisitor.generic_visit(self, node)





if __name__ == '__main__':
    node = ast.parse("res= e**(((-0.5*one)*((delta_w*one/delta*one)**2)))")
    import ast_pretty
    print ast.dump(node)
    pprintAst(node)
    v = Py2do()
    v.visit(node)
    print v.tree
Run Code Online (Sandbox Code Playgroud)

我想要得到的是这样的:

res= e**(delta*((one/delta_w*one)**2)))
Run Code Online (Sandbox Code Playgroud)

或某种有效的随机方程式.这将用于Fortran程序,因此如果得到的方程式也可以转移到Fortran中,那就太好了.请评论您的代码并提供测试样本/单元测试.

tux*_*21b -1

你想做什么?寻找方程的正确排列可能很容易但很耗时(n!种可能性),但是生成新的方程并使用遗传算法优化它们是不可能的,因为这不是一个优化问题......例如x^ 0.00 和 x^0.01 是根本不同的。此外,您无法针对正确的运算符进行优化,这是行不通的。对不起。

虽然,情况并没有那么糟糕。寻找正确的功能是一项极其常见的任务。我现在假设您不知道该函数,但您从测量中知道几个点(无论如何您都需要它来计算遗传算法中的适应度,不是吗?)。现在,您可以使用拉格朗日来获取通过这些给定点的多项式。维基百科文章中间有两个很好的例子,拉格朗日很容易实现(我猜代码少于 10 行)。另请注意,您只需添加更多参考点即可提高多项式的准确性。