Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Printing matrices in casadi #288

Closed
yugiero opened this issue Aug 24, 2022 · 2 comments
Closed

Printing matrices in casadi #288

yugiero opened this issue Aug 24, 2022 · 2 comments

Comments

@yugiero
Copy link

yugiero commented Aug 24, 2022

Hi!

I was wondering why it is not possible to print vectors/matrices when working with a casadi model using .to_array(). Is there another option to do that?
A minimal example:

import numpy as np
import biorbd
import biorbd_casadi as casadi

model = biorbd.Model("pendulum.bioMod")
q = np.array([[1,2,3,4],[1.1,2.1,3.1,4.1],[1.2,2.2,3.2,4.2]])
com = model.CoM(q[0]).to_array()
print(com)

model = casadi.Model("pendulum.bioMod")
q = np.array([[1,2,3,4],[1.1,2.1,3.1,4.1],[1.2,2.2,3.2,4.2]])
com = model.CoM(q[0]).to_array()
print(com)
@pariterre
Copy link
Member

pariterre commented Aug 24, 2022

Hi there!
Casadi does not actually carry actual data, but graph of the code that can generate the results of a computation. Therefore, it is sort of meaningless to get the array, as MX are graphs. Henceforth, there is no such thing as to_array(), but you can get the graph using to_mx().

That said, you can evaluate the graph. You must, however, first convert the graph (the MX) to a casadi.Function and then you can call that very function to evaluate the graph. I made an easy interface to convert to casadi.Function in Python. It would look something like:

import biorbd_casadi as casadi
from casadi import MX
import numpy as np

# Get a model
model = biorbd.Model("pendulum.bioMod")

# Create a symbolic variable of dimension (nq x 1) that will be used to create the graph
q_symbolic = MX.sym("q", model.nbQ(), 1) 

# Create the casadi function
com_func = biorbd.to_casadi_func('com', model.CoM, q_symbolic)  # Alternatively you can create yourself the function using casadi.Function

# Evaluate the graph with actual data
q = np.random.rand(model.nbQ())  # This can also be casadi.DM
com = com_func(q)  # This a DM, but can be converted to array using "com = np.array(com)"
print(com)

Hope this helps!

@yugiero yugiero closed this as completed Aug 25, 2022
@yugiero
Copy link
Author

yugiero commented Aug 25, 2022

Interesting, thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants