ternadecov package

Submodules

ternadecov.base_cli module

Command-line functionality

ternadecov.base_cli.get_argument_parser() ArgumentParser

Return a prepared ArgumentParser.

Returns:

ArgumentParser

Return type:

argparse.ArgumentParser

ternadecov.base_cli.main()

Main entry function for cli

ternadecov.cli_tools module

Helper functions for command-line functionality

ternadecov.cli_tools.do_deconvolution(args)

Main function that processes and executes deconvolution sub-command

Parameters:

args – parsed cli params

ternadecov.cli_tools.get_torch_device(args)

Get the torch device based on availability and cli params

ternadecov.dataset module

Objects representing datasets

class ternadecov.dataset.DeconvolutionDataset(types: DeconvolutionDatatypeParametrization, parametrization: DeconvolutionDatasetParametrization)

Bases: object

This class represents a bulk and single-cell dataset to be deconvolved in tandem

property bulk_raw_gex_mg: tensor
property bulk_sample_names: List[str]

Get the names of the bulk samples

Parameters:

self – An instance of object

Returns:

List of string names of bulk samples

cell_type_str_list

Return a list of stings of celltypes

Parameters:

self – An instance of object

cell_type_str_to_index_map

Get dictionary of celltypes to index in array

Parameters:

self – An instance of object

Returns:

Dictionary from celltype string to integer index

num_cell_types

Get number of cell types

Parameters:

self – An instance of object

Returns:

Number of cell types

num_samples

Get number of bulk samples in the dataset

Parameters:

self – An instance of object

Returns:

Number of samples

property t_m: tensor

Get the times of the individual points

Parameters:

self – An instance of object

Returns:

Tensor of times

w_hat_gc

Calculate and return the estimate cell profiles

Parameters:

self – An instance of object

Returns:

Array of dimention gene x celltype

class ternadecov.dataset.SingleCellDataset(sc_anndata: AnnData, sc_celltype_col: str, dtype_np: dtype, dtype: dtype, device: device)

Bases: object

A reduced dataset with only single-cell data for use with the simulator.

cell_type_str_list

Return a list of stings of celltypes

Parameters:

self – An instance of object

cell_type_str_to_index_map

Get dictionary of celltypes to index in array

Parameters:

self – An instance of object

Returns:

Dictionary from celltype string to integer index

num_cell_types

Get number of cell types

Parameters:

self – An instance of object

Returns:

Number of cell types

w_hat_gc

Calculate the estimate cell profiles

Parameters:

self – An instance of object

ternadecov.deconvolution_exporter module

Deconvolution exporter object for automated export

class ternadecov.deconvolution_exporter.DeconvolutionExporter(deconvolution: TimeRegularizedDeconvolutionModel, prefix='')

Bases: object

Class for automated exporting of the deconvolution results

export_results(output_directory, save_pdf=True, save_png=True, save_csv=True)

Export all the results

Parameters:
  • self – An instance of object

  • output_directory – A directory location to export the results to

  • save_pdf – Save the figures as PDF?

  • save_png – Save the figures as PNG?

  • save_csv – Save the numerical output as CSV

ternadecov.deconvolution_plotter module

Deconvolution plotter for plotting figures from deconvolution

class ternadecov.deconvolution_plotter.DeconvolutionPlotter(deconvolution: TimeRegularizedDeconvolutionModel)

Bases: object

Class for plotting deconvolution results

plot_beta_g_distribution(filenames=()) Axes

Plot distribution of beta_g from the param_store.

Parameters:
  • self – An instance of self

  • filenames – An iterable of filenames to save the plot to

Returns:

A matplotlib.axes.Axes object.

plot_composition_trajectories(show_hypercluster=False, show_sampled_trajectories=False, filenames=(), **kwargs)

Plot the inferred composition trajectories

Parameters:
  • self – An instance of self

  • show_hypercluster – Show hyper cluster

  • show_sampled_trajectories

  • filenames – Names of files to save results to

  • **kwargs – See below

Keyword Arguments:

Everything else

plot_composition_trajectories_via_posterior_sampling(show_iqr: bool = True, show_combined: bool = True, iqr_alpha: float = 0.2, t_begin: float = 0.0, t_end: float = 1.0, n_bins: int = 1000, n_samples_per_bin: int = 2000, n_windows: int = 10, savgol_polyorder: int = 1, figsize: Tuple[float, float] = (3.0, 2.0), celltype_summarization: dict = {}, sharey: bool = True, lw: float = 1.0, cell_type_to_color_dict: Optional[Dict[str, str]] = None, filenames=(), return_data=False, **kwargs)

Plot the composition trajectories by sampling from the posterior.

Parameters:
  • self – An instance of self

  • show_iqr – Plot the Inter-quantile ranges

  • show_combined – Show all trajectories on one plot

  • iqr_alpha – alpha transparency for the IQR ranges

  • t_begin

  • t_end

  • n_bins – number of time bins

  • n_samples_per_bin – number of samples per bin

  • n_windows – number of windows

  • savgol_polyorder – smoothing polynomial order

  • figsize – Figure size

  • celltype_summarization – celltype summarization dictionary (for plotting only)

  • sharey – Share the y axis

  • lw – line width

  • cell_type_to_color_dict – Cell type to color dictionary

  • filenames – Filenames to save the plots to

  • **kwargs – Everything else

plot_gp_composition_trajectories(n_samples=500, filenames=())

” Plot per-celltype (deprecated)

Parameters:
  • self – An instance of self

  • n_samples – Number of samples to draw from GP

  • filenames – Filenames to save to

plot_loss(filenames=()) Axes

Plot of ELBO loss during training from the deconvolution object.

Parameters:
  • self – An instance of self.

  • filenames – An iterable of filenames to save the plot to.

Returns:

A matplotlib.axes.Axes object.

plot_phi_g_distribution(filenames=()) Axes

Plot the distribution of $phi_g$ values from the param_store.

Parameters:
  • self – An instance of self

  • filenames – An iterable of filenames to save the plot to

Returns:

A matplotlib.axes.Axes object.

plot_sample_compositions_boxplot(figsize=(16, 9), filenames=())

Plot sample compositions in boxplot form

Parameters:
  • self – An instance of self.

  • figsize – Figure size

  • filenames – Filename to save the plots to

plot_sample_compositions_boxplot_confidence(n_draws=100, verbose=False, figsize=(20, 15), dpi=80, spacing=1, filenames=())

Plot individual sample compositions as boxplots representing confidence in predictions

Parameters:
  • self – An instance of object

  • n_draws – Number of draws to perform for CI estimation

  • verbose – Verbosity

  • figsize – Size of figure to plot

  • dpi – DPI of output figure

  • spacing – x-axis spacing of groups of samples from different timepoints

  • filenames – Filenames to save the files as

plot_sample_compositions_scatter(figsize=(16, 9), ignore_hypercluster=False, filenames=())

Plot a scatter plot of the sample composition facetted by celltype

Parameters:
  • self – An instance of self

  • figsize – tuple of size 2 with figure size information

  • ignore_hypercluster – ignore hyperclustering and plot individual clusters without summarization

  • filenames – An iterable of filenames to save the plot to.

plot_summarized_cell_compositions(celltype_summarization, n_intervals=100, filenames=(), **kwargs)

Plot the composition trajectories

Parameters:
  • self

  • celltype_summarization

  • n_intervals

  • filenames

  • **kwargs – See below

Keyword Arguments:

Everything else

ternadecov.deconvolution_writer module

Deconvolution writter for writting output tables

class ternadecov.deconvolution_writer.DeconvolutionWriter(deconvolution: TimeRegularizedDeconvolutionModel)

Bases: object

Writer for deconvolution results

write_cell_compositions(filename=None, n_intervals=100, return_table=False)

Write cell composition trajectories to csv file

Parameters:
  • self – Instance of object

  • filename – name of file to csv data to

  • n_intervals – number of intervals to evaluate the trajectories at:

  • return_table – optionally return the calculated table as a pandas df

write_sample_draws_quantiles(filename=None, n_draws=1000, return_table=True)

Write sample draws as quantiles

Parameters:
  • self – Instance of object

  • filename – Filename to save data to

  • n_draws – Number of draws for the quantile estimates

  • return_table – Return the table

Returns:

the table with the summary information

write_summarized_cell_compositions(celltype_summarization: Dict[str, List[str]], filename=None, n_intervals=100, return_table=False)

Write summarized composition trajectories to csv file

Parameters:
  • celltype_summarization – dictionary of lists with the cell summarization to be performed

  • filename – name of csv file to save table to

  • n_intervals – number of points to evaluate the trajectories at

  • return_table – flag to return the resulting data as a pandas DataFrame

Returns:

The Dataframe that is saved (optional)

ternadecov.evaluation module

Functions for fitting multiple models with different hyper parameters

ternadecov.evaluation.calculate_prediction_error(sim_res, pseudo_time_reg_deconv_sim, n_intervals=1000)

Calculate the prediction error of a deconvolution on simulated results

Parameters:
  • sim_res – results of a simulation

  • pseudo_time_reg_deconv_sim – the deconvolution object to evaluate

N_intervals:

number of intervals over which to evaluate the results

Returns:

dictionary of different errors

ternadecov.evaluation.evaluate_model(params: dict, reference_deconvolution: TimeRegularizedDeconvolutionModel)

Perform model evaluation by simulating, deconvolving and calculating errors

Parameters:
  • params – Dictionary of parameters to pass to different functions

  • reference_deconvolution – A reference deconvolution

Returns:

Prediction error as calculated from calculate_prediction_error()

ternadecov.evaluation.evaluate_paramset(param_set, sc_anndata, reference_deconvolution, show_progress=True)

Evaluate parameter set.

Parameters:
  • param_set – Parameter set for evaluation

  • sc_anndata – single-cell AnnData object

  • reference_deconvolution – A reference deconvolution (required for auxiliary data)

  • show_progress – Boolean to show progress

Returns:

list of results

ternadecov.evaluation.evaluate_with_trajectory(sc_dataset: SingleCellDataset, n_samples: int, trajectory_type: str, trajectory_coef: Dict, types: DeconvolutionDatatypeParametrization, deconvolution_params: Dict, n_iters=5000)

Evaluate L1_error and measure fit time for fitting on a simulated dataset from a given trajectory

Parameters:
  • sc_dataset – SingleCellDataset for generated simulations from

  • n_samples – number of samples along the time axis to generate

  • trajectory_type – string indicating the trajectory type to which the trajectory_coef correspond

  • trajectory_coef – trajectory coefficients

  • types – DeconvolutionDatatypeParametrization identifying datatypes to use

  • deconvolution_params – Dictionary with deconvolution parameters

  • n_iters – Number of learning iterations for each execution

Returns:

Dictionary with results

ternadecov.evaluation.get_default_evaluation_param(device, dtype, dtype_np)

Get default parametrization for algorithm parametrization

Parameters:

device – torch device

;param dtype: torch datatype :param dtype_np: numpy datatype

ternadecov.gene_selector module

Algorithms for selecting genes for the deconvolution

class ternadecov.gene_selector.GeneSelector

Bases: object

Class of static methods for selecting features (genes)

static select_features(bulk_anndata: AnnData, sc_anndata: AnnData, feature_selection_method: str, dispersion_cutoff: int = 5, log_sc_cutoff: int = 2, polynomial_degree: int = 2) List[str]

ternadecov.hypercluster module

Methods for hyper-clustering single-cells prior to deconvolution

ternadecov.hypercluster.hypercluster_anndata(anndata_obj, original_clustering_name, min_cells_recluster=500, subcluster_resolution=1, min_new_cluster_size=0, verbose=True, return_anndata=False, type='leiden', do_preproc=True)

Generate a hyperclustering of an AnnData object

Parameters:
  • anndata_obj – AnnData object

  • original_clustering_name – name of clustering column in .obs to hypercluster, cluster partitions will be maintained

  • min_cells_recluster – minimum number of cells in a cluster to consider for reclustering

  • subcluster_resolution – resolution parameter to be passed to clustering function, smaller values give more clusters

  • min_new_cluster_size – cutoff size for keeping new clusters

  • verbose – verbosity

  • return_anndata – flag specifying if the processed anndata object should be returned

  • type – clustering algorithm to use ‘leiden’ or ‘louvain’

  • do_preproc – flag specifying if the anndata object should be preprocessed

ternadecov.hypercluster.preproc_anndata_hypercluster(anndata_obj)

Preproces anndata object for hyperclustering

Parameters:

anndata_obj – AnnData object

Returns:

ann_data_working

ternadecov.parametrization module

Parametrization objects holding for parametrizing datasets and deconvolution execution

class ternadecov.parametrization.DeconvolutionDatasetParametrization(sc_anndata, sc_celltype_col, bulk_anndata, bulk_time_col, feature_selection_method='overdispersed_bulk_and_high_sc', cell_type_to_color_dict: Optional[Dict[str, str]] = None, verbose=True, hypercluster=False, hypercluster_min_new_cluster_size=100, hypercluster_min_cells_recluster=1000, hypercluster_return_anndata=False, hypercluster_subcluster_resolution=1, hypercluster_type='louvain', hypercluster_do_preproc=True, hypercluster_verbose=True, dispersion_cutoff: int = 5, log_sc_cutoff: int = 2, polynomial_degree: int = 2)

Bases: object

property hypercluster_params

The hyperclustering parameters as a dictionary (for backward compatibility of some routines)

Parameters:

self – Instance of object

Returns:

Dictionary of hyperclustering parameters

class ternadecov.parametrization.DeconvolutionDatatypeParametrization(device=None, dtype=None, dtype_np=None)

Bases: object

Parametrization for datatypes of model

class ternadecov.parametrization.TimeRegularizedDeconvolutionGPParametrization(init_rbf_kernel_lengthscale=0.5, init_rbf_kernel_variance=0.5, init_whitenoise_kernel_variance=0.1, gp_cholesky_jitter=0.0001)

Bases: object

Parametrization specific to GP deconvolution

property num_inducing_points

Getter for number of inducing points (deprecated, current GP is full not sparse)

Parameters:

self – Instance of object

)

class ternadecov.parametrization.TimeRegularizedDeconvolutionModelParametrization(log_beta_prior_scale=1.0, tau_prior_scale=1.0, log_phi_prior_loc=-5.0, log_phi_prior_scale=1.0, init_posterior_global_scale_factor=0.05, log_beta_posterior_scale_factor=1.0, tau_posterior_scale_factor=1.0, log_phi_posterior_loc_factor=-5.0, log_phi_posterior_scale_factor=0.1)

Bases: object

Parametrizaition for TimeRegularizedDeconvolutionModel object

ternadecov.plotting_functions module

Stand-alone plotting fuctions, called from DeconvolutionPlotter

ternadecov.plotting_functions.generate_posterior_samples(deconvolution: TimeRegularizedDeconvolutionModel, t_begin: float = 0.0, t_end: float = 1.0, n_bins: int = 1000, n_samples_per_bin: int = 10000)

Generate samples from the posterior of a gp

Parameters:
  • deconvolution – deconvolution model to get posterior samples from

  • t_begin – start time

  • t_end – end time

  • n_bins – number of bins

  • n_samples_per_bin – number of samples per bin

Returns:

ternadecov.plotting_functions.get_iqr_from_posterior_samples(pi_sampled_scn: Tensor, perform_smoothing: bool = False, n_windows: int = 10, savgol_polyorder: int = 1) Tuple[ndarray, ndarray, ndarray]

Calculate IQR range from posterior samples

Parameters:
  • pi_sampled_scn – Sampled tensor

  • perform_smoothing – Flag for performing smoothing

  • n_windows – Number of windows to smooth

  • savgol_polyorder – Polynomial degree for smoothing

Returns:

tumple of arrays for (0.25, 0.50, 0.75) quantiles

ternadecov.plotting_functions.summarize_posterior_samples(deconvolution: TimeRegularizedDeconvolutionModel, pi_sampled_scn: Tensor, celltype_summarization: Dict[str, List[str]]) Tensor

Summarize posterior samples by celltype summarization

Parameters:
  • deconvolution – deconvolution object

  • pi_sampled_scn – Posterior samples to summarize

  • celltype_summarization – Celltype summarization dictionary

Returns:

Tensor of summarized posterior samples

ternadecov.sensitivity_analyzer module

Class for automated sensitivity analysis

class ternadecov.sensitivity_analyzer.SensitivityAnalyzer

Bases: object

Container class for static methods pertaining to parameter sensitivity analysis

static evaluate_deconvolution(dataset_param: DeconvolutionDatasetParametrization, hyperparameters: TimeRegularizedDeconvolutionModelParametrization, trajectory_hyperparameters: TimeRegularizedDeconvolutionGPParametrization, datatype_param: DeconvolutionDatatypeParametrization, n_iters=10000)

Evaluate deconvolution with specified parametrization

Parameters:
  • dataset_param – Dataset parametrization

  • hyperparameters – Hyperparameters for TimeRegularizedDeconvolutionModel

  • trajectory_hyperparameters – Trajecotry hyperparameters for TimeRegularizedDeconvolutionModel

  • datatype_param – a DeconvolutionDatatypeParametrization

  • n_iters – Numver of iterations to run

Returns:

Composition trajectories

static plot_scan_trajectories(results, variable)

Plot the results of scan_parameter

Parameters:
  • results – scan results from scan_parameter()

  • variable – variable to plot

Returns:

matplotlib axes

static scan_parameter(parameter: str, dataset_param: DeconvolutionDatasetParametrization, datatype_param, parameter_type='model', parameter_variable_type='continuous', start=None, end=None, num=None, discrete_values: Optional[List[str]] = None, model_param: Optional[TimeRegularizedDeconvolutionModelParametrization] = None, trajectory_param: Optional[TimeRegularizedDeconvolutionGPParametrization] = None, n_iters=10000)

Scan the defined parameter with values in the specified range and save results, performing deconvolution for each value

Parameters:
  • parameter – name of parameter to scan

  • dataset_param – dataset parametrization to use

  • datatype_param – datatype parametrization to use

  • parameter_type – type of parameter (‘model’, ‘trajectory’ or ‘dataset’)

  • parameter_variable_type – variable type of parameter (‘discrete’ or ‘continous’)

  • start – start value, for continous variables

  • end – end value, for continous variables

  • num – number of values in the interval, for continous variables

  • discrete_values – list of discrete values, for discrete variables

  • model_param – Model parameters (which are modified as above)

  • traject_param – Trajectory parameters (which are modified as above)

Returns:

dictionary of results

ternadecov.simulator module

Simulator for bulk datasets

ternadecov.simulator.calculate_sample_prediction_error(sim_res, pseudo_time_reg_deconv_sim) Dict

Calculate the error at the level of individual sample proportion prediction

Parameters:
  • sim_res – Simulation results to use as base truth

  • pseudo_time_reg_deconv_sim – The trained object to simulate

Returns:

Dictionary of errors

ternadecov.simulator.calculate_trajectory_prediction_error(sim_res, pseudo_time_reg_deconv_sim, n_intervals=1000)

Calculate the prediction error of a deconvolution on simulated results

Parameters:
  • sim_res – results of a simulation

  • pseudo_time_reg_deconv_sim – the deconvolution object to evaluate

N_intervals:

number of intervals over which to evaluate the results

Returns:

Dictionary of results

ternadecov.simulator.generate_anndata_from_sim(sim_res: Dict, sc_dataset: SingleCellDataset) AnnData

Generate AnnData object from the simulation results

Parameters:
  • sim_res – Simulation results dictonary

  • sc_dataset – A single-cell dataset object (for the gene names)

Returns:

AnnData object with simulated data

ternadecov.simulator.plot_simulated_proportions(sim_res, dataset, show_sample_proportions=True, show_trajectories=True, figsize=(20, 10))

Plot simulated proportion results

Parameters:
  • sim_res – simulation results objects

  • show_sample_proportions – show the generated proportions plot

  • show_trajectories – show underlying trajectories plot

Dataset:

Returns:

matplotlib axes

ternadecov.simulator.sample_linear_proportions(num_cell_types, num_samples, t_m, dirichlet_alpha=10000.0, trajectory_coef=None, trajectory_sample_params=None, seed=None)

Generate a sample of linear proportions

Parameters:
  • num_cell_types – number of cell types to simulate

  • num_samples – number of samples

  • t_m – torch tensor of times

  • dirichlet_alpha – multiplier for normalized dirichlet coefficients

Returns:

Dictionary of coefficients

ternadecov.simulator.sample_linear_trajectories(num_cell_types: int, seed: Optional[int] = None, a_min: float = 0.0, a_max: float = 10.0, b_min: float = -10.0, b_max: float = 10.0) Dict

Generate a sample of linear trajectory coefficients

Parameters:
  • num_cell_types – number of cell types in trajectories

  • seed – Random seed (for reproducibility)

  • a_min – minimum value for a coefficient

  • a_max – maximum values for a coefficient

  • b_min – minimum value for b coefficient

  • b_max – maximum value for b coefficient

Returns:

Dictionary coefficient and their values

ternadecov.simulator.sample_periodic_proportions(num_cell_types, num_samples, t_m, dirichlet_alpha=10000.0, trajectory_coefficients=None, trajectory_sample_params=None, seed=None)

Get a sample of periodic cell proportions, optionally from a given trajectory

Parameters:
  • num_cell_types – number of cell types to simulate

  • num_samples – number of samples to simulate

  • t_m – time points to simulate results for

  • dirichlet_alpha – global diriechlet concentration

  • trajectory_coefficients – trajectory, if not provided a random trajectory is drawn

  • trajectory_sample_params – optional parameter dictionary for sampling trajectories

  • seed – optional seed for drawing coefficients

ternadecov.simulator.sample_periodic_trajectories(num_cell_types: int, seed: Optional[int] = None, a_min: float = -3.0, a_max: float = 3.0, b_min: float = 0.25, b_max: float = 1.0, c_min: float = 0.0, c_max: float = 5.0) Dict

Get a sample of coefficients for periodic trajectories

Parameters:
  • num_cell_types – Number of celltypes

  • seed – Seed for reproducibility

  • a_min – min value for a

  • a_max – max value for a

  • b_min – min value for b

  • b_max – max value for b

  • c_min – min value for c

  • c_max – max value for c

Returns:

Dictionary of coefficients

ternadecov.simulator.sample_sigmoid_proportions(num_cell_types, num_samples, t_m, dirichlet_alpha=10000.0, trajectory_coefficients=None, trajectory_sample_params={}, seed=None)

Generate a sample of sigmoid proportions

Parameters:
  • num_cell_types – number of cell types to simulate

  • num_samples – number of samples

  • t_m – torch tensor of times

  • dirichlet_alpha – multiplier for normalized dirichlet coefficients

Returns:

Dictionary of coefficients

ternadecov.simulator.sample_sigmoid_trajectories(num_cell_types, seed=None, effect_size_min=-1, effect_size_max=1, shift_min=-2, shift_max=2)

Return sigmoid trajectory param dictionary

ternadecov.simulator.sample_trajectories(type, num_cell_types, seed=None)

Generate a random trajectory

Parameters:
  • type – trajectory type (linear, sigmoid, periodical)

  • num_cell_types – number of cell types in the trajectory

Return simulated trajectories:

ternadecov.simulator.sigmoid(x)

Return sigmoid function value

ternadecov.simulator.simulate_data(w_hat_gc, start_time=-5, end_time=5, num_samples=100, lib_size_mean=1000000.0, lib_size_std=200000.0, use_betas=False, dirichlet_alpha=1000, trajectory_type='sigmoid', trajectory_coef=None, phi_mean=0.15, phi_std=0.05, beta_mean=1.0, beta_std=0.1, trajectory_sample_params={}, seed=None)

Simulate bulk data with compositional changes

Parameters:
  • w_hat_gc – reference matrix

  • start_time – time start

  • end_time – time end

  • num_samples – number of samples to simulate

  • lib_size_mean – mean library size

  • lib_size_std – library size standard deviation

  • use_betas – use beta values from the reference model

  • dirichlet_alpha – global dirichlet alpha coefficient

  • trajectory_type – type of trajectory (‘sigmoid’,’linear’,’periodic’)

  • trajectory_coef – predefined trajectory coefficients, if not provided they are sampled

  • phi_mean – $phi_{mean}$ value

  • phi_std – $phi_{std}$ values

  • beta_mean – $eta_{mean}$ values

  • beta_std – $eta_{std}$ values

  • trajectory_sample_params – Dictionary of trajectory sample parameters

  • seed – seed for trajectory sampling (optional)

Returns:

dictionary of simulated values and underlying coefficients

ternadecov.stats_helpers module

Statistics helper functions

ternadecov.stats_helpers.NegativeBinomialAltParam(mu, phi)

Creates a negative binomial distribution.

Parameters:
  • mu – mean (must be strictly positive)

  • phi – overdispersion (must be strictly positive)

Returns:

pyro distribution

ternadecov.stats_helpers.legendre_coefficient_mat(k_max, dtype, epsilon=1e-08)

Return the coefficient matrix of legendre polynomials.

Parameters:
  • k_max – legenre polynomial max degree

  • epsilon – minimum coefficient value

Returns:

torch tensor with legendre coefficients

ternadecov.time_deconv module

Main deconvolution functionality

class ternadecov.time_deconv.TimeRegularizedDeconvolutionModel(dataset: DeconvolutionDataset, types: DeconvolutionDatatypeParametrization, use_betas: bool = True, trajectory_model_type: str = 'polynomial', hyperparameters=None, trajectory_hyperparameters=None, **kwargs)

Bases: object

Main deconvolution class

fit_model(n_iters=3000, log_frequency=100, verbose=True, clear_param_store=True, keep_param_store_history=False)

Iteratively fit the mode

Parameters:
  • self – instance of object

  • n_inters – number of iterations to execute

  • log_frequency – log frequncy (in iterations)

  • verbose – verbosity flat

  • clear_param_store – flag to clear parameter store before starting iterations

  • keep_param_store_history – flag to keep full parameter store copies during learning (warning: high memory consumption)

guide(x_mg: Tensor, t_m: Tensor)

Main guide

Parameters:
  • self – instance of object

  • x_mg – expression matrix

  • t_m – times

Returns:

posterior draw

model(x_mg: Tensor, t_m: Tensor)

Main model

Parameters:
  • self – instance of Object

  • x_mg – gene expression

  • t_m – obseration time

sample_composition_default()

Return the sample composition in a pandas DataFrame

Parameters:

self – instance of object

Returns:

return the current sample composition in pandas dataframe format

write_sample_composition_default(csv_filename)

Write sample composition proportions to csv file

Parameters:
  • self – instance of object

  • csv_filename – filename of csv file to write to

write_sample_compositions(csv_filename, ignore_hypercluster=False)

Write sample composition to csv file

Parameters:
  • self – instance of object

  • csv_filename – filename to save the results to

  • ignore_hypercluster – Flag to ignore hyperclustering if present

ternadecov.time_deconv.generate_batch(dataset: DeconvolutionDataset, device: device, dtype: dtype)

Generate a full training batch

Parameters:
  • dataset – DeconvolutionDataset

  • device – torch device

  • dtype – torch dataset

ternadecov.trajectories module

Alternative trajectories of cell proportions

class ternadecov.trajectories.BasicTrajectoryModule(basis_functions: str, polynomial_degree: int, num_cell_types: int, num_samples: int, init_posterior_global_scale_factor: float, device: device, dtype: dtype)

Bases: TrajectoryModule

Basic trajectory module representing a trajectory derived from a parametric form of polynomials or other basis functions

get_composition_trajectories(dataset, n_intervals=1000)

Calculate the composition trajectories

Parameters:
  • self – instance of object

  • dataset – dataset for getting times and celltype labels

  • n_intervals – number of points to evaluate the trajectories at

guide(xi_mq: Tensor) Tensor

Main guide

Parameters:
  • self – instance of object

  • xi_mq – covariate tensor with shape (num_sample, covariate_n_dim)

Returns:

posterior cell population proportions

model(xi_mq: Tensor) Tensor
Parameters:
  • self – instance of object

  • xi_mq – covariate tensor with shape (num_sample, covariate_n_dim)

Returns:

cell population proportions

class ternadecov.trajectories.NonTrajectoryModule(num_cell_types: int, num_samples: int, device: device, dtype: dtype)

Bases: TrajectoryModule

guide(xi_mq: Tensor) Tensor

Main guide

Parameters:
  • self – instance of class

  • xi_mq – covariate tensor with shape (num_sample, covariate_n_dim)

Returns:

posterior draw

model(xi_mq: Tensor) Tensor

Main model

Parameters:
  • self – instance of class

  • xi_mq – covariate tensor with shape (num_sample, covariate_n_dim)

class ternadecov.trajectories.ParameterizedTrajectoryModule

Bases: TrajectoryModule, Parameterized

Abstract base class for a parametrized trajectory module

training: bool
class ternadecov.trajectories.TrajectoryModule

Bases: object

The base class of all trajectory modules.

abstract guide(xi_mq: Tensor) Tensor

TBW.

abstract model(xi_mq: Tensor) Tensor

TBW.

class ternadecov.trajectories.VGPTrajectoryModule(xi_mq: ~torch.Tensor, num_cell_types: int, init_posterior_global_scale_factor: float, device: ~torch.device, dtype: ~torch.dtype, parametrization: ~ternadecov.parametrization.TimeRegularizedDeconvolutionGPParametrization = <ternadecov.parametrization.TimeRegularizedDeconvolutionGPParametrization object>)

Bases: ParameterizedTrajectoryModule

Trajectory module for gaussian process trajectories

get_composition_trajectories(dataset, n_intervals=1000) Dict

Get the composition trajectories

Parameters:
  • self – instance of object

  • dataset – dataset object

  • n_intervals – number of itervals to evaluate trajectory at

Returns:

dictionary of composition trajectory information

guide(xi_mq: Tensor) Tensor

Default guide

Parameters:
  • self – instance of object

  • xi_mq – covariate tensor with shape (num_sample, covariate_n_dim)

Returns:

tensor of cell populations

model(xi_mq: Tensor) Tensor

Default model

Parameters:
  • self – instance of object

  • xi_mq – covariate tensor with shape (num_sample, covariate_n_dim)

Returns:

tensor of cell populations

training: bool

ternadecov.utils module

General purpose utility functions

ternadecov.utils.melt_tensor_to_pandas(input_tensor: Tensor, dimnames, *dimlabels) DataFrame

Like pandas.melt() but for torch tensors. Creates a long form table with values and their indices

Parameters:
  • input_tensor – tensor of arbitrary dimentionality to flatten

  • dimnames – dimension names

  • *dimlabels – labels for each dimenstion

Returns:

pandas dataframe with flattened information

Module contents