# How to convert Ufl objects to pytorch tensor?

Hello,

I would like to create a function that takes the values from an ufl object and then convert it to pytorch tensor so that it can use a trained ml model to make the prediction. This function (prediction) also goes in to the variational form that will be solved. I have following questions.

1. Is possible to convert an ufl object to pytorch tensor or get its associated values at each nodes/qudrature points at each time step for the said conversion? If so, then how?
2. Also, is there any ufl wrapper to wrap a python function? Because my function is a term in the weak form that needs to solved.

Interpolate said tensor into a Quadrature space. See for instance: Mapped quadrature points, weights and solution at these quadrature points - #4 by dokken

You could use @Andrash’s external operator:

Thank you @dokken for your prompt response. I’ll look into those. This is really helpful.

My code:

``````def Mn(stress_tensor):
# Evaluating the stress tensor (which is an ufl expression) to a numpy array       fist
I1 = (z**2)*ufl.tr(stress_tensor)
SQJ2 = (z**2)*sigmavm(stress_tensor,u)
P = dolfinx.fem.FunctionSpace(domain, ufl.FiniteElement(
I1_nparry = I1_expression.eval(domain)
SQJ2_nparry = SQJ2_expression.eval(domain)
# numpy to Pytorch tensor conversion
input = torch.tensor([I1_nparry, SQJ2_nparry],  dtype=torch.float32).unsqueeze(0)
# Prediction using trained ML
Mn = model(input_moe)
return Mn.numpy()
``````

``````# variational form
``````

I’m getting the following error running the code for variational form (I’ve all the dependencies installed properly).

``````Cell In[28], line 6, in Mn(stress_tensor)
4 SQJ2 = (z**2)*sigmavm(stress_tensor,u)