Skip to content

utilities API

yabplot.utils.load_gii(gii_path)

Load GIfTI geometry (vertices, faces).

Source code in yabplot/utils.py
 8
 9
10
11
12
13
def load_gii(gii_path):
    """Load GIfTI geometry (vertices, faces)."""
    mesh = nib.load(gii_path)
    verts = mesh.darrays[0].data
    faces = mesh.darrays[1].data
    return verts, faces

yabplot.utils.load_gii2pv(gii_path, smooth_i=0, smooth_f=0.1)

Load GIfTI and convert to PyVista format with optional smoothing.

Parameters:

Name Type Description Default
smooth_i int

Number of smoothing iterations (e.g. 15).

0
smooth_f float

Relaxation factor (0.0 to 1.0, e.g. 0.6).

0.1
Source code in yabplot/utils.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def load_gii2pv(gii_path, smooth_i=0, smooth_f=0.1):
    """
    Load GIfTI and convert to PyVista format with optional smoothing.

    Parameters
    ----------
    smooth_i : int
        Number of smoothing iterations (e.g. 15).
    smooth_f : float
        Relaxation factor (0.0 to 1.0, e.g. 0.6).
    """
    verts, faces = load_gii(gii_path)

    # create pyvista mesh
    faces_pv = np.hstack([np.full((faces.shape[0], 1), 3), faces]).flatten().astype(int)
    mesh = pv.PolyData(verts, faces_pv)

    # apply smoothing
    if smooth_i > 0:
        # use Laplacian smoothing (standard vtkSmoothPolyDataFilter)
        # note: higher relaxation factors can shrink the mesh significantly
        # if shrinkage is an issue, could consider mesh.smooth_taubin() instead
        mesh = mesh.smooth(n_iter=smooth_i, relaxation_factor=smooth_f)

    return mesh

yabplot.utils.array_to_gifti(arr, out_path)

Save a 1D numpy array as a GIFTI metric file.

Parameters:

Name Type Description Default
arr ndarray

1D array of shape (n_vertices,).

required
out_path str

Output path, e.g. 'input.L.func.gii'.

required
Source code in yabplot/utils.py
41
42
43
44
45
46
47
48
49
50
51
52
53
def array_to_gifti(arr, out_path):
    """Save a 1D numpy array as a GIFTI metric file.

    Parameters
    ----------
    arr : np.ndarray
        1D array of shape (n_vertices,).
    out_path : str
        Output path, e.g. 'input.L.func.gii'.
    """
    darray = nib.gifti.GiftiDataArray(arr.astype(np.float32))
    img = nib.gifti.GiftiImage(darrays=[darray])
    nib.save(img, out_path)

yabplot.utils.load_tsf(tsf_path)

Reads an MRtrix3 .tsf (track scalar file). Useful for users who have already computed tractometry metrics using MRtrix3's tcksample command and want to plot the resulting values in yabplot.

Parameters:

Name Type Description Default
tsf_path str

absolute path to the .tsf file.

required

Returns:

Type Description
ndarray

1D array of scalar values for the streamlines.

Source code in yabplot/utils.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def load_tsf(tsf_path: str) -> np.ndarray:
    """
    Reads an MRtrix3 .tsf (track scalar file). Useful for users who 
    have already computed tractometry metrics using MRtrix3's `tcksample` 
    command and want to plot the resulting values in yabplot.

    Parameters
    ----------
    tsf_path : str
        absolute path to the .tsf file.

    Returns
    -------
    numpy.ndarray
        1D array of scalar values for the streamlines.
    """
    if not os.path.isfile(tsf_path):
        raise FileNotFoundError(f"File not found: {tsf_path}")

    header: dict[str, str] = {}
    data_offset: int | None = None

    with open(tsf_path, "rb") as fh:
        # first line must be the magic string
        magic_line = fh.readline().decode("ascii", errors="replace").strip()
        if not magic_line.lower().startswith("mrtrix track scalars"):
            raise ValueError(
                "Not a valid MRtrix TSF file (missing 'mrtrix track scalars' magic)."
            )
        header["magic"] = magic_line

        while True:
            line = fh.readline()
            if not line:
                raise ValueError("Unexpected end of file while reading header.")
            line = line.decode("ascii", errors="replace").strip()
            if line == "END":
                break

            # parse "key: value" pairs
            colon_pos = line.find(":")
            if colon_pos > 0:
                key = line[:colon_pos].strip()
                value = line[colon_pos + 1 :].strip()
                header[key] = value

                # capture the data offset
                if key.lower() == "file":
                    parts = value.split()
                    data_offset = int(parts[-1])

        if data_offset is None:
            raise ValueError("Could not determine data offset from header.")

        # read the binary data
        fh.seek(data_offset)
        raw_bytes = fh.read()

    # determine byte order from header
    datatype = header.get("datatype", "Float32LE").lower()
    byte_order = ">" if datatype.endswith("be") else "<"

    if "64" in datatype:
        dtype = np.dtype(f"{byte_order}f8")
    else:
        dtype = np.dtype(f"{byte_order}f4")

    # trim any trailing bytes that don't fill a complete element
    element_size = dtype.itemsize
    usable = len(raw_bytes) - (len(raw_bytes) % element_size)
    raw_data = np.frombuffer(raw_bytes[:usable], dtype=dtype)

    # split into per-streamline vectors
    inf_mask = np.isinf(raw_data)
    inf_indices = np.where(inf_mask)[0]
    if inf_indices.size > 0:
        raw_data = raw_data[: inf_indices[0]]

    nan_mask = np.isnan(raw_data)
    return raw_data[~nan_mask]