Skip to content

Visualization API

Auto-generated from docstrings.

visualization.ecg_plots

ECG-specific plotting utilities.

plot_ecg_leads

plot_ecg_leads(ecg: Tensor | ndarray, lead_names: list[str] = None, sampling_rate: int = 500, title: str = 'ECG Signal', figsize: tuple = (15, 10)) -> plt.Figure

Plot all 12 ECG leads.

Parameters:

Name Type Description Default
ecg Tensor | ndarray

ECG signal of shape (num_leads, seq_length)

required
lead_names list[str]

Names of leads (default: standard 12-lead names)

None
sampling_rate int

Sampling rate in Hz

500
title str

Plot title

'ECG Signal'
figsize tuple

Figure size

(15, 10)

Returns:

Type Description
Figure

matplotlib Figure object

Source code in visualization/ecg_plots.py
def plot_ecg_leads(
    ecg: Tensor | np.ndarray,
    lead_names: list[str] = None,
    sampling_rate: int = 500,
    title: str = "ECG Signal",
    figsize: tuple = (15, 10),
) -> plt.Figure:
    """
    Plot all 12 ECG leads.

    Args:
        ecg: ECG signal of shape (num_leads, seq_length)
        lead_names: Names of leads (default: standard 12-lead names)
        sampling_rate: Sampling rate in Hz
        title: Plot title
        figsize: Figure size

    Returns:
        matplotlib Figure object
    """
    if isinstance(ecg, Tensor):
        ecg = ecg.cpu().numpy()

    if lead_names is None:
        lead_names = ["I", "II", "III", "aVR", "aVL", "aVF", 
                     "V1", "V2", "V3", "V4", "V5", "V6"]

    num_leads, seq_length = ecg.shape
    time = np.arange(seq_length) / sampling_rate

    fig, axes = plt.subplots(num_leads, 1, figsize=figsize, sharex=True)

    for i, (lead, ax) in enumerate(zip(ecg, axes)):
        ax.plot(time, lead, 'b-', linewidth=0.5)
        ax.set_ylabel(lead_names[i] if i < len(lead_names) else f"Lead {i+1}")
        ax.grid(True, alpha=0.3)

    axes[-1].set_xlabel("Time (s)")
    fig.suptitle(title, fontsize=14)
    plt.tight_layout()

    return fig

plot_ecg_comparison

plot_ecg_comparison(real: Tensor | ndarray, generated: Tensor | ndarray, lead_idx: int = 0, lead_name: str = 'Lead I', sampling_rate: int = 500, figsize: tuple = (12, 4)) -> plt.Figure

Compare real and generated ECG signals for a single lead.

Parameters:

Name Type Description Default
real Tensor | ndarray

Real ECG signal

required
generated Tensor | ndarray

Generated ECG signal

required
lead_idx int

Index of lead to plot

0
lead_name str

Name of the lead

'Lead I'
sampling_rate int

Sampling rate in Hz

500
figsize tuple

Figure size

(12, 4)

Returns:

Type Description
Figure

matplotlib Figure object

Source code in visualization/ecg_plots.py
def plot_ecg_comparison(
    real: Tensor | np.ndarray,
    generated: Tensor | np.ndarray,
    lead_idx: int = 0,
    lead_name: str = "Lead I",
    sampling_rate: int = 500,
    figsize: tuple = (12, 4),
) -> plt.Figure:
    """
    Compare real and generated ECG signals for a single lead.

    Args:
        real: Real ECG signal
        generated: Generated ECG signal
        lead_idx: Index of lead to plot
        lead_name: Name of the lead
        sampling_rate: Sampling rate in Hz
        figsize: Figure size

    Returns:
        matplotlib Figure object
    """
    if isinstance(real, Tensor):
        real = real.cpu().numpy()
    if isinstance(generated, Tensor):
        generated = generated.cpu().numpy()

    seq_length = real.shape[-1]
    time = np.arange(seq_length) / sampling_rate

    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=figsize, sharex=True)

    ax1.plot(time, real[lead_idx], 'b-', linewidth=0.8, label='Real')
    ax1.set_ylabel(f"{lead_name} (Real)")
    ax1.grid(True, alpha=0.3)
    ax1.legend()

    ax2.plot(time, generated[lead_idx], 'r-', linewidth=0.8, label='Generated')
    ax2.set_ylabel(f"{lead_name} (Generated)")
    ax2.set_xlabel("Time (s)")
    ax2.grid(True, alpha=0.3)
    ax2.legend()

    plt.tight_layout()

    return fig

plot_ecg_overlay

plot_ecg_overlay(signals: list[Tensor | ndarray], labels: list[str], lead_idx: int = 0, lead_name: str = 'Lead I', sampling_rate: int = 500, figsize: tuple = (12, 4)) -> plt.Figure

Overlay multiple ECG signals for comparison.

Parameters:

Name Type Description Default
signals list[Tensor | ndarray]

List of ECG signals

required
labels list[str]

Labels for each signal

required
lead_idx int

Index of lead to plot

0
lead_name str

Name of the lead

'Lead I'
sampling_rate int

Sampling rate in Hz

500
figsize tuple

Figure size

(12, 4)

Returns:

Type Description
Figure

matplotlib Figure object

Source code in visualization/ecg_plots.py
def plot_ecg_overlay(
    signals: list[Tensor | np.ndarray],
    labels: list[str],
    lead_idx: int = 0,
    lead_name: str = "Lead I",
    sampling_rate: int = 500,
    figsize: tuple = (12, 4),
) -> plt.Figure:
    """
    Overlay multiple ECG signals for comparison.

    Args:
        signals: List of ECG signals
        labels: Labels for each signal
        lead_idx: Index of lead to plot
        lead_name: Name of the lead
        sampling_rate: Sampling rate in Hz
        figsize: Figure size

    Returns:
        matplotlib Figure object
    """
    fig, ax = plt.subplots(figsize=figsize)

    for signal, label in zip(signals, labels):
        if isinstance(signal, Tensor):
            signal = signal.cpu().numpy()

        seq_length = signal.shape[-1]
        time = np.arange(seq_length) / sampling_rate
        ax.plot(time, signal[lead_idx], linewidth=0.8, label=label, alpha=0.7)

    ax.set_xlabel("Time (s)")
    ax.set_ylabel(lead_name)
    ax.set_title(f"ECG Comparison - {lead_name}")
    ax.grid(True, alpha=0.3)
    ax.legend()

    plt.tight_layout()

    return fig

visualization.latent_space

Latent space visualization utilities.

plot_latent_space_2d

plot_latent_space_2d(latents: Tensor | ndarray, labels: ndarray = None, method: str = 'pca', title: str = 'Latent Space Visualization', figsize: tuple = (10, 8)) -> plt.Figure

Visualize latent space in 2D using PCA or t-SNE.

Parameters:

Name Type Description Default
latents Tensor | ndarray

Latent vectors of shape (n_samples, latent_dim, latent_length) or (n_samples, latent_dim)

required
labels ndarray

Optional labels for coloring points

None
method str

"pca" or "tsne"

'pca'
title str

Plot title

'Latent Space Visualization'
figsize tuple

Figure size

(10, 8)

Returns:

Type Description
Figure

matplotlib Figure object

Source code in visualization/latent_space.py
def plot_latent_space_2d(
    latents: Tensor | np.ndarray,
    labels: np.ndarray = None,
    method: str = "pca",
    title: str = "Latent Space Visualization",
    figsize: tuple = (10, 8),
) -> plt.Figure:
    """
    Visualize latent space in 2D using PCA or t-SNE.

    Args:
        latents: Latent vectors of shape (n_samples, latent_dim, latent_length)
                 or (n_samples, latent_dim)
        labels: Optional labels for coloring points
        method: "pca" or "tsne"
        title: Plot title
        figsize: Figure size

    Returns:
        matplotlib Figure object
    """
    if isinstance(latents, Tensor):
        latents = latents.cpu().numpy()

    # Flatten if needed
    if latents.ndim == 3:
        n_samples, latent_dim, latent_length = latents.shape
        latents = latents.reshape(n_samples, -1)

    # Dimensionality reduction
    if method == "pca":
        reducer = PCA(n_components=2)
        latents_2d = reducer.fit_transform(latents)
        explained_var = reducer.explained_variance_ratio_
        subtitle = f"PCA (explained variance: {explained_var[0]:.2%}, {explained_var[1]:.2%})"
    elif method == "tsne":
        reducer = TSNE(n_components=2, random_state=42)
        latents_2d = reducer.fit_transform(latents)
        subtitle = "t-SNE"
    else:
        raise ValueError(f"Unknown method: {method}")

    fig, ax = plt.subplots(figsize=figsize)

    if labels is not None:
        scatter = ax.scatter(latents_2d[:, 0], latents_2d[:, 1], 
                           c=labels, cmap='tab10', alpha=0.6, s=20)
        plt.colorbar(scatter, ax=ax, label="Label")
    else:
        ax.scatter(latents_2d[:, 0], latents_2d[:, 1], 
                  alpha=0.6, s=20, c='blue')

    ax.set_xlabel("Component 1")
    ax.set_ylabel("Component 2")
    ax.set_title(f"{title}\n{subtitle}")
    ax.grid(True, alpha=0.3)

    plt.tight_layout()

    return fig

plot_latent_distribution

plot_latent_distribution(latents: Tensor | ndarray, figsize: tuple = (12, 4)) -> plt.Figure

Plot distribution of latent dimensions.

Parameters:

Name Type Description Default
latents Tensor | ndarray

Latent vectors

required
figsize tuple

Figure size

(12, 4)

Returns:

Type Description
Figure

matplotlib Figure object

Source code in visualization/latent_space.py
def plot_latent_distribution(
    latents: Tensor | np.ndarray,
    figsize: tuple = (12, 4),
) -> plt.Figure:
    """
    Plot distribution of latent dimensions.

    Args:
        latents: Latent vectors
        figsize: Figure size

    Returns:
        matplotlib Figure object
    """
    if isinstance(latents, Tensor):
        latents = latents.cpu().numpy()

    if latents.ndim == 3:
        latents = latents.reshape(latents.shape[0], -1)

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)

    # Mean and std per dimension
    means = latents.mean(axis=0)
    stds = latents.std(axis=0)

    ax1.plot(means, 'b-', label='Mean')
    ax1.fill_between(range(len(means)), 
                     means - stds, means + stds, 
                     alpha=0.3, label='±1 std')
    ax1.set_xlabel("Latent Dimension")
    ax1.set_ylabel("Value")
    ax1.set_title("Latent Dimension Statistics")
    ax1.legend()
    ax1.grid(True, alpha=0.3)

    # Histogram of all latent values
    ax2.hist(latents.flatten(), bins=50, alpha=0.7, edgecolor='black')
    ax2.set_xlabel("Latent Value")
    ax2.set_ylabel("Frequency")
    ax2.set_title("Latent Value Distribution")
    ax2.grid(True, alpha=0.3)

    plt.tight_layout()

    return fig

visualization.training_curves

Training progress visualization utilities.

plot_training_curves

plot_training_curves(train_losses: list[float], val_losses: list[float], metric_name: str = 'Loss', figsize: tuple = (10, 6)) -> plt.Figure

Plot training and validation curves.

Parameters:

Name Type Description Default
train_losses list[float]

Training losses per epoch

required
val_losses list[float]

Validation losses per epoch

required
metric_name str

Name of the metric

'Loss'
figsize tuple

Figure size

(10, 6)

Returns:

Type Description
Figure

matplotlib Figure object

Source code in visualization/training_curves.py
def plot_training_curves(
    train_losses: list[float],
    val_losses: list[float],
    metric_name: str = "Loss",
    figsize: tuple = (10, 6),
) -> plt.Figure:
    """
    Plot training and validation curves.

    Args:
        train_losses: Training losses per epoch
        val_losses: Validation losses per epoch
        metric_name: Name of the metric
        figsize: Figure size

    Returns:
        matplotlib Figure object
    """
    epochs = range(1, len(train_losses) + 1)

    fig, ax = plt.subplots(figsize=figsize)

    ax.plot(epochs, train_losses, 'b-', label=f'Train {metric_name}', linewidth=2)
    ax.plot(epochs, val_losses, 'r-', label=f'Val {metric_name}', linewidth=2)

    ax.set_xlabel("Epoch")
    ax.set_ylabel(metric_name)
    ax.set_title(f"Training Progress - {metric_name}")
    ax.legend()
    ax.grid(True, alpha=0.3)

    plt.tight_layout()

    return fig

plot_multiple_metrics

plot_multiple_metrics(metrics_dict: dict[str, dict[str, list[float]]], figsize: tuple = (15, 10)) -> plt.Figure

Plot multiple metrics in subplots.

Parameters:

Name Type Description Default
metrics_dict dict[str, dict[str, list[float]]]

Dictionary of metrics, e.g.: {"loss": {"train": [...], "val": [...]}, "accuracy": {"train": [...], "val": [...]}}

required
figsize tuple

Figure size

(15, 10)

Returns:

Type Description
Figure

matplotlib Figure object

Source code in visualization/training_curves.py
def plot_multiple_metrics(
    metrics_dict: dict[str, dict[str, list[float]]],
    figsize: tuple = (15, 10),
) -> plt.Figure:
    """
    Plot multiple metrics in subplots.

    Args:
        metrics_dict: Dictionary of metrics, e.g.:
                     {"loss": {"train": [...], "val": [...]},
                      "accuracy": {"train": [...], "val": [...]}}
        figsize: Figure size

    Returns:
        matplotlib Figure object
    """
    n_metrics = len(metrics_dict)
    n_cols = 2
    n_rows = (n_metrics + 1) // 2

    fig, axes = plt.subplots(n_rows, n_cols, figsize=figsize)
    axes = axes.flatten() if n_metrics > 1 else [axes]

    for idx, (metric_name, values) in enumerate(metrics_dict.items()):
        ax = axes[idx]

        for split_name, split_values in values.items():
            epochs = range(1, len(split_values) + 1)
            ax.plot(epochs, split_values, label=split_name, linewidth=2)

        ax.set_xlabel("Epoch")
        ax.set_ylabel(metric_name)
        ax.set_title(metric_name.replace("_", " ").title())
        ax.legend()
        ax.grid(True, alpha=0.3)

    # Hide unused subplots
    for idx in range(n_metrics, len(axes)):
        axes[idx].set_visible(False)

    plt.tight_layout()

    return fig

plot_learning_rate_schedule

plot_learning_rate_schedule(learning_rates: list[float], figsize: tuple = (10, 4)) -> plt.Figure

Plot learning rate schedule over epochs.

Parameters:

Name Type Description Default
learning_rates list[float]

Learning rates per epoch

required
figsize tuple

Figure size

(10, 4)

Returns:

Type Description
Figure

matplotlib Figure object

Source code in visualization/training_curves.py
def plot_learning_rate_schedule(
    learning_rates: list[float],
    figsize: tuple = (10, 4),
) -> plt.Figure:
    """
    Plot learning rate schedule over epochs.

    Args:
        learning_rates: Learning rates per epoch
        figsize: Figure size

    Returns:
        matplotlib Figure object
    """
    epochs = range(1, len(learning_rates) + 1)

    fig, ax = plt.subplots(figsize=figsize)

    ax.plot(epochs, learning_rates, 'g-', linewidth=2)
    ax.set_xlabel("Epoch")
    ax.set_ylabel("Learning Rate")
    ax.set_title("Learning Rate Schedule")
    ax.set_yscale('log')
    ax.grid(True, alpha=0.3)

    plt.tight_layout()

    return fig