Skip to content

Commit 2d17aa7

Browse files
authored
Repackaging RISE (#507)
* Repackaging RISE * Update sphinx * Refactor plotting code * Fixed ruff checks * Last fix * Fix warnings * Lupus is now compressed * Memory usage fixes
1 parent 9e74319 commit 2d17aa7

56 files changed

Lines changed: 1914 additions & 1756 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎RISE/factorization.py‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from scipy.stats import gmean
77
from sklearn.decomposition import PCA
88
from sklearn.linear_model import LinearRegression
9-
from sklearn.preprocessing import scale
109
from tqdm import tqdm
1110

1211

@@ -95,8 +94,10 @@ def pf2(
9594
- X.uns["Pf2_B"]: Eigen-state factors (shape: rank, rank)
9695
- X.varm["Pf2_C"]: Gene factors (shape: n_genes, rank)
9796
- X.obsm["projections"]: Cell projections (shape: n_cells, rank)
98-
- X.obsm["weighted_projections"]: Weighted cell projections (shape: n_cells, rank)
99-
- X.obsm["X_pf2_PaCMAP"]: PaCMAP embedding (shape: n_cells, 2) if doEmbedding=True
97+
- X.obsm["weighted_projections"]: Weighted cell projections
98+
(shape: n_cells, rank)
99+
- X.obsm["X_pf2_PaCMAP"]: PaCMAP embedding (shape: n_cells, 2)
100+
if doEmbedding=True
100101
"""
101102
pf_out, _ = parafac2_nd(
102103
X, rank=rank, random_state=random_state, tol=tolerance, n_iter_max=max_iter
@@ -145,7 +146,8 @@ def rise_pca_r2x(X: anndata.AnnData, ranks):
145146
r2x_rise[index] = R2X
146147

147148
# Mean center because this is done within RISE
148-
XX = scale(XX.todense(), with_mean=True, with_std=False)
149+
XX = XX.toarray()
150+
XX = XX - np.mean(XX, axis=0)
149151

150152
pca = PCA(n_components=ranks[-1])
151153
pca.fit(XX)

‎RISE/figures/__init__.py‎

Lines changed: 0 additions & 1 deletion
This file was deleted.

‎RISE/figures/commonFuncs/__init__.py‎

Lines changed: 0 additions & 1 deletion
This file was deleted.

‎RISE/plotting/__init__.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""
2+
Plotting and visualization functions for RISE.
3+
"""
4+
5+
from .factors import (
6+
plot_condition_factors,
7+
plot_eigenstate_factors,
8+
plot_gene_factors,
9+
)
10+
from .general import (
11+
avegene_per_status,
12+
cell_count_perc_df,
13+
cell_count_perc_lupus_df,
14+
gene_plot_cells,
15+
plot_avegene_per_category,
16+
plot_avegene_per_celltype,
17+
plot_cell_gene_corr,
18+
plot_r2x,
19+
rotate_xaxis,
20+
rotate_yaxis,
21+
)
22+
from .pacmap import (
23+
plot_gene_pacmap,
24+
plot_labels_pacmap,
25+
plot_wp_pacmap,
26+
)
27+
from .stability import (
28+
calculateFMS,
29+
plot_fms_diff_ranks,
30+
plot_fms_percent_drop,
31+
)
32+
33+
__all__ = [
34+
"plot_condition_factors",
35+
"plot_eigenstate_factors",
36+
"plot_gene_factors",
37+
"avegene_per_status",
38+
"cell_count_perc_df",
39+
"cell_count_perc_lupus_df",
40+
"gene_plot_cells",
41+
"plot_avegene_per_category",
42+
"plot_avegene_per_celltype",
43+
"plot_cell_gene_corr",
44+
"plot_r2x",
45+
"rotate_xaxis",
46+
"rotate_yaxis",
47+
"plot_gene_pacmap",
48+
"plot_labels_pacmap",
49+
"plot_wp_pacmap",
50+
"calculateFMS",
51+
"plot_fms_diff_ranks",
52+
"plot_fms_percent_drop",
53+
]
Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ def plot_condition_factors(
2222
color_key=None,
2323
group_cond=False,
2424
):
25-
"""Plot condition factors as a heatmap showing how conditions contribute to components.
25+
"""Plot condition factors as a heatmap showing how conditions contribute to
26+
components.
2627
2728
This visualization shows how each experimental condition (rows) contributes to
2829
each RISE component (columns). High values indicate strong association between
@@ -46,7 +47,8 @@ def plot_condition_factors(
4647
Series mapping conditions to group labels for colored row annotations.
4748
Useful for grouping related conditions (e.g., drug classes, patient cohorts).
4849
ThomsonNorm : bool, optional (default: False)
49-
If True, normalizes factors using only control conditions (those containing 'CTRL').
50+
If True, normalizes factors using only control conditions (those
51+
containing 'CTRL').
5052
color_key : list, optional (default: None)
5153
Custom colors for condition group labels. If None, uses default palette.
5254
group_cond : bool, optional (default: False)
@@ -162,7 +164,8 @@ def plot_gene_factors(data: anndata.AnnData, ax: Axes, weight=0.08, trim=True):
162164
163165
This visualization reveals coordinated gene modules by showing which genes (rows)
164166
are highly weighted in each component (columns). The weight parameter filters out
165-
genes with low contributions, focusing on the most important genes for interpretation.
167+
genes with low contributions, focusing on the most important genes for
168+
interpretation.
166169
167170
Parameters
168171
----------
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import seaborn as sns
55
from matplotlib.axes import Axes
66

7-
from ...factorization import rise_pca_r2x
7+
from ..factorization import rise_pca_r2x
88

99

1010
def plot_r2x(data, rank_vec, ax: Axes):
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def plot_gene_pacmap(gene: str, X: anndata.AnnData, ax: Axes, clip_outliers=0.99
7575
points = np.array(X.obsm["X_pf2_PaCMAP"])
7676

7777
canvas = _get_canvas(points)
78-
data = pd.DataFrame(points, columns=("x", "y"))
78+
data = pd.DataFrame(points, columns=["x", "y"]) # type: ignore
7979

8080
values -= np.min(values)
8181
values /= np.max(values)
@@ -126,7 +126,7 @@ def plot_wp_pacmap(X: anndata.AnnData, cmp: int, ax: Axes, cbarMax: float = 1.0)
126126
cmap = sns.diverging_palette(240, 10, as_cmap=True)
127127

128128
canvas = _get_canvas(points)
129-
data = pd.DataFrame(points, columns=("x", "y"))
129+
data = pd.DataFrame(points, columns=["x", "y"]) # type: ignore
130130

131131
values /= np.max(np.abs(values))
132132

@@ -195,7 +195,7 @@ def plot_labels_pacmap(
195195
labels = labels.iloc[indices]
196196

197197
canvas = _get_canvas(points)
198-
data = pd.DataFrame(points, columns=("x", "y"))
198+
data = pd.DataFrame(points, columns=["x", "y"]) # type: ignore
199199

200200
data["label"] = pd.Categorical(labels)
201201
aggregation = canvas.points(data, "x", "y", agg=ds.count_cat("label"))
Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -41,20 +41,22 @@ def seriate(
4141
dists: numpy.ndarray, approximation_multiplier: int = 1000, timeout: float = 2.0
4242
) -> list[int]:
4343
"""
44-
Order the elements of a set so that the sum of sequential pairwise distances is minimal.
44+
Order the elements of a set so that the sum of sequential pairwise
45+
distances is minimal.
4546
4647
We solve the Travelling Salesman Problem (TSP) under the hood.
4748
Reference: http://nicolas.kruchten.com/content/2018/02/seriation/
4849
49-
:param dists: Either a condensed pdist-like or a symmetric square distance matrix.
50-
:param approximation_multiplier: Multiply by this number before converting distances \
51-
to integers.
52-
:param timeout: Maximum amount of time allowed to spend for solving the TSP, in seconds. \
53-
This value cannot be less than 0. If timeout is 0 it will try to solve \
54-
the problem with timeout = 1, and double the timeout every time it fails \
55-
until a valid solution is found.
56-
:return: list with ordered element indexes, the same length as the number of elements \
57-
involved in calculating `dists`.
50+
:param dists: Either a condensed pdist-like or a symmetric square distance
51+
matrix.
52+
:param approximation_multiplier: Multiply by this number before converting
53+
distances to integers.
54+
:param timeout: Maximum amount of time allowed to spend for solving the TSP,
55+
in seconds. This value cannot be less than 0. If timeout is 0
56+
it will try to solve the problem with timeout = 1, and double
57+
the timeout every time it fails until a valid solution is found.
58+
:return: list with ordered element indexes, the same length as the number of
59+
elements involved in calculating `dists`.
5860
"""
5961
_validate_data(dists)
6062
if timeout > 0:
@@ -83,17 +85,20 @@ def _seriate(
8385
dists: numpy.ndarray, approximation_multiplier=1000, timeout=2.0
8486
) -> list[int]:
8587
"""
86-
Order the elements of a set so that the sum of sequential pairwise distances is minimal.
88+
Order the elements of a set so that the sum of sequential pairwise
89+
distances is minimal.
8790
8891
We solve the Travelling Salesman Problem (TSP) under the hood.
8992
Reference: http://nicolas.kruchten.com/content/2018/02/seriation/
9093
91-
:param dists: Either a condensed pdist-like or a symmetric square distance matrix.
92-
:param approximation_multiplier: Multiply by this number before converting distances \
93-
to integers.
94-
:param timeout: Maximum amount of time allowed to spend for solving the TSP, in seconds.
95-
:return: list with ordered element indexes, the same length as the number of elements \
96-
involved in calculating `dists`.
94+
:param dists: Either a condensed pdist-like or a symmetric square distance
95+
matrix.
96+
:param approximation_multiplier: Multiply by this number before converting
97+
distances to integers.
98+
:param timeout: Maximum amount of time allowed to spend for solving the TSP,
99+
in seconds.
100+
:return: list with ordered element indexes, the same length as the number of
101+
elements involved in calculating `dists`.
97102
"""
98103
assert dists[dists < 0].size == 0, "distances must be non-negative"
99104
assert timeout > 0
Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""
2-
Figure S4
2+
Decomposition stability analysis and plotting functions.
33
"""
44

55
import anndata
@@ -12,26 +12,9 @@
1212
from tlviz.factor_tools import factor_match_score as fms
1313

1414
from ..factorization import pf2
15-
from .common import getSetup, subplotLabel
1615

17-
# from ..imports import import_thomson
1816

19-
20-
def makeFigure():
21-
ax, f = getSetup((6, 3), (1, 2))
22-
subplotLabel(ax)
23-
24-
# X = import_thomson()
25-
# percentList = np.arange(0.0, 8.0, 5.0)
26-
# plot_fms_percent_drop(X, ax[0], percentList=percentList, runs=3)
27-
28-
# ranks = list(range(1, 3))
29-
# plot_fms_diff_ranks(X, ax[1], ranksList=ranks, runs=3)
30-
31-
return f
32-
33-
34-
def calculateFMS(A: anndata.AnnData, B: anndata.AnnData):
17+
def calculateFMS(A: anndata.AnnData, B: anndata.AnnData) -> float:
3518
"""Calculate Factor Match Score (FMS) between two RISE decompositions.
3619
3720
Factor Match Score measures the similarity between two tensor decompositions
@@ -80,7 +63,7 @@ def calculateFMS(A: anndata.AnnData, B: anndata.AnnData):
8063
)
8164
)
8265

83-
return fms(A_CP, B_CP, consider_weights=False, skip_mode=1) # type: ignore
66+
return fms(A_CP, B_CP, consider_weights=False, skip_mode=1)
8467

8568

8669
def plot_fms_percent_drop(

‎RISE/tests/test_parafac2.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@
55
import numpy as np
66
import pandas as pd
77

8+
from analysis.imports import import_thomson
9+
810
from ..factorization import pf2, rise_pca_r2x
9-
from ..imports import import_thomson
1011

1112

1213
def test_factor_thomson_reprod():

0 commit comments

Comments
 (0)