Skip to content

Commit 8c842c0

Browse files
authored
Merge pull request #509 from meyer-lab/new-pf2
Refactor plotting package and replace ortools with component block ordering
2 parents a3c020c + 33ed4e6 commit 8c842c0

15 files changed

Lines changed: 1500 additions & 2008 deletions

File tree

‎.github/workflows/build.yml‎

Lines changed: 0 additions & 22 deletions
This file was deleted.

‎.github/workflows/test.yml‎

Lines changed: 0 additions & 26 deletions
This file was deleted.

‎README.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,25 @@ To add RISE to your Python environment, you can install it directly from GitHub:
1515
pip install git+https://github.com/meyer-lab/RISE.git@main
1616
```
1717

18+
For GPU acceleration support (propagated to `parafac2[gpu]`):
19+
20+
```bash
21+
pip install "RISE[gpu] @ git+https://github.com/meyer-lab/RISE.git@main"
22+
```
23+
1824
Or add the following line to your `requirements.txt`:
1925

2026
```
2127
git+https://github.com/meyer-lab/RISE.git@main
2228
```
2329

30+
or with GPU support:
31+
32+
```
33+
RISE[gpu] @ git+https://github.com/meyer-lab/RISE.git@main
34+
```
35+
36+
2437
## Quick Start
2538

2639
RISE works with preprocessed AnnData objects containing single-cell RNA-seq data:

‎RISE/plotting/__init__.py‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,23 +31,23 @@
3131
)
3232

3333
__all__ = [
34-
"plot_condition_factors",
35-
"plot_eigenstate_factors",
36-
"plot_gene_factors",
3734
"avegene_per_status",
35+
"calculateFMS",
3836
"cell_count_perc_df",
3937
"cell_count_perc_lupus_df",
4038
"gene_plot_cells",
4139
"plot_avegene_per_category",
4240
"plot_avegene_per_celltype",
4341
"plot_cell_gene_corr",
44-
"plot_r2x",
45-
"rotate_xaxis",
46-
"rotate_yaxis",
42+
"plot_condition_factors",
43+
"plot_eigenstate_factors",
44+
"plot_fms_diff_ranks",
45+
"plot_fms_percent_drop",
46+
"plot_gene_factors",
4747
"plot_gene_pacmap",
4848
"plot_labels_pacmap",
49+
"plot_r2x",
4950
"plot_wp_pacmap",
50-
"calculateFMS",
51-
"plot_fms_diff_ranks",
52-
"plot_fms_percent_drop",
51+
"rotate_xaxis",
52+
"rotate_yaxis",
5353
]

‎RISE/plotting/factors.py‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,6 @@
55
from matplotlib import pyplot as plt
66
from matplotlib.axes import Axes
77
from matplotlib.patches import Patch
8-
from scipy.spatial.distance import pdist
9-
10-
from .seriate import seriate
118

129
cmap = sns.diverging_palette(240, 10, as_cmap=True)
1310

@@ -54,7 +51,6 @@ def plot_condition_factors(
5451
group_cond : bool, optional (default: False)
5552
If True and cond_group_labels provided, sorts conditions by group.
5653
"""
57-
pd.set_option("display.max_rows", None)
5854
yt = pd.Series(np.unique(data.obs[cond]))
5955
X = np.array(data.uns["Pf2_A"])
6056

@@ -194,7 +190,7 @@ def plot_gene_factors(data: anndata.AnnData, ax: Axes, weight=0.08, trim=True):
194190
ind = reorder_table(X)
195191
X = X[ind]
196192
X = X / np.max(np.abs(X))
197-
yt = [yt[ii] for ii in ind]
193+
yt = yt[ind]
198194
xticks = np.arange(1, rank + 1)
199195

200196
sns.heatmap(
@@ -210,6 +206,8 @@ def plot_gene_factors(data: anndata.AnnData, ax: Axes, weight=0.08, trim=True):
210206
ax.set(xlabel="Component")
211207

212208

213-
def reorder_table(projs: np.ndarray):
214-
"""Reorder a table's rows using heirarchical clustering"""
215-
return seriate(pdist(projs))
209+
def reorder_table(projs: np.ndarray) -> np.ndarray:
210+
"""Reorder a table's rows using dominant component block ordering."""
211+
max_comp = np.argmax(np.abs(projs), axis=1)
212+
comp_vals = projs[np.arange(projs.shape[0]), max_comp]
213+
return np.lexsort((-comp_vals, max_comp))

‎RISE/plotting/general.py‎

Lines changed: 33 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -191,86 +191,65 @@ def plot_cell_gene_corr(
191191
dataDF = dataDF.subtract(X.var["means"].values)
192192
dataDF[hue] = X.obs[hue].values
193193
dataDF["Cell Type"] = X.obs[cellType].values
194-
alpha = 0.3
195194

196-
dataDF = dataDF.groupby([hue, "Cell Type"], observed=True).mean().reset_index()
197-
alpha = 1
195+
meanDF = dataDF.groupby([hue, "Cell Type"], observed=True).mean().reset_index()
196+
pivoted = meanDF.pivot(index=hue, columns="Cell Type", values=genes)
198197

199-
corrDF = pd.DataFrame()
200-
for cond in dataDF[hue].unique():
201-
cell_gene1 = dataDF.loc[
202-
(dataDF[hue] == cond) & (dataDF["Cell Type"] == cells[0])
203-
][genes[0]].values
204-
cell_gene2 = dataDF.loc[
205-
(dataDF[hue] == cond) & (dataDF["Cell Type"] == cells[1])
206-
][genes[1]].values
207-
corrDF = pd.concat(
208-
[
209-
corrDF,
210-
pd.DataFrame(
211-
{
212-
hue: cond,
213-
cells[0] + " " + genes[0]: cell_gene1,
214-
cells[1] + " " + genes[1]: cell_gene2,
215-
}
216-
),
217-
]
218-
)
198+
col1 = (genes[0], cells[0])
199+
col2 = (genes[1], cells[1])
200+
201+
x_name = f"{cells[0]} {genes[0]}"
202+
y_name = f"{cells[1]} {genes[1]}"
203+
204+
if col1 in pivoted.columns and col2 in pivoted.columns:
205+
corrDF = pd.DataFrame(
206+
{
207+
hue: pivoted.index,
208+
x_name: pivoted[col1].values,
209+
y_name: pivoted[col2].values,
210+
}
211+
).dropna()
212+
else:
213+
corrDF = pd.DataFrame(columns=[hue, x_name, y_name])
219214

220215
if unique is not None:
221216
corrDF[hue] = corrDF[hue].astype(str)
222217
corrDF.loc[~corrDF[hue].isin(unique), hue] = "Other"
223218

224219
sns.scatterplot(
225220
data=corrDF,
226-
x=cells[0] + " " + genes[0],
227-
y=cells[1] + " " + genes[1],
221+
x=x_name,
222+
y=y_name,
228223
hue=hue,
229224
ax=ax,
230-
alpha=alpha,
225+
alpha=1.0,
231226
)
232227

233228

234229
def cell_count_perc_df(X, celltype="Cell Type"):
235230
"""Returns DF with cell counts and percentages for experiment"""
236-
237231
grouping = [celltype, "Condition"]
238-
239232
df = X.obs[grouping].reset_index(drop=True)
240233

241-
dfCond = (
242-
df.groupby(["Condition"], observed=True).size().reset_index(name="Cell Count")
243-
)
244234
dfCellType = (
245235
df.groupby(grouping, observed=True).size().reset_index(name="Cell Count")
246236
)
247237
dfCellType["Cell Count"] = dfCellType["Cell Count"].astype("float")
248238

249-
dfCellType["Cell Type Percentage"] = 0.0
250-
for cond in np.unique(df["Condition"]):
251-
dfCellType.loc[dfCellType["Condition"] == cond, "Cell Type Percentage"] = (
252-
100
253-
* dfCellType.loc[dfCellType["Condition"] == cond, "Cell Count"].to_numpy()
254-
/ dfCond.loc[dfCond["Condition"] == cond]["Cell Count"].to_numpy()
255-
)
256-
257-
dfCellType.rename(columns={celltype: "Cell Type"}, inplace=True)
239+
dfCellType["Cell Type Percentage"] = (
240+
100
241+
* dfCellType["Cell Count"]
242+
/ dfCellType.groupby("Condition")["Cell Count"].transform("sum")
243+
)
258244

245+
dfCellType = dfCellType.rename(columns={celltype: "Cell Type"})
259246
return dfCellType
260247

261248

262249
def cell_count_perc_lupus_df(X, celltype="Cell Type"):
263-
"""Returns DF with cell counts and percentages for experiment"""
264-
grouping_all = [
265-
celltype,
266-
"Condition",
267-
"SLE_status",
268-
"Processing_Cohort",
269-
"condition_unique_idxs",
270-
]
271-
grouping = [celltype, "Condition"]
250+
"""Returns DF with cell counts and percentages for experiment with Lupus metadata"""
251+
dfCellType = cell_count_perc_df(X, celltype=celltype)
272252

273-
df = X.obs[grouping_all].reset_index(drop=True)
274253
status_mapping = X.obs.groupby("Condition", observed=False)["SLE_status"].first()
275254
cohort_mapping = X.obs.groupby("Condition", observed=False)[
276255
"Processing_Cohort"
@@ -279,37 +258,18 @@ def cell_count_perc_lupus_df(X, celltype="Cell Type"):
279258
"condition_unique_idxs"
280259
].first()
281260

282-
dfCond = (
283-
df.groupby(["Condition"], observed=True).size().reset_index(name="Cell Count")
284-
)
285-
dfCellType = (
286-
df.groupby(grouping, observed=True).size().reset_index(name="Cell Count")
287-
)
288-
dfCellType["Cell Count"] = dfCellType["Cell Count"].astype("float")
289-
290-
dfCellType["Cell Type Percentage"] = 0.0
291-
for cond in np.unique(df["Condition"]):
292-
dfCellType.loc[dfCellType["Condition"] == cond, "Cell Type Percentage"] = (
293-
100
294-
* dfCellType.loc[dfCellType["Condition"] == cond, "Cell Count"].to_numpy()
295-
/ dfCond.loc[dfCond["Condition"] == cond]["Cell Count"].to_numpy()
296-
)
297-
298261
dfCellType["SLE_status"] = dfCellType["Condition"].map(status_mapping)
299262
dfCellType["Processing_Cohort"] = dfCellType["Condition"].map(cohort_mapping)
300263
dfCellType["condition_unique_idxs"] = dfCellType["Condition"].map(idx_mapping)
301-
dfCellType.rename(columns={celltype: "Cell Type"}, inplace=True)
302264

303265
return dfCellType
304266

305267

306268
def rotate_xaxis(ax, rotation=90):
307-
"""Rotates text by 90 degrees for x-axis"""
308-
ax.set_xticks(ax.get_xticks())
309-
ax.set_xticklabels(labels=ax.get_xticklabels(), rotation=rotation)
269+
"""Rotates text for x-axis"""
270+
ax.tick_params(axis="x", rotation=rotation)
310271

311272

312273
def rotate_yaxis(ax, rotation=90):
313-
"""Rotates text by 90 degrees for y-axis"""
314-
ax.set_yticks(ax.get_yticks())
315-
ax.set_yticklabels(labels=ax.get_yticklabels(), rotation=rotation)
274+
"""Rotates text for y-axis"""
275+
ax.tick_params(axis="y", rotation=rotation)

0 commit comments

Comments
 (0)