Skip to content

Commit d3256be

Browse files
committed
Apply LR pairs and centralise code.
1 parent e577393 commit d3256be

15 files changed

Lines changed: 236 additions & 168 deletions

‎stlearn/add.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
from .adds.annotation import annotation
55
from .adds.image import image
66
from .adds.labels import labels
7-
from .adds.lr import lr
87
from .adds.parsing import parsing
98
from .adds.polygon_annotations import polygon_annotations
109
from .adds.positions import positions
@@ -18,7 +17,6 @@
1817
"apply_mask",
1918
"image",
2019
"labels",
21-
"lr",
2220
"parsing",
2321
"polygon_annotations",
2422
"positions",

‎stlearn/adds/lr.py‎

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

‎stlearn/pl/cci_plot.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929

3030
from ..tl.cci import LR_RESULTS
3131
from ..tl.cci._results import check_lr_results, lr_result
32+
from ..tl.cci.ligand_receptors import split_name
3233
from ..utils import _docs_params
3334
from ._docs import doc_het_plot, doc_spatial_base_plot
3435
from .cci_plot_helpers import (
@@ -673,7 +674,7 @@ def lr_plot(
673674
"""
674675

675676
# Input checking #
676-
ligand, receptor = lr.split("_")
677+
ligand, receptor = split_name(lr)
677678
results = None if lr_results is None else check_lr_results(lr_results, adata)
678679
# Whether st.tl.cci.run tested this LR and found it significant in some spot.
679680
lr_sig = (

‎stlearn/pl/classes_bokeh.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
from stlearn.classes import Spatial
4646
from stlearn.tl.cci import get_edges, lr_result
4747
from stlearn.tl.cci._results import check_lr_results
48+
from stlearn.tl.cci.ligand_receptors import split_name
4849
from stlearn.utils import _read_trajectory, as_uint8_image
4950

5051

@@ -1123,7 +1124,7 @@ def _get_cci_lr_edges(self):
11231124
selected = self.annot_select.value
11241125

11251126
# Extracting the data #
1126-
ligand, receptor = lr.split("_")
1127+
ligand, receptor = split_name(lr)
11271128
L_bool = adata[:, ligand].X.toarray()[:, 0] > 0
11281129
R_bool = adata[:, receptor].X.toarray()[:, 0] > 0
11291130
sig_bool = lr_result(self.lr_results, "lr_sig_scores", lr) > 0

‎stlearn/tl/cci/analysis.py‎

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,15 @@
2727
get_interaction_pvals,
2828
label_keys,
2929
)
30-
from .ligand_receptors import LRPairs, lr_pairs
30+
from .ligand_receptors import LRPairs, genes_of, lr_pairs, split_name
3131
from .neighbours import calc_distance, calc_neighbours, get_neighbourhoods
3232
from .permutation import perform_spot_testing
3333
from .scoring import get_lrs_scores
3434

3535

3636
def _report_dropped_lrs(
3737
adata: AnnData,
38-
lrs: npt.NDArray[np.str_],
38+
lrs: LRPairs,
3939
n_scored: npt.NDArray[np.int64],
4040
min_spots: int,
4141
min_expr: float,
@@ -45,28 +45,31 @@ def _report_dropped_lrs(
4545
(with min_expr 0, such a pair scores in no spot; above 0 it can still score
4646
through its partner, so only dropped pairs are looked at), or else scored in
4747
min_spots spots or fewer."""
48-
dropped = lrs[n_scored <= min_spots]
49-
by_gene, unexpressed = [], set()
50-
if dropped.size:
51-
genes = np.unique([lr.split("_") for lr in dropped])
48+
dropped = lrs.filter(n_scored <= min_spots)
49+
n_by_gene, unexpressed = 0, np.array([], dtype=np.str_)
50+
if len(dropped):
51+
genes = dropped.genes()
5252
n_above = np.asarray((min_expr < adata[:, genes].X).sum(axis=0)).ravel()
53-
unexpressed = set(genes[n_above == 0])
54-
by_gene = [lr for lr in dropped if unexpressed.intersection(lr.split("_"))]
55-
too_few = dropped.size - len(by_gene)
56-
if by_gene:
57-
named = ", ".join(sorted(unexpressed)[:max_named])
53+
unexpressed = genes[n_above == 0] # sorted, as genes() are
54+
by_gene = np.isin(dropped.ligands(), unexpressed) | np.isin(
55+
dropped.receptors(), unexpressed
56+
)
57+
n_by_gene = int(by_gene.sum())
58+
too_few = len(dropped) - n_by_gene
59+
if n_by_gene:
60+
named = ", ".join(unexpressed[:max_named])
5861
more = (
5962
f" and {len(unexpressed) - max_named} more"
6063
if len(unexpressed) > max_named
6164
else ""
6265
)
6366
print(
64-
f"Dropping {len(by_gene)} LR pairs with a gene never expressed above "
67+
f"Dropping {n_by_gene} LR pairs with a gene never expressed above "
6568
f"min_expr={min_expr}: {named}{more}."
6669
)
6770
if too_few:
6871
print(f"Dropping {too_few} LR pairs scored in {min_spots} or fewer spots.")
69-
print(f"Altogether {lrs.size - dropped.size} valid L-R pairs")
72+
print(f"Altogether {len(lrs) - len(dropped)} valid L-R pairs")
7073

7174

7275
def run(
@@ -238,11 +241,11 @@ def run(
238241

239242
# 1. Filter any LRs without stored expression.
240243
# Calculating the lr_scores across spots for the inputted lrs #
241-
lr_scores, new_lrs = get_lrs_scores(
244+
lr_scores, scored = get_lrs_scores(
242245
adata, lrs, neighbours, het_vals, min_expr, sparse_result=True
243246
)
244247
# Fail fast.
245-
if new_lrs.size == 0:
248+
if len(scored) == 0:
246249
raise ValueError(
247250
f"None of the {len(lrs)} {lrs.species} LR pairs are in adata.var_names; "
248251
"check the pairs' species matches the data, e.g. "
@@ -251,10 +254,10 @@ def run(
251254
n_scored = np.diff(lr_scores.indptr).astype(np.int64) # spots scored per LR
252255
lr_bool = n_scored > min_spots
253256
if verbose:
254-
_report_dropped_lrs(adata, new_lrs, n_scored, min_spots, min_expr)
255-
new_lrs = new_lrs[lr_bool]
257+
_report_dropped_lrs(adata, scored, n_scored, min_spots, min_expr)
258+
tested = scored.filter(lr_bool)
256259
lr_scores = lr_scores[:, lr_bool]
257-
if new_lrs.size == 0:
260+
if len(tested) == 0:
258261
raise ValueError(
259262
f"No LR pairs had scores in more than {min_spots} spots; "
260263
"try lowering min_spots or min_expr."
@@ -263,7 +266,7 @@ def run(
263266
tests = perform_spot_testing(
264267
adata,
265268
lr_scores,
266-
new_lrs,
269+
tested,
267270
n_pairs,
268271
neighbours,
269272
het_vals,
@@ -274,10 +277,10 @@ def run(
274277
random_state=random_state,
275278
)
276279
lr_results = AnnData(
277-
obs=pd.DataFrame(index=adata.obs_names), var=pd.DataFrame(index=new_lrs)
280+
obs=pd.DataFrame(index=adata.obs_names), var=pd.DataFrame(index=tested.names())
278281
)
279282

280-
lr_results.var["source"] = lrs.source_of(new_lrs).astype(str)
283+
lr_results.var["source"] = tested.to_frame()["source"].to_numpy(dtype=str)
281284
lr_results.uns["lr_species"] = lrs.species
282285
lr_results.uns["lrfeatures"] = tests.lr_features
283286

@@ -398,7 +401,7 @@ def run_lr_go(
398401
lrs = lr_results.var_names.to_numpy().astype(str)
399402
n_sig = lr_results.var["n_spots_sig"].to_numpy().astype(int)
400403
top_lrs = lrs[n_sig > min_sig_spots][0:n_top]
401-
top_genes = np.unique([lr.split("_") for lr in top_lrs])
404+
top_genes = genes_of(top_lrs)
402405

403406
# Determining the background genes if not inputted
404407
if bg_genes is None:
@@ -571,7 +574,7 @@ def run_cci(
571574
col = "lr_sig_scores" if sig_spots else "lr_scores"
572575
best_lr_indices = np.flatnonzero(lr_summary[count_col].to_numpy() > min_spots)
573576
best_lrs = lr_summary.index.values[best_lr_indices]
574-
lr_genes = np.unique([lr.split("_") for lr in best_lrs])
577+
lr_genes = genes_of(best_lrs)
575578
if len(lr_genes) == 0:
576579
raise ValueError(
577580
"No LR pairs returned with current filtering params; \n"
@@ -602,7 +605,7 @@ def expressed(gene: str) -> npt.NDArray[np.bool_]:
602605
disable=not verbose,
603606
) as pbar:
604607
for i, best_lr in enumerate(best_lrs):
605-
ligand, receptor = best_lr.split("_")
608+
ligand, receptor = split_name(best_lr)
606609

607610
L_bool = expressed(ligand)
608611
R_bool = expressed(receptor)

0 commit comments

Comments
 (0)