Skip to content

Visualization Module

LONVisualizer

Visualizer for Local Optima Networks.

Produces 2D and 3D visualizations of LON and CMLON graphs, including static images and animated GIFs.

Example

viz = LONVisualizer() viz.plot_2d(lon, output_path="lon.png") viz.plot_3d(cmlon, output_path="cmlon_3d.png")

Source code in src/lonpy/visualization.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 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
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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
class LONVisualizer:
    """
    Visualizer for Local Optima Networks.

    Produces 2D and 3D visualizations of LON and CMLON graphs,
    including static images and animated GIFs.

    Example:
        >>> viz = LONVisualizer()
        >>> viz.plot_2d(lon, output_path="lon.png")
        >>> viz.plot_3d(cmlon, output_path="cmlon_3d.png")
    """

    def __init__(
        self,
        min_edge_width: float = 1.0,
        max_edge_width: float = 3.0,
        min_node_size: float = 2.0,
        max_node_size: float = 8.0,
        arrow_size: float = 0.2,
        alpha: int = 255,
    ):
        """
        Initialize visualizer.

        Args:
            min_edge_width: Minimum edge width.
            max_edge_width: Maximum edge width.
            min_node_size: Minimum node size.
            max_node_size: Maximum node size.
            arrow_size: Arrow size for directed edges.
            alpha: Alpha value for colors (0-255).
        """
        self.min_edge_width = min_edge_width
        self.max_edge_width = max_edge_width
        self.min_node_size = min_node_size
        self.max_node_size = max_node_size
        self.arrow_size = arrow_size
        self.alpha = alpha

    def compute_edge_widths(self, graph) -> list[float]:
        """Compute edge widths based on edge weight (Count attribute)."""
        if graph.ecount() == 0:
            return [1.0]

        counts = graph.es["Count"] if "Count" in graph.es.attributes() else [1] * graph.ecount()
        max_count = max(counts) if counts else 1

        widths = []
        for c in counts:
            w = (self.max_edge_width * c) / max_count
            w = max(w, self.min_edge_width)
            w = min(w, self.max_edge_width)
            widths.append(w)

        return widths

    def compute_node_sizes(self, graph) -> list[float]:
        """Compute node sizes based on incoming strength (weighted degree)."""
        if graph.ecount() == 0:
            return [self.max_node_size] * graph.vcount()

        weights = graph.es["Count"] if "Count" in graph.es.attributes() else None
        strengths = graph.strength(mode="in", weights=weights)

        sizes = []
        for s in strengths:
            size = 2 * s
            size = max(size, self.min_node_size)
            size = min(size, self.max_node_size)
            sizes.append(size)

        return sizes

    def compute_lon_colors(self, lon: LON) -> list[str]:
        """Compute node colors for LON visualization."""
        colors = []
        fits = lon.vertex_fitness
        best = lon.best_fitness

        for f in fits:
            if f == best:
                colors.append(COLORS["lon_global"])
            else:
                colors.append(COLORS["lon_local"])

        return colors

    def compute_cmlon_colors(self, cmlon: CMLON) -> list[str]:
        """Compute node colors for CMLON visualization."""
        n_vertices = cmlon.n_vertices
        colors = [COLORS["local_basin"]] * n_vertices

        sinks = cmlon.get_sinks()
        global_sinks = cmlon.get_global_sinks()
        fits = cmlon.vertex_fitness
        best = cmlon.best_fitness

        # Color global basins (nodes that can reach global optima)
        for gs in global_sinks:
            component = cmlon.graph.subcomponent(gs, mode="in")
            for v in component:
                colors[v] = COLORS["global_basin"]

        # Color suboptimal sinks
        for s in sinks:
            if fits[s] != best:
                colors[s] = COLORS["local_sink"]

        # Color global optima (overrides basin color)
        for i, f in enumerate(fits):
            if f == best:
                colors[i] = COLORS["global_optimum"]

        return colors

    def get_layout(self, graph, seed: int | None = None) -> np.ndarray:
        """Get 2D layout coordinates for graph nodes."""
        if seed is not None:
            np.random.seed(seed)
            ig.set_random_number_generator(random.Random(seed))
        layout = graph.layout_auto()
        return np.array(layout.coords)

    def plot_2d(
        self,
        lon_or_cmlon: LON | CMLON,
        output_path: str | Path | None = None,
        figsize: tuple[int, int] = (8, 8),
        dpi: int = 100,
        seed: int | None = None,
    ) -> plt.Figure:
        """
        Create 2D plot of LON or CMLON.

        Args:
            lon_or_cmlon: LON or CMLON instance.
            output_path: Path to save PNG (optional).
            figsize: Figure size in inches.
            dpi: DPI for output.
            seed: Random seed for reproducible layout.

        Returns:
            matplotlib Figure.
        """
        graph = lon_or_cmlon.graph

        edge_widths = self.compute_edge_widths(graph)
        node_sizes = self.compute_node_sizes(graph)

        node_colors = (
            self.compute_cmlon_colors(lon_or_cmlon)
            if isinstance(lon_or_cmlon, CMLON)
            else self.compute_lon_colors(lon_or_cmlon)
        )
        layout = self.get_layout(graph, seed=seed)

        # Create figure
        fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
        ax.set_aspect("equal")
        ax.axis("off")

        # Draw edges
        if graph.ecount() > 0:
            for i, edge in enumerate(graph.es):
                src_idx = edge.source
                tgt_idx = edge.target

                x0, y0 = layout[src_idx]
                x1, y1 = layout[tgt_idx]

                # Draw arrow
                ax.annotate(
                    "",
                    xy=(x1, y1),
                    xytext=(x0, y0),
                    arrowprops=dict(
                        arrowstyle=f"->,head_length={self.arrow_size},head_width={self.arrow_size}",
                        color=COLORS["edge"],
                        lw=edge_widths[i],
                        shrinkA=node_sizes[src_idx] * 2,
                        shrinkB=node_sizes[tgt_idx] * 2,
                    ),
                )

        # Scale node sizes for matplotlib
        scatter_sizes = [s**2 * 10 for s in node_sizes]

        ax.scatter(
            layout[:, 0],
            layout[:, 1],
            s=scatter_sizes,
            c=node_colors,
            edgecolors="black",
            linewidths=0.5,
            zorder=10,
        )

        plt.tight_layout()

        if output_path:
            fig.savefig(output_path, dpi=dpi, bbox_inches="tight", facecolor="white")

        return fig

    def plot_3d(
        self,
        lon_or_cmlon: LON | CMLON,
        output_path: str | Path | None = None,
        width: int = 800,
        height: int = 800,
        seed: int | None = None,
    ) -> go.Figure:
        """
        Create 3D plot with fitness as Z-axis.

        Args:
            lon_or_cmlon: LON or CMLON instance.
            output_path: Path to save PNG (optional).
            width: Image width in pixels.
            height: Image height in pixels.
            seed: Random seed for reproducible layout.

        Returns:
            plotly Figure.
        """
        graph = lon_or_cmlon.graph

        edge_widths = self.compute_edge_widths(graph)
        node_sizes = self.compute_node_sizes(graph)

        node_colors = (
            self.compute_cmlon_colors(lon_or_cmlon)
            if isinstance(lon_or_cmlon, CMLON)
            else self.compute_lon_colors(lon_or_cmlon)
        )

        layout = self.get_layout(graph, seed=seed)

        z_coords = np.array(lon_or_cmlon.vertex_fitness)

        x = layout[:, 0]
        y = layout[:, 1]
        z = z_coords

        fig = go.Figure()

        # Draw edges
        if graph.ecount() > 0:
            for i, edge in enumerate(graph.es):
                src_idx = edge.source
                tgt_idx = edge.target

                fig.add_trace(
                    go.Scatter3d(
                        x=[x[src_idx], x[tgt_idx]],
                        y=[y[src_idx], y[tgt_idx]],
                        z=[z[src_idx], z[tgt_idx]],
                        mode="lines",
                        line=dict(
                            color=COLORS["edge"],
                            width=edge_widths[i] * 2,
                        ),
                        hoverinfo="none",
                        showlegend=False,
                    )
                )

        # Draw nodes
        fig.add_trace(
            go.Scatter3d(
                x=x,
                y=y,
                z=z,
                mode="markers",
                marker=dict(
                    size=np.array(node_sizes) * 2,
                    color=node_colors,
                    line=dict(color="black", width=0.5),
                ),
                hovertemplate="Fitness: %{z}<extra></extra>",
                showlegend=False,
            )
        )

        fig.update_layout(
            scene=dict(
                xaxis=dict(
                    showgrid=False,
                    showticklabels=False,
                    title="",
                    showbackground=False,
                ),
                yaxis=dict(
                    showgrid=False,
                    showticklabels=False,
                    title="",
                    showbackground=False,
                ),
                zaxis=dict(
                    showgrid=False,
                    title="Fitness",
                    showbackground=False,
                ),
                camera=dict(
                    eye=dict(x=0, y=-2, z=0.5),
                    up=dict(x=0, y=0, z=1),
                ),
                aspectmode="manual",
                aspectratio=dict(x=1, y=1, z=0.8),
            ),
            width=width,
            height=height,
            margin=dict(l=0, r=0, t=0, b=0),
            paper_bgcolor=BACKGROUND_COLOR,
            plot_bgcolor=BACKGROUND_COLOR,
        )

        if output_path:
            fig.write_image(str(output_path))

        return fig

    def create_rotation_gif(
        self,
        lon_or_cmlon: LON | CMLON,
        output_path: str | Path,
        duration: float = 3.0,
        fps: int = 10,
        width: int = 800,
        height: int = 800,
        seed: int | None = None,
        loop: int = 0,
        disposal: int = 2,
    ) -> None:
        """
        Create rotating GIF animation of 3D plot.

        Args:
            lon_or_cmlon: LON or CMLON instance.
            output_path: Path to save GIF.
            duration: Animation duration in seconds.
            fps: Frames per second.
            width: Image width in pixels.
            height: Image height in pixels.
            seed: Random seed for reproducible layout.
            loop: GIF loop count (0 = infinite).
            disposal: GIF disposal method. Use 2 (restore to background) to avoid frame overlap.
        """
        output_path = _ensure_parent_dir(output_path)
        graph = lon_or_cmlon.graph

        edge_widths = self.compute_edge_widths(graph)
        node_sizes = self.compute_node_sizes(graph)

        node_colors = (
            self.compute_cmlon_colors(lon_or_cmlon)
            if isinstance(lon_or_cmlon, CMLON)
            else self.compute_lon_colors(lon_or_cmlon)
        )

        layout = self.get_layout(graph, seed=seed)

        z_coords = np.array(lon_or_cmlon.vertex_fitness)
        x = layout[:, 0]
        y = layout[:, 1]
        z = z_coords

        total_frames = int(duration * fps)
        angles = np.linspace(0, 2 * np.pi, total_frames)

        frames: list[np.ndarray] = []

        try:
            for angle in angles:
                fig = go.Figure()

                # Draw edges
                if graph.ecount() > 0:
                    for j, edge in enumerate(graph.es):
                        src_idx = edge.source
                        tgt_idx = edge.target

                        fig.add_trace(
                            go.Scatter3d(
                                x=[x[src_idx], x[tgt_idx]],
                                y=[y[src_idx], y[tgt_idx]],
                                z=[z[src_idx], z[tgt_idx]],
                                mode="lines",
                                line=dict(color=COLORS["edge"], width=edge_widths[j] * 2),
                                hoverinfo="none",
                                showlegend=False,
                            )
                        )

                # Draw nodes
                fig.add_trace(
                    go.Scatter3d(
                        x=x,
                        y=y,
                        z=z,
                        mode="markers",
                        marker=dict(
                            size=np.array(node_sizes) * 2,
                            color=node_colors,
                            line=dict(color="black", width=0.5),
                        ),
                        showlegend=False,
                    )
                )

                # Rotating camera
                cam_dist = 2.0
                eye_x = cam_dist * np.sin(angle)
                eye_y = -cam_dist * np.cos(angle)
                eye_z = 0.5

                fig.update_layout(
                    scene=dict(
                        xaxis=dict(
                            showgrid=False,
                            showticklabels=False,
                            title="",
                            showbackground=False,
                        ),
                        yaxis=dict(
                            showgrid=False,
                            showticklabels=False,
                            title="",
                            showbackground=False,
                        ),
                        zaxis=dict(
                            showgrid=False,
                            title="Fitness",
                            showbackground=False,
                        ),
                        camera=dict(
                            eye=dict(x=eye_x, y=eye_y, z=eye_z),
                            up=dict(x=0, y=0, z=1),
                        ),
                        aspectmode="manual",
                        aspectratio=dict(x=1, y=1, z=0.8),
                    ),
                    width=width,
                    height=height,
                    margin=dict(l=0, r=0, t=0, b=0),
                    paper_bgcolor=BACKGROUND_COLOR,
                    plot_bgcolor=BACKGROUND_COLOR,
                )

                # Render directly to memory (avoids temp files and stray alpha blending)
                png_bytes = fig.to_image(format="png", width=width, height=height, scale=1)
                frames.append(imageio.v3.imread(png_bytes, extension=".png"))

            imageio.mimsave(
                str(output_path),
                frames,
                fps=fps,
                loop=loop,
                disposal=disposal,
            )

        finally:
            # Backwards-compat: older versions created temp frames on disk.
            temp_dir = Path(output_path).parent / ".temp_frames"
            if temp_dir.exists():
                shutil.rmtree(temp_dir)

    def visualize_all(
        self,
        lon: LON,
        output_folder: str | Path,
        seed: int | None = None,
    ) -> dict[str, Path]:
        """
        Create all visualizations for a LON.

        Generates a complete set of visualizations:
        - lon.png: 2D LON plot
        - cmlon.png: 2D CMLON plot
        - 3D_lon.png: 3D LON plot
        - 3D_cmlon.png: 3D CMLON plot
        - lon.gif: Rotating 3D LON animation
        - cmlon.gif: Rotating 3D CMLON animation

        Args:
            lon: LON instance.
            output_folder: Output directory path.
            create_gifs: Whether to create rotation GIFs (slower).
            seed: Random seed for reproducible layouts.

        Returns:
            Dictionary mapping output type to file path.
        """
        output_folder = Path(output_folder)
        output_folder.mkdir(parents=True, exist_ok=True)

        outputs = {}

        # Create CMLON
        cmlon = lon.to_cmlon()

        # 2D plots
        lon_2d_path = output_folder / "lon.png"
        self.plot_2d(lon, output_path=lon_2d_path, seed=seed)
        outputs["lon_2d"] = lon_2d_path
        plt.close()

        cmlon_2d_path = output_folder / "cmlon.png"
        self.plot_2d(cmlon, output_path=cmlon_2d_path, seed=seed)
        outputs["cmlon_2d"] = cmlon_2d_path
        plt.close()

        # 3D plots
        lon_3d_path = output_folder / "3D_lon.png"
        self.plot_3d(lon, output_path=lon_3d_path, seed=seed)
        outputs["lon_3d"] = lon_3d_path

        cmlon_3d_path = output_folder / "3D_cmlon.png"
        self.plot_3d(cmlon, output_path=cmlon_3d_path, seed=seed)
        outputs["cmlon_3d"] = cmlon_3d_path

        lon_gif_path = output_folder / "lon.gif"
        self.create_rotation_gif(lon, output_path=lon_gif_path, seed=seed)
        outputs["lon_gif"] = lon_gif_path

        cmlon_gif_path = output_folder / "cmlon.gif"
        self.create_rotation_gif(cmlon, output_path=cmlon_gif_path, seed=seed)
        outputs["cmlon_gif"] = cmlon_gif_path

        return outputs

plot_2d(lon_or_cmlon: LON | CMLON, output_path: str | Path | None = None, figsize: tuple[int, int] = (8, 8), dpi: int = 100, seed: int | None = None) -> plt.Figure

Create 2D plot of LON or CMLON.

Parameters:

Name Type Description Default
lon_or_cmlon LON | CMLON

LON or CMLON instance.

required
output_path str | Path | None

Path to save PNG (optional).

None
figsize tuple[int, int]

Figure size in inches.

(8, 8)
dpi int

DPI for output.

100
seed int | None

Random seed for reproducible layout.

None

Returns:

Type Description
Figure

matplotlib Figure.

Source code in src/lonpy/visualization.py
def plot_2d(
    self,
    lon_or_cmlon: LON | CMLON,
    output_path: str | Path | None = None,
    figsize: tuple[int, int] = (8, 8),
    dpi: int = 100,
    seed: int | None = None,
) -> plt.Figure:
    """
    Create 2D plot of LON or CMLON.

    Args:
        lon_or_cmlon: LON or CMLON instance.
        output_path: Path to save PNG (optional).
        figsize: Figure size in inches.
        dpi: DPI for output.
        seed: Random seed for reproducible layout.

    Returns:
        matplotlib Figure.
    """
    graph = lon_or_cmlon.graph

    edge_widths = self.compute_edge_widths(graph)
    node_sizes = self.compute_node_sizes(graph)

    node_colors = (
        self.compute_cmlon_colors(lon_or_cmlon)
        if isinstance(lon_or_cmlon, CMLON)
        else self.compute_lon_colors(lon_or_cmlon)
    )
    layout = self.get_layout(graph, seed=seed)

    # Create figure
    fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
    ax.set_aspect("equal")
    ax.axis("off")

    # Draw edges
    if graph.ecount() > 0:
        for i, edge in enumerate(graph.es):
            src_idx = edge.source
            tgt_idx = edge.target

            x0, y0 = layout[src_idx]
            x1, y1 = layout[tgt_idx]

            # Draw arrow
            ax.annotate(
                "",
                xy=(x1, y1),
                xytext=(x0, y0),
                arrowprops=dict(
                    arrowstyle=f"->,head_length={self.arrow_size},head_width={self.arrow_size}",
                    color=COLORS["edge"],
                    lw=edge_widths[i],
                    shrinkA=node_sizes[src_idx] * 2,
                    shrinkB=node_sizes[tgt_idx] * 2,
                ),
            )

    # Scale node sizes for matplotlib
    scatter_sizes = [s**2 * 10 for s in node_sizes]

    ax.scatter(
        layout[:, 0],
        layout[:, 1],
        s=scatter_sizes,
        c=node_colors,
        edgecolors="black",
        linewidths=0.5,
        zorder=10,
    )

    plt.tight_layout()

    if output_path:
        fig.savefig(output_path, dpi=dpi, bbox_inches="tight", facecolor="white")

    return fig

plot_3d(lon_or_cmlon: LON | CMLON, output_path: str | Path | None = None, width: int = 800, height: int = 800, seed: int | None = None) -> go.Figure

Create 3D plot with fitness as Z-axis.

Parameters:

Name Type Description Default
lon_or_cmlon LON | CMLON

LON or CMLON instance.

required
output_path str | Path | None

Path to save PNG (optional).

None
width int

Image width in pixels.

800
height int

Image height in pixels.

800
seed int | None

Random seed for reproducible layout.

None

Returns:

Type Description
Figure

plotly Figure.

Source code in src/lonpy/visualization.py
def plot_3d(
    self,
    lon_or_cmlon: LON | CMLON,
    output_path: str | Path | None = None,
    width: int = 800,
    height: int = 800,
    seed: int | None = None,
) -> go.Figure:
    """
    Create 3D plot with fitness as Z-axis.

    Args:
        lon_or_cmlon: LON or CMLON instance.
        output_path: Path to save PNG (optional).
        width: Image width in pixels.
        height: Image height in pixels.
        seed: Random seed for reproducible layout.

    Returns:
        plotly Figure.
    """
    graph = lon_or_cmlon.graph

    edge_widths = self.compute_edge_widths(graph)
    node_sizes = self.compute_node_sizes(graph)

    node_colors = (
        self.compute_cmlon_colors(lon_or_cmlon)
        if isinstance(lon_or_cmlon, CMLON)
        else self.compute_lon_colors(lon_or_cmlon)
    )

    layout = self.get_layout(graph, seed=seed)

    z_coords = np.array(lon_or_cmlon.vertex_fitness)

    x = layout[:, 0]
    y = layout[:, 1]
    z = z_coords

    fig = go.Figure()

    # Draw edges
    if graph.ecount() > 0:
        for i, edge in enumerate(graph.es):
            src_idx = edge.source
            tgt_idx = edge.target

            fig.add_trace(
                go.Scatter3d(
                    x=[x[src_idx], x[tgt_idx]],
                    y=[y[src_idx], y[tgt_idx]],
                    z=[z[src_idx], z[tgt_idx]],
                    mode="lines",
                    line=dict(
                        color=COLORS["edge"],
                        width=edge_widths[i] * 2,
                    ),
                    hoverinfo="none",
                    showlegend=False,
                )
            )

    # Draw nodes
    fig.add_trace(
        go.Scatter3d(
            x=x,
            y=y,
            z=z,
            mode="markers",
            marker=dict(
                size=np.array(node_sizes) * 2,
                color=node_colors,
                line=dict(color="black", width=0.5),
            ),
            hovertemplate="Fitness: %{z}<extra></extra>",
            showlegend=False,
        )
    )

    fig.update_layout(
        scene=dict(
            xaxis=dict(
                showgrid=False,
                showticklabels=False,
                title="",
                showbackground=False,
            ),
            yaxis=dict(
                showgrid=False,
                showticklabels=False,
                title="",
                showbackground=False,
            ),
            zaxis=dict(
                showgrid=False,
                title="Fitness",
                showbackground=False,
            ),
            camera=dict(
                eye=dict(x=0, y=-2, z=0.5),
                up=dict(x=0, y=0, z=1),
            ),
            aspectmode="manual",
            aspectratio=dict(x=1, y=1, z=0.8),
        ),
        width=width,
        height=height,
        margin=dict(l=0, r=0, t=0, b=0),
        paper_bgcolor=BACKGROUND_COLOR,
        plot_bgcolor=BACKGROUND_COLOR,
    )

    if output_path:
        fig.write_image(str(output_path))

    return fig

create_rotation_gif(lon_or_cmlon: LON | CMLON, output_path: str | Path, duration: float = 3.0, fps: int = 10, width: int = 800, height: int = 800, seed: int | None = None, loop: int = 0, disposal: int = 2) -> None

Create rotating GIF animation of 3D plot.

Parameters:

Name Type Description Default
lon_or_cmlon LON | CMLON

LON or CMLON instance.

required
output_path str | Path

Path to save GIF.

required
duration float

Animation duration in seconds.

3.0
fps int

Frames per second.

10
width int

Image width in pixels.

800
height int

Image height in pixels.

800
seed int | None

Random seed for reproducible layout.

None
loop int

GIF loop count (0 = infinite).

0
disposal int

GIF disposal method. Use 2 (restore to background) to avoid frame overlap.

2
Source code in src/lonpy/visualization.py
def create_rotation_gif(
    self,
    lon_or_cmlon: LON | CMLON,
    output_path: str | Path,
    duration: float = 3.0,
    fps: int = 10,
    width: int = 800,
    height: int = 800,
    seed: int | None = None,
    loop: int = 0,
    disposal: int = 2,
) -> None:
    """
    Create rotating GIF animation of 3D plot.

    Args:
        lon_or_cmlon: LON or CMLON instance.
        output_path: Path to save GIF.
        duration: Animation duration in seconds.
        fps: Frames per second.
        width: Image width in pixels.
        height: Image height in pixels.
        seed: Random seed for reproducible layout.
        loop: GIF loop count (0 = infinite).
        disposal: GIF disposal method. Use 2 (restore to background) to avoid frame overlap.
    """
    output_path = _ensure_parent_dir(output_path)
    graph = lon_or_cmlon.graph

    edge_widths = self.compute_edge_widths(graph)
    node_sizes = self.compute_node_sizes(graph)

    node_colors = (
        self.compute_cmlon_colors(lon_or_cmlon)
        if isinstance(lon_or_cmlon, CMLON)
        else self.compute_lon_colors(lon_or_cmlon)
    )

    layout = self.get_layout(graph, seed=seed)

    z_coords = np.array(lon_or_cmlon.vertex_fitness)
    x = layout[:, 0]
    y = layout[:, 1]
    z = z_coords

    total_frames = int(duration * fps)
    angles = np.linspace(0, 2 * np.pi, total_frames)

    frames: list[np.ndarray] = []

    try:
        for angle in angles:
            fig = go.Figure()

            # Draw edges
            if graph.ecount() > 0:
                for j, edge in enumerate(graph.es):
                    src_idx = edge.source
                    tgt_idx = edge.target

                    fig.add_trace(
                        go.Scatter3d(
                            x=[x[src_idx], x[tgt_idx]],
                            y=[y[src_idx], y[tgt_idx]],
                            z=[z[src_idx], z[tgt_idx]],
                            mode="lines",
                            line=dict(color=COLORS["edge"], width=edge_widths[j] * 2),
                            hoverinfo="none",
                            showlegend=False,
                        )
                    )

            # Draw nodes
            fig.add_trace(
                go.Scatter3d(
                    x=x,
                    y=y,
                    z=z,
                    mode="markers",
                    marker=dict(
                        size=np.array(node_sizes) * 2,
                        color=node_colors,
                        line=dict(color="black", width=0.5),
                    ),
                    showlegend=False,
                )
            )

            # Rotating camera
            cam_dist = 2.0
            eye_x = cam_dist * np.sin(angle)
            eye_y = -cam_dist * np.cos(angle)
            eye_z = 0.5

            fig.update_layout(
                scene=dict(
                    xaxis=dict(
                        showgrid=False,
                        showticklabels=False,
                        title="",
                        showbackground=False,
                    ),
                    yaxis=dict(
                        showgrid=False,
                        showticklabels=False,
                        title="",
                        showbackground=False,
                    ),
                    zaxis=dict(
                        showgrid=False,
                        title="Fitness",
                        showbackground=False,
                    ),
                    camera=dict(
                        eye=dict(x=eye_x, y=eye_y, z=eye_z),
                        up=dict(x=0, y=0, z=1),
                    ),
                    aspectmode="manual",
                    aspectratio=dict(x=1, y=1, z=0.8),
                ),
                width=width,
                height=height,
                margin=dict(l=0, r=0, t=0, b=0),
                paper_bgcolor=BACKGROUND_COLOR,
                plot_bgcolor=BACKGROUND_COLOR,
            )

            # Render directly to memory (avoids temp files and stray alpha blending)
            png_bytes = fig.to_image(format="png", width=width, height=height, scale=1)
            frames.append(imageio.v3.imread(png_bytes, extension=".png"))

        imageio.mimsave(
            str(output_path),
            frames,
            fps=fps,
            loop=loop,
            disposal=disposal,
        )

    finally:
        # Backwards-compat: older versions created temp frames on disk.
        temp_dir = Path(output_path).parent / ".temp_frames"
        if temp_dir.exists():
            shutil.rmtree(temp_dir)

visualize_all(lon: LON, output_folder: str | Path, seed: int | None = None) -> dict[str, Path]

Create all visualizations for a LON.

Generates a complete set of visualizations: - lon.png: 2D LON plot - cmlon.png: 2D CMLON plot - 3D_lon.png: 3D LON plot - 3D_cmlon.png: 3D CMLON plot - lon.gif: Rotating 3D LON animation - cmlon.gif: Rotating 3D CMLON animation

Parameters:

Name Type Description Default
lon LON

LON instance.

required
output_folder str | Path

Output directory path.

required
create_gifs

Whether to create rotation GIFs (slower).

required
seed int | None

Random seed for reproducible layouts.

None

Returns:

Type Description
dict[str, Path]

Dictionary mapping output type to file path.

Source code in src/lonpy/visualization.py
def visualize_all(
    self,
    lon: LON,
    output_folder: str | Path,
    seed: int | None = None,
) -> dict[str, Path]:
    """
    Create all visualizations for a LON.

    Generates a complete set of visualizations:
    - lon.png: 2D LON plot
    - cmlon.png: 2D CMLON plot
    - 3D_lon.png: 3D LON plot
    - 3D_cmlon.png: 3D CMLON plot
    - lon.gif: Rotating 3D LON animation
    - cmlon.gif: Rotating 3D CMLON animation

    Args:
        lon: LON instance.
        output_folder: Output directory path.
        create_gifs: Whether to create rotation GIFs (slower).
        seed: Random seed for reproducible layouts.

    Returns:
        Dictionary mapping output type to file path.
    """
    output_folder = Path(output_folder)
    output_folder.mkdir(parents=True, exist_ok=True)

    outputs = {}

    # Create CMLON
    cmlon = lon.to_cmlon()

    # 2D plots
    lon_2d_path = output_folder / "lon.png"
    self.plot_2d(lon, output_path=lon_2d_path, seed=seed)
    outputs["lon_2d"] = lon_2d_path
    plt.close()

    cmlon_2d_path = output_folder / "cmlon.png"
    self.plot_2d(cmlon, output_path=cmlon_2d_path, seed=seed)
    outputs["cmlon_2d"] = cmlon_2d_path
    plt.close()

    # 3D plots
    lon_3d_path = output_folder / "3D_lon.png"
    self.plot_3d(lon, output_path=lon_3d_path, seed=seed)
    outputs["lon_3d"] = lon_3d_path

    cmlon_3d_path = output_folder / "3D_cmlon.png"
    self.plot_3d(cmlon, output_path=cmlon_3d_path, seed=seed)
    outputs["cmlon_3d"] = cmlon_3d_path

    lon_gif_path = output_folder / "lon.gif"
    self.create_rotation_gif(lon, output_path=lon_gif_path, seed=seed)
    outputs["lon_gif"] = lon_gif_path

    cmlon_gif_path = output_folder / "cmlon.gif"
    self.create_rotation_gif(cmlon, output_path=cmlon_gif_path, seed=seed)
    outputs["cmlon_gif"] = cmlon_gif_path

    return outputs

compute_edge_widths(graph) -> list[float]

Compute edge widths based on edge weight (Count attribute).

Source code in src/lonpy/visualization.py
def compute_edge_widths(self, graph) -> list[float]:
    """Compute edge widths based on edge weight (Count attribute)."""
    if graph.ecount() == 0:
        return [1.0]

    counts = graph.es["Count"] if "Count" in graph.es.attributes() else [1] * graph.ecount()
    max_count = max(counts) if counts else 1

    widths = []
    for c in counts:
        w = (self.max_edge_width * c) / max_count
        w = max(w, self.min_edge_width)
        w = min(w, self.max_edge_width)
        widths.append(w)

    return widths

compute_node_sizes(graph) -> list[float]

Compute node sizes based on incoming strength (weighted degree).

Source code in src/lonpy/visualization.py
def compute_node_sizes(self, graph) -> list[float]:
    """Compute node sizes based on incoming strength (weighted degree)."""
    if graph.ecount() == 0:
        return [self.max_node_size] * graph.vcount()

    weights = graph.es["Count"] if "Count" in graph.es.attributes() else None
    strengths = graph.strength(mode="in", weights=weights)

    sizes = []
    for s in strengths:
        size = 2 * s
        size = max(size, self.min_node_size)
        size = min(size, self.max_node_size)
        sizes.append(size)

    return sizes

compute_lon_colors(lon: LON) -> list[str]

Compute node colors for LON visualization.

Source code in src/lonpy/visualization.py
def compute_lon_colors(self, lon: LON) -> list[str]:
    """Compute node colors for LON visualization."""
    colors = []
    fits = lon.vertex_fitness
    best = lon.best_fitness

    for f in fits:
        if f == best:
            colors.append(COLORS["lon_global"])
        else:
            colors.append(COLORS["lon_local"])

    return colors

compute_cmlon_colors(cmlon: CMLON) -> list[str]

Compute node colors for CMLON visualization.

Source code in src/lonpy/visualization.py
def compute_cmlon_colors(self, cmlon: CMLON) -> list[str]:
    """Compute node colors for CMLON visualization."""
    n_vertices = cmlon.n_vertices
    colors = [COLORS["local_basin"]] * n_vertices

    sinks = cmlon.get_sinks()
    global_sinks = cmlon.get_global_sinks()
    fits = cmlon.vertex_fitness
    best = cmlon.best_fitness

    # Color global basins (nodes that can reach global optima)
    for gs in global_sinks:
        component = cmlon.graph.subcomponent(gs, mode="in")
        for v in component:
            colors[v] = COLORS["global_basin"]

    # Color suboptimal sinks
    for s in sinks:
        if fits[s] != best:
            colors[s] = COLORS["local_sink"]

    # Color global optima (overrides basin color)
    for i, f in enumerate(fits):
        if f == best:
            colors[i] = COLORS["global_optimum"]

    return colors

get_layout(graph, seed: int | None = None) -> np.ndarray

Get 2D layout coordinates for graph nodes.

Source code in src/lonpy/visualization.py
def get_layout(self, graph, seed: int | None = None) -> np.ndarray:
    """Get 2D layout coordinates for graph nodes."""
    if seed is not None:
        np.random.seed(seed)
        ig.set_random_number_generator(random.Random(seed))
    layout = graph.layout_auto()
    return np.array(layout.coords)