Display displacement, stress and deformation gradient in one vtk file

Hi,

I am solving solid mechanics problem in Fenics and I want to visualize displacement, stress and deformation gradient in a single vtu file. Currently, I can output these parameters in different vtu files, but is there any way to get them in a single file?

Here is a minimal code:

def grad and stress output

W_DFnStress = TensorFunctionSpace(mesh, "DG", 0)
defGrad = Function(W_DFnStress, name='F')
PK1_stress = Function(W_DFnStress, name='PK1')

files for writing output

disp_file = File(output_dir+'/Displacement.pvd')
defgrad_file = File(output_dir+'/DefGrad.pvd')
stress_file = File(output_dir+'/Stress.pvd')

Save solution to file in VTK format

    disp_file << (u,t)

Save DefGrad to file in VTK format

  DF = I + grad(u)
  defGrad.assign(project(DF, W_DFnStress))
  defgrad_file << (defGrad,t)

Save Stress to file in VTK format

 PK1_s,pp_t = stress(u, p)
 PK1_stress.assign(project(PK1_s, W_DFnStress))
 stress_file << (PK1_stress,t)

with this I can output displacement, deformation gradient and stress in three different vtu files. Could anyone please let me know how to get these things in a single vtu file?

Currently, I am using a crude method to combine all outputs. Once I have these separate .vtu files for displacement, stress and displacement gradient, I read the stress and deformation gradient .vtu (XML) files, and then write the field values in the displacement file.

here is a minimal code for the same.

commbine all vtu output, pick the DF and stress data from the xml files and write them to the Disp xml file

    Stress_tree = ET.parse(output_dir+'/Stress.vtu')
    Stress_root = Stress_tree.getroot()
    Stress_att = Stress_root[0][0][2][0].attrib
    Stress_txt = Stress_root[0][0][2][0].text
    DF_tree = ET.parse(output_dir+'/DefGrad.vtu')
    DF_root = DF_tree.getroot()
    DF_att = DF_root[0][0][2][0].attrib
    DF_txt = DF_root[0][0][2][0].text
    
    tree = ET.parse(output_dir+'/Displacement.vtu')
    root = tree.getroot()
    CellData = ET.SubElement(root[0][0], 'CellData') # adding an element to the root node

    DataArray = ET.SubElement(CellData, 'DataArray') # stress data
    for key, value in Stress_att.items():
        DataArray.set(key,value)
    DataArray.text = Stress_txt
    
    DataArray = ET.SubElement(CellData, 'DataArray') # DF data
    for key, value in DF_att.items():
        DataArray.set(key,value)
    DataArray.text = DF_txt

    tree.write(output_dir+'/Displacement'+counter_str+'.vtu') # create a new XML file with the new element

Hi,
best practice is to save in .xdmf format to have all outputs in one single file, see for instance
https://comet-fenics.readthedocs.io/en/latest/demo/elasticity/2D_elasticity.py.html