Perturbation API

Import the perturbation module:

from intratalkerpy import perturbation

The perturbation module keeps its method, utility, and plotting namespaces:

Methods

IntraTalkerPy Methods Module (mt)

This module provides analysis methods for receptor-ligand interaction studies in single-cell data, including differential pseudotime analysis, perturbation simulation, and embedding projection methods.

Functions:
Analysis Methods:
  • differential_pseudotime_analysis: Analyze receptor effects on pseudotime trajectories

Regression Methods:
  • calculate_coef_matrix_ridge: Estimate receptor influence on target gene expression

  • compute_receptor_coeff_stats: Summarize a regression coefficient matrix per receptor

Simulation Methods:
  • simulation_of_perturbation: Simulate gene expression perturbations through propagation

  • project_perturbation_in_embedding: Project perturbations into embedding space

  • permute_rows_nsign: Helper function for random matrix permutation

intratalkerpy.perturbation.mt.calculate_coef_matrix_ridge(data, regulon, alpha=10.0, source_col='Receptor', target_col='Target_Gene')

Fit Ridge regression models to estimate receptor influence on target gene expression and store the resulting coefficient matrix and regression statistics in the AnnData object.

For each gene in the expression matrix, a Ridge regression model is trained using the expression of its upstream regulators (receptors) as predictors. Genes that are not present in the regulon or have no valid receptor regulators are assigned zero coefficients. Results are stored in data.uns.

Parameters

dataanndata.AnnData

Annotated data matrix where rows are observations (cells/samples) and columns are genes. Expression values are retrieved via data.to_df().

regulonpandas.DataFrame

A DataFrame describing receptor-target relationships. Must contain at least two columns: one for source receptors and one for target genes (see source_col and target_col).

alphafloat, optional

Regularisation strength for Ridge regression. Larger values impose stronger regularisation. Default is 10.0.

source_colstr, optional

Name of the column in regulon that contains receptor (source) gene names. Default is "Receptor", the naming used by the receptome.

target_colstr, optional

Name of the column in regulon that contains target gene names. Default is "Target_Gene", the naming used by the receptome.

Returns

anndata.AnnData

The input data object with the following entries added to data.uns:

"regression_coef_matrix"pandas.DataFrame

A (genes × genes) coefficient matrix where entry [i, j] represents the Ridge regression coefficient of receptor i predicting target gene j. Columns are target genes; rows are all genes. Entries are zero when a gene is not a regulator of that target.

"regression_statistics"pandas.DataFrame

Per-target-gene regression diagnostics, indexed by target gene name, with the following columns:

  • num_receptors – number of receptors used as predictors.

  • num_selected_features – number of non-zero receptor coefficients.

  • alpha – regularisation strength used by the fitted model.

  • mse – mean squared error on the training data.

  • rmse – root mean squared error on the training data.

  • nrmse_mean – RMSE normalised by the mean of the target.

  • nrmse_maxmin – RMSE normalised by the (max − min) range of the target.

  • r2 – R² coefficient of determination on the training data.

"regression_coef_statistics"object

Summary statistics over the coefficient matrix, as returned by compute_receptor_coeff_stats().

Notes

  • Self-regulation is excluded: if a gene appears as both source and target for itself, it is removed from the predictor set before fitting.

  • Only receptors present in both the regulon and the expression matrix are used as predictors.

  • Genes absent from the regulon receive an all-zero coefficient vector.

  • Regression metrics are computed on training data (in-sample), so they reflect model fit rather than generalisation performance.

Examples

>>> from intratalkerpy.perturbation.ut import generate_receptome
>>> receptome = generate_receptome(
...     intracellular_networks=tf_obj.intracellular_network_cluster,
...     CTR_input=crosstalker_input,
... )
>>> data = calculate_coef_matrix_ridge(
...     data=adata,
...     regulon=receptome["receptome_wo_celltype"],
...     alpha=5.0,
... )
>>> coef_matrix = data.uns["regression_coef_matrix"]
>>> stats = data.uns["regression_statistics"]
intratalkerpy.perturbation.mt.compute_receptor_coeff_stats(coeff_matrix: DataFrame, regulon: DataFrame, source_col: str = 'Receptor') DataFrame

Compute coefficient statistics from a regression coefficient matrix stored in an AnnData object and save the results back into adata.uns.

Intended to be called directly after training the regression model.

Parameters

coeff_matrixpd.DataFrame

DataFrame containing the coefficient matrix with receptors as rows and samples/iterations as columns.

regulonpd.DataFrame

DataFrame with a receptor column used to count how many target genes each receptor regulates.

source_colstr, optional

Name of the column in regulon that contains receptor (source) gene names. Default is "Receptor", the naming used by the receptome.

Returns

pd.DataFrame
DataFrame containing the computed statistics for each receptor:
  • Gene : receptor/gene name

  • Mean_Coeff : mean coefficient across columns

  • Median_Coeff : median coefficient across columns

  • Std_Coeff : standard deviation of coefficients

  • Sum_Coeff : sum of coefficients

  • AbsSum_Coeff : sum of absolute values of coefficients

  • Max_Coeff : maximum coefficient

  • Min_Coeff : minimum coefficient

  • Num_Positive : number of positive coefficients

  • Num_Negative : number of negative coefficients

  • Num_Nonzero : number of non-zero coefficients

  • count : number of target genes regulated (from regulon)

intratalkerpy.perturbation.mt.differential_pseudotime_analysis(adata: AnnData, folder_path: str | Path, save_path: str | Path, red_namem: str, cell_anno: str, pseudo_name: str, grid_size: int = 25, offset_frac: float = 0.005, n_neigh: int = 10, n_cpu: int = 1, file_suffix: str | None = '_delta_matrix', output_name: str = 'differential_pseudotime.h5ad') AnnData

Perform differential pseudotime analysis for receptor-ligand interactions.

This function analyzes how receptor-ligand interactions affect pseudotime trajectories by computing vector fields and differential pseudotime changes for each receptor from CSV files containing perturbation data.

Parameters

adataAnnData

Annotated data object containing single-cell data.

folder_pathstr or Path

Path to folder containing CSV files with receptor perturbation data. Each CSV file should be named “{receptor}{file_suffix}.csv”; other files in the folder are ignored unless file_suffix is None.

save_pathstr or Path

Directory where the output AnnData object will be written; created if needed.

red_namemstr

Key in adata.obsm containing the embedding coordinates (e.g., ‘X_umap’).

cell_annostr

Key in adata.obs containing cell type annotations.

pseudo_namestr

Key in adata.obs containing pseudotime values.

grid_sizeint, default=25

Size of the grid for vector field calculation (both rows and columns).

offset_fracfloat, default=0.005

Fraction of embedding range to use as offset from boundaries.

n_neighint, default=10

Number of nearest neighbors for gradient computation.

n_cpuint, default=1

Number of CPU cores to use for parallel processing.

file_suffixstr or None, default=”_delta_matrix”

Constant part of the CSV filenames that follows the receptor name. Only files ending in this suffix are read, and it is stripped to recover the receptor name. Pass None to read every CSV in the folder and use the whole filename stem as the receptor name.

output_namestr, default=”differential_pseudotime.h5ad”

Name of the .h5ad file written into save_path. The “.h5ad” extension is appended if missing.

Returns

AnnData

Updated AnnData object with: - New columns in .obs: ‘pseudotime_{receptor}’ for each receptor - .uns[‘receptor_scores’]: Dictionary with scores and p-values - .uns[‘vector_fields’]: Dictionary with vector field data

Raises

FileNotFoundError

If folder_path doesn’t exist or contains no CSV files.

KeyError

If required keys are missing from adata.

ValueError

If input parameters are invalid.

intratalkerpy.perturbation.mt.permute_rows_nsign(A: ndarray) None

Permute entries in place and randomly flip the sign for each row of a matrix independently.

Adapted from CellOracle.

Parameters

A:

2-D array whose rows are shuffled in place.

intratalkerpy.perturbation.mt.project_perturbation_in_embedding(anndata: AnnData, perturbed_matrix: DataFrame, reduction_name: str, original_matrix: DataFrame | None = None, sigma_corr: float = 0.05, n_cpu: int = 1) ndarray

Project a perturbation simulation result onto a low-dimensional embedding.

Based on CellOracle / Velocyto code.

Parameters

anndata:

AnnData object containing the embedding in obsm.

perturbed_matrix:

Gene expression DataFrame of the perturbed state (cells x genes).

reduction_name:

Key in anndata.obsm to use as the embedding (e.g. "X_umap").

original_matrix:

Gene expression DataFrame of the unperturbed state (cells x genes). Defaults to anndata.to_df() when None.

sigma_corr:

Kernel width for the transition probability calculation. Default 0.05.

n_cpu:

Number of threads / CPUs to use. Default 1.

Returns

np.ndarray

Delta embedding vectors for each cell (cells x embedding dimensions).

Raises

ValueError

If reduction_name is not found in anndata.obsm.

intratalkerpy.perturbation.mt.simulation_of_perturbation(gem, simulation_input, coef_matrix, n_propagation)

Simulate gene expression perturbations through iterative propagation.

This function simulates the effect of gene expression perturbations by iteratively propagating changes through a coefficient matrix representing gene-gene interactions. The simulation ensures non-negative gene expression values throughout the process.

Parameters

gemarray-like

Original gene expression matrix with shape (n_cells, n_genes).

simulation_inputarray-like

Target gene expression matrix after perturbation with shape (n_cells, n_genes). Must have the same shape as gem.

coef_matrixarray-like

Coefficient matrix representing gene-gene interactions with shape (n_genes, n_genes). Used for propagating perturbation effects across genes.

n_propagationint

Number of propagation iterations to perform. Must be non-negative.

Returns

array-like

Simulated gene expression matrix after perturbation propagation. Same type and shape as input gem.

Raises

ValueError

If input matrices have incompatible shapes. If n_propagation is negative.

Utilities

IntraTalkerPy Utilities Module (ut)

This module provides utility functions for data processing and analysis, including grid-based vector field calculations, statistical ranking functions, pseudotime gradient computation, and differential pseudotime analysis.

Functions:
Grid Calculations:
  • calculate_grid_arrows: Calculate smoothed vector field on regular grid

  • validate_grid_parameters: Validate parameters for grid calculation

  • estimate_optimal_grid_size: Estimate optimal grid size for data

Statistical Rankings:
  • calculate_pseudotime_comparison: Comprehensive pseudotime comparison (returns dict)

  • calculate_effect_size_from_differences: Effect size analysis (returns dict)

Pseudotime Analysis:
  • compute_pseudotime_gradient: Compute gradient vectors from pseudotime

  • compute_differential_pseudotime: Compute differential pseudotime changes

  • estimate_optimal_neighbors: Estimate optimal neighbor count for gradients

Receptome Generation:
  • generate_receptome: Link intercellular to intracellular interactions

intratalkerpy.perturbation.ut.calculate_effect_size_from_differences(differences: ndarray, test_method: str = 'wilcoxon', confidence_level: float = 0.95) Tuple[float, float]

Calculate effect size from pseudotime differences.

This function calculates Cohen’s d effect size and provides statistical significance testing for pseudotime differences.

Parameters

differencesnp.ndarray

Array of pseudotime differences (new - old).

test_methodstr, default=”wilcoxon”

Statistical test method: “wilcoxon”, “sign_test”, or “t_test”.

confidence_levelfloat, default=0.95

Confidence level for confidence interval calculation.

Returns

Tuple[float, float]
cohens_dfloat

Cohen’s d effect size.

p_valuefloat

Statistical significance.

Raises

ValueError

If differences array is empty or test_method is invalid.

Examples

>>> differences = np.array([0.1, -0.05, 0.2, 0.15, -0.1])
>>> cohens_d, p_value = calculate_effect_size_from_differences(differences)
>>> print(f"Cohen's d: {cohens_d:.3f}")
>>> print(f"P-value: {p_value:.3e}")
intratalkerpy.perturbation.ut.calculate_grid_arrows(embedding: ndarray, delta_embedding: ndarray, offset_frac: float = 0.1, n_grid_cols: int = 25, n_grid_rows: int = 25, n_neighbors: int = 30, n_cpu: int = 1, gaussian_scale: float = 0.5) Tuple[ndarray, ndarray, ndarray]

Calculate smoothed vector field on a regular grid from perturbation data.

This function creates a regular grid over the embedding space and calculates smoothed vector field arrows by averaging nearby perturbation vectors using a Gaussian kernel weighting scheme.

Parameters

embeddingnp.ndarray

2D embedding coordinates of shape (n_cells, 2).

delta_embeddingnp.ndarray

Perturbation vectors of shape (n_cells, 2).

offset_fracfloat, default=0.1

Fraction of the embedding range to use as offset from boundaries. Must be between 0 and 0.5.

n_grid_colsint, default=25

Number of grid columns (x-direction).

n_grid_rowsint, default=25

Number of grid rows (y-direction).

n_neighborsint, default=30

Number of nearest neighbors to consider for each grid point.

n_cpuint, default=1

Number of CPU cores to use for nearest neighbor search.

gaussian_scalefloat, default=0.5

Scale parameter for the Gaussian kernel weighting.

Returns

Tuple[np.ndarray, np.ndarray, np.ndarray]
  • grid_xy: Grid point coordinates of shape (n_grid_points, 2)

  • uv: Smoothed vector field of shape (n_grid_points, 2)

  • mask: Boolean mask indicating valid grid points

Raises

ValueError

If input arrays have incompatible shapes or invalid parameters.

Notes

The function uses a Gaussian kernel to weight the contribution of nearby cells to each grid point. The mask identifies grid points that are too far from any actual data points and should be excluded from visualization.

intratalkerpy.perturbation.ut.calculate_pseudotime_comparison(old_pseudotime: ndarray, new_pseudotime: ndarray, pseudocount: float = 1e-06, tolerance: float = 1e-10) Tuple[float, float]

Comprehensive comparison of old vs new pseudotime distributions.

This function performs multiple statistical tests to compare two pseudotime distributions and provides a comprehensive summary of the differences.

Parameters

old_pseudotimenp.ndarray

Original pseudotime values.

new_pseudotimenp.ndarray

Modified pseudotime values.

pseudocountfloat, default=1e-6

Small value added to prevent log(0) in odds ratio calculation.

tolerancefloat, default=1e-10

Tolerance for considering values as unchanged.

Returns

Tuple[float, float]
log_odds_ratiofloat

Log odds ratio of increase vs decrease.

p_valuefloat

Statistical significance (Wilcoxon test).

Raises

ValueError

If arrays have different lengths or contain invalid values.

Examples

>>> old_pt = np.array([0.1, 0.2, 0.3, 0.4])
>>> new_pt = np.array([0.15, 0.25, 0.35, 0.45])
>>> log_odds_ratio, p_value = calculate_pseudotime_comparison(old_pt, new_pt)
>>> print(f"Log odds ratio: {log_odds_ratio:.3f}")
>>> print(f"P-value: {p_value:.3e}")
intratalkerpy.perturbation.ut.compute_differential_pseudotime(emb, grid_xy, uv, gradient_vectors)

Compute differential pseudotime changes based on vector field analysis.

This function calculates the pseudotime differential by projecting velocity vectors onto gradient vectors at each point in the embedding space.

Parameters

embarray_like

Cell embedding coordinates with shape (n_cells, 2).

grid_xyarray_like

Grid point coordinates with shape (n_grid_points, 2).

uvarray_like

Velocity vectors at grid points with shape (n_grid_points, 2).

gradient_vectorsarray_like

Gradient vectors at cell positions with shape (n_cells, 2).

Returns

np.ndarray

Differential pseudotime values with shape (n_cells,).

intratalkerpy.perturbation.ut.compute_pseudotime_gradient(emb, pseudotime, n_neigh=10)

Compute pseudotime gradient vectors using nearest neighbor analysis.

This function calculates gradient vectors that represent the direction of pseudotime increase in the embedding space. For each point, it uses least squares fitting on the nearest neighbors to estimate the local gradient direction.

Parameters

embarray_like

Cell embedding coordinates with shape (n_cells, n_dims). Typically 2D embeddings with shape (n_cells, 2).

pseudotimearray_like

Pseudotime values for each cell with shape (n_cells,).

n_neighint, default=10

Number of nearest neighbors to use for gradient estimation.

Returns

np.ndarray

Normalized gradient vectors with shape (n_cells, n_dims). Each vector points in the direction of steepest pseudotime increase.

intratalkerpy.perturbation.ut.estimate_optimal_grid_size(embedding: ndarray) Tuple[int, int]

Estimate optimal grid size based on embedding density.

Parameters

embeddingnp.ndarray

2D embedding coordinates.

Returns

Tuple[int, int]

Recommended (n_grid_cols, n_grid_rows).

intratalkerpy.perturbation.ut.estimate_optimal_neighbors(emb, pseudotime, max_neighbors=50)

Estimate optimal number of neighbors for gradient computation.

Parameters

embnp.ndarray

Embedding coordinates.

pseudotimenp.ndarray

Pseudotime values.

max_neighborsint, default=50

Maximum number of neighbors to consider.

Returns

int

Estimated optimal number of neighbors.

intratalkerpy.perturbation.ut.generate_receptome(intracellular_networks: DataFrame | Sequence[DataFrame] | Mapping[str, DataFrame], CTR_input: DataFrame, celltypes: Iterable[str] | None = None, out_path: str | None = None) Dict[str, DataFrame]

Build the receptome by linking intercellular to intracellular interactions.

Keeps the intracellular receptor to target gene connections whose receptor is actually engaged by a ligand in the receiving cell type, according to the ligand-receptor interactions of the CrossTalkeR input. Receptor complexes in the CrossTalkeR input are split into their subunits, and node type suffixes added by intratalkerpy.tf.add_node_type (e.g. "|R") are removed before matching.

The resulting receptor to target gene table is the regulon input of calculate_coef_matrix_ridge, whose source_col and target_col default to the "Receptor" and "Target_Gene" naming used here.

Parameters

intracellular_networkspandas.DataFrame or sequence or mapping of pandas.DataFrame

Intracellular network(s) as returned by intratalkerpy.tf.generate_intracellular_network, containing the columns "Receptor", "celltype" and "Target_Gene". A mapping such as TFObj.intracellular_network_cluster is accepted directly; all networks are pooled and deduplicated.

CTR_inputpandas.DataFrame

CrossTalkeR result table with ligand-receptor interactions. The function accepts the tables as are generated by the differential CrossTalkeR analysis, or also the interaction tables used as input of CrossTalkeR. Must contain the columns "type_gene_A", "type_gene_B", "gene_B" and "target".

celltypesiterable of str, optional

Cell types for which an additional, separate receptome table is returned. All cell types present in the receptome are used if None.

out_pathstr, optional

Output path to save the resulting tables as csv. Nothing is written if None.

Returns

Dict[str, pandas.DataFrame]

Dictionary with the following entries:

"receptome"pandas.DataFrame

Receptor, celltype and target gene of every retained connection.

"receptome_wo_celltype"pandas.DataFrame

Receptor to target gene connections pooled over all cell types.

"<celltype>_receptome"pandas.DataFrame

One table per entry of celltypes, subset to that cell type.

Raises

ValueError

If no intracellular network is provided.

NameError

If an intracellular network or the CrossTalkeR input is missing required columns.

Examples

>>> from intratalkerpy.perturbation.ut import generate_receptome
>>> receptome = generate_receptome(
...     intracellular_networks=tf_obj.intracellular_network_cluster,
...     CTR_input=crosstalker_input,
...     out_path="results/",
... )
>>> data = calculate_coef_matrix_ridge(
...     data=adata,
...     regulon=receptome["receptome_wo_celltype"],
... )
intratalkerpy.perturbation.ut.validate_grid_parameters(n_grid_cols: int, n_grid_rows: int, offset_frac: float, n_neighbors: int) None

Validate parameters for grid calculation.

Parameters

n_grid_colsint

Number of grid columns.

n_grid_rowsint

Number of grid rows.

offset_fracfloat

Offset fraction.

n_neighborsint

Number of neighbors.

Raises

ValueError

If any parameter is invalid.

Plotting

IntraTalkerPy Plotting Module (pl)

This module provides comprehensive plotting functions for receptor analysis, including barplots, heatmaps, pseudotime analysis, and vector field visualization.

The module contains the following main plotting functions:

Score Visualization:
  • plot_score_barplots: Create barplots of receptor scores across cell types

  • plot_score_heatmap: Generate clustered heatmaps of receptor scores

Pseudotime Analysis:
  • plot_differential_pseudotime: Plot pseudotime differences on embeddings

  • plot_pseudotime_distributions: Compare pseudotime distributions

Vector Field Analysis:
  • plot_metadata_given_ax: Plot metadata on 2D embeddings

  • vector_field_wrapper: Create streamline vector field plots

  • plot_raw_vector_field: Plot raw perturbation vector fields

  • plot_smoothed_vector_field: Plot smoothed perturbation vector fields

intratalkerpy.perturbation.pl.plot_differential_pseudotime(emb: ndarray, pseudotime_diff: ndarray, ax: Axes, receptor: str, colors: List[str] | None = None, n_bins: int = 256, point_size: float = 15, title: str | None = None, colorbar: bool = True, colorbar_label: str = 'Pseudotime Difference', alpha: float = 1.0, edgecolors: str = 'none') Axes

Plot differential pseudotime values on a 2D embedding.

Parameters

embnp.ndarray

2D embedding coordinates of shape (n_cells, 2).

pseudotime_diffnp.ndarray

Pseudotime difference values for each cell.

axplt.Axes

Matplotlib axes object to plot on.

receptorstr

Name of the receptor being analyzed.

colorsList[str], optional

Custom colors for the colormap. Default uses blue-white-red.

n_binsint, default=256

Number of bins for the colormap.

point_sizefloat, default=15

Size of scatter plot points.

titlestr, optional

Custom title for the plot. If None, uses default format.

colorbarbool, default=True

Whether to add a colorbar.

colorbar_labelstr, default=”Pseudotime Difference”

Label for the colorbar.

alphafloat, default=1.0

Transparency of points (0-1).

edgecolorsstr, default=’none’

Edge colors for scatter points.

Returns

plt.Axes

The modified axes object.

Raises

ValueError

If input arrays have incompatible shapes or invalid values.

intratalkerpy.perturbation.pl.plot_metadata_given_ax(anndata, ax: <module 'matplotlib.axes' from '/opt/hostedtoolcache/Python/3.12.14/x64/lib/python3.12/site-packages/matplotlib/axes/__init__.py'>, reduction_name: str, variable: str, color_dictionary, receptor: str, remove_nan: bool | None = True, show_label: bool | None = True, show_legend: bool | None = False, cmap: str | <module 'matplotlib.cm' from '/opt/hostedtoolcache/Python/3.12.14/x64/lib/python3.12/site-packages/matplotlib/cm.py'> | None = <matplotlib.colors.ListedColormap object>, dot_size: int | None = 10, text_size: int | None = 10, alpha: float | int | None = 1, seed: int | None = 555, selected_cells: List[str] | None = None)

Plot metadata on a 2D embedding. Based on the CellOracle implementation.

Parameters

anndataAnnData

Annotated data object containing embedding and metadata.

axmatplotlib.axes

Matplotlib axes object to plot on.

reduction_namestr

Name of the reduction/embedding in anndata.obsm (e.g., ‘X_umap’, ‘X_pca’).

variablestr

Variable name to plot from anndata.obs.

color_dictionarydict

Dictionary containing color mappings for categorical variables. Expected format: {variable_name: {category: color}}.

receptorstr

Name of the receptor being analyzed (used in plot title).

remove_nanbool, default=True

Whether to remove NaN values from categorical data.

show_labelbool, default=True

Whether to show category labels on the plot.

show_legendbool, default=False

Whether to display legend.

cmapstr or matplotlib.cm, default=cm.viridis

Colormap for continuous variables.

dot_sizeint, default=10

Size of scatter plot points.

text_sizeint, default=10

Size of label text.

alphafloat or int, default=1

Transparency of points (0-1).

seedint, default=555

Random seed for color generation.

selected_cellsList[str], optional

Subset of cell names to plot.

Returns

matplotlib.axes

The modified axes object.

intratalkerpy.perturbation.pl.plot_pseudotime_distributions(adata: Any, orig_pseudotime: str, receptor: str, cell_anno: str, result_path: str, figsize: Tuple[float, float] = (6, 4), aspect: float = 1.5, height: float = 3, alpha: float = 0.5, palette: str | None = None, save_format: str = 'pdf', title_template: str | None = None, show_plot: bool = True, dpi: int = 300) FacetGrid

Plot and compare distributions of original and receptor-specific pseudotime.

Parameters

adataAnnData

Annotated data object containing pseudotime information.

orig_pseudotimestr

Column name for original pseudotime in adata.obs.

receptorstr

Name of the receptor being analyzed.

cell_annostr

Column name for cell annotations in adata.obs.

result_pathstr

Path where the plot will be saved.

figsizeTuple[float, float], default=(6, 4)

Figure size as (width, height) in inches.

aspectfloat, default=1.5

Aspect ratio of each facet.

heightfloat, default=3

Height of each facet in inches.

alphafloat, default=0.5

Transparency of density plots (0-1).

palettestr, optional

Color palette for the plots.

save_formatstr, default=”pdf”

File format for saving the plot.

title_templatestr, optional

Custom title template. If None, uses default.

show_plotbool, default=True

Whether to display the plot.

dpiint, default=300

Resolution for saved figure.

Returns

sns.FacetGrid

The seaborn FacetGrid object.

Raises

ValueError

If required columns are missing from adata.obs.

KeyError

If specified columns don’t exist in the data.

intratalkerpy.perturbation.pl.plot_raw_vector_field(emb: ndarray, delta_vec: ndarray, figsize: Tuple[float, float] = (8, 6), point_size: float = 5, point_alpha: float = 0.5, vector_color: str = 'red', vector_alpha: float = 0.7, vector_scale: float = 1, title: str = 'Raw Perturbation Vector Field', save_path: str | None = None, show_plot: bool = True, dpi: int = 300) Figure

Plot raw vector field showing perturbation vectors.

Parameters

embnp.ndarray

2D embedding coordinates of shape (n_cells, 2).

delta_vecnp.ndarray

Perturbation vectors of shape (n_cells, 2).

figsizeTuple[float, float], default=(8, 6)

Figure size as (width, height) in inches.

point_sizefloat, default=5

Size of cell points.

point_alphafloat, default=0.5

Transparency of cell points.

vector_colorstr, default=”red”

Color of vector arrows.

vector_alphafloat, default=0.7

Transparency of vector arrows.

vector_scalefloat, default=1

Scale factor for vector arrows.

titlestr, default=”Raw Perturbation Vector Field”

Title for the plot.

save_pathstr, optional

Path to save the figure.

show_plotbool, default=True

Whether to display the plot.

dpiint, default=300

Resolution for saved figure.

Returns

plt.Figure

The matplotlib figure object.

Raises

ValueError

If input arrays have incompatible shapes.

intratalkerpy.perturbation.pl.plot_score_barplots(receptor_scores: Dict[str, Dict[str, Any]], result_path: str, cohens_d_threshold: float = 0.5, fig_width: float = 15, fig_height: float = 6, top_n: int = 10, x_limits: Tuple[float, float] | None = None, palette: str = 'Blues_r', exclude_cell_types: list | None = None, save_format: str = 'pdf') Figure

Plot barplots of receptor scores for different cell types.

Parameters

receptor_scoresDict[str, Dict[str, Any]]

Dictionary containing receptor scores and p-values. Expected structure: {receptor: {“scores”: {cell_type: score}, “p_vals”: {cell_type: pval}}}

result_pathstr

Path where the plot will be saved.

cohens_d_thresholdfloat, default=0.5

Minimum absolute Cohen’s d value to include in the plot.

fig_widthfloat, default=15

Width of the figure in inches.

fig_heightfloat, default=6

Height of the figure in inches.

top_nint, default=10

Number of top receptors to show per cell type.

x_limitsTuple[float, float], optional

Custom x-axis limits. If None, uses (-3, 3).

palettestr, default=”Blues_r”

Color palette for the barplots.

exclude_cell_typeslist, optional

List of cell types to exclude from plotting.

save_formatstr, default=”pdf”

File format for saving the plot.

Returns

plt.Figure

The matplotlib figure object.

Raises

ValueError

If input data is invalid or empty.

intratalkerpy.perturbation.pl.plot_score_heatmap(receptor_scores: Dict[str, Dict[str, Any]], result_path: str, max_score_limit: float = 3.0, figsize: Tuple[float, float] = (12, 8), cmap: str = 'coolwarm', significance_method: str = 'score', score_thresholds: Tuple[float, float, float] = (0.2, 0.5, 0.8), pval_thresholds: Tuple[float, float, float] = (0.05, 0.01, 0.001), cluster_rows: bool = True, cluster_cols: bool = True, dendrogram_ratio: Tuple[float, float] = (0.2, 0.2), linewidths: float = 0.5, save_csv: bool = True, save_format: str = 'pdf', exclude_cell_types: list | None = None, title: str | None = None) ClusterGrid

Create a clustered heatmap of receptor scores across cell types.

Parameters

receptor_scoresDict[str, Dict[str, Any]]

Dictionary containing receptor scores and p-values. Expected structure: {receptor: {“scores”: {cell_type: score}, “p_vals”: {cell_type: pval}}}

result_pathstr

Path where the plot and CSV will be saved.

max_score_limitfloat, default=3.0

Maximum absolute value for score clipping.

figsizeTuple[float, float], default=(12, 8)

Figure size as (width, height) in inches.

cmapstr, default=”coolwarm”

Colormap for the heatmap.

significance_methodstr, default=”score”

Method for significance annotation: “score” (based on Cohen’s d) or “pval” (based on p-values).

score_thresholdsTuple[float, float, float], default=(0.2, 0.5, 0.8)

Thresholds for one-, two-, and three-star significance based on absolute Cohen’s d values.

pval_thresholdsTuple[float, float, float], default=(0.05, 0.01, 0.001)

Thresholds for one-, two-, and three-star significance based on p-values (from high to low).

cluster_rowsbool, default=True

Whether to cluster rows (receptors).

cluster_colsbool, default=True

Whether to cluster columns (cell types).

dendrogram_ratioTuple[float, float], default=(0.2, 0.2)

Ratio of dendrogram size to main plot.

linewidthsfloat, default=0.5

Width of lines separating heatmap cells.

save_csvbool, default=True

Whether to save the data as CSV.

save_formatstr, default=”pdf”

File format for saving the plot.

exclude_cell_typeslist, optional

List of cell types to exclude from the heatmap.

titlestr, optional

Custom title for the plot. If None, uses default title.

Returns

sns.matrix.ClusterGrid

The seaborn ClusterGrid object.

Raises

ValueError

If input data is invalid or empty.

intratalkerpy.perturbation.pl.plot_smoothed_vector_field(emb: ndarray, delta_vec: ndarray, figsize: Tuple[float, float] = (8, 6), point_size: float = 5, point_alpha: float = 0.5, vector_color: str = 'red', vector_alpha: float = 0.7, vector_scale: float = 1, title: str = 'Smoothed Perturbation Vector Field', save_path: str | None = None, show_plot: bool = True, dpi: int = 300) Figure

Plot smoothed vector field showing perturbation vectors.

Parameters

embnp.ndarray

2D embedding coordinates of shape (n_cells, 2).

delta_vecnp.ndarray

Smoothed perturbation vectors of shape (n_cells, 2).

figsizeTuple[float, float], default=(8, 6)

Figure size as (width, height) in inches.

point_sizefloat, default=5

Size of cell points.

point_alphafloat, default=0.5

Transparency of cell points.

vector_colorstr, default=”red”

Color of vector arrows.

vector_alphafloat, default=0.7

Transparency of vector arrows.

vector_scalefloat, default=1

Scale factor for vector arrows.

titlestr, default=”Smoothed Perturbation Vector Field”

Title for the plot.

save_pathstr, optional

Path to save the figure.

show_plotbool, default=True

Whether to display the plot.

dpiint, default=300

Resolution for saved figure.

Returns

plt.Figure

The matplotlib figure object.

Raises

ValueError

If input arrays have incompatible shapes.

intratalkerpy.perturbation.pl.vector_field_wrapper(adata, grid, vectors, distances, red_name, cell_anno, receptor, color_dict, ax, stream_density=1, zorder=10, grid_dist=25)

Create a vector field plot with streamlines overlay.

Parameters

adataAnnData

Annotated data object containing embedding and metadata.

gridnp.ndarray

Grid points for the vector field of shape (n_grid_points, 2).

vectorsnp.ndarray

Vector field values at grid points of shape (n_grid_points, 2).

distancesnp.ndarray

Distance values for coloring streamlines of shape (n_grid_points,).

red_namestr

Name of the reduction/embedding in adata.obsm.

cell_annostr

Cell annotation variable name from adata.obs.

receptorstr

Receptor name for labeling (used in plot title).

color_dictdict

Color dictionary mapping cell types to colors. Format: {variable_name: {cell_type: color_hex_string}}.

axmatplotlib.axes

Matplotlib axes object to plot on.

stream_densityint, default=1

Density of streamlines.

zorderint, default=10

Z-order for streamline plotting.

grid_distint, default=25

Grid distance parameter (grid will be grid_dist x grid_dist).

Returns

matplotlib.axes

The modified axes object with vector field plot.