nico_interactions package

Submodules

nico_interactions.Interactions module

nico_interactions.Interactions.create_directory(outputFolder)[source]

Create an empty directory.

This function checks if a specified directory exists, and if not, it creates the directory.

Parameters

outputFolderstr

The path of the directory to be created.

Raises

OSError

If the directory cannot be created due to permission issues or other OS-related errors.

Notes

  • If the directory already exists, no action is taken.

  • This function ensures that the directory path is available for subsequent file operations.

Example

>>> create_directory('./new_out/')
nico_interactions.Interactions.create_spatial_CT_feature_matrix(radius, PP, louvain, noct, fraction_CT, saveSpatial, epsilonThreshold)[source]

Generate the expected spatial cell type neighborhood matrix.

This helper function is used in spatial_neighborhood_analysis to create a matrix that represents the expected neighborhood cell type composition based on spatial data. It uses either a radius-based approach or Delaunay triangulation to determine neighboring cells.

Parameters

radiusfloat

Radius within which to find neighbors. If set to 0, Delaunay triangulation is used instead.

PPnp.ndarray

Array of spatial coordinates of cells. Shape (n_cells, n_dimensions).

louvainnp.ndarray

Array containing Louvain clustering results for each cell. Shape (n_cells, 1).

noctint

Number of cell types.

fraction_CTlist of float

List representing the fraction of each cell type.

saveSpatialstr

Path to save the output file containing the normalized spatial neighborhood matrix.

epsilonThresholdfloat

Threshold distance cutoff to limit the distant neighbors when using Delaunay triangulation.

Returns

tuple
  • Mint

    Placeholder for future calculations (currently always returns 0).

  • neighborslist of list of int

    List of neighbors for each cell. Each sublist contains indices of neighboring cells.

  • distancelist of list of float

    List of distances to neighbors for each cell. Each sublist contains distances to the neighboring cells.

Notes

  • If radius is set to 0, Delaunay triangulation is used to find the neighbors within the epsilonThreshold distance.

  • The function saves the normalized spatial neighborhood matrix as a .npz file at the specified location.

nico_interactions.Interactions.euclidean_dist(p1, p2)[source]

Calculate euclidean distance between two points in 2d/3d.

nico_interactions.Interactions.findNeighbors_in_given_radius(location, radius)[source]

Find the neighbors for each cell using the given radius.

This helper function used in create_spatial_CT_feature_matrix identifies the neighboring cells for each cell within the specified radius and computes the average distance to these neighbors.

Parameters:

locationnp.ndarray

An array of shape (n, 3) representing the coordinates of the cells.

radiusfloat

The radius within which to search for neighboring cells. For immediate neighbors it is 0

Returns:

list

A list of lists where each sublist contains the indices of the neighbors for each cell.

nico_interactions.Interactions.find_interacting_cell_types(input, choose_celltypes=[], celltype_niche_interaction_cutoff=0.1, dpi=300, coeff_cutoff=20, saveas='pdf', transparent_mode=False, showit=True, figsize=(4.0, 2.0))[source]

Display regression coefficients indicating cell type interactions.

Parameters:

inputobject

The main input is the output from spatial_neighborhood_analysis.

choose_celltypeslist, optional

List of cell types to display the regression coefficients for. If empty, the output will be shown for all cell types. Default is [].

celltype_niche_interaction_cutofffloat, optional

The cutoff value to consider for cell type niche interactions for normalized coefficients. This is visualized by blue dotted line. Default is 0.1.

coeff_cutoffint, optional

Maximum number of neighborhood cell types shown on the X-axis of the figures for each central cell type. If there are too many interacting cell types, choosing a more stringet cutoff limits the display to the cell types with the largest positive or negative regression coefficients to avoid crowding in the figure. Default is 20.

saveasstr, optional

Format to save the figures in, either ‘pdf’ or ‘png’. Default is ‘pdf’.

transparent_modebool, optional

Background color of the figures. Default is False.

showitbool, optional

Whether to display the figures. Default is True.

figsizetuple, optional

Dimension of the figure size. Default is (4.0, 2.0).

Outputs:

The figures are saved in ./nico_out/niche_prediction_linear/TopCoeff_R0/*

Notes:

  • The function normalizes the coefficients by dividing by maximum and then it visualizes by blue dotted line.

nico_interactions.Interactions.find_neighbors(pindex, triang)[source]

Find the neighbors for a given point index using Delaunay triangulation.

This helper function used in `create_spatial_CT_feature_matrix` identifies the neighboring points (cells) for a given point index using the Delaunay triangulation.

Parameters:

pindexint

The index of the point (cell) for which neighbors are to be found.

triangscipy.spatial.Delaunay

The Delaunay triangulation of the point set.

Returns:

np.ndarray

An array of indices representing the neighbors of the given point.

nico_interactions.Interactions.model_log_regression(K_fold, n_repeats, neighborhoodClass, target, lambda_c, strategy, BothLinearAndCrossTerms, seed, n_jobs)[source]

Perform logistic regression classification to learn the probabilities of each cell type class. This helper function used in spatial_neighborhood_analysis.

Parameters:

K_foldint

Number of folds for cross-validation.

n_repeatsint

Number of times the cross-validation is repeated.

neighborhoodClassnumpy.ndarray

Matrix of neighborhood class features.

targetnumpy.ndarray

Target labels (cell types).

lambda_clist or numpy.ndarray

Regularization strength(s) to be tested in the logistic regression.

strategystr

The regularization and multi-class strategy. Options include ‘L1_multi’, ‘L1_ovr’, ‘L2_multi’, ‘L2_ovr’, ‘elasticnet_multi’, ‘elasticnet_ovr’.

BothLinearAndCrossTermsint

Degree of polynomial features including interaction terms only.

seedint

Random seed for reproducibility.

n_jobsint

Number of jobs to run in parallel.

Returns:

log_reg_modelsklearn.linear_model.LogisticRegression

The logistic regression model with specified parameters.

parametersdict

Dictionary of parameters used for model training.

hyperparameter_scoringdict

Dictionary of scoring metrics used for hyperparameter tuning.

Notes:

  • The function uses polynomial features to create interaction terms based on the specified degree.

  • Hyperparameter tuning is performed using cross-validation with f1_weighted scoring metrics.

nico_interactions.Interactions.plot_coefficient_matrix(input, saveas='pdf', showit=True, transparent_mode=False, dpi=300, figsize=(5, 8))[source]

Generate and save a coefficient matrix plot from the results of spatial_neighborhood_analysis.

Parameters:

inputdict, or similar object

The main input is the output from spatial_neighborhood_analysis.

saveasstr, optional, default=’pdf’

Format to save the figure. Options are ‘pdf’ or ‘png’. If ‘png’, the dpi is set to 300.

showitbool, optional, default=True

Whether to display the plot after saving. If False, the plot will be closed after saving.

transparent_modebool, optional, default=False

Whether to save the figure with a transparent background.

figsizetuple of float, optional, default=(5, 8)

Size of the figure in inches.

Outputs:

The function saves the coefficient matrix plot in the directory specified by ./nico_out/niche_prediction_linear/. The filename will be in the format “weight_matrix_R<Radius>.<saveas>”, where <Radius> is the radius value from the input and <saveas> is the file format.

nico_interactions.Interactions.plot_confusion_matrix(input, saveas='pdf', showit=True, transparent_mode=False, dpi=300, figsize=(5.5, 5))[source]

Generate and save a confusion matrix plot from the results of spatial_neighborhood_analysis.

Parameters:

inputdict, or similar object

The main input is the output from spatial_neighborhood_analysis.

saveasstr, optional, default=’pdf’

Format to save the figure. Options are ‘pdf’ or ‘png’. If ‘png’, the dpi is set to 300.

showitbool, optional, default=True

Whether to display the plot after saving. If False, the plot will be closed after saving.

transparent_modebool, optional, default=False

Whether to save the figure with a transparent background.

figsizetuple of float, optional, default=(5.5, 5)

Size of the figure in inches.

Outputs:

The function saves the confusion matrix plot in the directory specified by nico_out/niche_prediction_linear/. The filename will be in the format ‘Confusing_matrix_R<Radius>.<saveas>’, where <Radius> is the radius value from the input and <saveas> is the file format.

Notes:

  • The function loads data from a numpy file specified by input.fout, which should contain the confusion matrix and related data.

  • The confusion matrix is plotted using seaborn’s heatmap function with annotations.

  • The plot is saved in the specified format and directory, and optionally displayed based on the showit parameter.

nico_interactions.Interactions.plot_evaluation_scores(input, saveas='pdf', transparent_mode=False, showit=True, dpi=300, figsize=(4, 3))[source]

This function generates and saves plots of evaluation scores obtained from the spatial_neighborhood_analysis. The plots can be saved in PDF or PNG format and can be displayed during execution.

Parameters

inputdict or similar

The main input is the output from spatial_neighborhood_analysis. This should contain the evaluation scores to be plotted.

saveasstr, optional

Format to save the figures. Options are ‘pdf’ or ‘png’. Default is ‘pdf’.

transparent_modebool, optional

If True, the background color of the figures will be transparent. Default is False.

showitbool, optional

If True, the figures will be displayed when the function is called. Default is True.

figsizetuple, optional

Dimensions of the figure size in inches (width, height). Default is (4, 3).

Outputs

None

The function saves the generated figures in the directory “./nico_out/niche_prediction_linear/” with filenames starting with “scores”.

Notes

  • The order of scores saved in input.score as follows:

      1. accuracy

      1. macro F1

      1. macro precision

      1. macro recall

      1. micro F1

      1. micro precision

      1. micro recall

      1. weighted F1

      1. weighted precision

      1. weighted recall

      1. Cohen Kappa

      1. cross entropy

      1. mathhew correlation coefficient

      1. heming loss

      1. zeros one loss

nico_interactions.Interactions.plot_multiclass_roc(clf, X_test, y_test, n_classes)[source]

Compute the ROC (Receiver Operating Characteristic) curve for each cell type prediction and evaluate its performance on the test dataset.

Parameters:

clfclassifier object

The classifier used for making predictions. It should have a decision_function method.

X_testarray-like of shape (n_samples, n_features)

Test feature set.

y_testarray-like of shape (n_samples,)

True labels for the test set.

n_classesint

Number of unique classes (cell types) in the dataset.

Returns:

fprdict

A dictionary where the keys are class indices and the values are arrays of false positive rates.

tprdict

A dictionary where the keys are class indices and the values are arrays of true positive rates.

roc_aucdict

A dictionary where the keys are class indices and the values are the area under the ROC curve (AUC) scores.

Notes:

  • This function uses the decision_function method of the classifier to get the confidence scores for each class.

  • The true labels y_test are converted into a binary format using one-hot encoding.

  • The ROC curve is computed for each class and the AUC score is calculated for each ROC curve.

nico_interactions.Interactions.plot_niche_interactions_with_edge_weight(input, niche_cutoff=0.1, saveas='pdf', transparent_mode=False, showit=True, figsize=(10, 7), dpi=300, input_colormap='jet', with_labels=True, node_size=300, linewidths=0.5, node_font_size=8, alpha=0.5, font_weight='normal', edge_label_pos=0.35, edge_font_size=3)[source]

Plot niche interactions map with edge weights.

This function generates and saves a directed graph that represents niche interactions map based on the output of spatial_neighborhood_analysis. The nodes represent cell types, and the edges (with weights) indicate the strength of interactions between central cell typ and niche cell types. The plot can be saved in PDF or PNG format and can be displayed during execution.

Parameters

inputdict or similar

The main input is the output from spatial_neighborhood_analysis. This should contain the necessary data to plot the niche interactions.

niche_cutofffloat, optional

Threshold for including interactions in the graph. Higher values result in fewer connections, while lower values include more connections. Default is 0.1.

saveasstr, optional

The format for saving the figures. Options are ‘pdf’ or ‘png’. Default is ‘pdf’.

transparent_modebool, optional

If True, saves the figure with a transparent background. Default is False.

showitbool, optional

If True, displays the plot after generating. Default is True.

figsizetuple, optional

Size of the figure in inches (width, height). Default is (10, 7).

dpiint, optional

Resolution in dots per inch for saving the figure. Default is 300.

input_colormapstr, optional

Color map for node colors, based on matplotlib colormaps. Default is ‘jet’. For details see documentation https://matplotlib.org/stable/gallery/color/colormap_reference.html

with_labelsbool, optional

If True, displays cell type labels on the nodes. Default is True.

node_sizeint, optional

Size of the nodes. Default is 300.

linewidthsint, optional

Width of the node border lines. Default is 0.5.

node_font_sizeint, optional

Font size for node labels. Default is 8.

alphafloat, optional

Opacity level for nodes and edges. Default is 0.5.

font_weightstr, optional

Weight of the font for node labels. Options are ‘normal’ or ‘bold’. Default is ‘normal’.

edge_label_posfloat, optional

Position of edge labels along the edges. Default is 0.35.

edge_font_sizeint, optional

Font size for edge labels. Default is 3.

Outputs

None

The function saves the generated figures in the directory “./nico_out/niche_prediction_linear/” with filenames starting with “Niche_interactions_*”.

nico_interactions.Interactions.plot_niche_interactions_without_edge_weight(input, niche_cutoff=0.1, saveas='pdf', transparent_mode=False, showit=True, figsize=(10, 7), dpi=300, input_colormap='jet', with_labels=True, node_size=300, linewidths=0.5, node_font_size=8, alpha=0.5, font_weight='normal')[source]

Plot niche interactions map without edge weights.

This function generates and saves a niche interactions map using data from the output of spatial_neighborhood_analysis. The graph illustrates connections between cell types based on their niche interactions, without weighting the edges by interaction strength. The output plot can be saved in either PDF or PNG format, and optionally displayed after generation.

Parameters

inputdict or similar

The main input containing data from spatial_neighborhood_analysis. This should include information on cell types and interaction strengths needed to plot niche cell type interactions.

niche_cutofffloat, optional

Threshold for plotting connections in the niche interactions map. Only connections with normalized interaction

strengths above this cutoff are displayed. Higher values reduce connections, while lower values increase them. Default is 0.1.

saveasstr, optional

Format to save the figures. Options are ‘pdf’ or ‘png’. Default is ‘pdf’.

transparent_modebool, optional

If True, the plot background will be transparent. Default is False.

showitbool, optional

If True, the figures will be displayed when the function is called. Default is True.

figsizetuple, optional

Dimensions of the plot in inches (width, height). Default is (10, 7).

dpiint, optional

Resolution in dots per inch for saving the figure. Default is 300.

input_colormapstr, optional

Color map for node colors, based on matplotlib colormaps. Default is ‘jet’. For details see documentation https://matplotlib.org/stable/gallery/color/colormap_reference.html

with_labelsbool, optional

If True, displays cell type labels on the nodes. Default is True.

node_sizeint, optional

Size of the nodes. Default is 300.

linewidthsint, optional

Width of the node border lines. Default is 0.5.

node_font_sizeint, optional

Font size for node labels. Default is 8.

alphafloat, optional

Opacity level for nodes and edges. Default is 0.5.

font_weightstr, optional

Weight of the font for node labels. Options are ‘normal’ or ‘bold’. Default is ‘normal’.

Outputs

None

The function saves the generated figures in the directory “./nico_out/niche_prediction_linear/” with filenames starting with “Niche_interactions_*”.

nico_interactions.Interactions.plot_predicted_probabilities(input, saveas='pdf', showit=True, transparent_mode=False, dpi=300, figsize=(12, 6))[source]

Generate and save a plot of predicted probabilities from the results of spatial_neighborhood_analysis.

Parameters:

inputdict, or similar object

The main input is the output from spatial_neighborhood_analysis.

saveasstr, optional, default=’pdf’

Format to save the figure. Options are ‘pdf’ or ‘png’. If ‘png’, the dpi is set to 300.

showitbool, optional, default=True

Whether to display the plot after saving. If False, the plot will be closed after saving.

transparent_modebool, optional, default=False

Whether to save the figure with a transparent background.

figsizetuple of float, optional, default=(12, 6)

Size of the figure in inches.

Outputs:

The function saves the plot of predicted probabilities in the directory specified by ./nico_out/niche_prediction_linear/. The filename will be in the format ‘predicted_probability_R<Radius>.<saveas>’, where <Radius> is the radius value from the input and <saveas> is the file format.

nico_interactions.Interactions.plot_roc_results(input, nrows=4, ncols=4, saveas='pdf', showit=True, transparent_mode=False, dpi=300, figsize=(10, 7))[source]

Generate and save ROC curves for the top 16 cell type predictions from the results of spatial_neighborhood_analysis.

Parameters:

inputdict, or similar object

The main input is the output from spatial_neighborhood_analysis.

nrowsint, optional, default=4

Number of rows in the subplot grid.

ncolsint, optional, default=4

Number of columns in the subplot grid.

saveasstr, optional, default=’pdf’

Format to save the figure. Options are ‘pdf’ or ‘png’. If ‘png’, the dpi is set to 300.

showitbool, optional, default=True

Whether to display the plot after saving. If False, the plot will be closed after saving.

transparent_modebool, optional, default=False

Whether to save the figure with a transparent background.

figsizetuple of float, optional, default=(10, 7)

Size of the figure in inches.

Outputs:

The function saves the ROC curves plot in the directory specified by ./nico_out/niche_prediction_linear. The filename will be in the format ‘ROC_R<Radius>.<saveas>’, where <Radius> is the radius value from the input and <saveas> is the file format.

Notes:

  • The function creates a grid of ROC curves for the top 16 cell types with the highest ROC AUC values.

nico_interactions.Interactions.read_processed_data(radius, inputdir)[source]

Read and process the neighborhood expected feature matrix for spatial_neighborhood_analysis.

Parameters:

radiusint or float

The radius value used in the spatial analysis.

inputdirstr

The directory containing the input data file.

Returns:

neighborhoodClassnumpy.ndarray

The matrix of neighborhood class features.

targetnumpy.ndarray

The target labels (cell types).

inputFeaturesrange

A range object representing the indices of the input features.

Notes:

  • The function reads a compressed .npz file containing the neighborhood expected feature matrix.

  • It filters out rows with NaN values.

  • It calculates the proportion of each cell type in the dataset.

  • The function returns the processed neighborhood class features, target labels, and input feature indices.

nico_interactions.Interactions.reading_data(coordinates, louvainFull, degbased_ctname, saveSpatial, removed_CTs_before_finding_CT_CT_interactions)[source]

Helper function used in spatial_neighborhood_analysis to read the cell coordinate file, cluster file, and cluster name file according to the input cell type list provided for the prediction.

Parameters:

coordinatesstr

Path to the file containing cell coordinates.

louvainFullstr

Path to the file containing the full louvain clustering information.

degbased_ctnamelist of tuples

A list where each element is a tuple containing the cell type ID and the cell type name.

saveSpatialstr

Path where the spatial analysis results should be saved.

removed_CTs_before_finding_CT_CT_interactionslist of str

A list of cell type names that should be excluded from the analysis.

Returns:

CTnamelist of str

A list of cell type names that are included in the analysis after filtering out the removed cell types.

CTidlist of int

A list of cell type IDs corresponding to the filtered cell type names.

Notes:

  • This function assumes that degbased_ctname is a list of tuples where the first element is an integer representing the cell type ID and the second element is a string representing the cell type name.

  • The function filters out the cell types listed in removed_CTs_before_finding_CT_CT_interactions from the degbased_ctname list and returns the remaining cell type names and IDs.

nico_interactions.Interactions.remove_extra_character_from_name(name)[source]

Remove special characters from cell type names to avoid errors while saving figures.

This function replaces certain special characters in the input name with underscores or other appropriate characters to ensure the name is safe for use as a filename.

Parameters

namestr

The original cell type name that may contain special characters.

Returns

str

The modified cell type name with special characters removed or replaced.

Example

>>> name = 'T-cell (CD4+)/CD8+'
>>> clean_name = remove_extra_character_from_name(name)
>>> print(clean_name)
'T-cell_CD4p_CD8p'

Notes

The following replacements are made:

  • ‘/’ is replaced with ‘_’

  • ‘ ‘ (space) is replaced with ‘_’

  • ‘”’ (double quote) is removed

  • “’” (single quote) is removed

  • ‘)’ is removed

  • ‘(’ is removed

  • ‘+’ is replaced with ‘p’

  • ‘-’ is replaced with ‘n’

  • ‘.’ (dot) is removed

These substitutions help in creating filenames that do not contain characters that might be problematic for file systems or software.

nico_interactions.Interactions.spatial_neighborhood_analysis(output_nico_dir=None, anndata_object_name='nico_celltype_annotation.h5ad', spatial_cluster_tag='nico_ct', spatial_coordinate_tag='spatial', Radius=0, n_repeats=1, K_fold=5, seed=36851234, n_jobs=-1, lambda_c_ranges=[0.000244140625, 0.00048828125, 0.0009765625, 0.001953125, 0.00390625, 0.0078125, 0.015625, 0.03125, 0.0625, 0.125, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0, 1024.0, 2048.0], epsilonThreshold=100, removed_CTs_before_finding_CT_CT_interactions=[])[source]

Perform spatial neighborhood analysis to reconstruct the niche interaction patterns.

This is the primary function called by the user to perform spatial neighborhood analysis, i.e., reconstruction of the niche.

Prerequisites: Before calling this function, the user must have an annotation of the spatial cell from any method. This annotation is expected to comprise two files: clusterFilename that contains cells and cluster-ID information, and celltypeFilename that contains cluster-ID and cell type name information.

Inputs:

output_nico_dirstr, optional

Directory to save the output of niche interaction prediction. Default is ‘./nico_out/’.

anndata_object_namestr, optional

Name of the AnnData object file containing cell type annotations. Default is ‘nico_celltype_annotation.h5ad’.

spatial_cluster_tagstr, optional

Slot for spatial cluster information. Default is ‘nico_ct’ that means it is stored in anndata.obs[‘nico_ct’] slot.

spatial_coordinate_tagstr, optional

Slot for spatial coordinate information. Default is ‘spatial’ that means it is stored in anndata.obsm[‘spatial’] slot.

Radiusint, optional

Niche radius to predict the cell type-cell type interactions. Radius 0 focuses on direct spatial neighbors inferred by Delaunay triangulation, and nonzero Radius extends the neighborhood to include all cells within a given radius for predicting niche interactions. Default is 0.

n_repeatsint, optional

Number of times to repeat the logistic regression after finding the hyperparameters. Default is 1.

K_foldint, optional

Number of cross-folds for the logistic regression. Default is 5.

seedint, optional

Random seed used in RepeatedStratifiedKFold. Default is 36851234.

n_jobsint, optional

Number of processors to use. See https://scikit-learn.org/stable/glossary.html#term-n_jobs for details. Default is -1.

lambda_c_rangeslist, optional

The initial range of the inverse regularization parameter used in the logistic regression to find the optimal parameter. Default is list(np.power(2.0, np.arange(-12, 12))).

epsilonThresholdint, optional

Threshold value for neighboring cell during Delaunay Triangulation. This means those cells which are large then this cutoff cannot become neighbor at any cost. Default is 100.

removed_CTs_before_finding_CT_CT_interactionslist, optional

Exclude cell types from the niche interactions analysis. Default is [].

Outputs:

The function saves the output of niche interaction prediction in the specified “nico_out” directory.

Notes:

  • Before running this function, ensure you have the cell type annotation files in the anndata object slot.

  • If running for multiple radius parameters, it’s good practice to change the output directory name or delete the previously created one.

  • If the average number of neighbors is relatively low (<1), consider increasing the radius for neighborhood analysis.

  • Every input CSV file (positionFilename, clusterFilename, celltypeFilename) must contain header information.

Module contents