Skip to content

plot_utils

Generate points on a sphere.

Source code in navis/plotting/plot_utils.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def fibonacci_sphere(samples: int = 1, randomize: bool = True) -> list:
    """Generate points on a sphere."""
    rnd = 1.0
    if randomize:
        rnd = random.random() * samples

    points = []
    offset = 2.0 / samples
    increment = math.pi * (3.0 - math.sqrt(5.0))

    for i in range(samples):
        y = ((i * offset) - 1) + (offset / 2)
        r = math.sqrt(1 - pow(y, 2))

        phi = ((i + rnd) % samples) * increment

        x = math.cos(phi) * r
        z = math.sin(phi) * r

        points.append([x, y, z])

    return np.array(points)

Generate tube mesh (vertices + faces) from lines.

This code was modified from the vispy library.

PARAMETER DESCRIPTION
segments
        List of lists of x/y/z coordinates.

TYPE: list

radii
        Either a single radius used for all nodes or list of lists of
        floats with the same shape as `segments`.

TYPE: float | list of floats DEFAULT: 1.0

tube_points
        Number of points making up the circle of the cross-section
        of the tube.

TYPE: int DEFAULT: 8

use_normals
        If True will rotate tube along it's curvature.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
vertices

TYPE: np.ndarray

faces

TYPE: np.ndarray

Source code in navis/plotting/plot_utils.py
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def make_tube(segments, radii=1.0, tube_points=8, use_normals=True):
    """Generate tube mesh (vertices + faces) from lines.

    This code was modified from the vispy library.

    Parameters
    ----------
    segments :      list
                    List of lists of x/y/z coordinates.
    radii :         float | list of floats
                    Either a single radius used for all nodes or list of lists of
                    floats with the same shape as `segments`.
    tube_points :   int
                    Number of points making up the circle of the cross-section
                    of the tube.
    use_normals :   bool
                    If True will rotate tube along it's curvature.

    Returns
    -------
    vertices :      np.ndarray
    faces :         np.ndarray

    """
    vertices = np.empty((0, 3), dtype=np.float_)
    indices = np.empty((0, 3), dtype=np.uint32)

    if not isinstance(radii, Iterable):
        radii = [[radii] * len(points) for points in segments]

    for points, radius in zip(segments, radii):
        # Need to make sure points are floats
        points = np.array(points).astype(float)

        # Skip single points
        if len(points) < 2:
            continue

        if use_normals:
            _, normals, binormals = _frenet_frames(points)
        else:
            _ = normals = binormals = np.ones((len(points), 3))

        n_segments = len(points) - 1

        if not isinstance(radius, Iterable):
            radius = [radius] * len(points)

        radius = np.array(radius)

        # Vertices for each point on the circle
        verts = np.repeat(points, tube_points, axis=0)

        v = np.arange(tube_points, dtype=np.float_) / tube_points * 2 * np.pi

        all_cx = (
            radius
            * -1.0
            * np.tile(np.cos(v), points.shape[0]).reshape(
                (tube_points, points.shape[0]), order="F"
            )
        ).T
        cx_norm = (all_cx[:, :, np.newaxis] * normals[:, np.newaxis, :]).reshape(
            verts.shape
        )

        all_cy = (
            radius
            * np.tile(np.sin(v), points.shape[0]).reshape(
                (tube_points, points.shape[0]), order="F"
            )
        ).T
        cy_norm = (all_cy[:, :, np.newaxis] * binormals[:, np.newaxis, :]).reshape(
            verts.shape
        )

        verts = verts + cx_norm + cy_norm

        # Generate indices for the first segment
        ix = np.arange(0, tube_points)

        # Repeat indices n_segments-times
        ix = np.tile(ix, n_segments)

        # Offset indices by number segments and tube points
        offsets = np.repeat((np.arange(0, n_segments)) * tube_points, tube_points)
        ix += offsets

        # Turn indices into faces
        ix_a = ix
        ix_b = ix + tube_points

        ix_c = ix_b.reshape((n_segments, tube_points))
        ix_c = np.append(ix_c[:, 1:], ix_c[:, [0]], axis=1)
        ix_c = ix_c.ravel()

        ix_d = ix_a.reshape((n_segments, tube_points))
        ix_d = np.append(ix_d[:, 1:], ix_d[:, [0]], axis=1)
        ix_d = ix_d.ravel()

        faces1 = np.concatenate((ix_a, ix_b, ix_d), axis=0).reshape(
            (n_segments * tube_points, 3), order="F"
        )
        faces2 = np.concatenate((ix_b, ix_c, ix_d), axis=0).reshape(
            (n_segments * tube_points, 3), order="F"
        )

        faces = np.append(faces1, faces2, axis=0)

        # Offset faces against already existing vertices
        faces += vertices.shape[0]

        # Add vertices and faces to total collection
        vertices = np.append(vertices, verts, axis=0)
        indices = np.append(indices, faces, axis=0)

    return vertices, indices

Generate a 4x4 rotation matrix for rotation about a vector.

Modified from vispy.utils.transforms.

PARAMETER DESCRIPTION
angle
    The angle of rotation, in degrees.

TYPE: float

axis
    The x, y, z coordinates of the axis direction vector.

TYPE: ndarray

RETURNS DESCRIPTION
M

Transformation matrix describing the rotation.

TYPE: ndarray

Source code in navis/plotting/plot_utils.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def rotate(angle, axis, dtype=None):
    """Generate a 4x4 rotation matrix for rotation about a vector.

    Modified from `vispy.utils.transforms`.

    Parameters
    ----------
    angle :     float
                The angle of rotation, in degrees.
    axis :      ndarray
                The x, y, z coordinates of the axis direction vector.

    Returns
    -------
    M :     ndarray
            Transformation matrix describing the rotation.

    """
    angle = np.radians(angle)
    assert len(axis) == 3
    x, y, z = axis / np.linalg.norm(axis)
    c, s = math.cos(angle), math.sin(angle)
    cx, cy, cz = (1 - c) * x, (1 - c) * y, (1 - c) * z
    M = np.array(
        [
            [cx * x + c, cy * x - z * s, cz * x + y * s, 0.0],
            [cx * y + z * s, cy * y + c, cz * y - x * s, 0.0],
            [cx * z - y * s, cy * z + x * s, cz * z + c, 0.0],
            [0.0, 0.0, 0.0, 1.0],
        ],
        dtype,
    ).T
    return M