GRN

Gene-network inference, correlation, regulon construction and TF-list loading.

rustscenic.grn

GRN inference (GRNBoost2 replacement).

Public API: rustscenic.grn.infer(adata_or_matrix, tf_names, ...) -> pd.DataFrame

infer

infer(
    expression,
    tf_names: Iterable[str],
    *,
    n_estimators: int = 5000,
    learning_rate: float = 0.01,
    max_features: float = 0.1,
    subsample: float = 0.9,
    max_depth: int = 3,
    early_stop_window: int = 25,
    early_stop_mode: str = "arboreto",
    top_targets_per_tf: int | None = None,
    min_importance: float | None = None,
    seed: int = 777,
    target_block_size: int | None = None,
    verbose: bool = True,
) -> pd.DataFrame

Infer a gene regulatory network.

Parameters:

Name Type Description Default
expression

An AnnData object, a pandas.DataFrame (cells × genes), or a (matrix, gene_names) tuple where matrix is shape (n_cells, n_genes) float32/float64.

required
tf_names Iterable[str]

Iterable of candidate transcription factor gene symbols.

required
n_estimators int

Maximum number of boosting trees fitted for each target gene.

5000
learning_rate float

Positive shrinkage applied to each tree's prediction update.

0.01
max_features float

Fraction of candidate TF features considered at each split, in (0, 1]. At least one feature is considered.

0.1
subsample float

Fraction of cells sampled for each boosting tree, in (0, 1]. Values below one leave out-of-bag cells for the stopping monitor.

0.9
max_depth int

Maximum depth of each regression tree; at least one.

3
early_stop_window int

Number of recent improvements used by the stopping monitor. Zero disables early stopping.

25
top_targets_per_tf int | None

If set, keep only the top-K targets per TF by importance, descending. Useful on under-determined inputs (n_samples ≪ n_features) where rustscenic's histogram-GBM emits more near-zero-importance edges than sklearn-backed pipelines and downstream regulon construction wants a sparser GRN.

None
min_importance float | None

If set, drop edges with importance < min_importance before returning. Cheap floor filter; combine with top_targets_per_tf for arboreto-like edge-density behaviour.

None
target_block_size int | None

Retained for API compatibility. The flat target scheduler no longer blocks targets, so this value is validated but does not affect execution.

None
early_stop_mode str

"arboreto" (default) uses the trailing mean of out-of-bag improvements, matching arboreto with modern scikit-learn semantics. "legacy_inbag" retains RustScenic's historical two-point in-bag MSE rule for reproducing older RustScenic artefacts. Set early_stop_window=0 to disable either rule. Arboreto OOB stopping also has no OOB rows at subsample=1.0 and therefore fits to the estimator ceiling.

'arboreto'
seed int

Seed passed to the Rust GRN backend's random-number generator.

777
verbose bool

Print progress and timing information to standard error.

True

Returns:

Type Description
pandas.DataFrame with columns ``['TF', 'target', 'importance']``,
filtered to ``importance > 0``, sorted descending per target.
Matches the schema produced by ``arboreto.algo.grnboost2``.
Notes

These additional provenance fields were added in version 0.5.1. They are absent from the 0.5.0 wheel.

result.attrs["grn_fit"] records normalized fitting and output-filter settings alongside fitted-tree summaries. The ignored compatibility option is recorded as target_block_size_requested; its effective value is always None under flat target scheduling. min_importance is a float or None, except accepted nonfinite values are recorded as the strict-JSON strings "NaN", "Infinity" or "-Infinity". Filtering is unchanged. These settings alone do not capture the inputs and environment needed to reproduce a complete analysis.

add_correlation

add_correlation(
    adjacencies: DataFrame,
    expression,
    *,
    rho_threshold: float = 0.03,
    mask_dropouts: bool = False,
) -> pd.DataFrame

Add TF-target Pearson correlation and SCENIC regulation polarity.

The returned frame preserves the adjacency row order and input columns, then adds regulation (1 activator, -1 repressor, 0 indeterminate) and rho. With mask_dropouts=True, only cells where both the TF and target are non-zero contribute to a pair's correlation, matching pySCENIC's historical dropout-masked option.

Parameters:

Name Type Description Default
adjacencies DataFrame

Edge table containing TF, target and importance columns.

required
expression

AnnData, a cells-by-genes DataFrame, or a (matrix, gene_names) tuple covering every TF and target in the edge table.

required
rho_threshold float

Positive correlation magnitude separating activating and repressing edges from neutral edges.

0.03
mask_dropouts bool

Restrict each correlation to cells with nonzero TF and target expression when true.

False

Returns:

Type Description
DataFrame

A copy of the edge table with rho and regulation columns.

build_regulons

build_regulons(
    correlated_adjacencies: DataFrame,
    *,
    top_targets_per_tf: int = 50,
    min_targets: int = 10,
    include_repressors: bool = True,
) -> dict[str, list[str]]

Build deterministic activator/repressor regulons from signed edges.

Names use <TF>_activator and <TF>_repressor. Neutral edges (regulation == 0) are excluded rather than silently assigned a sign.

Parameters:

Name Type Description Default
correlated_adjacencies DataFrame

Edge table with TF, target, importance and regulation columns, such as the output of add_correlation.

required
top_targets_per_tf int

Maximum number of targets retained per TF and polarity by importance.

50
min_targets int

Minimum number of targets needed to retain a regulon.

10
include_repressors bool

Include negatively correlated target sets as repressor regulons. False returns activator regulons only.

True

Returns:

Type Description
dict[str, list[str]]

Signed regulon names mapped to their retained target genes.

load_tfs

load_tfs(path: str | Path) -> list[str]

Load a TF list (one gene symbol per line) from a text file.

Strips whitespace (including \r from Windows line endings) and skips blank lines / comment lines starting with #.

Parameters:

Name Type Description Default
path str | Path

Path to the text file containing TF symbols.

required

Returns:

Type Description
list[str]

Nonblank, noncomment TF symbols in file order.

Reexported helpers

These names are also available from this module. They share the underlying implementation and source documentation of their original definitions.

rustscenic.grn.dedupe_backend_symbol_for_matrix

dedupe_backend_symbol_for_matrix(X) -> str | None

Return the Rust dedupe kernel symbol that dedupe_by_symbol will use.

Parameters:

Name Type Description Default
X

Dense NumPy or SciPy sparse matrix whose dtype and sparse status select the kernel. Unsupported dtypes return None.

required

rustscenic.grn.dedupe_by_symbol

dedupe_by_symbol(X, gene_names: Sequence[str])

Collapse duplicate gene-symbol columns by summing their expression.

When an ENSEMBL → symbol swap produces duplicate symbols (e.g. several transcripts collapsing onto the same HGNC symbol, or pseudogenes sharing a parent name), downstream regulon lookup is ambiguous. The scanpy / limma convention is to sum the columns: total per-gene expression aggregated across transcripts. This preserves signal; the alternative (drop all but one) silently loses half the gene's reads.

Parameters:

Name Type Description Default
X

Dense NumPy or SciPy sparse cells-by-genes matrix with numeric float32/float64, int32/int64 or uint32/uint64 values.

required
gene_names Sequence[str]

Gene symbols corresponding to the columns of X.

required

Returns:

Type Description
(X_deduped, unique_gene_names) - X may be sparse (scipy.sparse) or
dense numpy; the return type matches the input.

rustscenic.grn.duplicate_gene_summary

duplicate_gene_summary(
    gene_names: Sequence[str], *, max_examples: int = 3
) -> tuple[int, list[str]]

Return duplicate gene count and example names from the Rust stage helper.

Parameters:

Name Type Description Default
gene_names Sequence[str]

Gene symbols to inspect for duplicates.

required
max_examples int

Maximum number of duplicate-name examples to return.

3

rustscenic.grn.warn_if_max_likely_unnormalized

warn_if_max_likely_unnormalized(
    max_val: float | None, *, max_threshold: float = 50.0, stacklevel: int = 2
) -> None

Warn from a Rust-collected expression maximum without rescanning in Python.

Parameters:

Name Type Description Default
max_val float | None

Observed expression maximum; None skips the check.

required
max_threshold float

Finite maximum above which the normalization warning is emitted.

50.0
stacklevel int

Stack depth passed to warnings.warn to locate the caller.

2

rustscenic.grn.as_float32_array

as_float32_array(values) -> np.ndarray

Return a float32 ndarray without changing memory layout.

Parameters:

Name Type Description Default
values

Array-like values accepted by numpy.asarray.

required

rustscenic.grn.as_float32_contiguous

as_float32_contiguous(values) -> np.ndarray

Return a C-contiguous float32 ndarray, copying only when needed.

Parameters:

Name Type Description Default
values

Array-like values accepted by numpy.asarray.

required

rustscenic.grn.string_list

string_list(values: Iterable) -> list[str]

Return Python strings with minimal pandas boundary overhead.

Parameters:

Name Type Description Default
values Iterable

Iterable, pandas Series or Index, or NumPy array of values to convert to strings in input order.

required