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.

Thanks for your help.

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)
    quadrature_degree = 1
    P = dolfinx.fem.FunctionSpace(domain, ufl.FiniteElement(
    "Quadrature", mesh.ufl_cell(), quadrature_degree, quad_scheme="default"))
    quadrature_points, wts = basix.make_quadrature(
    basix.cell.string_to_type(mesh.topology.cell_name()), quadrature_degree)
    I1_expression = dolfinx.fem.Expression(I1, quadrature_points)
    SQJ2_expression = dolfinx.fem.Expression(SQJ2, quadrature_points)
    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
    with torch.no_grad():
        Mn = model(input_moe)
    return Mn.numpy()


# variational form
R = q*Mn(sigma(u)) *dx + 3*delta*Gc/96*(-y/eps + 2*eps*ufl.inner(ufl.grad(z),ufl.grad(q)))*dx

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)
      5 quadrature_degree = 1
----> 6 P = dolfinx.fem.FunctionSpace(domain, ufl.FiniteElement(
      7 "Quadrature", mesh.ufl_cell(), quadrature_degree, quad_scheme="default"))
      8 quadrature_points, wts = basix.make_quadrature(
      9 basix.cell.string_to_type(mesh.topology.cell_name()), quadrature_degree)


AttributeError: module 'ufl' has no attribute 'FiniteElement'

Does the example for mapping that you provided earlier still work? Thanks for your help.