API Reference#
- coregtor.RunCoRegTor(ge_data, source_gene, target_gene, ge_sparsity_threshold=0.1, ensemble_method='rf', ensemble_options=None, distance_measure='canberra_distance', cluster_method='community_detection', cluster_options=None)[source]#
Run CoRegTor to predict co-regulators for a specific target gene.
- Parameters:
ge_data (pd.DataFrame) – Gene expression data matrix (samples by genes).
source_gene (list) – List of candidate regulator/predictor gene names present in ge_data. These genes serve as feature variables in the ensemble model.
target_gene (srt) – Target gene name. Must exists as a column in the gene expression data.
ge_sparsity_threshold (float) – Minimum fraction of non-zero expression values required per column. Only sources that pass this threshold will be considered for model training. Default: 0.10.
ensemble_method (str, optional) –
The ensemble model used to model the expression of target_gene using candidate regulators in source_gene.
’rf’ (Random Forest Regressor) (default)
’et’ (Extra Trees Regressor)
ensemble_options (dict, optional) – Hyperparameters passed directly to the underlying scikit-learn estimator. See RandomForestRegressor or ExtraTreesRegressor for full parameter options. Default to generating 1000 estimators with a max depth of 5 utilizing all available CPUs
distance_measure (str,optional) – The distance metric used to measure the pairwise dissimilarity between the transformed gene context of selected most predictive genes. Supported metrics include: ‘canberra_distance’ (default), ‘cosine_distance’, ‘euclidean_distance’, ‘manhattan_distance’,’weighted_jaccard’, ‘sorensen_distance’, ‘chebyshev_distance’
cluster_method (str) –
Clustering method for identifying coregulatory clusters from the gene context similarity matrix. Supported options:
’community_detection’ (Leiden Algorithm): Converts the similarity matrix into a network graph and detects communities by optimizing graph modularity.
’hierarchical’ (Agglomerative Hierarchical Clustering): Builds a dendrogram from distance metrics and slices it into discrete gene clusters.
cluster_options (dict, optional) –
Additional options for clustering.
- For ‘community_detection’:
’edge_creation_method’: Method to build network edges (‘threshold_percentile’ or ‘knn’). Default: ‘threshold_percentile’.
’edge_creation_value’: Threshold cutoff or number of neighbors for graph construction. Default: 0.5.
’resolution’: Controls cluster granularity (higher values yield smaller modules). Default: 0.5.
’objective_function’: Optimization metric (‘CPM’ or ‘modularity’). Default: ‘CPM’.
’n_iterations’: Optimization passes for the Leiden algorithm. Default: 2.
- For ‘hierarchical’:
’linkage_method’: Dendrogram linkage criteria (‘average’, ‘complete’, ‘single’, ‘ward’). Default: ‘average’.
’auto_threshold’: Cutoff strategy (‘inconsistency’ or ‘elbow’). Default: ‘inconsistency’.
’threshold’: Fixed distance threshold for slicing the tree.
’n_clusters’: Target number of clusters to extract.
- Returns:
A 2-element tuple containing:
results (pd.DataFrame): Formatted summary DataFrame containing target gene predictions, assigned co-regulator module IDs, importance scores, and cluster metrics.
- intermediates (dict): Dictionary containing internal pipeline artifacts for downstream validation and plotting, structured as:
model: Trained ensemble estimator object.
feature_importance: Feature importance for source genes.
path: Extracted root to leaf paths from ensemble trees.
matrix: Pairwise context distance matrix.
edges: Network edge list helpful to visualize the clusters.
time_taken: Total execution time in seconds.
- Return type:
tuple
- coregtor.PlotClusters(result, details, evidence=None, network_options=None)[source]#
Plot one network graph for each unique cluster returned by RunCoRegTor.
- Parameters:
result – Output from RunCoRegTor.
details – Dictionary returned alongside the main result. It must contain an “edges” DataFrame with columns: cluster_id, target, source, fi_score.
evidence – Optional list of dicts such as: [{“target”: “TP53”, “sources”: [“GENE_A”, “GENE_B”], “title”: “related”, “details”: “…”}]
network_options – Optional dict with plotting settings such as: - figsize - node_size - font_size - title_prefix - save_path - show - evidence_colors
- Returns:
One matplotlib figure per cluster.
- Return type:
list
- coregtor.PlotExprData(df_matrix, tf_list, log_scale=True)[source]#
Plot mean expression versus variance for transcription factors. This can be helpful during the data preprocessing part.
- Parameters:
df_matrix – pandas.DataFrame Expression matrix where rows are samples and columns are genes.
tf_list – list of str List of transcription factor gene names to filter and plot.
log_scale – bool, optional If True (default), log2-transforms the expression values with a +1 pseudo-count before computing statistics.
- coregtor.create_model_input(raw_ge_data, target_gene, t_factors=None, sparsity_threshold=0.1)[source]#
Prepare gene expression data for training by splitting and validating feature and target matrices.
This function splits raw gene expression data into features (X) and target (Y), filters features to transcription factors if provided, drops duplicate columns, and enforces sparsity validation.
- Parameters:
raw_ge_data (pd.DataFrame) – Gene expression data in samples x genes format.
target_gene (str) – Name of the target gene to predict. Must be present in raw_ge_data columns.
t_factors (list, optional) – A list of transcription factor gene names.
sparsity_threshold (float) – Minimum fraction of non-zero expression values required per column.
- Returns:
X - Validated feature matrix (samples x TFs) filtered by sparsity_threshold Y - Validated target matrix (samples x 1)
- Return type:
tuple[pd.DataFrame, pd.DataFrame]
- coregtor.create_model(X, Y, method='rf', options=None)[source]#
Train an ensemble regression model to predict the expression of target gene Y using feature genes X.
Currently supported models: - RandomForestRegressor (rf) - ExtraTreesRegressor (et)
- Parameters:
X (pd.DataFrame) – Gene expression feature matrix (samples x TFs). Generated via create_model_input.
Y (pd.DataFrame) – Gene expression target matrix (samples x 1). Generated via create_model_input.
method (str) – Type of ensemble model (‘rf’ or ‘et’). Default is ‘rf’.
options (dict, optional) –
Hyperparameters for the estimator. Overrides defaults (max_depth=5, n_estimators=1000, n_jobs=-1). See RandomForestRegressor or ExtraTreesRegressor for full parameter options.
- Returns:
- A tuple containing:
ensemble (RegressorMixin): The trained scikit-learn ensemble model.
importance (dict): Feature gene importances ordered from highest to lowest score.
- Return type:
tuple
- coregtor.tree_paths(model, X, Y)[source]#
Extract all root-to-leaf decision paths from a trained ensemble model.
This is the main entry point for path extraction. It processes a trained ensemble model to extract all unique decision paths.
- Parameters:
model – sklearn ensemble model
X (pd.DataFrame) – Input of the model. This is required to get gene names
Y (pd.DataFrame) – Training output of the model. This is required to get gene name of the target
- Returns:
- DataFrame containing all decision tree paths with columns:
tree: Tree index within the ensemble (0-based)
source: First gene in the decision path (root decision)
target: Target gene being predicted (constant across all rows)
path_length: Number of decision nodes in the path
node1, node2, …: Genes used at each decision level (excluding source)
Unused node columns are filled with None
- Return type:
pd.DataFrame
- coregtor.create_context(data, method='tree_paths', genes=None, **kwargs)[source]#
Generates context sets for the given genes (or all root genes by default).
- Parameters:
data (
Union[DataFrame,Any]) – Input data in format appropriate for the method: tree_paths: DataFrame with ‘source’ and ‘node*’ columns.method (
str) – One of ‘tree_paths’ (default: ‘tree_paths’)genes (
list) – Optional list of gene names to build context for, regardless of their position in the path (root or intermediate node). Defaults to all root genes.**kwargs – Method-specific arguments
- Returns:
{gene: [list of subpaths]}
- Return type:
dict
- Raises:
CoRegTorError – If method is unknown
- coregtor.transform_context(context_set, method='gene_frequency', **kwargs)[source]#
Transform context sets into feature representations easier for comparison.
- Parameters:
context_set (
dict) – Dictionary with structure {source: [[gene1, gene2, …], …]} (output from the create_context method)method (
str) – Transformation method to apply. Currently available: - “gene_frequency”: Returns a gene frequency histogram**kwargs – Method-specific parameters passed to the transformation function
- Returns:
Transformed representation (format depends on method)
- Return type:
pd.DataFrame
- Raises:
CoRegTorError – If method is unknown
- coregtor.compare_context(transformed_data, method, transformation_type='gene_frequency', **kwargs)[source]#
Compare contexts using specified similarity/distance metric.
- Parameters:
transformed_data – Output from transform_context() - DataFrame with sources as rows
method – Similarity/distance metric name (e.g., ‘cosine’)
transformation_type – Type of transformation used .If None, attempts to read from DataFrame metadata.
**kwargs – Metric-specific parameters - convert_to_distance (bool): Convert similarity to distance (1 - similarity)
- Returns:
Symmetric pairwise similarity/distance matrix (sources x sources)
- Return type:
pd.DataFrame
- Raises:
CoRegTorError – If method is unknown or incompatible with transformation type
- coregtor.identify_coregulators(distance_matrix, target_gene, method='community_detection', options=None, note='', feature_importance=None)[source]#
Identify co-regulatory modules from gene distance matrix.
- Parameters:
distance_matrix – distance_matrix DataFrame from context comparison.
target_gene – Target gene identifier.
method – Clustering method name. (hierarchical)
options – Method-specific parameters dictionary.
- Returns:
model: Fitted clustering model or None
clusters_df: DataFrame of all clusters
best: Best cluster information dict or None
best_df: Best cluster as single-row DataFrame or None
methodology: Complete parameter string
validation_scores: Validation scores dict (validation_index only)
- Return type:
Dict containing