File size: 6,810 Bytes
8e28462
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
"""
plot_util.py — Plotting utilities for Squidiff reproducibility notebooks.

The original authors used a local private script that was not included
in the public repository. This file reimplements the required functions
based on their call signatures in the reproducibility notebooks.

Functions:
    plot_pca    -- PCA scatter plot of embeddings colored by group label.
    display_reconst -- Scatter + kernel density comparison of original
                       vs. reconstructed gene expressions.
"""

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from sklearn.decomposition import PCA
import torch


def plot_pca(
    data,
    label=None,
    size=3,
    alpha=0.8,
    colorlist=None,
    color_label=None,
    title=None,
    figsize=(3, 3),
    dpi=300,
):
    """
    Project data to 2D via PCA and render a scatter plot colored by label.

    Parameters
    ----------
    data : torch.Tensor or numpy.ndarray
        Input matrix of shape (n_cells, n_features).
    label : array-like, optional
        Group labels for each cell (e.g., obs['Group']). Used for coloring.
    size : float, optional
        Marker size for scatter points. Default is 3.
    alpha : float, optional
        Marker opacity. Default is 0.8.
    colorlist : list of str, optional
        List of hex color strings, one per unique label value.
        Default cycles through a built-in palette.
    color_label : list, optional
        Subset of label values to include in the legend. If None, all
        unique label values are shown.
    title : str, optional
        Plot title. If None, no title is shown.
    figsize : tuple, optional
        Figure size in inches. Default is (3, 3).
    dpi : int, optional
        Figure DPI. Default is 300.
    """
    # Convert torch.Tensor to numpy if necessary
    if isinstance(data, torch.Tensor):
        data = data.detach().cpu().numpy()
    else:
        data = np.array(data)

    # Reduce to 2D via PCA
    if data.shape[1] > 2:
        pca = PCA(n_components=2)
        coords = pca.fit_transform(data)
    else:
        coords = data  # Already 2D

    # Resolve labels
    if label is not None:
        labels = np.array(label)
        unique_labels = np.unique(labels)
    else:
        labels = np.zeros(len(coords), dtype=int)
        unique_labels = np.array([0])

    # Resolve colors
    default_palette = [
        '#3145a8', '#fa2616', '#40a8f7', '#f5bf36',
        '#2ca02c', '#9467bd', '#8c564b', '#e377c2',
    ]
    if colorlist is None:
        colorlist = default_palette

    # Determine which labels to show in legend
    if color_label is not None:
        legend_labels = [str(v) for v in color_label]
    else:
        legend_labels = [str(v) for v in unique_labels]

    # Plot
    fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
    handles = []
    for idx, ul in enumerate(unique_labels):
        mask = labels == ul
        color = colorlist[idx % len(colorlist)]
        ax.scatter(
            coords[mask, 0],
            coords[mask, 1],
            c=color,
            s=size,
            alpha=alpha,
            rasterized=True,
        )
        if str(ul) in legend_labels:
            handles.append(
                mpatches.Patch(color=color, label=str(ul))
            )

    ax.set_xlabel('PC1')
    ax.set_ylabel('PC2')
    if title:
        ax.set_title(title)
    if handles:
        ax.legend(handles=handles, markerscale=2, frameon=False,
                  bbox_to_anchor=(1.01, 1), loc='upper left')
    plt.tight_layout()
    plt.show()


def display_reconst(
    original_df,
    reconstructed_df,
    density=False,
    size=(2.5, 2.5),
    dpi=300,
    alpha=0.3,
    color_orig='#3145a8',
    color_reconst='#fa2616',
    xlabel='Original gene expression',
    ylabel='Reconstructed gene expression',
):
    """
    Display a scatter plot comparing original and reconstructed gene expression,
    with optional kernel-density overlays.

    Parameters
    ----------
    original_df : pandas.DataFrame or array-like
        Flattened original gene expression values.
    reconstructed_df : pandas.DataFrame or array-like
        Flattened reconstructed gene expression values.
    density : bool, optional
        If True, overlay a KDE (kernel density estimate) on 1-D marginals.
        Default is False.
    size : tuple, optional
        Figure size (width, height) in inches. Default is (2.5, 2.5).
    dpi : int, optional
        Figure DPI. Default is 300.
    alpha : float, optional
        Scatter point opacity. Default is 0.3.
    color_orig : str, optional
        Color for original values in density plot. Default is '#3145a8'.
    color_reconst : str, optional
        Color for reconstructed values in density plot. Default is '#fa2616'.
    xlabel : str, optional
        X-axis label. Default is 'Original gene expression'.
    ylabel : str, optional
        Y-axis label. Default is 'Reconstructed gene expression'.
    """
    import pandas as pd
    from scipy.stats import gaussian_kde

    # Flatten to 1-D numpy arrays
    orig = np.array(original_df).flatten()
    reconst = np.array(reconstructed_df).flatten()

    if density:
        # Two-panel layout: scatter (left) + KDE (right)
        fig, axes = plt.subplots(1, 2, figsize=(size[0] * 2, size[1]), dpi=dpi)

        # Left: scatter
        axes[0].scatter(reconst, orig, s=2, alpha=alpha, color=color_orig,
                        rasterized=True)
        axes[0].set_xlabel('Reconstructed')
        axes[0].set_ylabel('Original')
        # Diagonal reference line
        lims = [min(orig.min(), reconst.min()),
                max(orig.max(), reconst.max())]
        axes[0].plot(lims, lims, 'k--', linewidth=0.8, alpha=0.5)

        # Right: KDE of original vs reconstructed
        for vals, color, lbl in [
            (orig, color_orig, 'Original'),
            (reconst, color_reconst, 'Reconstructed'),
        ]:
            kde = gaussian_kde(vals, bw_method=0.3)
            x_range = np.linspace(vals.min(), vals.max(), 300)
            axes[1].plot(x_range, kde(x_range), color=color, label=lbl)
            axes[1].fill_between(x_range, kde(x_range), alpha=0.2, color=color)

        axes[1].set_xlabel('Gene expression')
        axes[1].set_ylabel('Density')
        axes[1].legend(frameon=False, fontsize=8)
    else:
        # Single scatter plot
        fig, ax = plt.subplots(figsize=size, dpi=dpi)
        ax.scatter(reconst, orig, s=2, alpha=alpha, color=color_orig,
                   rasterized=True)
        lims = [min(orig.min(), reconst.min()),
                max(orig.max(), reconst.max())]
        ax.plot(lims, lims, 'k--', linewidth=0.8, alpha=0.5)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)

    plt.tight_layout()
    plt.show()