diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7f762b1..596587b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -11,11 +11,11 @@ repos: hooks: - id: prettier - repo: https://github.com/tox-dev/pyproject-fmt - rev: v2.5.0 + rev: v2.6.0 hooks: - id: pyproject-fmt - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.8.2 + rev: v0.12.12 hooks: - id: ruff types_or: [python, pyi, jupyter] @@ -23,7 +23,7 @@ repos: - id: ruff-format types_or: [python, pyi, jupyter] - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v5.0.0 + rev: v6.0.0 hooks: - id: detect-private-key - id: check-ast diff --git a/docs/.ipynb_checkpoints/index-checkpoint.md b/docs/.ipynb_checkpoints/index-checkpoint.md index 6ddffb3..9b8873e 100644 --- a/docs/.ipynb_checkpoints/index-checkpoint.md +++ b/docs/.ipynb_checkpoints/index-checkpoint.md @@ -11,6 +11,7 @@ Tools Plotting ``` + ```{toctree} :maxdepth: 1 :caption: Tutorials @@ -26,4 +27,4 @@ changelog.md contributing.md references.md -``` \ No newline at end of file +``` diff --git a/docs/api/.ipynb_checkpoints/plotting-checkpoint.md b/docs/api/.ipynb_checkpoints/plotting-checkpoint.md index 5e4ea7c..e643e37 100644 --- a/docs/api/.ipynb_checkpoints/plotting-checkpoint.md +++ b/docs/api/.ipynb_checkpoints/plotting-checkpoint.md @@ -8,7 +8,7 @@ .. autosummary:: :toctree: generated/basic_plots - + crosstab histogram pie @@ -23,7 +23,7 @@ ```{eval-rst} .. autosummary:: :toctree: generated/quantification - + gene_metric_heatmap logfoldratio_over_noise metric_scatter @@ -33,18 +33,15 @@ moranI_histogram diffusion_results spatial_inout_expression - -``` - - +``` ## Source, target and communication ```{eval-rst} .. autosummary:: :toctree: generated/communication - + celltype_communication gene_communication global_distribution_from_source @@ -54,7 +51,7 @@ target_score_by_celltype interactions_with_arrows spatial_interactions - + ``` ## Factor analysis @@ -62,7 +59,7 @@ ```{eval-rst} .. autosummary:: :toctree: generated/factor_analysis - + factors_in_cells rank_factor_genes_loadings rank_factor_genes_loadings_matrixplot @@ -70,9 +67,8 @@ nmf_gene_contributions paired_nmf_factors apply_exrnaH_to_cellular_to_create_cellularW - -``` +``` ## Colormaps & palettes @@ -83,6 +79,3 @@ get_colormap get_palette ``` - - - diff --git a/docs/api/.ipynb_checkpoints/preprocessing-checkpoint.md b/docs/api/.ipynb_checkpoints/preprocessing-checkpoint.md index 9292295..d0f57fc 100644 --- a/docs/api/.ipynb_checkpoints/preprocessing-checkpoint.md +++ b/docs/api/.ipynb_checkpoints/preprocessing-checkpoint.md @@ -15,3 +15,4 @@ pp.define_urna pp.filter_urna pp.format_adata +``` diff --git a/docs/api/.ipynb_checkpoints/tools-checkpoint.md b/docs/api/.ipynb_checkpoints/tools-checkpoint.md index 5a64d75..cff9637 100644 --- a/docs/api/.ipynb_checkpoints/tools-checkpoint.md +++ b/docs/api/.ipynb_checkpoints/tools-checkpoint.md @@ -35,7 +35,7 @@ tl.calculate_target_cells tl.compute_target_score tl.define_target_by_celltype - tl.cluster_distribution_from_source + tl.cluster_distribution_from_source tl.get_gene_interaction_strength tl.communication_strength tl.gene_specific_interactions @@ -46,7 +46,7 @@ ```{eval-rst} .. autosummary:: :toctree: generated/cell_scores - + tl.compute_contribution_score ``` @@ -55,7 +55,7 @@ ```{eval-rst} .. autosummary:: :toctree: generated/factors - + tl.factors_to_cells tl.latent_factor ``` @@ -68,7 +68,7 @@ tl.assess_diffusion tl.compute_js_divergence - + ``` ## Multimodal quantication @@ -76,7 +76,6 @@ ```{eval-rst} .. autosummary:: :toctree: generated/multimodal - + tl.image_intensities_per_transcript ``` - diff --git a/docs/api/plotting.md b/docs/api/plotting.md index 5e4ea7c..e643e37 100644 --- a/docs/api/plotting.md +++ b/docs/api/plotting.md @@ -8,7 +8,7 @@ .. autosummary:: :toctree: generated/basic_plots - + crosstab histogram pie @@ -23,7 +23,7 @@ ```{eval-rst} .. autosummary:: :toctree: generated/quantification - + gene_metric_heatmap logfoldratio_over_noise metric_scatter @@ -33,18 +33,15 @@ moranI_histogram diffusion_results spatial_inout_expression - -``` - - +``` ## Source, target and communication ```{eval-rst} .. autosummary:: :toctree: generated/communication - + celltype_communication gene_communication global_distribution_from_source @@ -54,7 +51,7 @@ target_score_by_celltype interactions_with_arrows spatial_interactions - + ``` ## Factor analysis @@ -62,7 +59,7 @@ ```{eval-rst} .. autosummary:: :toctree: generated/factor_analysis - + factors_in_cells rank_factor_genes_loadings rank_factor_genes_loadings_matrixplot @@ -70,9 +67,8 @@ nmf_gene_contributions paired_nmf_factors apply_exrnaH_to_cellular_to_create_cellularW - -``` +``` ## Colormaps & palettes @@ -83,6 +79,3 @@ get_colormap get_palette ``` - - - diff --git a/docs/api/preprocessing.md b/docs/api/preprocessing.md index 9292295..d0f57fc 100644 --- a/docs/api/preprocessing.md +++ b/docs/api/preprocessing.md @@ -15,3 +15,4 @@ pp.define_urna pp.filter_urna pp.format_adata +``` diff --git a/docs/api/tools.md b/docs/api/tools.md index 5a64d75..cff9637 100644 --- a/docs/api/tools.md +++ b/docs/api/tools.md @@ -35,7 +35,7 @@ tl.calculate_target_cells tl.compute_target_score tl.define_target_by_celltype - tl.cluster_distribution_from_source + tl.cluster_distribution_from_source tl.get_gene_interaction_strength tl.communication_strength tl.gene_specific_interactions @@ -46,7 +46,7 @@ ```{eval-rst} .. autosummary:: :toctree: generated/cell_scores - + tl.compute_contribution_score ``` @@ -55,7 +55,7 @@ ```{eval-rst} .. autosummary:: :toctree: generated/factors - + tl.factors_to_cells tl.latent_factor ``` @@ -68,7 +68,7 @@ tl.assess_diffusion tl.compute_js_divergence - + ``` ## Multimodal quantication @@ -76,7 +76,6 @@ ```{eval-rst} .. autosummary:: :toctree: generated/multimodal - + tl.image_intensities_per_transcript ``` - diff --git a/docs/index.md b/docs/index.md index 6ddffb3..9b8873e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -11,6 +11,7 @@ Tools Plotting ``` + ```{toctree} :maxdepth: 1 :caption: Tutorials @@ -26,4 +27,4 @@ changelog.md contributing.md references.md -``` \ No newline at end of file +``` diff --git a/src/troutpy/pl/communication.py b/src/troutpy/pl/communication.py index 4ec4a37..12188a8 100644 --- a/src/troutpy/pl/communication.py +++ b/src/troutpy/pl/communication.py @@ -6,20 +6,11 @@ from mpl_chord_diagram import chord_diagram from spatialdata import SpatialData -def celltype_communication( - sdata, - kind="heatmap", - celltype_key="cell type", - vmax=None, - vmin=None, - cmap="BuPu", - dendrogram_ratio=0.1, - **kwargs -): + +def celltype_communication(sdata, kind="heatmap", celltype_key="cell type", vmax=None, vmin=None, cmap="BuPu", dendrogram_ratio=0.1, **kwargs): """ Plot cell type-cell type interaction strength as a heatmap or chord diagram. """ - interaction_strength = sdata["source_score"].uns["interaction_strength"] source_table = sdata["source_score"] target_table = sdata["target_score"] @@ -30,10 +21,7 @@ def celltype_communication( # Assign colors to cell types try: - cols = dict(zip( - np.unique(sdata["table"].obs[celltype_key]), - sdata["table"].uns[celltype_key + "_colors"] - )) + cols = dict(zip(np.unique(sdata["table"].obs[celltype_key]), sdata["table"].uns[celltype_key + "_colors"], strict=False)) colors = [cols[c] for c in source_table.var.index] except KeyError: colpalette = plt.get_cmap("tab20") @@ -50,20 +38,13 @@ def celltype_communication( col_colors=colors, dendrogram_ratio=dendrogram_ratio, cbar_pos=(0.02, 0.8, 0.02, 0.15), # Adjust colorbar position: (x, y, width, height) - **kwargs + **kwargs, ) g.fig.suptitle("Interaction Strength", y=1.05) g.ax_heatmap.grid(False) # remove grid from heatmap elif kind == "chord": - chord_diagram( - celltype_ints, - source_table.var.index, - directed=True, - fontsize=6, - colors=colors, - **kwargs - ) + chord_diagram(celltype_ints, source_table.var.index, directed=True, fontsize=6, colors=colors, **kwargs) plt.title("Interaction Strength", fontweight="bold") plt.grid(False) diff --git a/src/troutpy/tl/.ipynb_checkpoints/quantify_urna-checkpoint.py b/src/troutpy/tl/.ipynb_checkpoints/quantify_urna-checkpoint.py index 287bb68..5e6250a 100644 --- a/src/troutpy/tl/.ipynb_checkpoints/quantify_urna-checkpoint.py +++ b/src/troutpy/tl/.ipynb_checkpoints/quantify_urna-checkpoint.py @@ -51,7 +51,7 @@ def spatial_variability( ------- sdata: spatialdata.SpatialData Sdata containing Moran's I values for each gene, indexed by gene names. - + """ if coord_keys is None: coord_keys = ["x", "y"] diff --git a/src/troutpy/tl/.ipynb_checkpoints/source_cell-checkpoint.py b/src/troutpy/tl/.ipynb_checkpoints/source_cell-checkpoint.py index a0c0d7e..0407dee 100644 --- a/src/troutpy/tl/.ipynb_checkpoints/source_cell-checkpoint.py +++ b/src/troutpy/tl/.ipynb_checkpoints/source_cell-checkpoint.py @@ -458,7 +458,7 @@ def store_results_in_sdata(sdata, prob_table, closest_table, extracellular_trans sdata["table"].obs['normalized_urna_source_score'] = adata.obs['urna_source_score'] / cell_expr_sum except KeyError: print('Normalized urna source score could not be computed') - + def compute_contribution_score(sdata): diff --git a/src/troutpy/tl/factor_analysis.py b/src/troutpy/tl/factor_analysis.py index 1e53ca9..5f83b87 100644 --- a/src/troutpy/tl/factor_analysis.py +++ b/src/troutpy/tl/factor_analysis.py @@ -1,15 +1,12 @@ +import warnings + +import anndata as ad import numpy as np import pandas as pd from sklearn.decomposition import NMF, LatentDirichletAllocation from spatialdata import SpatialData -import numpy as np -import scanpy as sc -import anndata as ad -from sklearn.decomposition import NMF, LatentDirichletAllocation -import warnings - def latent_factor( sdata: SpatialData, method: str = "NMF", @@ -55,7 +52,6 @@ def latent_factor( sdata : SpatialData or None Modified SpatialData object or None if copy=False. """ - adata = sdata[layer] counts = adata.X.copy() @@ -74,15 +70,12 @@ def latent_factor( try: from drvi.model import DRVI from drvi.utils.tools import ( - traverse_latent, calculate_differential_vars, set_latent_dimension_stats, + traverse_latent, ) except ImportError: - raise ImportError( - "The 'drvi' package is required for method='DRVI'. " - "Please install it with: pip install drvi" - ) + raise ImportError("The 'drvi' package is required for method='DRVI'. Please install it with: pip install drvi") # DRVI-specific parameters encoder_dims = kwargs.pop("encoder_dims", [128, 128]) @@ -145,6 +138,7 @@ def latent_factor( sdata[layer] = adata return sdata if copy else None + def combine_loadings_arrays(gene_loadings_pos: np.ndarray, gene_loadings_neg: np.ndarray) -> np.ndarray: if gene_loadings_pos.shape != gene_loadings_neg.shape: raise ValueError("Input arrays must have the same shape.") @@ -157,8 +151,7 @@ def combine_loadings_arrays(gene_loadings_pos: np.ndarray, gene_loadings_neg: np # Raise warning if conflicts found if np.any(conflict_mask): conflict_indices = np.argwhere(conflict_mask) - warnings.warn(f"Conflicts found at {len(conflict_indices)} locations. " - f"Example: {conflict_indices[:5].tolist()}") + warnings.warn(f"Conflicts found at {len(conflict_indices)} locations. Example: {conflict_indices[:5].tolist()}") # Initialize combined output combined = np.zeros_like(gene_loadings_pos) @@ -168,7 +161,6 @@ def combine_loadings_arrays(gene_loadings_pos: np.ndarray, gene_loadings_neg: np return combined - def factors_to_cells( sdata: SpatialData, extracellular_layer: str = "segmentation_free_table", cellular_layer: str = "table", copy: bool | None = None ) -> SpatialData: diff --git a/src/troutpy/tl/source_cell.py b/src/troutpy/tl/source_cell.py index a0c0d7e..e654176 100644 --- a/src/troutpy/tl/source_cell.py +++ b/src/troutpy/tl/source_cell.py @@ -376,7 +376,7 @@ def process_gene(gene, extracellular_transcripts, cells, coord_cells, cell_types residual = 1e-6 # small stabilizing term row_sums = scores.sum(axis=1, keepdims=True) + residual scores = scores / row_sums - #scores=scores.div(scores.sum(axis=1),axis=0) + # scores=scores.div(scores.sum(axis=1),axis=0) gene_prob_df = compute_probability_table(scores, cell_indices, cell_types_filt, all_cell_types, gene_transcripts) gene_closest_df = build_closest_cell_table(distances_min, closest_cell_ids, closest_cell_types, gene_transcripts) @@ -452,13 +452,12 @@ def store_results_in_sdata(sdata, prob_table, closest_table, extracellular_trans sdata["table"].obs["urna_source_score"] = list(np.sum(cell_source_table, axis=1)) try: - adata=sdata['table'] - raw_expr=adata.layers['raw'] + adata = sdata["table"] + raw_expr = adata.layers["raw"] cell_expr_sum = np.array(np.sum(raw_expr.todense(), axis=1)).flatten() - sdata["table"].obs['normalized_urna_source_score'] = adata.obs['urna_source_score'] / cell_expr_sum + sdata["table"].obs["normalized_urna_source_score"] = adata.obs["urna_source_score"] / cell_expr_sum except KeyError: - print('Normalized urna source score could not be computed') - + print("Normalized urna source score could not be computed") def compute_contribution_score(sdata): @@ -509,4 +508,4 @@ def compute_contribution_score(sdata): score = contribution_matrix.sum(axis=1) adata.obs["urna_contribution_score"] = score - adata.obs["normalized_urna_contribution_score"]=score/np.sum(raw_expr,axis=1) + adata.obs["normalized_urna_contribution_score"] = score / np.sum(raw_expr, axis=1) diff --git a/src/troutpy/tl/target_cell.py b/src/troutpy/tl/target_cell.py index 1f19d23..ade48ae 100644 --- a/src/troutpy/tl/target_cell.py +++ b/src/troutpy/tl/target_cell.py @@ -168,7 +168,6 @@ def compute_target_score( sdata : SpatialData SpatialData object with target score table added. """ - # Coordinate keys if coords_key is None: coords_key = ["x", "y"] @@ -186,9 +185,7 @@ def compute_target_score( transcript_coords = extracellular_transcripts[[xcoord, ycoord]].to_numpy() # Output score table - target_scores_table = pd.DataFrame( - 0, index=extracellular_transcripts.index, columns=all_cell_types, dtype=float - ) + target_scores_table = pd.DataFrame(0, index=extracellular_transcripts.index, columns=all_cell_types, dtype=float) # KDTree on cell centroids kdtree = KDTree(coord_cells)