有没有办法在神秘的约束中使用变量名?
IE
equations = '''
abs(x0 - init_velocity) <= acceleration_constraint
abs(x1 - init_heading) <= turning_constraint
'''
以上导致此错误:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3418, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-68-254fb3031193>", line 14, in <module>
eqn = simplify(equations, all=True)
File "<string>", line 120, in simplify
File "<string>", line 93, in _simplify
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mystic/symbolic.py", line 381, in equals
after, before = eval(after,{},locals_), eval(before,{},locals_)
File "<string>", line unknown
^
SyntaxError: unexpected EOF while parsing
编辑:
下面使用的代码试图最小化当前本地点 (x_0, y_0) 和下一个本地点 (x_1, y_1) 之间的 l2 范数,同时遵循约束(物理加速度和转弯半径)。这个距离在速度和航向方面被最小化。
def formulate_objective(curr_x, curr_y, desired_x, desired_y):
def objective(x):
next_x = curr_x + x[0] * np.cos(np.radians(x[1]))
next_y = curr_y + x[0] * np.sin(np.radians(x[1]))
return np.linalg.norm(np.vstack([desired_x - next_x, desired_y - next_y]), ord=2)
return objective
objective = formulate_objective(init_x, init_y, desired_x, desired_y)
equations = '''
abs(x0 - iv) <= ac
abs(x1 - ih) <= tc
'''
var_dict = dict(iv=init_velocity, ih=init_heading,
ac=acceleration_constraint, tc=turning_constraint)
eqn = simplify(equations, locals=var_dict)
cf = generate_constraint(generate_conditions(eqn, nvars=2), join=and_)
x0 = [init_velocity, init_heading]
fmin(objective, x0=x0, constraint=cf)