cellmaps_coembedding.muse_sc package

Submodules

cellmaps_coembedding.muse_sc.architecture module

class cellmaps_coembedding.muse_sc.architecture.Protein_Dataset(data_train_x, data_train_y)[source]

Bases: Dataset

A dataset class for storing protein data for training in PyTorch.

Parameters:
class cellmaps_coembedding.muse_sc.architecture.ToTensor[source]

Bases: object

Convert numpy arrays to PyTorch tensors.

cellmaps_coembedding.muse_sc.architecture.init_weights(m)[source]

Initialize weights for linear layers using Xavier normal initialization and biases to zero.

Parameters:

m (torch.nn.Module) – A PyTorch module.

cellmaps_coembedding.muse_sc.architecture.init_weights_d(m)[source]

Initialize weights for linear layers using normal distribution.

Parameters:

m (torch.nn.Module) – A PyTorch module.

class cellmaps_coembedding.muse_sc.architecture.structured_embedding(x_input_size, y_input_size, latent_dim, hidden_size, dropout, l2_norm)[source]

Bases: Module

A PyTorch module for structured embedding of proteins using deep learning.

Parameters:
  • x_input_size (int) – Size of the input feature vector for x.

  • y_input_size (int) – Size of the input feature vector for y.

  • latent_dim (int) – Dimensionality of the latent space.

  • hidden_size (int) – Size of the hidden layers.

  • dropout (float) – Dropout rate for regularization.

  • l2_norm (bool) – Whether to apply L2 normalization on the embeddings.

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(x, y)[source]

Forward pass through the network.

Parameters:
  • x (torch.Tensor) – Input features for x.

  • y (torch.Tensor) – Input features for y.

Returns:

Tuple containing latent embeddings, reconstructed x and y, and hidden representations of x and y.

Return type:

tuple

cellmaps_coembedding.muse_sc.df_utils module

cellmaps_coembedding.muse_sc.df_utils.canberra_similarity(df)[source]

Calculate Canberra similarity between each pair of rows in a DataFrame. Similarity scaled into [0, 1]

cellmaps_coembedding.muse_sc.df_utils.check_symmetric(a, rtol=1e-05, atol=1e-08)[source]

Check if the given numpy matrix is symmetric or not.

cellmaps_coembedding.muse_sc.df_utils.cosine_similarity_scaled(df)[source]

Calculate Cosine similarity between each pair of rows in a DataFrame. Similarity scaled into [0, 1]

cellmaps_coembedding.muse_sc.df_utils.euclidean_similarity(df)[source]

Calculate Euclidean similarity between each pair of rows in a DataFrame. Similarity scaled into [0, 1]

cellmaps_coembedding.muse_sc.df_utils.kendall_scaled(df)[source]

Calculate Kendall correlation between each pair of rows in a DataFrame. Correlation scaled into [0, 1]

cellmaps_coembedding.muse_sc.df_utils.manhattan_similarity(df)[source]

Calculate Manhattan similarity between each pair of rows in a DataFrame. Similarity scaled into [0, 1]

cellmaps_coembedding.muse_sc.df_utils.pearson_scaled(df)[source]

Calculate Pearson correlation between each pair of rows in a DataFrame. Correlation scaled into [0, 1]

cellmaps_coembedding.muse_sc.df_utils.spearman_scaled(df)[source]

Calculate Spearman correlation between each pair of rows in a DataFrame. Correlation scaled into [0, 1]

cellmaps_coembedding.muse_sc.df_utils.upper_tri_values(df)[source]

Return array with values of upper triangle of the DataFrame.

Args:

df: Symmetric DataFrame

Return:

Numpy array

cellmaps_coembedding.muse_sc.df_utils.znorm(df)[source]

Z-transform within each column.

cellmaps_coembedding.muse_sc.file_utils module

cellmaps_coembedding.muse_sc.file_utils.load_obj(fname, method='pickle')[source]

Loading object that was saved in pickle format

Args:

fname: path to file method: {pickle, dill} specify package used for compressing

cellmaps_coembedding.muse_sc.file_utils.save_obj(obj, fname, method='pickle', large_file=False)[source]

Saving objects to designated filename in pickle format

Args:

obj: object that want to be saved fname: path to saved file method: {pickle, dill} specify package used for compressing

cellmaps_coembedding.muse_sc.triplet_loss module

Triplet loss modified from https://github.com/omoindrot/tensorflow-triplet-loss/blob/master/model/triplet_loss.py Author: Olivier Moindrot from Stanford CONVERTED TO PYTORCH LVS

cellmaps_coembedding.muse_sc.triplet_loss.batch_all_triplet_loss(labels, embeddings, margin, device)[source]

Build the triplet loss over a batch of embeddings. We generate all the valid triplets and average the loss over the positive ones. Args:

labels: labels of the batch, of size (batch_size,) embeddings: tensor of shape (batch_size, embed_dim) margin: margin for triplet loss

Returns:

triplet_loss: scalar tensor containing the triplet loss

cellmaps_coembedding.muse_sc.triplet_loss.batch_hard_triplet_loss(labels, embeddings, margin, device)[source]

Build the triplet loss over a batch of embeddings. For each anchor, we get the hardest positive and hardest negative to form a triplet. Args:

labels: labels of the batch, of size (batch_size,) embeddings: tensor of shape (batch_size, embed_dim) margin: margin for triplet loss

Returns:

triplet_loss: scalar tensor containing the triplet loss

cellmaps_coembedding.muse_sc.triplet_loss.fraction_triplets(labels, embeddings, margin, device)[source]

Module contents

cellmaps_coembedding.muse_sc.make_matrix_from_labels(labels)[source]

Creates a symmetric matrix from cluster labels, where each entry (i, j) is set to 1 if elements i and j belong to the same cluster, otherwise 0.

Parameters:

labels (array-like) – Array of cluster labels.

Returns:

A symmetric matrix indicating intra-cluster relationships.

Return type:

numpy.ndarray

cellmaps_coembedding.muse_sc.muse_fit_predict(resultsdir, modality_data=[], modality_names=[], name_index=[], label_x=[], label_y=[], test_subset=[], batch_size=64, latent_dim=128, n_epochs=500, n_epochs_init=200, lambda_regul=5, lambda_super=5, triplet_margin=0.1, hard_loss=False, l2_norm=True, k=10, dropout=0.25, save_update_epochs=False)[source]

Fits a model using provided datasets and predicts outputs.

Parameters:
  • resultsdir (str) – Directory where results and model states are saved.

  • modality_data (list of numpy.ndarray) – List of datasets for different modalities (X and Y).

  • modality_names (list of str) – Names of modalities.

  • name_index (list) – Index or names associated with the data samples.

  • label_x (list) – Cluster labels or matrices for modality X.

  • label_y (list) – Cluster labels or matrices for modality Y.

  • test_subset (list) – Indices of the test subset.

  • batch_size (int) – Size of each data batch.

  • latent_dim (int) – Dimension of the latent space.

  • n_epochs (int) – Total number of epochs for training.

  • n_epochs_init (int) – Number of initial epochs for training without label updates.

  • lambda_regul (float) – Regularization factor for the loss function.

  • lambda_super (float) – Supervision strength in loss function.

  • triplet_margin (float) – Margin for triplet loss calculation.

  • hard_loss (bool) – Flag to use hard triplet loss.

  • l2_norm (bool) – Flag to use L2 normalization.

  • k (int) – Number of neighbors for clustering.

  • dropout (float) – Dropout rate.

  • save_update_epochs (bool) – Flag to save model state at specified epoch intervals.

Returns:

Model and embeddings as final outputs.

Return type:

tuple

cellmaps_coembedding.muse_sc.train_model(model, optimizer, loader, label_x, label_y, epoch, lambda_super, train_name, train, device)[source]

Trains a model using a DataLoader, tracking and computing various losses.

Parameters:
  • model (torch.nn.Module) – Model to train.

  • optimizer (torch.optim.Optimizer) – Optimizer for updating model weights.

  • loader (DataLoader) – DataLoader for batch processing.

  • label_x (torch.Tensor) – Label matrix for input X.

  • label_y (torch.Tensor) – Label matrix for input Y.

  • epoch (int) – Current epoch number.

  • lambda_super (float) – Weighting factor for triplet losses.

  • train_name (str) – A name or tag for the training session, used in logging.

  • train (bool) – Boolean flag to determine if the model should be trained (True) or just evaluated (False).

  • device (torch.device) – Device to run the training on (e.g., ‘cuda’ or ‘cpu’).

cellmaps_coembedding.muse_sc.write_result_to_file(filepath, data, indexes)[source]

Writes results to a tab-separated file with headers. Each row corresponds to the data array indexed with the corresponding index from ‘indexes’.

Parameters:
  • filepath (str) – Path to the file where results will be saved.

  • data (numpy.ndarray) – Array of data to write.

  • indexes (list) – Index labels for each row of data.