Skip to content

Exporters

Module for exporting simulation results in CSV and VTK formats.

This module provides utility functions for exporting FEniCSx function data to VTK files for visualization, appending simulation results to CSV files, and cleaning up VTK output directories by gathering .pvtu files into a single .pvd file.

Functions:

Name Description
export_res_to_csv

Appends a dictionary of results to a CSV file. The keys of the dictionary become the column headers, and the values are appended as a row.

export_function

Exports a FEniCS function to a VTK file. The filename is constructed using the function name and the provided time step t.

clean_vtk_files

Cleans a directory by removing existing .pvd files and creating a new .pvd file that lists all .pvtu files with their corresponding timesteps.

clean_vtk_files(res_dir)

Clean the specified directory by removing existing .pvd files and create a new .pvd file listing all .pvtu files.

This function removes all existing .pvd files in the given directory and creates a new .pvd file that lists all .pvtu files with their corresponding timesteps. The new .pvd file is named 'displacement.pvd'.

Parameters:

Name Type Description Default
res_dir Path

The path to the directory containing .pvtu and .vtu files.

required
Source code in src/gcrack/exporters.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def clean_vtk_files(res_dir: Path):
    """
    Clean the specified directory by removing existing .pvd files and create a new .pvd file listing all .pvtu files.

    This function removes all existing .pvd files in the given directory and creates a new .pvd file that lists all .pvtu files
    with their corresponding timesteps. The new .pvd file is named 'displacement.pvd'.

    Args:
        res_dir (Path): The path to the directory containing .pvtu and .vtu files.
    """

    # Remove existing .pvd files
    for pvd_file in res_dir.glob("*.pvd"):
        pvd_file.unlink()

    # Collect all .pvtu files and sort them
    pvtu_files = sorted(res_dir.glob("*.pvtu"))

    # Create a new .pvd file content
    pvd_content = (
        '<VTKFile type="Collection" version="0.1" byte_order="LittleEndian">\n'
    )
    pvd_content += "  <Collection>\n"

    for timestep, pvtu_file in enumerate(pvtu_files):
        pvd_content += f'    <DataSet timestep="{timestep}" group="" part="0" file="{pvtu_file.name}"/>\n'

    pvd_content += "  </Collection>\n"
    pvd_content += "</VTKFile>"

    # Write the new .pvd file
    combined_pvd_path = res_dir / "displacement.pvd"
    with combined_pvd_path.open("w") as file:
        file.write(pvd_content)

    print(f"Created displacement.pvd with {len(pvtu_files)} timesteps.")

export_function(u, t, dir_path)

Export a FEniCS function to a VTK file.

This function writes the given FEniCS function to a VTK file for visualization. The filename is constructed using the function name with the provided time step t, and the file is saved in the specified directory.

Parameters:

Name Type Description Default
u Function

The FEniCS function to be exported.

required
t int

The time step used to construct the filename.

required
dir_path Path

The path to the directory where the VTK file will be saved.

required
Source code in src/gcrack/exporters.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def export_function(u: fem.Function, t: int, dir_path: Path):
    """
    Export a FEniCS function to a VTK file.

    This function writes the given FEniCS function to a VTK file for visualization. The filename
    is constructed using the function name with the provided time step `t`, and the file is saved
    in the specified directory.

    Args:
        u (fem.Function): The FEniCS function to be exported.
        t (int): The time step used to construct the filename.
        dir_path (Path): The path to the directory where the VTK file will be saved.
    """
    # Get function info
    V = u.function_space
    vtkfile = io.VTKFile(V.mesh.comm, dir_path / f"{u.name}_{t:04d}_.pvd", "w")
    vtkfile.write_function(u, 0)
    vtkfile.close()

export_heterogeneous_parameters(model, ela_pars, dir_path)

Export the heterogeneous parameters into a VTK file.

Parameters:

Name Type Description Default
model ElasticModel

ElasticModel in gcrack.

required
ela_pars dict

Input (raw) parameters of the elastic model.

required
dir_path Path

The path to the directory where the VTK file will be saved.

required
Source code in src/gcrack/exporters.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def export_heterogeneous_parameters(model, ela_pars: dict, dir_path: Path):
    """
    Export the heterogeneous parameters into a VTK file.

    Args:
        model (gcrack.ElasticModel): ElasticModel in gcrack.
        ela_pars (dict): Input (raw) parameters of the elastic model.
        dir_path (Path): The path to the directory where the VTK file will be saved.
    """
    # At first load step, also export the heterogeneous parameters
    if isinstance(ela_pars["E"], str):
        V = model.E.function_space
        model.E.name = "Young Modulus"
        vtkfile = io.VTKFile(V.mesh.comm, dir_path / "YoungModulus.pvd", "w")
        vtkfile.write_function(model.E, 0)
        vtkfile.close()
    if isinstance(ela_pars["nu"], str):
        V = model.nu.function_space
        model.nu.name = "Poisson Ratio"
        vtkfile = io.VTKFile(V.mesh.comm, dir_path / "PoissonRatio.pvd", "w")
        vtkfile.write_function(model.nu, 0)
        vtkfile.close()

export_res_to_csv(res, filename)

Append the res dictionary to a CSV file.

This function appends the contents of a dictionary to a CSV file. The keys of the dictionary become the column headers in the CSV file, and the values are appended to the associated column.

Parameters:

Name Type Description Default
res dict

The dictionary containing row data to be appended. The keys are column headers and the values are the row values.

required
filename str

The name of the CSV file to be created.

required
Source code in src/gcrack/exporters.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def export_res_to_csv(res: dict, filename: str):
    """
    Append the res dictionary to a CSV file.

    This function appends the contents of a dictionary to a CSV file. The keys of the dictionary
    become the column headers in the CSV file, and the values are appended to the associated column.

    Args:
        res (dict): The dictionary containing row data to be appended.
                     The keys are column headers and the values are the row values.
        filename (str): The name of the CSV file to be created.
    """
    with open(filename, mode="a", newline="", encoding="utf-8") as file:
        writer = csv.DictWriter(file, fieldnames=list(res.keys()))
        if res["t"] == 0:
            writer.writeheader()
        writer.writerow(res)