Easily evaluate expression in Drake - drake

The motivation is this: I want to evaluate some expressions in Drake using my initial guess.
(Pdb) sum_torques[0][0]
<Expression "(0.22118181414246227 * F(0) + 0.025169594403141499 * F(1) + 0.24812114211450653 * F(3) + 0.11159816296412806 * F(6) - 0.58491827687679454 * F(10))">
(Pdb) self.F
array([[Variable('F(0)', Continuous)],
[Variable('F(1)', Continuous)],
[Variable('F(2)', Continuous)],
[Variable('F(3)', Continuous)],
[Variable('F(4)', Continuous)],
[Variable('F(5)', Continuous)],
[Variable('F(6)', Continuous)],
[Variable('F(7)', Continuous)],
[Variable('F(8)', Continuous)],
[Variable('F(9)', Continuous)],
[Variable('F(10)', Continuous)],
[Variable('F(11)', Continuous)],
[Variable('F(12)', Continuous)],
[Variable('F(13)', Continuous)],
[Variable('F(14)', Continuous)]], dtype=object)
How can I easily evaluate the first expression? I thought Evaluate would work, but it doesn't:
(Pdb) sum_torques[0][0].Evaluate(prog.GetInitialGuess(self.F))
*** TypeError: Evaluate(): incompatible function arguments. The following argument types are supported:
1. (self: pydrake.symbolic.Expression, env: Dict[pydrake.symbolic.Variable, float] = {}, generator: pydrake.common._module_py.RandomGenerator = None) -> float
2. (self: pydrake.symbolic.Expression, generator: pydrake.common._module_py.RandomGenerator) -> float
Invoked with: <Expression "(0.22118181414246227 * F(0) + 0.025169594403141499 * F(1) + 0.24812114211450653 * F(3) + 0.11159816296412806 * F(6) - 0.58491827687679454 * F(10))">, array([10.6457846 , 10.32468297, 10.51971119, 10.00005536, 10.31186022,
10.42545154, 10.88533766, 10.67987946, 10.45612977, 10.48340862,
10.78873943, 10.22944183, 10.8802976 , 10.31369239, 10.95745086])
I could of course rewrite the sum_torques expression using prog.InitialGuess for every expression I want to evaluate, but this is extremely cumbersome... I thought there would be some easy way to evaluate the expressions without doing that.

To evaluate a symbolic::Expression, you will need to provide a dictionary that maps each variable to its value. Here is the code
env = {self.F[i][0] : prog.GetInitialGuess(self.F[i][0]) for i in range(self.F.shape[0])}
sum_torques[0][0].Evaluate(env)

Related

norm along a dimension is not supported in drake autodiff

I have the the following line of code which fails:
contact_forces = contact_forces / (np.linalg.norm(contact_forces, axis=-1) + 1e-5)[..., np.newaxis]
*** TypeError: loop of ufunc does not support argument 0 of type pydrake.symbolic.Variable which has no callable conjugate method
Below, I show the various debugging outputs in PDB. Basically the norm fails if you specify the axis argument.
(Pdb) contact_forces
array([[[Variable('x(0)', Continuous), Variable('x(1)', Continuous)],
[Variable('x(2)', Continuous), Variable('x(3)', Continuous)],
[Variable('x(4)', Continuous), Variable('x(5)', Continuous)]]],
dtype=object)
(Pdb) np.linalg.norm(contact_forces, axis=-1)
*** TypeError: loop of ufunc does not support argument 0 of type pydrake.symbolic.Variable which has no callable conjugate method
(Pdb) np.linalg.norm(contact_forces)
<Expression "sqrt((pow(x(0), 2) + pow(x(1), 2) + pow(x(2), 2) + pow(x(3), 2) + pow(x(4), 2) + pow(x(5), 2)))">
(Pdb) contact_forces.shape
(1, 3, 2)

How to parse list return value into sympy expression which you can substitute values in?

Hey I am new to using sympy and I have a problem working with the return value of solve(), because it always gives back a list
instead of a sympy expression. I want to substitute values into
my solution using sol.subs() which only works for sympy expressions. Can anyone tell me how to do this ?
eq1 = sp.Eq(sp.sqrt(2 * m * E) / h_bar, n * pi)
E_n = sp.solve(eq1, E)
type(E_n) is a list now. I want to use continue using it
as an expression. For example:
E_1 = E_n.subs(n, 1)
E_2 = E_n.subs(n, 2)
Thank you.
You can get the element from the list with [0] i.e.:
In [19]: import sympy as sp
In [20]: m, E, h_bar, n = sp.symbols('m, E, h_bar, n', positive=True)
In [21]: eq1 = sp.Eq(sp.sqrt(2 * m * E) / h_bar, n * pi)
In [22]: E_n = solve(eq1, E)[0]
In [23]: E_n
Out[23]:
2 2 2
π ⋅h_bar ⋅n
────────────
2⋅m
In [24]: E_n.subs(n, 1)
Out[24]:
2 2
π ⋅h_bar
─────────
2⋅m

Octave fminunc doesn't converge

I'm trying to use fminunc in Octave for a logistic problem, but it doesn't work. It says that I didn't define variables, but actually I did. If I define variables directly in the costFunction,and not in the main, it doesn't give any problem, but the function doesn't work really. In fact the exitFlag is equal to -3 and it doesn't converge at all.
Here's my function:
function [jVal, gradient] = cost(theta, X, y)
X = [1,0.14,0.09,0.58,0.39,0,0.55,0.23,0.64;1,-0.57,-0.54,-0.16,0.21,0,-0.11,-0.61,-0.35;1,0.42,0.45,-0.41,-0.6,0,-0.44,0.38,-0.29];
y = [1;0;1];
theta = [0.8;0.2;0.6;0.3;0.4;0.5;0.6;0.2;0.4];
jVal = 0;
jVal = costFunction2(X, y, theta); %this is another function that gives me jVal. I'm quite sure it is
%correct because I use it also with other algorithms and it
%works perfectly
m = length(y);
xSize = size(X, 2);
gradient = zeros(xSize, 1);
sig = X * theta;
h = 1 ./(1 + exp(-sig));
for i = 1:m
for j = 1:xSize
gradient(j) = (1/m) * sum(h(i) - y(i)) .* X(i, j);
end
end
Here's my main:
theta = [0.8;0.2;0.6;0.3;0.4;0.5;0.6;0.2;0.4];
options = optimset('GradObj', 'on', 'MaxIter', 100);
[optTheta, functionVal, exitFlag] = fminunc(#cost, theta, options)
if I compile it:
optTheta =
0.80000
0.20000
0.60000
0.30000
0.40000
0.50000
0.60000
0.20000
0.40000
functionVal = 0.15967
exitFlag = -3
How can I resolve this problem?
You are not in fact using fminunc correctly. From the documentation:
-- fminunc (FCN, X0)
-- fminunc (FCN, X0, OPTIONS)
FCN should accept a vector (array) defining the unknown variables,
and return the objective function value, optionally with gradient.
'fminunc' attempts to determine a vector X such that 'FCN (X)' is a
local minimum.
What you are passing is not a handle to a function that accepts a single vector argument. Instead, what you are passing (i.e. #cost) is a handle to a function that takes three arguments.
You need to 'convert' this into a handle to a function that takes only one input, and does what you want under the hood. The easiest way to do this is by 'wrapping' your cost function into an anonymous function that only takes one argument, and calls the cost function in the appropriate way, e.g.
fminunc( #(t) cost(t, X, y), theta, options )
Note: This assumes X and y are defined in the scope where you do this 'wrapping' business

Using >= for constraint throws RuntimeError (please use pydrake.common.containers.EqualToDict)

I am trying to use direct transcription to solve my trajectory optimization problem which involves some trigonometric functions.
I have the following variable types
a[i] = array([<Expression "(state_0(0) + 0.001 * state_0(4))">,
<Expression "(state_0(1) + 0.001 * state_0(5))">,
<Expression "(state_0(2) + 0.001 * state_0(6))">,
<Expression "(state_0(3) + 0.001 * state_0(7))">,
<Expression "...omitted...">,
<Expression "...omitted...">,
<Expression "...omitted...">,
<Expression "...omitted...">], dtype=object)
b[i] = array([Variable('state_1(0)', Continuous),
Variable('state_1(1)', Continuous),
Variable('state_1(2)', Continuous),
Variable('state_1(3)', Continuous),
Variable('state_1(4)', Continuous),
Variable('state_1(5)', Continuous),
Variable('state_1(6)', Continuous),
Variable('state_1(7)', Continuous)], dtype=object)
I'm trying to create a constraint as follows
mp.AddConstraint(b[i] <= a[i])
But I get the following error
RuntimeError: You should not call `__bool__` / `__nonzero__` on `Formula`. If you are trying to make a map with `Variable`, `Expression`, or `Polynomial` as keys (and then access the map in Python), please use pydrake.common.containers.EqualToDict`.
That's correct. Although you can also use the function names like eq(a,b)
https://github.com/RobotLocomotion/drake/issues/8315
It appears that the constraint must be specified per element, i.e.
for j in range(8):
mp.AddConstraint(b[i][j] <= a[i][j])

How do I use lhs and rhs to define a function?

In the Maxima session below, how come f(1) is not 0?
(%i1) eq: 2 * x + 1 = 3;
(%o1) 2 x + 1 = 3
(%i2) f(x) := lhs(eq) - rhs(eq);
(%o2) f(x) := lhs(eq) - rhs(eq)
(%i3) f(1);
(%o3) 2 x - 2
the process of function calling in maxima here binds x to 1 in the function
definition, lhs(eq)-rhs(eq). That has no x in it, so that binding does nothing.
Next, lhs(eq) is evaluated to 2*x+1. rhs(eq) is evaluated to 3. etc.
Do you always want the same equation eq? perhaps you want to do
define(f(x),lhs(eq)-rhs(eq));
to check what the definition is, try
grind(f);
If you want to vary the equation maybe something like
g(val, eq) := subst(val,x, lhs(eq)-rhs(eq)) ;
would do.

Resources