Regulons API reference

Contents

Regulons API reference#

cytearc.regulons builds transcription-factor regulons the way SCENIC does, and co-regulated gene programs, from RNA, ATAC, and binding data such as CUT&RUN. Every set it returns, from modules and regulons to programs and cistromes, is a table with source (the set) and target (a member) columns, which ds.scores.aucell (genes) and ds.scores.chromvar (peaks) score per cell and set_overlaps compares. Regions are named by their chrom:start-end ids, as ATAC peaks are. Reading cisTarget ranking databases needs the regulons extra: pip install "cytearc[regulons]".

The cell-level steps run on a DataStore: ds.regulons.grn infers the co-expression network, ds.regulons.profiles sums groups of cells such as metacells into profiles, the scoring methods above write enrichment_scores artifacts, which EnrichmentResult.to_pandas reads as a table, and ds.regulons.specificity and ds.regulons.connection_specificity score those artifacts a block of cells at a time. The functions on this page work on those results and on reference files, such as cisTarget databases, JASPAR motifs, a genome FASTA, a gene annotation, and peak files.

RNA regulons (SCENIC)#

GRNBoost2 importances become co-expression modules, motif enrichment keeps the targets that an enriched, annotated motif of each module’s factor recovers, and the leading edges merge into TF(+) regulons.

cytearc.regulons.infer_grn(expression, gene_names, tf_names, *, targets=None, seed, parameters=GrnParameters(learningRate=0.01, maxStages=5000, maxFeatures=0.1, subsample=0.9, earlyStopWindow=25, earlyStopping='stage'), nthreads=1, progress=None)#

Score how well each transcription factor predicts each target gene.

For every target gene, a stochastic gradient boosting regressor predicts its expression from the expression of the transcription factors, leaving the target out when it is a factor itself, and each factor’s importance is recorded. This reproduces arboreto’s GRNBoost2 as pySCENIC runs it: the same regressor settings, the same seed for every target, factors in expression column order, and importances scaled by the stages fitted. A target with constant expression has no links.

Parameters:
  • expression (ndarray) – Cells-by-genes matrix. SCENIC uses raw counts.

  • gene_names (Sequence[str]) – Names of the expression columns; must be unique.

  • tf_names (Sequence[str]) – Candidate regulators. Names absent from gene_names are ignored.

  • targets (Sequence[str] | None) – Target genes to model, by default every gene.

  • seed (int) – Random state given to every target’s regressor.

  • parameters (GrnParameters) – Regressor settings; GRNBoost2 defaults when omitted.

  • nthreads (int) – The most targets fitted at once. Targets are fitted in the calling process, and with nthreads above 1, those left after about two seconds of fitting go to nthreads worker processes, each with its own copy of the factors’ expression. Worker processes start as new interpreters that import the main module, so a script that calls this keeps its own work under if __name__ == "__main__":. The links do not depend on nthreads.

  • progress (Callable[[int, int], None] | None) – Optional callback(done, total) after each target.

Return type:

DataFrame

Returns:

A DataFrame with TF, target, importance, and correlation (Pearson, across cells) columns, one row per positive importance, sorted by decreasing importance, then by target and factor name for a deterministic order. pySCENIC splits modules into activating and repressing links by the correlation.

class cytearc.regulons.GrnParameters(learningRate=0.01, maxStages=5000, maxFeatures=0.1, subsample=0.9, earlyStopWindow=25, earlyStopping='stage')#

Settings of the per-target gradient boosting regressor.

The defaults are those of arboreto’s GRNBoost2 (SGBM_KWARGS with an out-of-bag early-stopping window of 25 rounds), the regressor that pySCENIC runs.

learningRate#

Shrinkage of each boosting stage.

maxStages#

Upper bound on boosting stages; early stopping usually ends a fit much sooner.

maxFeatures#

Fraction of the transcription factors drawn at each split.

subsample#

Fraction of cells drawn for each stage. Must be below 1, because early stopping reads the out-of-bag improvement.

earlyStopWindow#

Stop once the mean out-of-bag improvement over this many most recent stages is negative.

earlyStopping#

How a stage’s out-of-bag improvement is measured. "stage" compares the loss of the stage’s out-of-bag cells before and after the stage, as GRNBoost2 was published and as arboreto computes it with scikit-learn before 1.3, which the pySCENIC 0.12.1 container uses. "consecutive" subtracts the out-of-bag losses of consecutive stages, which are measured on different cells, as arboreto computes it with scikit-learn 1.3 and later.

cytearc.regulons.modules_from_adjacencies(adjacencies, *, parameters=ModuleParameters(thresholds=(0.75, 0.9), topTargets=(50,), topRegulators=(5, 10, 50), minGenes=20, rhoThreshold=0.03, keepOnlyActivating=True))#

Build pySCENIC’s co-expression modules from a TF-target network.

Each factor gets one module per rule: its targets above each importance quantile of all links (weight>75.0%), its top targets (top50), and the targets for which it is among the top factors (top5perTarget). Links are split by the sign of their correlation into activating and repressing modules, the factor joins each of its modules with weight 1, and modules smaller than minGenes are dropped.

Ties in importance are broken by row order, so pass links in the order of the network that produced them.

Parameters:
  • adjacencies (DataFrame) – TF, target, importance, and correlation columns, such as GrnResult.adjacencies.

  • parameters (ModuleParameters) – Module rules; pySCENIC defaults when omitted.

Returns:

source (a unique module name), TF, direction (activating or repressing), context (the rule), target, and weight (the link importance, 1 for the factor).

Return type:

DataFrame

class cytearc.regulons.ModuleParameters(thresholds=(0.75, 0.9), topTargets=(50,), topRegulators=(5, 10, 50), minGenes=20, rhoThreshold=0.03, keepOnlyActivating=True)#

Rules that turn importance links into candidate regulon modules.

The defaults are pySCENIC 0.12.1’s (modules_from_adjacencies and the pyscenic ctx command line).

thresholds#

Importance quantiles over all links; a module holds a factor’s targets above each quantile.

topTargets#

A module holds each factor’s top targets by importance.

topRegulators#

A target joins the modules of its top factors by importance.

minGenes#

Smallest module size, counting the factor itself.

rhoThreshold#

Links whose Pearson correlation exceeds this are activating; those below its negative are repressing; the rest are ignored.

keepOnlyActivating#

Build only activating modules.

class cytearc.regulons.RankingDatabase(path, *, name=None)#

A cisTarget rankings database read column by column.

A database is a Feather version 2 (Arrow IPC) file whose rows are motifs or tracks and whose columns are ranked features, genes or regions, plus one index column naming the rows. Each value is the zero-based rank of a feature in that motif’s ranking of all total features. Only the columns of requested features are read and decompressed, so databases far larger than memory can be queried.

Parameters:
  • path (str | PathLike[str]) – Database file, such as hg38_10kbp_up_10kbp_down_full_tx_v10_clust.genes_vs_motifs.rankings.feather.

  • name (str | None) – Display name; the file name when omitted.

ranks(features)#

Read the ranks of the features that the database ranks.

Parameters:

features (Iterable[str]) – Feature names; names the database does not rank are skipped, as ctxcore does.

Return type:

tuple[ndarray, ndarray]

Returns:

The found feature names in database column order, and their (rows, found) int32 ranks.

property total: int#

Number of ranked features.

cytearc.regulons.read_motif_annotations(path, *, motif_similarity_fdr=0.001, orthologous_identity_threshold=0.0, categories=None)#

Read a cisTarget motif-to-TF annotation table (.tbl).

Rows whose motif similarity q-value exceeds motif_similarity_fdr or whose orthologous identity is below orthologous_identity_threshold are dropped, as pySCENIC does.

Parameters:
  • path (str | PathLike[str]) – Annotation table, such as motifs-v10nr_clust-nr.hgnc-m0.001-o0.0.tbl.

  • motif_similarity_fdr (float) – Largest motif similarity q-value kept.

  • orthologous_identity_threshold (float) – Smallest orthologous identity kept.

  • categories (Sequence[str] | None) – Keep only these annotation categories: "direct", "similarity", "orthology", and "similarity_and_orthology".

Return type:

DataFrame

Returns:

A DataFrame with motif, TF, motif_similarity_qvalue, orthologous_identity, description, and category columns.

Raises:

ValueError – If a category is unknown, the table lacks an annotation column, a row holds fewer or more fields than the header names, or a q-value or identity is not a number; the message names the file and the line.

cytearc.regulons.prune_modules(modules, databases, annotations, *, parameters=PruningParameters(rankThreshold=5000, aucThreshold=0.05, nesThreshold=3.0, maxMissingFraction=0.2), nthreads=1, progress=None)#

Keep the module targets that an enriched motif of the module’s factor recovers.

For every module and database, each motif’s ranking is scored by the AUC of the module’s recovery curve and standardized against all motifs of the database (NES). Enriched motifs (NES >= nesThreshold) that the annotation table assigns to the module’s factor contribute their leading edge: the module genes ranked at or before the rank where the motif’s recovery curve rises furthest above the mean plus two standard deviations of all motifs’ curves. This is pySCENIC’s prune2df with each leading edge taken from its own motif’s curve. pySCENIC 0.12.1 pairs the annotated motifs, after sorting them by annotation quality, with curves in database order, so most of its leading edges come from another enriched motif and its regulon targets differ from these.

Parameters:
  • modules (DataFrame) – Output of modules_from_adjacencies.

  • databases (Sequence[RankingDatabase]) – Gene-based ranking databases.

  • annotations (DataFrame) – Output of read_motif_annotations; every listed (factor, motif) pair counts, whatever its category.

  • parameters (PruningParameters) – cisTarget settings; pyscenic ctx defaults when omitted.

  • nthreads (int) – Modules pruned concurrently.

  • progress (Callable[[int, int], None] | None) – Optional callback(done, total) after each module and database.

Return type:

DataFrame

Returns:

One row per module, database, and enriched annotated motif, with the motif statistics, the annotation, and the leading-edge targets with their module target_weights.

class cytearc.regulons.PruningParameters(rankThreshold=5000, aucThreshold=0.05, nesThreshold=3.0, maxMissingFraction=0.2)#

cisTarget settings for pruning modules.

The defaults are those of pyscenic ctx 0.12.1.

rankThreshold#

Length of the recovery curves that define leading edges, in ranks.

aucThreshold#

Fraction of each motif’s ranking covered by the AUC.

nesThreshold#

Smallest NES of an enriched motif.

maxMissingFraction#

Skip a module once this fraction of its genes, the factor included, is missing from a database.

cytearc.regulons.regulons_from_motifs(motifs)#

Merge the leading edges of each factor and direction into one regulon.

A regulon TF(+) (activating) or TF(-) (repressing) holds the union of its factor’s leading-edge targets over all modules, databases, and enriched motifs, each with its largest weight, as pySCENIC’s df2regulons builds them. The factor is a member only when some leading edge holds it. No minimum size is applied.

Parameters:

motifs (DataFrame) – Output of prune_modules.

Return type:

DataFrame

Returns:

A network with source (the regulon), TF, direction, target, and weight columns, which ds.scores.aucell scores.

Motifs, genomes, and cistromes#

class cytearc.regulons.IndexedFasta(path, *, index_path=None)#

Read intervals of an uncompressed FASTA file without loading it.

The file is memory mapped and read through a samtools faidx index. The index is read from <path>.fai when that file exists, or from index_path; otherwise the FASTA file is scanned once to build it in memory. Nothing is written next to the FASTA file.

Coordinates are zero-based and half-open, as in BED files.

Parameters:
  • path (str | PathLike[str]) – Uncompressed FASTA file. Compressed files are not supported.

  • index_path (str | PathLike[str] | None) – Optional samtools faidx index of path.

close()#

Release the memory map and file handle.

Return type:

None

encode(name, start, end)#

Return fetch(name, start, end) as nucleotide codes (see encode_sequence).

Return type:

ndarray

fetch(name, start, end)#

Return the upper-case bases of name in [start, end).

Return type:

bytes

length(name)#

Number of bases in sequence name.

Return type:

int

property names: tuple[str, ...]#

Sequence names in index order.

cytearc.regulons.gc_content(genome, regions)#

Return the fraction of G and C among the A, C, G, and T bases of each region.

N and other ambiguity codes count in neither the numerator nor the denominator, as in chromVAR’s addGCBias. A region without any A, C, G, or T base has no defined content and gives NaN.

Parameters:
  • genome (IndexedFasta) – Genome the regions refer to.

  • regions (Iterable[str]) – Region ids chrom:start-end, such as ATAC peak ids.

Return type:

ndarray

class cytearc.regulons.Motif(motifId, name, counts)#

A DNA motif as a position frequency matrix.

motifId#

Identifier, such as a JASPAR matrix ID.

name#

Display name, usually the transcription factor.

counts#

(width, 4) non-negative counts or probabilities in A, C, G, T column order.

cytearc.regulons.read_jaspar_motifs(path)#

Read count matrices from a JASPAR-format file.

Each motif is a >ID NAME header followed by A, C, G, and T rows, with or without brackets, as in the JASPAR collection downloads.

Return type:

list[Motif]

cytearc.regulons.read_meme_motifs(path)#

Read motifs from a MEME-format file as counts.

Each letter-probability row is multiplied by its matrix’s nsites (20 when absent, the MEME format’s default), so a pseudocount weighs as much as it does for count matrices such as JASPAR’s.

Return type:

list[Motif]

cytearc.regulons.match_motifs(regions, genome, motifs, *, p_value=5e-05, background='subject', pseudocount=0.8, log_base=2.0, batch_size=4096)#

Find which regions contain a match of each motif on either strand.

Counts become log-odds scores against the background (log_odds_matrix), each strand’s threshold is the MOODS score threshold at p_value of that strand’s matrix, and a region matches when any window on either strand scores at least its strand’s threshold. Windows never span an N or other ambiguity code. These are the motifmatchr defaults that chromVAR uses, except that scores are proper log-odds against the "subject" background, and that the reverse strand has its own threshold, as in MOODS: motifmatchr reuses the forward one, which misses p_value for a background whose A and T, or C and G, frequencies differ.

Parameters:
  • regions (Sequence[str] | ndarray) – Region ids chrom:start-end (zero-based, half-open), such as ATAC peak ids.

  • genome (IndexedFasta) – Genome the regions refer to.

  • motifs (Sequence[Motif]) – Motifs to scan, for example from read_jaspar_motifs.

  • p_value (float) – Probability under the background of a window scoring at least the threshold.

  • background (Union[Literal['subject', 'even'], Sequence[float], ndarray]) – "subject" uses the pooled base frequencies of the regions, "even" uses 0.25 each, or pass four frequencies.

  • pseudocount (float) – Total pseudocount per motif position, split by the background.

  • log_base (float) – Base of the log-odds scores.

  • batch_size (int) – Regions scanned per parallel batch.

Return type:

DataFrame

Returns:

A network with source (motif ID), target (region id), and motif_name columns, one row per matching motif and region, sorted by motif then region order.

cytearc.regulons.motif_annotations(motifs)#

Annotate each motif to the factors that its name lists.

JASPAR and MEME names list one factor or a dimer such as FOS::JUN, sometimes with a variant suffix such as (var.2). Each listed factor is a direct annotation, upper-cased like human gene symbols; recase TF for other species.

Parameters:

motifs (Sequence[Motif]) – Motifs such as read_jaspar_motifs returns.

Returns:

motif (the motif ID), TF, motif_similarity_qvalue (0), orthologous_identity (1), description, and category ("direct").

Return type:

DataFrame

cytearc.regulons.cistromes_from_motifs(motif_network, annotations, *, categories=('direct',))#

Assign motif-matched regions to the factors their motifs are annotated to.

Each factor’s cistrome is the union of the regions matched by every motif the annotation table assigns to it in categories. The default keeps direct annotations; categories=("orthology",) builds cistromes from orthology annotations alone.

Parameters:
  • motif_network (DataFrame) – source (motif ID) and target (region) columns, as match_motifs returns, or the leading-edge regions of enriched motifs.

  • annotations (DataFrame) – Output of read_motif_annotations.

  • categories (Sequence[str]) – Annotation categories that link a motif to a factor.

Return type:

DataFrame

Returns:

A network with source (factor), target (region), and motifs (sorted, comma-separated motif IDs that support the link).

cytearc.regulons.read_peak_file(path)#

Read peaks from a BED, narrowPeak, or SEACR BED file, optionally gzipped.

Coordinates are kept as zero-based half-open BED intervals. Track and browser lines and # comments are skipped.

Return type:

DataFrame

Returns:

A DataFrame with chrom, start, end, name, score, and summit columns; score is the fifth column when present and summit the narrowPeak summit offset (-1 when absent).

cytearc.regulons.binding_cistromes(peaks, regions, *, min_overlap_fraction=0.0)#

Map each factor’s binding peaks onto a set of regions.

A region joins a factor’s cistrome when one of the factor’s peaks overlaps it. With min_overlap_fraction above zero, the shared bases must also exceed that fraction of the peak or of the region.

Parameters:
  • peaks (Mapping[str, DataFrame | str | PathLike[str]]) – Factor name to binding peaks, as a read_peak_file table or a path such as a CUT&RUN narrowPeak file.

  • regions (Sequence[str] | ndarray) – Region names chrom:start-end, such as ATAC peak names.

  • min_overlap_fraction (float) – Required overlap fraction in [0, 1).

Return type:

DataFrame

Returns:

A network with source (factor), target (region), and n_peaks (binding peaks overlapping the region).

Gene programs and specificity#

regulon_specificity and connection_specificity take a table of activity in memory. For the scores of many cells, the ds.regulons methods above give the same scores from the stored artifact without reading it whole.

cytearc.regulons.gene_programs(profiles, *, parameters=GeneProgramParameters(nNeighbors=15, minCorrelation=0.2, resolution=1.0, minMembership=0.3, alpha=0.05, minSize=10, seed=0), block_size=2048)#

Partition genes into co-regulated programs.

Parameters:
  • profiles (DataFrame) – Samples-by-genes expression named by gene, over independent samples such as the metacell or pseudobulk profiles of ds.regulons.profiles. Smoothed or overlapping cells share their counts, which inflates every correlation and admits chance programs. Constant genes are skipped.

  • parameters (GeneProgramParameters) – Discovery settings.

  • block_size (int) – Genes whose correlations are computed at once.

Return type:

DataFrame

Returns:

One row per assigned gene with source (the program, P1 the largest), target (the gene), and membership, the gene’s Pearson correlation with the mean standardized profile of its program’s other genes; rows sort by program, then decreasing membership.

class cytearc.regulons.GeneProgramParameters(nNeighbors=15, minCorrelation=0.2, resolution=1.0, minMembership=0.3, alpha=0.05, minSize=10, seed=0)#

Settings of gene-program discovery.

nNeighbors#

Most correlated genes linked to each gene.

minCorrelation#

Links need at least this Pearson correlation.

resolution#

Leiden resolution of the gene graph.

minMembership#

Genes correlating less than this with the mean profile of their program’s other genes are left unassigned.

alpha#

A screen against chance groupings: a gene’s membership must also exceed the correlation that is significantly positive at this family-wise level over all genes (one-sided Fisher z, Bonferroni) for that many independent samples. It assumes independent samples and ignores that each program was chosen from the same correlations, so it is a filter, not a calibrated test of the programs.

minSize#

Programs with fewer genes are left unassigned.

seed#

Leiden random seed.

cytearc.regulons.program_scores(profiles, programs)#

Mean standardized profile of each program’s genes in each sample.

Parameters:
  • profiles (DataFrame) – Samples-by-genes values named by gene.

  • programs (DataFrame) – Output of gene_programs.

Return type:

DataFrame

Returns:

A samples-by-programs DataFrame indexed like profiles.

cytearc.regulons.program_regulators(programs, database, annotations, *, rank_threshold=5000, auc_threshold=0.05, nes_threshold=3.0, categories=None, profiles=None)#

Nominate the transcription factors whose motifs explain each program.

Each program’s genes are tested with cisTarget against a gene-based ranking database, as pySCENIC tests modules, and enriched motifs are assigned to factors by the annotation table. A large program enriches many weak motifs, so pass profiles to check that each factor’s own expression follows its program.

Parameters:
  • programs (DataFrame) – Output of gene_programs (any source/target table).

  • database (RankingDatabase) – Gene-based ranking database.

  • annotations (DataFrame) – Output of read_motif_annotations.

  • rank_threshold (int) – cisTarget settings.

  • auc_threshold (float) – cisTarget settings.

  • nes_threshold (float) – cisTarget settings.

  • categories (Sequence[str] | None) – Annotation categories to accept; all when omitted.

  • profiles (DataFrame | None) – Samples-by-genes expression named by gene, such as metacell profiles.

Returns:

program, TF, motif, NES, AUC, n_targets (leading-edge genes), and category, sorted by program and decreasing NES. With profiles, correlation is the Pearson correlation of the factor’s expression with the program’s program_scores across samples, NaN for a factor without a varying profile.

Return type:

DataFrame

cytearc.regulons.set_overlaps(queries, references, universe)#

Test every query set for overlap with every reference set.

Parameters:
  • queries (DataFrame) – source (set) and target (gene) columns, such as programs.

  • references (DataFrame) – source and target columns, such as regulons.

  • universe (Sequence[str] | ndarray) – Genes that could have been in any set.

Return type:

DataFrame

Returns:

query, reference, overlap, expected, odds_ratio, one-sided hypergeometric p_value, and Benjamini-Hochberg q_value across all tests.

cytearc.regulons.regulon_specificity(activity, labels)#

Regulon specificity scores (RSS) of each regulon for each group.

RSS = 1 - JSD(p, q) ** 0.5 where p is the regulon’s activity over cells normalized to sum to one, q the group’s indicator normalized the same way, and JSD the Jensen-Shannon divergence with natural logarithms, as pySCENIC’s regulon_specificity_scores computes it. The score is 1 when the regulon is active only, and uniformly, in the group.

The divergence follows from sums over cells, which this adds up block by block of rows; ds.regulons.specificity computes the same scores from a stored score artifact without reading it whole.

Parameters:
  • activity (DataFrame) – Cells-by-regulons non-negative activity, such as AUCell AUCs.

  • labels (Sequence[object] | ndarray | Series) – Group of each cell, aligned by position with activity. Every cell needs a label. Labels of any types may mix as long as they group as their text reads, so 1 beside np.int64(1) is one group and "a" beside 1 two; 0.0 and -0.0 are one group.

Return type:

DataFrame

Returns:

A groups-by-regulons DataFrame, groups in order of first appearance and named by their first label. A regulon without activity scores NaN.

Raises:

ValueError – If labels does not hold one label for each row of activity, a label is missing or blank (None, NaN, pd.NA, pd.NaT, a missing categorical value, or empty or whitespace text), the labels hold values that would form one group but print differently, such as 1, 1.0 and True, or values that print alike but would form separate groups, such as 1 and "1", or a value of activity is negative or not finite.

cytearc.regulons.connection_specificity(activity, *, margin=0.05)#

Connection specificity index (CSI) of every pair of regulons.

For regulons a and b with activity correlation r, the CSI is the fraction of all regulons whose correlation with a and with b are both below r - margin (Fuxman Bass et al. 2013). Regulons that co-vary with each other but not with the rest score near 1, which SCENIC analyses use to group regulons into modules.

The correlations follow from sums over cells, which this adds up block by block of rows; ds.regulons.connection_specificity computes the same index from a stored score artifact without reading it whole. A regulon of constant activity correlates 0 with every regulon.

Parameters:
  • activity (DataFrame) – Cells-by-regulons activity.

  • margin (float) – Correlation margin.

Return type:

DataFrame

Returns:

A symmetric regulons-by-regulons DataFrame.

cytearc.regulons.regulon_modules(csi, n_modules)#

Group regulons into co-activity modules by clustering their CSI profiles.

Rows of the CSI matrix are clustered with Ward linkage and the tree is cut into n_modules clusters, numbered by decreasing size.

Parameters:
  • csi (DataFrame) – Output of connection_specificity.

  • n_modules (int) – Number of modules.

Return type:

Series

Returns:

Module number of each regulon, indexed by regulon.