Skip to content

Commit 9cf7805

Browse files
fishidahoclaude
andcommitted
Bring all seven C901 functions under the complexity limit
`ruff check --select C901 --duplicate` at max-complexity=10 flagged seven functions. Each is now under the limit by extracting the phases it was interleaving; no logic moved between phases and no control flow changed. score_cell_type_alignment 26 -> 7 load_factors 15 -> <5 plot_cell_type_alignment 14 -> <5 bicv 12 -> <5 cell_type_alignment 12 -> <5 export_factors 11 -> <5 plot_condition_factors 11 -> <5 The largest single win is a genuine duplicate rather than a split: `cell_type_alignment` and `score_cell_type_alignment` each carried their own copy of the permutation-null and Mann-Whitney p-value computation, identical but for the variable names, which is why pylint's duplicate-code check never paired them. Both now call `_component_p_values`. The `n_permutations` dispatch keeps its exact original shape -- a negative value still leaves the p-values at 1.0 rather than falling through to the asymptotic test, which a plain `if > 0 / else` would have changed. Verified with a golden harness of 69 keys covering all seven functions: every returned frame, series and array, the rendered PNG hash of eleven plot configurations, and the type and message of ten error paths. The harness is bit-identical before and after, and was confirmed deterministic across repeat runs first. 90 passed / 1 skipped, ruff clean, `ty` clean over `scrise/`, and no new duplicate-code pairs. Note these extractions add lines rather than remove them, since each helper gains a docstring: the five touched files grow by 159 lines net. Cutting file length means splitting modules, which is a separate structural decision. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016VJRB1RMUAb1id11XZ6KWS
1 parent 44ee7b0 commit 9cf7805

5 files changed

Lines changed: 608 additions & 434 deletions

File tree

‎scrise/annotation_alignment.py‎

Lines changed: 153 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,143 @@ def _validate_and_encode_cell_types(
329329
return codes, categories
330330

331331

332+
_CELL_TYPE_COLUMN_CANDIDATES = (
333+
"cell_type",
334+
"CellType",
335+
"cell_types",
336+
"Cell_Type",
337+
"celltype",
338+
)
339+
340+
341+
def _permutation_p_values(
342+
y: np.ndarray,
343+
codes: np.ndarray,
344+
n_types: int,
345+
n_cells: int,
346+
aurocs: np.ndarray,
347+
n_permutations: int,
348+
rng: np.random.Generator,
349+
) -> np.ndarray:
350+
"""Empirical one-sided p-values against a rank-permutation null."""
351+
ranks = sp.rankdata(y, method="average")
352+
counts = np.bincount(codes, minlength=n_types).astype(float)
353+
null_counts = np.zeros(n_types, dtype=int)
354+
355+
for _ in range(n_permutations):
356+
perm_ranks = rng.permutation(ranks)
357+
perm_sums = np.bincount(codes, weights=perm_ranks, minlength=n_types).astype(
358+
float
359+
)
360+
for k in range(n_types):
361+
n1 = counts[k]
362+
n0 = n_cells - n1
363+
if n1 > 0 and n0 > 0:
364+
u_null = perm_sums[k] - n1 * (n1 + 1.0) / 2.0
365+
auc_null = u_null / (n1 * n0)
366+
if auc_null >= aurocs[k]:
367+
null_counts[k] += 1
368+
369+
return (1.0 + null_counts) / (1.0 + n_permutations)
370+
371+
372+
def _asymptotic_p_values(y: np.ndarray, codes: np.ndarray, n_types: int) -> np.ndarray:
373+
"""One-sided Mann-Whitney U p-values, used when ``n_permutations == 0``."""
374+
p_values = np.ones(n_types, dtype=float)
375+
for k in range(n_types):
376+
pos = y[codes == k]
377+
neg = y[codes != k]
378+
if pos.size > 0 and neg.size > 0:
379+
res = sp.mannwhitneyu(pos, neg, alternative="greater")
380+
p_values[k] = float(res.pvalue)
381+
return p_values
382+
383+
384+
def _component_p_values(
385+
y: np.ndarray,
386+
codes: np.ndarray,
387+
n_types: int,
388+
n_cells: int,
389+
aurocs: np.ndarray,
390+
n_permutations: int,
391+
rng: np.random.Generator,
392+
) -> np.ndarray:
393+
"""Per-cell-type p-values for one component's loadings.
394+
395+
Shared by :func:`cell_type_alignment` and
396+
:func:`score_cell_type_alignment`, which compute this identically. A
397+
single cell type (or no cells) leaves every p-value at 1.0, since there
398+
is nothing to be enriched against.
399+
"""
400+
if n_types <= 1 or n_cells == 0:
401+
return np.ones(n_types, dtype=float)
402+
if n_permutations > 0:
403+
return _permutation_p_values(
404+
y, codes, n_types, n_cells, aurocs, n_permutations, rng
405+
)
406+
if n_permutations == 0:
407+
return _asymptotic_p_values(y, codes, n_types)
408+
return np.ones(n_types, dtype=float)
409+
410+
411+
def _as_generator(
412+
random_state: int | np.random.Generator | None,
413+
) -> np.random.Generator:
414+
"""Accept a seed, an existing Generator, or None."""
415+
if isinstance(random_state, np.random.Generator):
416+
return random_state
417+
return np.random.default_rng(random_state)
418+
419+
420+
def _loadings_from_anndata(data: anndata.AnnData, projection_key: str) -> np.ndarray:
421+
"""Pull the cell-loading matrix out of ``obsm``, falling back to projections."""
422+
if projection_key in data.obsm:
423+
return np.asarray(data.obsm[projection_key])
424+
if projection_key == "weighted_projections" and "projections" in data.obsm:
425+
return np.asarray(data.obsm["projections"])
426+
raise KeyError(f"Could not find '{projection_key}' in data.obsm.")
427+
428+
429+
def _cell_types_from_anndata(
430+
data: anndata.AnnData, cell_types: pd.Series | np.ndarray | str | None
431+
) -> pd.Series:
432+
"""Resolve cell-type labels for an AnnData: named column, guess, or literal."""
433+
if cell_types is None:
434+
for candidate in _CELL_TYPE_COLUMN_CANDIDATES:
435+
if candidate in data.obs:
436+
return pd.Series(data.obs[candidate])
437+
raise KeyError(
438+
"Cell-type column not specified and none of ['cell_type', 'CellType', 'cell_types'] found in data.obs."
439+
)
440+
if isinstance(cell_types, str):
441+
if cell_types not in data.obs:
442+
raise KeyError(f"Column '{cell_types}' not found in data.obs.")
443+
return pd.Series(data.obs[cell_types])
444+
return pd.Series(cell_types)
445+
446+
447+
def _resolve_loadings_and_cell_types(
448+
data: anndata.AnnData | np.ndarray | pd.DataFrame,
449+
cell_types: pd.Series | np.ndarray | str | None,
450+
projection_key: str,
451+
) -> tuple[np.ndarray, pd.Series]:
452+
"""Normalise the three accepted input shapes to (matrix, label series)."""
453+
if isinstance(data, anndata.AnnData):
454+
return (
455+
_loadings_from_anndata(data, projection_key),
456+
_cell_types_from_anndata(data, cell_types),
457+
)
458+
459+
loadings_matrix = (
460+
data.to_numpy() if isinstance(data, pd.DataFrame) else np.asarray(data)
461+
)
462+
if cell_types is None or isinstance(cell_types, str):
463+
raise ValueError(
464+
"cell_types must be provided when data is a DataFrame or array."
465+
)
466+
return loadings_matrix, pd.Series(cell_types)
467+
468+
332469
def cell_type_alignment(
333470
loadings: np.ndarray | pd.Series,
334471
cell_types: pd.Series | np.ndarray,
@@ -381,41 +518,15 @@ def cell_type_alignment(
381518
# Compute observed AUROC per cell type
382519
aurocs = compute_auroc_per_cell_type(y, codes, n_types)
383520

384-
# Compute permutation p-values
385-
p_values = np.ones(n_types, dtype=float)
386-
if n_permutations > 0 and n_types > 1 and n_cells > 0:
387-
rng = (
388-
random_state
389-
if isinstance(random_state, np.random.Generator)
390-
else np.random.default_rng(random_state)
391-
)
392-
ranks = sp.rankdata(y, method="average")
393-
counts = np.bincount(codes, minlength=n_types).astype(float)
394-
null_counts = np.zeros(n_types, dtype=int)
395-
396-
for _ in range(n_permutations):
397-
perm_ranks = rng.permutation(ranks)
398-
perm_sums = np.bincount(
399-
codes, weights=perm_ranks, minlength=n_types
400-
).astype(float)
401-
for k in range(n_types):
402-
n1 = counts[k]
403-
n0 = n_cells - n1
404-
if n1 > 0 and n0 > 0:
405-
u_null = perm_sums[k] - n1 * (n1 + 1.0) / 2.0
406-
auc_null = u_null / (n1 * n0)
407-
if auc_null >= aurocs[k]:
408-
null_counts[k] += 1
409-
410-
p_values = (1.0 + null_counts) / (1.0 + n_permutations)
411-
elif n_permutations == 0 and n_types > 1 and n_cells > 0:
412-
# Asymptotic one-sided Mann-Whitney test
413-
for k in range(n_types):
414-
pos = y[codes == k]
415-
neg = y[codes != k]
416-
if pos.size > 0 and neg.size > 0:
417-
res = sp.mannwhitneyu(pos, neg, alternative="greater")
418-
p_values[k] = float(res.pvalue)
521+
p_values = _component_p_values(
522+
y,
523+
codes,
524+
n_types,
525+
n_cells,
526+
aurocs,
527+
n_permutations,
528+
_as_generator(random_state),
529+
)
419530

420531
# BH FDR correction across cell types for this component
421532
if n_types > 1:
@@ -491,50 +602,9 @@ def score_cell_type_alignment(
491602
CellTypeAlignmentResults
492603
Container with full results across all components.
493604
"""
494-
# Extract loadings and cell_types
495-
if isinstance(data, anndata.AnnData):
496-
if projection_key in data.obsm:
497-
loadings_matrix = np.asarray(data.obsm[projection_key])
498-
elif projection_key == "weighted_projections" and "projections" in data.obsm:
499-
loadings_matrix = np.asarray(data.obsm["projections"])
500-
else:
501-
raise KeyError(f"Could not find '{projection_key}' in data.obsm.")
502-
503-
if cell_types is None:
504-
for candidate in [
505-
"cell_type",
506-
"CellType",
507-
"cell_types",
508-
"Cell_Type",
509-
"celltype",
510-
]:
511-
if candidate in data.obs:
512-
cell_type_series = pd.Series(data.obs[candidate])
513-
break
514-
else:
515-
raise KeyError(
516-
"Cell-type column not specified and none of ['cell_type', 'CellType', 'cell_types'] found in data.obs."
517-
)
518-
elif isinstance(cell_types, str):
519-
if cell_types not in data.obs:
520-
raise KeyError(f"Column '{cell_types}' not found in data.obs.")
521-
cell_type_series = pd.Series(data.obs[cell_types])
522-
else:
523-
cell_type_series = pd.Series(cell_types)
524-
elif isinstance(data, pd.DataFrame):
525-
loadings_matrix = data.to_numpy()
526-
if cell_types is None or isinstance(cell_types, str):
527-
raise ValueError(
528-
"cell_types must be provided when data is a DataFrame or array."
529-
)
530-
cell_type_series = pd.Series(cell_types)
531-
else:
532-
loadings_matrix = np.asarray(data)
533-
if cell_types is None or isinstance(cell_types, str):
534-
raise ValueError(
535-
"cell_types must be provided when data is a DataFrame or array."
536-
)
537-
cell_type_series = pd.Series(cell_types)
605+
loadings_matrix, cell_type_series = _resolve_loadings_and_cell_types(
606+
data, cell_types, projection_key
607+
)
538608

539609
if loadings_matrix.ndim == 1:
540610
loadings_matrix = loadings_matrix[:, np.newaxis]
@@ -548,11 +618,7 @@ def score_cell_type_alignment(
548618
f"Length mismatch: data has {n_cells} cells but cell_types has {codes.size}."
549619
)
550620

551-
rng = (
552-
random_state
553-
if isinstance(random_state, np.random.Generator)
554-
else np.random.default_rng(random_state)
555-
)
621+
rng = _as_generator(random_state)
556622

557623
component_labels = [i + 1 for i in range(n_comps)]
558624
aurocs_mat = np.zeros((n_comps, n_types), dtype=float)
@@ -561,8 +627,6 @@ def score_cell_type_alignment(
561627
eta2_vec = np.zeros(n_comps, dtype=float)
562628
eps2_vec = np.zeros(n_comps, dtype=float)
563629

564-
counts = np.bincount(codes, minlength=n_types).astype(float)
565-
566630
for comp_idx in range(n_comps):
567631
y = loadings_matrix[:, comp_idx].astype(float)
568632
if signed:
@@ -574,30 +638,9 @@ def score_cell_type_alignment(
574638
eta2_vec[comp_idx] = compute_eta_squared(y, codes, n_types)
575639
eps2_vec[comp_idx] = compute_kruskal_epsilon_squared(y, codes, n_types)
576640

577-
if n_permutations > 0 and n_types > 1 and n_cells > 0:
578-
ranks = sp.rankdata(y, method="average")
579-
null_counts = np.zeros(n_types, dtype=int)
580-
for _ in range(n_permutations):
581-
perm_ranks = rng.permutation(ranks)
582-
perm_sums = np.bincount(
583-
codes, weights=perm_ranks, minlength=n_types
584-
).astype(float)
585-
for k in range(n_types):
586-
n1 = counts[k]
587-
n0 = n_cells - n1
588-
if n1 > 0 and n0 > 0:
589-
u_null = perm_sums[k] - n1 * (n1 + 1.0) / 2.0
590-
auc_null = u_null / (n1 * n0)
591-
if auc_null >= auc[k]:
592-
null_counts[k] += 1
593-
p_vals_mat[comp_idx] = (1.0 + null_counts) / (1.0 + n_permutations)
594-
elif n_permutations == 0 and n_types > 1 and n_cells > 0:
595-
for k in range(n_types):
596-
pos = y[codes == k]
597-
neg = y[codes != k]
598-
if pos.size > 0 and neg.size > 0:
599-
res = sp.mannwhitneyu(pos, neg, alternative="greater")
600-
p_vals_mat[comp_idx, k] = float(res.pvalue)
641+
p_vals_mat[comp_idx] = _component_p_values(
642+
y, codes, n_types, n_cells, auc, n_permutations, rng
643+
)
601644

602645
# Joint BH FDR correction across all (component x cell_type) tests
603646
if aurocs_mat.size > 1:

0 commit comments

Comments
 (0)