API Reference

gcen2.preprocessing

Data normalization and filtering.

Data normalization and filtering.

Python reimplementation of GCEN v1 data_norm / data_filter, ported from src/util/norm.hpp and src/data_filter.cpp.

Bug fixes vs GCEN v1:
  • deviation() now uses sample std dev (ddof=1) instead of population std dev (ddof=0). Pass ddof=0 explicitly if you need the old population-std behaviour.

gcen2.preprocessing.normalize(expr: ExpressionMatrix | DataFrame, method: str = 'tmm', housekeeping_genes: list[str] | None = None) → ExpressionMatrix | DataFrame[source]

Normalize gene expression data.

Parameters:
  • expr – Expression matrix (genes × samples).

  • method – Normalization method: ‘upqt’, ‘median’, ‘deseq’, ‘tmm’, or ‘hkg’.

  • housekeeping_genes – Required when method=’hkg’. List of reference gene identifiers.

Return type:

Normalized expression matrix of the same type as the input.

gcen2.preprocessing.normalize_upqt(expr: DataFrame) → DataFrame[source]

Upper quartile normalization.

Mirrors GCEN v1 norm_upqt(): divide each sample by the 75th percentile of its nonzero values, then rescale so that the global mean of upper quartiles is preserved.

gcen2.preprocessing.normalize_median(expr: DataFrame) → DataFrame[source]

Median normalization.

Mirrors GCEN v1 norm_median(): same idea as upqt but uses the median of nonzero values.

gcen2.preprocessing.normalize_deseq(expr: DataFrame) → DataFrame[source]

DESeq size-factor normalization.

Mirrors GCEN v1 norm_deseq():
  1. For each gene, compute geometric mean across samples.

  2. For each sample, compute the ratio of its expression to the gene geometric mean.

  3. Size factor = median of these ratios across all genes with nonzero geometric mean.

  4. Divide each sample by its size factor, then rescale so the mean size factor is 1.

gcen2.preprocessing.normalize_tmm(expr: DataFrame) → DataFrame[source]

TMM (Trimmed Mean of M-values) normalization.

Mirrors GCEN v1 norm_tmm() / calc_weighted_factor() exactly:
  1. Select reference sample = sample whose upper quartile is closest to the global mean of upper quartiles.

  2. For each sample, compute weighted trimmed mean of log₂ fold-change (M values) against the reference, trimming 30% of M and 5% of A.

  3. Normalize: divide each sample by 2^TMM factor.

  4. Rescale so geometric mean of factors = 1.

gcen2.preprocessing.normalize_hkg(expr: DataFrame, housekeeping_genes: list[str]) → DataFrame[source]

Housekeeping gene normalization.

Mirrors GCEN v1 norm_hkg():
  1. For each sample, compute the median expression of housekeeping genes.

  2. Scale factor = global_mean_of_medians / per_sample_median.

  3. Multiply each sample by its scale factor.

gcen2.preprocessing.filter_genes(expr: ExpressionMatrix | DataFrame, cutoff_mean: float = 0.0, cutoff_sd: float = 0.0, percent_mean: float = 1.0, percent_sd: float = 1.0) → ExpressionMatrix | DataFrame[source]

Filter genes by expression mean and standard deviation.

Mirrors GCEN v1 data_filter logic.

Bug fix vs GCEN v1: standard deviation uses ddof=1 (sample std dev).

Parameters:
  • expr – Expression matrix (genes × samples).

  • cutoff_mean – Minimum absolute mean expression. Genes below this are removed.

  • cutoff_sd – Minimum absolute standard deviation. Genes below this are removed.

  • percent_mean – Retain genes with mean expression in the top percent_mean fraction. E.g. 0.75 keeps the top 75% (genes above the 25th percentile of means).

  • percent_sd – Retain genes with std dev in the top percent_sd fraction.

gcen2.preprocessing.log_transform(expr: ExpressionMatrix | DataFrame, base: str = 'log2', pseudo: float = 1.0) → ExpressionMatrix | DataFrame[source]

Apply log transformation: log_base(x + pseudo).

Mirrors GCEN v1 string_to_log / string_to_log2 / string_to_log10.

Parameters:
  • base – ‘log’ (natural log), ‘log2’, or ‘log10’.

  • pseudo – Pseudo-count added before taking the log (default 1.0 = GCEN v1 default).

gcen2.network

Network construction and utilities.

Network construction and utility operations.

gcen2.network.GEMM_MIN_SAMPLES = 64

Samples from which kernel="auto" uses the matrix-product kernel.

gcen2.network.build(expr: ExpressionMatrix | pd.DataFrame, method: str = 'spearman', cor: float = 0.1, pval: float = 0.001, signed: bool = False, fdr: bool = False, log: str | None = None, all_edges: bool = False, threads: int = 2, layer: str | None = None, use_highly_variable: bool = False, tom: bool = False, power: float | str = 'auto', tom_min: float = 0.0, kernel: str = 'auto') → Network[source]

Build a gene co-expression network.

Parameters:
  • expr – Expression matrix (genes × samples), or an AnnData (cells × genes, dense or sparse; see gcen2.single_cell.adata_matrix()).

  • method – Correlation method: ‘pearson’, ‘spearman’, or a dropout-aware Pearson (see METHODS): ‘pearson_nonzero’ (per gene pair, only the samples where both genes are non-zero) or ‘pearson_pairwise_complete’ (where at least one is non-zero).

  • cor – Minimum absolute correlation coefficient for an edge to be retained.

  • pval – Maximum p-value cutoff.

  • signed – If True, build a signed network: only positive correlations are kept (same as GCEN v1 network_build -s and WGCNA’s “signed” network). If False (default), edges are selected by |r| and both signs are kept.

  • fdr – If True, apply Benjamini-Hochberg FDR correction.

  • log – Optional log transformation before correlation: ‘log’, ‘log2’, ‘log10’.

  • all_edges – If True, return all edges (ignoring cor and pval cutoffs).

  • threads – Number of threads for the C++ correlation kernel.

  • layer – AnnData input only: the layer instead of X, and keep the highly variable genes.

  • use_highly_variable – AnnData input only: the layer instead of X, and keep the highly variable genes.

  • tom – Add WGCNA’s topological overlap as a tom column (pearson or spearman only; see TOM_DOC): power is the soft threshold, "auto" picks it as WGCNA’s pickSoftThreshold. Edges with TOM below tom_min are dropped (unless all_edges). The power and the scale-free fit table go to network.metadata["tom"].

  • power – Add WGCNA’s topological overlap as a tom column (pearson or spearman only; see TOM_DOC): power is the soft threshold, "auto" picks it as WGCNA’s pickSoftThreshold. Edges with TOM below tom_min are dropped (unless all_edges). The power and the scale-free fit table go to network.metadata["tom"].

  • tom_min – Add WGCNA’s topological overlap as a tom column (pearson or spearman only; see TOM_DOC): power is the soft threshold, "auto" picks it as WGCNA’s pickSoftThreshold. Edges with TOM below tom_min are dropped (unless all_edges). The power and the scale-free fit table go to network.metadata["tom"].

  • kernel – Pearson / Spearman kernel: "pairwise" (each pair summed in turn, exactly as GCEN v1), "gemm" (rows standardised once, r from a tiled matrix product with a fixed summation order; about 4x faster at 128 samples and 10x at 512 and more; r agrees with "pairwise" to rounding, about 1e-15 to 1e-14, so an edge exactly on a cutoff can differ) or "auto" ("gemm" from GEMM_MIN_SAMPLES samples). Both give the same results for any number of threads. Ignored by the dropout-aware methods.

Return type:

Network

gcen2.network.build_to_file(expr: ExpressionMatrix | pd.DataFrame | np.ndarray, path, method: str = 'spearman', cor: float = 0.1, pval: float = 0.001, signed: bool = False, fdr: bool = False, log: str | None = None, all_edges: bool = False, threads: int = 2, max_pairs_per_block: int = 500000, gene_names=None, layer: str | None = None, use_highly_variable: bool = False, tom: bool = False, power: float | str = 'auto', tom_min: float = 0.0, kernel: str = 'auto') → dict[source]

Build a network and stream it to path block by block.

Same edges, columns, order and number formatting as build(...).to_edgelist(path) (the files are byte-identical; numbers are written like GCEN v1: correlation %f, p-value/FDR %e), but the gene pairs are computed in blocks of rows of at most max_pairs_per_block pairs and written immediately, so peak memory is bounded by one block instead of the whole network (GCEN v1 also streams its output). This matters for large or all_edges networks.

With fdr=True the Benjamini-Hochberg ranks need every p-value first: one pass keeps the p-values of all tests with p <= pval (8 bytes each) and the edges that pass the other filters (24 bytes each, up to 2^24 of them; beyond that the blocks are correlated a second time to write them). All of it runs in the compiled extension (_gcen_core.correlation.build_network_array, src/network_stream.cpp).

expr may also be a plain genes x samples array, with the gene names in gene_names (this path does not need pandas), or an AnnData (with layer / use_highly_variable as in build()).

tom / power / tom_min and kernel as in build() (TOM needs the whole adjacency matrix in memory: 4 bytes x genes^2).

Returns {"node_count": ..., "edge_count": ...}, plus "tom" (power and fit table, see build()) with tom=True.

gcen2.network.TOM_DOC = 'Adjacency a_ij = ((1 + r_ij) / 2)^power for a signed network, |r_ij|^power\notherwise (r: Pearson, or Pearson of the ranks for spearman), connectivity\nk_i = sum_u a_iu, and TOM_ij = (sum_u a_iu a_uj + a_ij) / (min(k_i, k_j) + 1 - a_ij),\nas WGCNA\'s TOMsimilarityFromExpr (TOMType = networkType, TOMDenom = "min").\npower="auto": the first of 1..10, 12..20 whose scale-free fit R^2 exceeds\n0.85 (WGCNA 1.74 pickSoftThreshold), else the WGCNA FAQ power for the number\nof samples (signed 18/16/14/12, unsigned 9/8/7/6 below 20/30/40 samples and\nabove). Single precision for the adjacency: relative error ~1e-6.'

How the tom edge score is computed (src/tom.hpp).

gcen2.network.pick_soft_threshold(expr: ExpressionMatrix | pd.DataFrame | np.ndarray, method: str = 'pearson', signed: bool = False, powers=None, log: str | None = None, threads: int = 2, gene_names=None) → pd.DataFrame[source]

WGCNA’s pickSoftThreshold table: for each power the scale-free fit R^2 and slope and the mean / median / max connectivity (see TOM_DOC), with the power power="auto" would pick marked in the chosen column.

gcen2.network.merge(networks: list[Network], cor_cutoff: float = 0.5) → Network[source]

Merge multiple networks.

Edges present in multiple networks are aggregated by summing their correlations. The direction (sign) is output as a separate column, fixing the GCEN v1 bug.

Parameters:
  • networks – List of Network objects to merge.

  • cor_cutoff – Minimum absolute aggregated correlation for an edge to appear in the output.

gcen2.network.extract(network: Network, genes: list[str]) → Network[source]

Extract a subnetwork containing edges where at least one node is in genes.

gcen2.network.extract_file(path, genes: list[str], output) → dict[source]

extract() from an edge-list file to an edge-list file.

Writes the same file as extract(read_network(path), genes).to_edgelist(output). The compiled extension streams the file, keeps the rows with a listed gene and writes them (_gcen_core.network.extract_edge_file), so pandas is not imported. It falls back to that pipeline without the extension, for gene columns that are not the first two, and when it cannot be sure how pandas would read the file (it then writes nothing). Returns {"node_count", "edge_count"}.

gcen2.network.merge_files(paths: list, output, cor_cutoff: float = 0.5) → dict[source]

merge() from edge-list files to an edge-list file.

Same output as merge([read_network(p) for p in paths], cor_cutoff) .to_edgelist(output); the compiled extension reads, sums, sorts and writes the edges (_gcen_core.network.merge_edge_files) without pandas. Falls back to that call without the extension or for files whose gene columns are not the first two. Returns {"node_count", "edge_count"}.

gcen2.network.shuffle_file(path, output, swap_factor: int = 100, seed: int = 42) → dict[source]

shuffle() from an edge-list file to an edge-list file.

Writes the same file as shuffle(read_network(path), swap_factor, seed).to_edgelist(output): the compiled extension reads the file, applies the swaps with numpy’s random stream reproduced in C++ and writes the rows (_gcen_core.network.shuffle_edge_file), so pandas is not imported. Falls back to that pipeline without the extension, for gene columns that are not the first two, and for files whose pandas reading the extension cannot be sure of (it then writes nothing). Returns {"node_count", "edge_count"}.

gcen2.network.shuffle(network: Network, swap_factor: int = 100, seed: int = 42) → Network[source]

Degree-preserving edge swap randomization.

Repeatedly picks two edges (a1, b1), (a2, b2) and rewires them to (a1, b2), (a2, b1) unless that would create a self-loop or an edge that already exists in either orientation.

Parameters:
  • swap_factor – Number of swaps = swap_factor × number_of_edges.

  • seed – Random seed for reproducibility.

gcen2.network.stats(network: Network) → NetworkStats[source]

Compute network statistics.

gcen2.network.stats_from_file(path, threads: int = 2) → NetworkStats[source]

Statistics of the network in an edge-list file, read without pandas.

Same values as stats(read_network(path)): the compiled extension reads the two gene columns into the symmetric adjacency (module.read_file_adjacency) and counts degrees, triangles and components on it. Without the extension it falls back to that call.

class gcen2.network.NetworkSummary(stats: NetworkStats, degrees: np.ndarray, method: str = 'spearman', is_signed: bool = False)[source]

Bases: object

What a report needs of a network, without its edge table: the statistics, the node degrees (any order) and the build settings (Network defaults for a network read from a file).

stats: NetworkStats
degrees: np.ndarray
method: str = 'spearman'
is_signed: bool = False
gcen2.network.summary_from_file(path, threads: int = 2) → NetworkSummary | Network[source]

NetworkSummary of an edge-list file, read without pandas.

Statistics as stats_from_file() and degrees as networkx G.degree gives them, from one module.read_file_adjacency / graph_stats pass. Without the compiled extension it returns read_network(path) instead, which gcen2.report accepts too.

gcen2.module

Gene module identification.

Module identification via Jaccard similarity + DFS clustering.

gcen2.module.identify(network: Network, similarity: float = 0.5, threads: int = 2) → ModuleSet[source]

Identify gene modules from a co-expression network.

Uses Jaccard similarity-based module detection with DFS clustering, identical to the algorithm in GCEN v1 module_identify.cpp.

Parameters:
  • network – Input co-expression network.

  • similarity – Jaccard similarity cutoff. Gene pairs above this threshold are considered to belong to the same module.

  • threads – Worker threads for the C++ similarity kernel.

Return type:

ModuleSet with singleton modules (< 2 genes) excluded.

gcen2.module.read_file_adjacency(path, with_counts: bool = False, descending: bool = False)[source]

Symmetric CSR adjacency of an edge-list file, read by the C++ extension.

Returns (indptr, indices, names) (plus counts, the entry multiplicities, with with_counts): nodes sorted by name, duplicate and reversed edges merged, a self-loop on the diagonal; columns ascending within each row (descending with descending). The header is detected as in gcen2.io.read_network(). Needs the compiled extension; imports neither pandas nor scipy.

gcen2.module.modules_from_file(path, similarity: float = 0.5, threads: int = 2) → list[set[str]][source]

Modules of the network in an edge-list file, read without pandas.

Same modules, in the same order, as identify(read_network(path), similarity, threads).modules, but the C++ extension reads the two gene columns and builds the adjacency directly (_gcen_core.module.read_edge_adjacency), so neither pandas nor scipy is imported. Used by gcen2 module. Without the compiled extension it falls back to identify().

gcen2.tom_modules

WGCNA-style modules from the topological overlap (gcen2 module -e): soft-thresholding power, TOM, tree cut, eigengenes, kME, trait correlations.

WGCNA-style modules: TOM, average-linkage clustering, dynamic tree cut.

tom_modules() follows WGCNA 1.74 blockwiseModules on one block (every gene in one TOM, as maxBlockSize >= the number of genes):

  1. 1 - TOM of all genes (the tom edge score of gcen2 build --tom; power="auto" picks the power as pickSoftThreshold);

  2. fastcluster::hclust(method = "average") on it (C++, same merges and heights);

  3. dynamicTreeCut::cutreeHybrid (1.63-1) with deepSplit, minClusterSize, cutHeight = 0.995 and the PAM stage (cutree_hybrid(), a line-by-line port);

  4. module eigengenes (first principal component of the scaled module genes, aligned with their average) and kME checks: a module with fewer than min_size / 3 genes at kME > 0.5 is dropped, genes with kME < 0.3 leave their module, and a module left with fewer than min_size genes is dropped;

  5. genes whose kME is much higher for another module (Fisher p-value ratio < 1e-6) are reassigned to it (as WGCNA does, by the eigengene’s column number);

  6. mergeCloseModules: modules whose eigengenes correlate above 1 - merge_cut (average linkage on 1 - cor) are merged, repeatedly.

Eigengenes and kME use the Pearson correlation of the expression values (WGCNA’s corType = "pearson"), also when the TOM is from Spearman correlations. Genes with a constant or non-finite row are left out (label 0), as WGCNA’s goodSamplesGenes removes them; missing values are not imputed. Modules are numbered 1, 2, … by decreasing size, 0 = unassigned.

Downstream (as the WGCNA tutorial): TomModules.eigengenes (moduleEigengenes of the merged modules, ME0 for the unassigned genes included, with varExplained), TomModules.kme() (signedKME and corPvalueStudent) and TomModules.trait_cor() (corAndPvalue of the eigengenes with sample traits, pairwise complete observations).

class gcen2.tom_modules.TomModules(genes: list[str], labels: ~numpy.ndarray, unmerged: ~numpy.ndarray, power: float, power_estimated: bool, fits: list[dict] = <factory>, power_rule: str | None = None, samples: list[str] = <factory>, me_labels: list[int] = <factory>, eigengenes: ~numpy.ndarray | None = None, var_explained: ~numpy.ndarray | None = None, signed: bool = False, metadata: dict = <factory>, _x: ~numpy.ndarray | None = None, _good: ~numpy.ndarray | None = None)[source]

Bases: object

Result of tom_modules().

genes: list[str]
labels: ndarray
unmerged: ndarray
power: float
power_estimated: bool
fits: list[dict]
power_rule: str | None = None
samples: list[str]
me_labels: list[int]
eigengenes: ndarray | None = None
var_explained: ndarray | None = None
signed: bool = False
metadata: dict
modules() → list[list[str]][source]

Genes of modules 1..K (sorted names).

hub_genes(n: int = 10)[source]

The n genes of each module with the highest kME for it (|kME| for unsigned networks; as hdWGCNA GetHubGenes): a table module (0-based, as write_module_files()), gene, kME, rank.

eigengene_frame()[source]

Eigengenes as a samples x ME<k> DataFrame (WGCNA MEs).

kme() → tuple[ndarray, ndarray][source]

WGCNA signedKME (Pearson correlation of every gene with every eigengene; genes x eigengenes, NaN for the genes left out) and its corPvalueStudent p-values.

trait_cor(traits) → pd.DataFrame[source]

Eigengene-trait correlations as WGCNA corAndPvalue(MEs, traits, use = "p"): a long table module, trait, cor, p, n. traits: a DataFrame with samples as rows (matched by name; samples missing from it count as missing values) and numeric columns.

gcen2.tom_modules.cutree_hybrid(merge, height, dist, min_cluster_size: int = 20, deep_split: int = 1, cut_height: float | None = None, pam_stage: bool = True, pam_respects_dendro: bool = True, max_pam_dist: float | None = None) → ndarray[source]

dynamicTreeCut::cutreeHybrid(...)$labels (1.63-1; no external split functions, useMedoids = FALSE, respectSmallClusters = TRUE).

merge / height: an R-convention dendrogram (as _gcen_core.module.hclust_average returns); dist: the n x n dissimilarities. max_pam_dist defaults to cut_height as given (cutreeDynamic passes it before it is capped at the tree height). Returns labels 0 (unassigned), 1, 2, … by decreasing cluster size.

gcen2.tom_modules.module_eigengene(x: ndarray) → ndarray[source]

WGCNA moduleEigengenes for one module: genes x samples -> samples.

The first right singular vector of the scaled genes, from the top eigenvector of the smaller Gram matrix only (same vector as the SVD up to sign and rounding), aligned with the average scaled expression.

gcen2.tom_modules.cor_p_student(r: ndarray, n) → ndarray[source]

WGCNA corPvalueStudent: two-sided Student t p-value of correlations from n observations (n broadcasts with r).

gcen2.tom_modules.cor_pairwise(x: ndarray, y: ndarray)[source]

Pearson correlation of the rows of x with the rows of y on pairwise complete observations (R cor(use = "p")), with WGCNA corAndPvalue’s Student p-values and observation counts.

gcen2.tom_modules.module_eigengenes(x: ndarray, labels: ndarray)[source]

WGCNA moduleEigengenes of every label present (0 included): (levels, eigengenes as levels x samples, varExplained).

gcen2.tom_modules.merge_close_modules(x: ndarray, labels: ndarray, cut_height: float) → ndarray[source]

WGCNA mergeCloseModules (one set, iterate, relabel): merge modules whose eigengenes have 1 - cor below cut_height (average linkage).

gcen2.tom_modules.wgcna_post_process(x: ndarray, labels: ndarray, signed: bool, min_size: int, min_core_kme: float = 0.5, min_kme_to_stay: float = 0.3, reassign_threshold: float = 1e-06) → ndarray[source]

blockwiseModules after cutreeDynamic, before mergeCloseModules: the kME checks and the reassignment (x: genes x samples).

gcen2.tom_modules.tom_modules(expr, method: str = 'pearson', signed: bool = False, power='auto', min_size: int = 20, deep_split: int = 2, merge_cut: float = 0.15, detect_cut: float = 0.995, pam_stage: bool = True, min_kme_to_stay: float = 0.3, reassign_threshold: float = 1e-06, power_method: str | None = None, power_r2: float | None = None, min_power: float = 0, powers=None, log: str | None = None, threads: int = 2, gene_names=None, layer=None, use_highly_variable: bool = False, sample_names=None) → TomModules[source]

WGCNA blockwiseModules modules (see the module docstring).

expr: genes x samples (DataFrame, ExpressionMatrix, AnnData, or an array with gene_names). signed: ((1 + r) / 2)^power adjacency and signed kME (WGCNA networkType = "signed", TOMType = "signed"), else |r|^power. Defaults are blockwiseModules’ (minModuleSize 20, deepSplit 2, mergeCutHeight 0.15, detectCutHeight 0.995). Memory: one genes x genes double matrix (the correlations, the adjacency and 1 - TOM are built in it; the clustering works in it too) plus about 1/16 of that while the TOM is built. sample_names (array input): names of the columns, else taken from the DataFrame / AnnData, or sample_1, sample_2, …

power="auto" picks the power as pickSoftThreshold (first power with R^2 > 0.85, Pearson / Spearman as method). power_method (“pearson”, “spearman” or “bicor”), power_r2, min_power and powers change that: the lowest of powers above min_power whose fit R^2 is at least power_r2, from correlations by power_method; if none, the WGCNA FAQ power. tom_modules(expr, **HDWGCNA) reproduces hdWGCNA’s ConstructNetwork with its TestSoftPowers power on the same datExpr. pam_stage, min_kme_to_stay and reassign_threshold (0: none) are the cutreeDynamic / blockwiseModules options of those names.

gcen2.tom_modules.soft_power_table(res: TomModules)[source]

The scale-free fit of every soft power tried (pickSoftThreshold’s table: power, r2, slope, mean_k, median_k, max_k), with the power used marked; a set column for consensus networks. Empty when the power was given.

gcen2.tom_modules.dendrogram_dict(res: TomModules) → dict | None[source]

The gene tree as a JSON-ready dict: genes (the leaves, in the order of the merge numbers), merge (R hclust convention), height, and each leaf’s module after and before merging (0-based as modules.tsv, -1 unassigned).

gcen2.tom_modules.hub_tom(res: TomModules, n_hubs: int = 25, threads: int = 2)[source]

The TOM between every gene in a module (rows) and the n_hubs genes of highest kME of each module (columns), recomputed from the result’s expression with its power: the input of the hub-gene networks and the module UMAP. Not for consensus networks (their TOM is a combination of the sets’ TOMs).

gcen2.tom_modules.gene_significance(res: TomModules, traits)[source]

WGCNA gene significance: correlation of every gene with every trait (pairwise complete observations) and its Student p-value; genes x (GS.<trait>, p.GS.<trait>). traits: samples x numeric traits.

gcen2.tom_modules.write_module_files(res: TomModules, modules=None, eigengenes=None, kme=None, hubs=None, n_hubs: int = 10, trait_table=None, trait_cor=None, soft_power=None, dendrogram=None, tom_hubs=None, n_tom_hubs: int = 25, gs_table=None, gs=None, threads: int = 2) → None[source]

Write tom_modules() results as TSV files (each path optional).

Modules are numbered 0..K-1 by size (gcen2 module format: module, gene; unassigned genes left out); eigengene ME<k> is module k and ME_unassigned WGCNA’s ME0 (the unassigned genes). eigengenes: samples x eigengenes; kme: gene, module (NA = unassigned), kME and Student p-value for every eigengene; hubs: TomModules.hub_genes(); trait_cor: trait_table (TomModules.trait_cor()) renamed.

gcen2.annotation

GO and KEGG functional annotation.

GO/KEGG functional annotation and enrichment analysis.

class gcen2.annotation.NetworkAdjacency(indptr: np.ndarray, indices: np.ndarray, names: list)[source]

Bases: NamedTuple

A network as symmetric CSR adjacency over sorted gene names, as returned by gcen2.module.read_file_adjacency(). Accepted wherever a Network is (annotation only needs who is adjacent to whom).

indptr: ndarray

Alias for field number 0

indices: ndarray

Alias for field number 1

names: list

Alias for field number 2

classmethod from_file(path) → NetworkAdjacency[source]
class gcen2.annotation.GOTerm(id: 'str', name: 'str' = '', namespace: 'str' = '', parents: 'set[str]' = <factory>, alt_ids: 'set[str]' = <factory>, is_obsolete: 'bool' = False)[source]

Bases: object

id: str
name: str = ''
namespace: str = ''
parents: set[str]
alt_ids: set[str]
is_obsolete: bool = False
class gcen2.annotation.GOOntology(terms: 'dict[str, GOTerm]'=<factory>)[source]

Bases: object

terms: dict[str, GOTerm]
propagate(gene_terms: dict[str, set[str]]) → dict[str, set[str]][source]

Add all ancestor terms to each gene’s annotation set.

The ancestor closure of each distinct term is computed once and shared, instead of walking the DAG again for every gene.

gcen2.annotation.load_go(obo_file: str | Path) → GOOntology[source]

Parse a GO OBO file and return a GOOntology object.

gcen2.annotation.load_association(assoc_file: str | Path, ontology: GOOntology | None = None) → dict[str, set[str]][source]

Load a gene-term association file (GCEN v1 format).

Each line is gene <tab> term [<tab> term ...]; a field may also hold several comma-separated terms. Repeated genes are merged. Genes listed without any term are kept (with an empty set) because GCEN v1 counts them as annotated.

If a GOOntology is provided, terms are propagated to all is_a ancestors (as GCEN v1 propagate).

class gcen2.annotation.KEGGMapping(k_to_pathways: dict[str, set[str]]=<factory>, pathway_names: dict[str, str]=<factory>)[source]

Bases: object

KO -> pathway mapping from a GCEN v1 K2ko file.

k_to_pathways: dict[str, set[str]]
pathway_names: dict[str, str]
gcen2.annotation.load_kegg(k2ko_file: str | Path) → KEGGMapping[source]

Parse a K2ko file: K number <tab> pathway id <tab> description.

gcen2.annotation.load_kegg_association(assoc_file: str | Path, kegg: KEGGMapping) → dict[str, set[str]][source]

Gene -> KEGG pathways, from a gene-to-K-number association file.

gcen2.annotation.annotate_go(network_or_modules: Network | ModuleSet, obo: str | Path | GOOntology, assoc: str | Path | dict, pval: float = 0.05, threads: int = 2) → dict[str, EnrichmentResult][source]

GO annotation of a network or module set (GCEN v1 annotate).

Network: every gene without GO terms is annotated from its annotated neighbours (guilt by association); the background is the set of annotated genes adjacent to an unannotated gene. Modules: each module is tested against all module genes. See build_annotation_queries(). The test is one-sided (over-representation), keeping p <= pval.

Returns a dict mapping gene / module_<i> -> EnrichmentResult; queries without any hit map to an empty result.

gcen2.annotation.annotate_kegg(network_or_modules: Network | ModuleSet, k2ko: str | Path | KEGGMapping, assoc: str | Path | dict, pval: float = 0.05, threads: int = 2) → dict[str, EnrichmentResult][source]

KEGG pathway annotation; same query/background rules as annotate_go().

assoc maps genes to KO (K) numbers; k2ko maps K numbers to pathways. A dict assoc is taken as gene -> pathways directly.

gcen2.annotation.annotate_to_dir(network_or_modules: Network | ModuleSet, out_dir: str | Path, assoc: str | Path | dict, go: str | Path | GOOntology | None = None, kegg: str | Path | KEGGMapping | None = None, pval: float = 0.05, threads: int = 2, chunk_size: int = 500) → int[source]

Run annotate_go() (go) or annotate_kegg() (kegg) and write the results like GCEN v1 annotate, chunk by chunk.

Writes <gene>.go / module_<i>.go (.kegg for KEGG) for every query with significant terms, plus module_<i>.txt with the module’s genes in module mode. Each file has the same content as result.results.to_csv(path, sep=" ", index=False) of the corresponding in-memory result, but results are written as each chunk of chunk_size queries is finished, so memory does not grow with the number of results. Returns the number of annotation files written.

gcen2.annotation.enrich(query_genes: list[str], background_genes: list[str], ontology: GOOntology | None, assoc: dict[str, set[str]], pval: float = 0.05) → EnrichmentResult[source]

Enrichment of a gene list against a background list (GCEN v1 enrich).

As in v1, only genes present in the association are counted, both in the query (study_n) and in the background (pop_n).

gcen2.annotation.build_annotation_queries(network_or_modules: Network | ModuleSet, gene_terms: dict[str, set[str]]) → tuple[dict[str, set[str]], set[str]][source]

Query gene sets and background, following GCEN v1 annotate.

Network (load_network in v1 enrich.hpp): for every edge between an unannotated gene u and an annotated gene a (annotated = listed in the association), a joins the query of u and the background. Edges between two annotated or two unannotated genes are ignored, so only unannotated genes are annotated.

Modules (load_module): each module (all its genes) is a query and the background is the union of all module genes.

A NetworkAdjacency gives the same queries and background as the Network it was read from.

gcen2.rwr

Random Walk with Restart for gene function prediction.

Random Walk with Restart (RWR) for gene function prediction.

gcen2.rwr.predict(network: Network, seed_genes: list[str], gamma: float = 0.5, prob_cutoff: float = 0.01, directed: bool = False, weighted_network: bool = False, weighted_genes: bool = False, gene_weights: dict[str, float] | None = None, max_iter: int = 1000000, tol: float = 1e-10) → RWRResult[source]

Predict gene function using Random Walk with Restart.

Parameters:
  • network – Input co-expression network.

  • seed_genes – List of known gene identifiers to use as seeds.

  • gamma – Restart probability (0 < gamma < 1).

  • prob_cutoff – Minimum probability to include a gene in results.

  • directed – If True, treat the network as directed.

  • weighted_network – If True, use correlation values as edge weights.

  • weighted_genes – If True, use gene_weights as seed weights; otherwise uniform.

  • gene_weights – Optional mapping of gene → weight when weighted_genes=True.

  • max_iter – Maximum iteration count.

  • tol – Convergence tolerance (L1 norm).

gcen2.rwr.predict_from_file(path, seed_genes: list[str], gamma: float = 0.5, prob_cutoff: float = 0.01, max_iter: int = 1000000, tol: float = 1e-10) → tuple[list[str], ndarray][source]

RWR on an edge-list file without pandas or scipy (used by gcen2 rwr).

Same result as predict(read_network(path), seed_genes, gamma, prob_cutoff).ranked_genes (undirected, unweighted), returned as (genes, probabilities) in the same order. The C++ extension reads the file and builds the adjacency (parallel edges counted, as in Network.sparse_adjacency()); without it this falls back to predict().

gcen2.single_cell

Single-cell analysis utilities.

Single-cell analysis functions: pseudo-bulk aggregation and cell-type networks.

gcen2.single_cell.core.pseudobulk(adata: Any, groupby: str, layer: str | None = None, method: str = 'sum', min_cells: int = 10) → DataFrame[source]

Aggregate single-cell data into pseudo-bulk samples.

Parameters:
  • adata – AnnData object with cells as rows and genes as columns.

  • groupby – Key in adata.obs to group cells by (e.g., cell type or cluster).

  • layer – Which layer to use for aggregation. Uses adata.X if None.

  • method – Aggregation method: ‘sum’ or ‘mean’.

  • min_cells – Minimum cells per group. Groups below this threshold are excluded with a warning.

Return type:

pd.DataFrame with genes as rows and pseudo-bulk samples as columns.

gcen2.single_cell.core.build_by_celltype(adata: Any, celltype_key: str, use_highly_variable: bool = False, min_cells: int = 10, strategy: str = 'metacell', k: int = 25, max_shared: int | None = None, max_metacells: int = 1000, use_rep: str | None = None, n_pcs: int = 30, layer: str | None = None, normalize: bool | None = None, pseudo_replicates: int = 10, seed: int = 42, max_genes_per_chunk: int | None = None, effective: str = 'overlap', fdr: bool = True, **build_kwargs) → dict[str, Network][source]

Build cell-type-specific co-expression networks.

Parameters:
  • adata – AnnData object.

  • celltype_key – Key in adata.obs identifying cell types.

  • use_highly_variable – If True, subset to highly variable genes before building networks.

  • min_cells – Minimum cells per cell type (for metacells, at least k).

  • strategy –

    How cells become correlation samples:

    • metacell (default): kNN metacells within each cell type (see gcen2.single_cell.metacells(); k, max_shared, max_metacells, use_rep, n_pcs), each a mean of k similar cells, so the samples follow the cell states.

    • pseudo_replicates (deprecated, kept for compatibility with GCEN v1; warns): cells randomly split into pseudo_replicates groups whose sums are the samples. Random groups have the same expected composition, so their sums estimate the cell-level correlations from a few samples: on PBMCs, 10 groups ranked gene pairs at chance level, and their edges were about the number expected by chance (benchmarks/hdwgcna_pbmc).

  • layer – Expression from adata.layers[layer] instead of X.

  • normalize – Metacells only: log-normalise each metacell (see gcen2.single_cell.metacells(); default: for integer counts).

  • seed – Random seed (metacell centres or the random split).

  • effective – Metacells only: the sample size of the p-values. overlap (default): per gene pair, from the metacells’ shared cells (see metacell_effective_samples()); cells: n_cells // k for every pair (GCEN2 before 2026-11-18).

  • fdr – Benjamini-Hochberg FDR over all gene pairs, the pval cutoff applying to it (default; gcen2 celltype --no-fdr turns it off). Unlike gcen2.network.build(), whose default is off: with calibrated p-values, pval alone keeps about pval x 30-40 million gene pairs of a cell type as chance edges, which dominate the networks and modules of small cell types (GCEN2 before 2026-11-18: off).

  • max_genes_per_chunk – Not used (kept for compatibility): the correlation kernel works through the gene pairs in blocks itself, and splitting the genes would have adjusted the FDR within each block instead of over all gene pairs.

  • **build_kwargs – Additional keyword arguments passed to gcen2.network.build().

Returns:

  • dict mapping cell type name → Network. metadata holds

  • cell_type, n_cells, n_samples, strategy (and k and

  • p_value_samples for metacells).

  • Metacells overlap and each averages k cells, so they are far fewer

  • independent samples than their number (p-values (and FDR) of metacell)

  • networks are computed on an effective sample size, and the pval /

  • fdr cutoffs apply to those. Counted on all metacells they would be

  • far too small (on simulated data, thousands of spurious edges between

  • module genes and unrelated genes). The effective size depends on the

  • gene (a gene that varies smoothly over overlapping metacells has fewer)

  • independent values than a noisy one (metacell_effective_samples();

  • metadata["gene_effective_samples"], and p_value_samples their

  • median).

gcen2.single_cell.core.build_dropout_aware(expr: Any, method: str = 'pearson', zero_handling: str = 'both_nonzero', **build_kwargs) → Network[source]

Build a co-expression network with dropout-aware correlation.

Parameters:
  • expr – Expression matrix (genes × samples DataFrame) or AnnData (any input of gcen2.network.build(); layer / use_highly_variable go in build_kwargs).

  • method – Correlation method; the two zero-masking modes support pearson only (the ranks would change with every pair’s cell subset), so log-transform the data first (e.g. log="log2").

  • zero_handling – ‘both_nonzero’: per gene pair, Pearson over the cells where both genes are non-zero, zeros being treated as missing values (technical dropouts); p-value on that number of cells (method="pearson_nonzero" of gcen2.network.build(), C++). Suited to zero-inflated data; when zeros mostly reflect low expression (UMI counts), plain Pearson on metacells is better. ‘pairwise_complete’: ignore only the cells where both genes are zero (pearson_pairwise_complete). Warns: on sparse data the cells left with one gene at zero make unrelated genes look anti-correlated. ‘impute’: apply MAGIC imputation before computing correlation. Warns: imputed cells are not independent samples, so the p-values (and FDR), which count every cell, are not valid. Diffusion also makes unrelated genes correlated: on PBMCs, 12-27% of the pairs with a permuted null gene became edges (benchmarks/hdwgcna_pbmc). Use it to rank pairs at most; metacells for networks.

gcen2.single_cell.core.metacell_effective_samples(expr: Any, members: Any, k: int, method: str = 'pearson', log: str | None = None) → Series[source]

Every gene’s effective number of independent metacells.

Metacells that share cells are not independent: a gene’s metacell values are correlated wherever metacells overlap. If gene x is unrelated to gene y and to the choice of metacells, its metacell values have the covariance of the overlap, C[a, b] = |cells(a) & cells(b)| / k, and the correlation of x with y has variance s(y) / M, where s(y) = y'Cy / y'y (y centred) and M is the number of metacells. The effective sample size of the pair is then M / s(y). A gene that varies smoothly across overlapping metacells (cell-state genes) has a large s and few effective samples; a noisy one has s near 1. With even, complete coverage of the cells, a perfectly smooth gene gets n_cells / k, the former fixed value.

expr: genes x metacells (as given to gcen2.network.build(), which applies log; Spearman networks: ranks); members: the member cells of every metacell (M x k, metacells().uns). Returns a Series of M / s, between 3 and M, indexed by gene; a pair is tested on the smaller of its two genes’ values. On PBMCs these agree with the variance of correlations of permuted null genes (median 351 against 372 for the half of the genes with the smallest s, 110 against 102 for the top 1%; benchmarks/hdwgcna_pbmc).

gcen2.single_cell.core.effective_samples(network: Network) → int[source]

One number of samples for a build_by_celltype() network, for the check for too few samples and Fisher’s z test between cell types when the network has no per-gene sizes (write_celltype_networks()): n_cells // k for metacells (a gene that varies smoothly across evenly overlapping metacells has about that many independent values; the network’s own p-values use every gene’s value, metacell_effective_samples()); pseudo-replicates are disjoint and count fully.

gcen2.single_cell.core.write_celltype_networks(networks: dict[str, Network], output_dir: Any, diff: bool = False, pval: float = 0.05, threads: int = 2) → DataFrame[source]

Write build_by_celltype() networks to output_dir.

Writes <cell type>.network per cell type (names made file-safe), celltypes.tsv (cell_type, file, n_cells, n_samples, effective_samples, node_count, edge_count) and, with diff, diff/<A>__vs__<B>.tsv for every pair of cell types (gcen2.differential.compare_files(), Fisher’s z test, Spearman’s variance when both networks are Spearman networks) plus diff/summary.tsv (category counts per pair; n_a, n_b the sample sizes, for per-gene sizes their median); threads for reading and writing them.

The sample sizes of the test are those of the networks’ own p-values: for metacell networks with per-gene effective sizes (metadata["gene_effective_samples"], effective="overlap") every edge is tested on the smaller of its two genes’ sizes in each cell type (edges with fewer than 4 in either: no test, shared_stable); otherwise effective_samples() per network, and pairs of cell types with fewer than 4 are skipped with a warning. Returns the celltypes.tsv table (effective_samples: the networks’ p_value_samples, the median gene’s for per-gene sizes).

Metacells: groups of transcriptionally similar cells aggregated into one profile, the usual input of single-cell co-expression networks (hdWGCNA MetacellsByGroups, Morabito et al., Cell Rep Methods 2023).

Single cells are too sparse for stable gene-gene correlations; averaging each cell with its nearest neighbours removes most dropout noise while keeping the biological variation between cell states. Within each group (cell type, sample, …):

  1. every cell’s k nearest neighbours (itself included) are found in a reduced space (adata.obsm[use_rep], X_pca when present, else a PCA computed here);

  2. cells are visited in random order and a cell’s neighbourhood becomes a metacell unless it shares more than max_shared cells with a metacell already chosen, until max_metacells are chosen;

  3. each metacell’s expression is the mean (or sum) of its k cells, then (for counts) scaled to 10,000 and log1p transformed.

gcen2.single_cell.metacell.metacells(adata: Any, groupby: str | list[str] | None = None, k: int = 25, max_shared: int | None = None, max_metacells: int = 1000, min_cells: int = 100, use_rep: str | None = None, n_pcs: int = 30, layer: str | None = None, aggregate: str = 'mean', normalize: bool | None = None, seed: int = 42, threads: int = 1, groups: Any = None) → Any[source]

Aggregate cells into metacells, separately within each group.

Parameters:
  • adata – AnnData (cells x genes, dense or sparse).

  • groupby – adata.obs column(s) whose combinations define the groups (e.g. cell type, or ["cell_type", "sample"]); no grouping when None. Metacells never mix cells of different groups.

  • k – Cells per metacell (the cell and its k - 1 nearest neighbours).

  • max_shared – Maximum number of cells a metacell may share with another one (default min(10, k - 1); hdWGCNA uses 10 with k = 25).

  • max_metacells – Maximum metacells per group.

  • min_cells – Groups with fewer cells are skipped (with a warning).

  • use_rep – adata.obsm key of the space for the neighbours. Default: X_pca when present, else a PCA of the expression (counts are first scaled to 10,000 per cell and log1p transformed; values that are not integer counts are used as they are), on the highly variable genes when adata.var["highly_variable"] exists.

  • n_pcs – Components used (of use_rep or of the PCA computed here).

  • layer – Expression aggregated (and used for the PCA): adata.layers[layer] instead of X.

  • aggregate – mean or sum of the member cells (the same correlations).

  • normalize – Scale each metacell to 10,000 in total and log1p transform it (as hdWGCNA NormalizeMetacells), so that sequencing depth does not correlate all genes. Default (None): when the expression holds integer counts.

  • seed – Random order in which cells are tried as metacell centres.

  • threads – Threads for the neighbour search.

  • groups – Only these groups (values of a single groupby column; the PCA, if computed, then uses only their cells). The same result as subsetting adata to them first, without copying the expression.

Note

Metacells overlap and each averages k cells: correlations computed on them are fine, but p-values that count every metacell as an independent sample are far too small. build_by_celltype() computes them on every gene pair’s effective samples from the overlap of the metacells (gcen2.single_cell.metacell_effective_samples(), which takes uns["metacell_members"]); when building from metacells directly, prefer correlation cutoffs (or pval with that in mind).

Returns:

One row per metacell (dense X; log-normalised when normalize), the genes of adata. obs holds the group column(s), n_cells and the centre cell; uns["metacell_members"] the member cells’ positions in adata (one row of k per metacell).

Return type:

AnnData

Cell-type modules (the hdWGCNA workflow, gcen2 celltype-modules), differential module eigengenes and module-trait correlations, and module projection:

WGCNA-style modules per cell type from single-cell data (the hdWGCNA workflow): genes expressed in enough of the type’s cells, kNN metacells within the type, then gcen2.tom_modules.tom_modules() on the metacells (by default with hdWGCNA’s ConstructNetwork settings, HDWGCNA).

gcen2.single_cell.modules.expressed_fraction(adata: Any, cells: ndarray, layer: str | None = None) → ndarray[source]

Fraction of the given cells (boolean mask) with a value > 0, per gene (hdWGCNA SetupForWGCNA(gene_select = "fraction") per group).

gcen2.single_cell.modules.fraction_genes(X, fraction: float) → ndarray[source]

Genes (columns) with a value > 0 in at least round(fraction * n) of the n rows of X: hdWGCNA SetupForWGCNA(gene_select = "fraction") (R’s round, half to even).

gcen2.single_cell.modules.modules_by_celltype(*args, **kwargs) → dict[source]

WGCNA-style modules of each cell type, as hdWGCNA builds them: a dict cell type -> gcen2.tom_modules.TomModules of iter_modules_by_celltype() (same arguments). On an atlas, iterate over iter_modules_by_celltype() instead and keep only what is needed: every result holds its genes x metacells matrix.

gcen2.single_cell.modules.iter_modules_by_celltype(adata: Any, celltype_key: str, groups=None, fraction: float = 0.05, use_highly_variable: bool = False, k: int = 25, max_shared: int | None = None, max_metacells: int = 1000, min_cells: int = 100, use_rep: str | None = None, n_pcs: int = 30, layer: str | None = None, normalize: bool | None = None, seed: int = 42, threads: int = 2, preset: str = 'hdwgcna', cell_level: bool = True, reassign: bool = True, consensus_by: str | None = None, harmonize_by: str | None = None, npcs: int = 50, harmony_kwargs: dict | None = None, dme_by: str | None = None, traits=None, trait_groupby: str | None = None, **tom_kwargs)[source]

WGCNA-style modules of each cell type, as hdWGCNA builds them; yields (cell type, TomModules) one cell type at a time.

For each cell type (groups: only these) with at least max(min_cells, k) cells: the genes with a value > 0 in at least round(fraction * n) of its n cells (fraction_genes(); and in adata.var["highly_variable"] with use_highly_variable), metacells of its cells (gcen2.single_cell.metacells(): k, max_shared, max_metacells, use_rep, n_pcs, layer, normalize, seed; computed on all genes, so the neighbour space does not depend on the gene selection), and gcen2.tom_modules.tom_modules() on the genes x metacells matrix with the preset options ("hdwgcna": gcen2.tom_modules.HDWGCNA; "wgcna": blockwiseModules defaults) updated by tom_kwargs (power, min_size, …).

Metacell members are chosen for all cell types first (cheap; one random generator, so the result does not depend on how the output is consumed), their profiles only when the cell type is reached, so memory holds one cell type’s metacells at a time.

Each gcen2.tom_modules.TomModules has a metadata with cell_type, n_cells, n_metacells, n_genes and the metacell matrix ("metacells", genes x metacells DataFrame). The result’s own eigengenes and kME are those of the metacells. With cell_level (default), as hdWGCNA’s ModuleEigengenes and ModuleConnectivity, the eigengenes and kME on the type’s single cells (cell_eigengenes()) are in metadata["cell_eigengenes"] (cells x ME<k>) and metadata["cell_kme"] (genes x kME<k>); with reassign (default; at least two modules) genes with a negative cell kME for their module move to the module of their largest one (hdWGCNA ReassignModules; metadata["reassigned"] lists them). Eigengenes are not recomputed afterwards (nor are they in hdWGCNA).

consensus_by (an adata.obs column, e.g. sample or study): hdWGCNA’s consensus network (MetacellsByGroups(group.by = c(type, consensus_by)), SetMultiExpr, TestSoftPowersConsensus, ConstructNetwork(consensus = TRUE)): metacells within each cell type and value of the column, and gcen2.consensus.consensus_tom_modules() over the values (the sets, in sorted order, the first being the calibration reference; values with no metacell of the type left out) with the preset options ("hdwgcna": gcen2.consensus.HDWGCNA_CONSENSUS). metadata then also has sets, set_powers and set_eigengenes (the metacells of each set).

harmonize_by (an adata.obs column; needs cell_level): hdWGCNA’s harmonized eigengenes (ModuleEigengenes(group.by.vars = ...); cell_eigengenes() with npcs, seed and harmony_kwargs) in metadata["cell_harmonized_eigengenes"]; the cell kME and the reassignment then use them, as ModuleConnectivity does.

dme_by (an adata.obs column; needs cell_level): hdWGCNA’s FindAllDMEs within each type (each value against the type’s other cells; gcen2.single_cell.find_all_dmes()) in metadata["dmes"]. traits (adata.obs columns; needs cell_level): hdWGCNA’s ModuleTraitCorrelation on the type’s cells, for all of them and per value of trait_groupby (gcen2.single_cell.module_trait_cor()) in metadata["trait_cor"]. Both use the harmonized eigengenes when there are any, as hdWGCNA does. Cell types that are too small or yield no TOM are skipped with a warning.

gcen2.single_cell.modules.cell_eigengenes(X, gene_idx, labels, levels, normalize: bool = True, scale: float = 10000.0, batches=None, npcs: int = 50, seed: int = 0, harmony_kwargs: dict | None = None)[source]

Module eigengenes and kME on single cells, as hdWGCNA’s ModuleEigengenes and ModuleConnectivity compute them.

X: cells x all genes (counts, sparse or dense); gene_idx: the columns of the module genes; labels: their module (0 = unassigned); levels: the modules (> 0). With normalize, Seurat LogNormalize first (library size over all genes); else X is used as it is. Eigengenes: per module, ScaleData (clipped at 10) and the first principal component score, signed by the average expression (gcen2.spatial.module_eigengene_scores(), the spatial code). kME: Pearson correlation of every gene in gene_idx with every eigengene, computed on the sparse matrix (as hdWGCNA’s corSparse), so a large cell type needs no dense cells x genes matrix. Returns (cells x levels, genes x levels).

With batches (one label per cell, or a list of such vectors), also hdWGCNA’s harmonized eigengenes (ModuleEigengenes(group.by.vars = ...)): per module, Harmony (gcen2.harmony.harmony_integrate(), seed and harmony_kwargs) on the module’s first min(npcs, genes - 1) principal components (Seurat RunPCA), and the first corrected component, signed as the eigengene. The kME is then computed against the harmonized eigengenes, as hdWGCNA’s ModuleConnectivity does when they exist. Returns (eigengenes, kME, harmonized eigengenes).

gcen2.single_cell.modules.write_celltype_modules(results: dict, output_dir: Any, n_hubs: int = 10, write_metacells: bool = False, write_tom: bool = False, threads: int = 2)[source]

Write modules_by_celltype() results (a dict, or the pairs of iter_modules_by_celltype(), written and released one at a time): per cell type a directory <cell type>/ (name made file-safe) with modules.tsv, eigengenes.tsv, kme.tsv and hub_genes.tsv (as gcen2 module -e writes them: gcen2.tom_modules.write_module_files(); eigengenes and kME of the metacells), cell_eigengenes.tsv and cell_kme.tsv (on the single cells, if computed; also cell_harmonized_eigengenes.tsv, dmes.tsv, trait_cor.tsv, sets.tsv and set_eigengenes.tsv when computed) metacell_members.tsv (metacell, cell, center: the cells averaged in each metacell, its centre cell first; gcen2 plot metacells) and, with write_metacells, metacells.tsv (genes x metacells, the input of gcen2 module -e); and celltypes.tsv (cell_type, dir, n_cells, n_metacells, n_genes, power, modules, genes_in_modules, reassigned). Returns that table.

Differential module eigengenes and module-trait correlations on single cells, as hdWGCNA’s FindDMEs / FindAllDMEs and ModuleTraitCorrelation compute them from the cell eigengenes (harmonized ones when there are any).

find_dmes: Seurat FindMarkers on the eigengenes clipped at 0 (as hdWGCNA does) with its defaults there (test.use = "wilcox", logfc.threshold = 0, min.pct = 0, pseudocount.use = 0): R’s wilcox.test p-value (exact for fewer than 50 cells per group without ties, else the normal approximation with tie and continuity corrections), avg_log2FC = log2 of the ratio of the group means of expm1(eigengene), pct.1 / pct.2 the fractions of cells above 0 (3 decimals), sorted by p-value and then by |pct.1 - pct.2| (descending), p_val_adj Bonferroni over all modules.

module_trait_cor: Pearson (or Spearman) correlation of every trait with every eigengene on the pairwise complete cells (Hmisc::rcorr), its Student t p-value, and Benjamini-Hochberg FDR over the traits x modules table, for all cells and for each group with at least 5 cells. Categorical traits become their level number (1, 2, …), as hdWGCNA’s as.numeric(factor).

gcen2.single_cell.dme.find_dmes(eigengenes, cells1, cells2, only_pos: bool = False, logfc_threshold: float = 0.0, min_pct: float = 0.0, pseudocount: float = 0.0) → DataFrame[source]

hdWGCNA FindDMEs: modules whose eigengene differs between the cells cells1 and cells2 (names in the index of eigengenes, a cells x modules DataFrame). Returns a table (index: module) with p_val, avg_log2FC, pct.1, pct.2, p_val_adj and module.

gcen2.single_cell.dme.find_all_dmes(eigengenes, groups, **kwargs) → DataFrame[source]

hdWGCNA FindAllDMEs: find_dmes() of the cells of each group against all other cells (groups: one label per row of eigengenes, or a Series indexed by cell), groups in order of first appearance. One table with a group column; groups with fewer than 3 cells (or fewer than 3 others) are skipped with a warning.

gcen2.single_cell.dme.module_trait_cor(eigengenes, traits, groups=None, method: str = 'pearson', min_cells: int = 5) → DataFrame[source]

hdWGCNA ModuleTraitCorrelation: correlation of every trait (columns of traits, rows matched to the cells of eigengenes by name) with every module eigengene, its p-value and the FDR, for all cells (group all_cells) and, with groups (one label per cell or a Series indexed by cell), for each group with at least min_cells cells (groups in sorted order). Returns a long table group, trait, module, cor, p, fdr, n.

Projecting modules onto another data set (hdWGCNA ProjectModules).

project_modules(): the eigengenes of reference modules on the cells of a query data set, as hdWGCNA computes them: modules with fewer than min_overlap (0.5) of their genes in the query are left out; the others keep their genes found in the query; then ModuleEigengenes on the query cells (Seurat LogNormalize, ScaleData of the module’s genes, first principal component signed by the average expression; gcen2.single_cell.cell_eigengenes()), optionally harmonized (group.by.vars).

gcen2.single_cell.projection.project_modules(adata: Any, modules, min_overlap: float = 0.5, layer: str | None = None, normalize: bool | None = None, cells=None, batches=None, harmonize_by: str | None = None, npcs: int = 50, seed: int = 0, include_unassigned: bool = False, **harmony_kwargs)[source]

Eigengenes of reference modules on the cells of adata (the query), as hdWGCNA’s ProjectModules.

modules: gene -> module (a Series or dict, a table with gene and module columns such as modules.tsv of GCEN2 or hdWGCNA’s GetModules, or a gcen2.tom_modules.TomModules); modules named “grey” (hdWGCNA’s unassigned genes) are skipped unless include_unassigned (hdWGCNA projects them too). cells: only these query cells (a boolean mask or names). batches (one label per cell) or harmonize_by (an obs column): also the harmonized eigengenes.

Returns (eigengenes, harmonized, table): cells x modules DataFrames (harmonized None without batches) and a table module, genes, genes_found, projected.

gcen2.spatial

Spatial transcriptomics: spatial modules (the hdWGCNA spatial workflow, gcen2 spatial-modules), networks with spatial information (gcen2 spatial-build) and Moran’s I.

WGCNA-style modules from spatial data, as hdWGCNA builds them: metaspots (each centre spot summed with its neighbours, within groups such as regions or clusters), log-normalized (NormalizeMetacells), then gcen2.tom_modules.tom_modules() on all metaspots (by default with hdWGCNA’s ConstructNetwork settings) and module eigengenes of the original spots (ModuleEigengenes).

Metaspots come from the Visium grid (hdWGCNA MetaspotsByGroups) or, for platforms without one (Slide-seq, Visium HD, Stereo-seq, imaging-based single-cell data), from the k nearest neighbours in physical coordinates (method="knn").

gcen2.spatial.modules.metaspots(adata: Any, groupby: str | None = None, row_key: str = 'array_row', col_key: str = 'array_col', min_spots: int = 50, layer: str | None = None, mode: str = 'sum', method: str = 'auto', spatial_key: str = 'spatial', k: int = 7, max_shared: int | None = None, seed: int = 42, threads: int = 1)[source]

Metaspots within each group of groupby (sorted; all spots if None) with at least min_spots spots, each centre aggregated (mode “sum” or “average”) with its neighbours. Needs counts (layer or X).

method="grid" is hdWGCNA MetaspotsByGroups: every 4th grid column and the rows of matching parity give the centre spots, and each centre is aggregated with its nearest grid neighbours and the spots two columns away in its row (the six neighbours of a Visium hexagon). Needs the Visium array coordinates in obs (row_key, col_key).

method="knn" needs only coordinates (obsm[spatial_key], any unit) and so works without a grid: each centre with its k - 1 nearest spots of the same group (k=7: a centre and its ring, the size of a Visium hexagon); centres are tried in random order (seed) and kept when they share at most max_shared spots with every metaspot kept so far (default round(2 * k / 7): 2 for k = 7, the overlap of neighbouring grid metaspots). Units much smaller than a Visium spot (Slide-seq beads, Visium HD bins, single cells) need a larger k for a comparable number of counts per metaspot: about 100 Slide-seq beads (10 um) cover the tissue a Visium metaspot captures.

method="auto" uses the grid when obs has integer row_key / col_key columns on a hexagonal (Visium) grid, i.e. row + col of one parity, else knn (also for the square grid of Visium HD bins).

Returns an AnnData (metaspots x genes; obs: the centre’s obs and n_spots; index: the centre barcode) with the member spot indices in uns["metaspot_members"] and the method in uns["metaspot_params"].

gcen2.spatial.modules.log_normalize(X, columns=None, scale: float = 10000.0) → ndarray[source]

Seurat LogNormalize of the rows of X (log1p of counts per scale counts of the row, all columns), dense, of the given columns only.

gcen2.spatial.modules.spot_eigengenes(data: ndarray, labels: ndarray, levels) → ndarray[source]

hdWGCNA ModuleEigengenes on spots: for each module the genes of data (spots x genes, log-normalized) are scaled (Seurat ScaleData: z-scores, clipped above at 10) and the eigengene is the score on the first principal component of that matrix (Seurat RunPCA: no re-centring), signed to correlate positively with the module’s average (unscaled) expression. Returns spots x modules.

gcen2.spatial.modules.module_pc_scores(x: ndarray, npcs: int = 50) → ndarray[source]

Seurat RunPCA of one module as hdWGCNA’s ModuleEigengenes runs it: the rows of x (rows x the module’s genes, log-normalized) scaled as module_eigengene_scores() does, then the scores (u * d) on the first min(npcs, genes - 1) principal components, PC1 signed as the eigengene. Rows x components.

gcen2.spatial.modules.module_eigengene_scores(x: ndarray) → ndarray[source]

The eigengene of one module on the rows of x (rows x the module’s genes, log-normalized): Seurat ScaleData (z-scores with the n - 1 SD, clipped above at 10), the first principal component score without re-centring, signed to correlate positively with the rows’ average. Computed in column-major order whatever the input layout (the BLAS products round differently by layout), so the result does not depend on how the caller built x. The first column of module_pc_scores().

gcen2.spatial.modules.spatial_modules(adata: Any, groupby: str | None = None, fraction: float = 0.05, use_highly_variable: bool = False, genes=None, min_spots: int = 50, mode: str = 'sum', row_key: str = 'array_row', col_key: str = 'array_col', layer: str | None = None, threads: int = 2, preset: str = 'hdwgcna', spot_level: bool = True, reassign: bool = True, method: str = 'auto', spatial_key: str = 'spatial', k: int = 7, max_shared: int | None = None, seed: int = 42, **tom_kwargs)[source]

WGCNA-style modules of a spatial sample as hdWGCNA builds them.

Genes: those with counts in at least round(fraction * n) of the n spots (gcen2.single_cell.modules.fraction_genes(); and in adata.var["highly_variable"] with use_highly_variable), or the list genes. Metaspots within each groupby group (metaspots(): the Visium grid, or the k nearest spots in obsm[spatial_key] for data without a grid; method, max_shared and seed as there), log-normalized; then gcen2.tom_modules.tom_modules() on the genes x metaspots matrix of all groups with the preset options ("hdwgcna": gcen2.tom_modules.HDWGCNA; "wgcna": blockwiseModules defaults) updated by tom_kwargs. Eigengenes and kME of the result are those of the metaspots; with spot_level the eigengene of every module on every spot (spot_eigengenes(), hdWGCNA ModuleEigengenes) is in metadata["spot_eigengenes"] (spots x ME<k> DataFrame), for spatial maps, and the Pearson correlation of every gene with them on the spots (hdWGCNA ModuleConnectivity) in metadata["spot_kme"] (genes x kME<k>); with reassign (and at least two modules), as ModuleConnectivity, genes with a negative spot kME for their module move to the module of their largest spot kME (reassign_negative_kme(); metadata["reassigned"] lists the genes considered). Eigengenes are not recomputed afterwards (nor are they in hdWGCNA).

metadata also holds n_spots, n_metaspots, n_genes, groups and metaspots (genes x metaspots DataFrame, the gcen2 module -e input).

gcen2.spatial.modules.reassign_negative_kme(labels: ndarray, kme: ndarray, levels)[source]

hdWGCNA ReassignModules (run by ModuleConnectivity): a gene of module k (> 0) whose kME for k is negative moves to the module with its largest kME (the first on ties), or to 0 (unassigned) if all its kMEs are negative. kme: genes x levels. Returns the new labels and the indices of the genes considered (kME < 0 for their module).

gcen2.spatial.modules.group_trait_cor(spot_me, groups)[source]

Correlation of every spot-level eigengene with each group indicator (spot in the group: 1, else 0), as TomModules.trait_cor(): a long table module, trait, cor, p, n.

gcen2.spatial.modules.write_spatial_modules(res, output_dir: Any, groups=None, n_hubs: int = 10, write_metaspots: bool = False, write_tom: bool = False, threads: int = 2)[source]

Write spatial_modules() results to output_dir: as gcen2 module -e (gcen2.tom_modules.write_module_files()) modules.tsv, eigengenes.tsv (metaspots), kme.tsv and hub_genes.tsv; spot_eigengenes.tsv (spots x ME0..ME<K-1>) and spot_kme.tsv (gene, module, kME0..: hdWGCNA’s kME), if computed; with groups (one label per spot, e.g. the groupby column) group_cor.tsv, their correlations (group_trait_cor(), the --trait-cor format of gcen2 report); with write_metaspots metaspots.tsv (genes x metaspots); and summary.tsv. Returns the summary as a dict.

Spatial co-expression network analysis: three build methods.

gcen2.spatial.core.spatial_autocorrelation(adata: Any, *, layer: str | None = None, fraction: float = 0.05, normalize: bool | None = None, n_neighbors: int | None = None, radius: float | None = None, smoothed: bool = False, bandwidth: float | None = None) → DataFrame[source]

Moran’s I of every gene (the genes and neighbour graph of build_spatial_filtered()): a table gene, morans_i, pval (one-sided test for positive autocorrelation under randomisation), fdr (Benjamini-Hochberg over the genes), mean and detected (fraction of spots with a value > 0); with smoothed, also morans_i_smoothed, the I of the expression smoothed as in build_spatial_weighted(). Rows in decreasing morans_i.

gcen2.spatial.core.build_spatial_filtered(adata: Any, *, layer: str | None = None, fraction: float = 0.05, normalize: bool | None = None, n_neighbors: int | None = None, radius: float | None = None, cor_cutoff: float = 0.6, p_cutoff: float = 0.05, moran_fdr: float = 0.05, **build_kwargs) → Network[source]

Build a co-expression network filtered by spatial autocorrelation.

Constructs a standard co-expression network, then keeps the edges between genes with significant positive spatial autocorrelation: Moran’s I > 0 and a Benjamini-Hochberg FDR <= moran_fdr of its one-sided test (moments under randomisation, Cliff and Ord 1981). moran_fdr=1: only I > 0, which is not a test (on a DLPFC section 82% of the genes, and 69% of genes permuted across spots of similar depth, have I > 0).

Parameters:
  • adata (AnnData with obsm['spatial'] coordinates.)

  • layer (Expression layer to use (adata.X if None).)

  • fraction (Only genes with a value > 0 in at least) – round(fraction * n_spots) spots (hdWGCNA’s gene selection; 0: all genes).

  • normalize (Log-normalize (Seurat LogNormalize); None: when the data are) – raw counts.

  • n_neighbors (KNN neighbours. Mutually exclusive with radius.)

  • radius (Radius cutoff. Mutually exclusive with n_neighbors.)

  • cor_cutoff (Minimum absolute correlation for an edge.)

  • p_cutoff (Maximum p-value for correlation significance (passed to network.build).)

  • moran_fdr (Maximum FDR of a gene's Moran's I test (see above).)

  • **build_kwargs (Additional keyword arguments forwarded to) – gcen2.network.build (e.g. method, signed).

Return type:

Network with spatially unsupported edges removed.

gcen2.spatial.core.build_spatial_weighted(adata: Any, *, layer: str | None = None, fraction: float = 0.05, normalize: bool | None = None, n_neighbors: int | None = None, radius: float | None = None, bandwidth: float | None = None, cor_cutoff: float = 0.6, p_cutoff: float = 0.05, **build_kwargs) → Network[source]

Build a co-expression network using spatially smoothed expression.

Smooths the expression matrix by replacing each spot’s expression with a Gaussian-weighted average of its spatial neighbours (including itself). The smoothed matrix is then used for standard co-expression network construction, which reduces dropout noise while preserving spatial signal.

Parameters:
  • adata (AnnData with obsm['spatial'] coordinates.)

  • layer (Expression layer to use (adata.X if None).)

  • fraction (Only genes with a value > 0 in at least) – round(fraction * n_spots) spots (hdWGCNA’s gene selection; 0: all genes).

  • normalize (Log-normalize (Seurat LogNormalize); None: when the data are) – raw counts.

  • n_neighbors (KNN neighbours. Mutually exclusive with radius.)

  • radius (Radius cutoff. Mutually exclusive with n_neighbors.)

  • bandwidth (Gaussian kernel bandwidth (in coordinate units). Auto-estimated) – from the median neighbour distance when None.

  • cor_cutoff (Minimum absolute correlation for an edge.)

  • p_cutoff (Maximum p-value for an edge.)

Return type:

Network built on spatially smoothed expression values.

gcen2.spatial.core.build_spatial_regions(adata: Any, *, region_key: str | None = None, n_regions: int = 5, layer: str | None = None, fraction: float = 0.05, normalize: bool | None = None, n_neighbors: int | None = None, radius: float | None = None, **build_kwargs) → dict[str, Network][source]

Build one co-expression network per spatial region.

Partitions spots into regions (manual annotation or automatic KMeans clustering on spatial coordinates), then builds a separate co-expression network for each region.

Parameters:
  • adata (AnnData with obsm['spatial'] coordinates.)

  • region_key (Column in adata.obs to use as region labels. If None,) – performs automatic KMeans clustering into n_regions clusters.

  • n_regions (Number of clusters for automatic partitioning (used only) – when region_key is None).

  • layer (Expression layer to use (adata.X if None).)

  • fraction (Only genes with a value > 0 in at least) – round(fraction * n_spots) spots (hdWGCNA’s gene selection; 0: all genes).

  • normalize (Log-normalize (Seurat LogNormalize); None: when the data are) – raw counts.

  • n_neighbors (Not used: accepted so that the three spatial build) – functions take the same arguments (the regions are not a neighbour graph).

  • radius (Not used: accepted so that the three spatial build) – functions take the same arguments (the regions are not a neighbour graph).

  • **build_kwargs (Forwarded to gcen2.network.build (e.g. cor, pval).)

Returns:

  • dict mapping region name → Network. Regions with fewer than 3 spots

  • are skipped with a UserWarning.

Spatial neighbor graph construction (KNN or radius-based).

gcen2.spatial.neighbors.build_neighbor_graph(coords: ndarray, n_neighbors: int | None = None, radius: float | None = None) → csr_matrix[source]

Build a Gaussian-weighted spatial neighbor graph.

Parameters:
  • coords – Array of shape (n_spots, 2) with 2-D spatial coordinates.

  • n_neighbors – Number of nearest neighbors (KNN mode). Mutually exclusive with radius.

  • radius – Distance cutoff (radius mode). Mutually exclusive with n_neighbors.

Returns:

  • scipy.sparse.csr_matrix of shape (n_spots, n_spots) with Gaussian

  • edge weights exp(-d² / (2σ²)), where σ = median neighbor distance.

gcen2.plot

Publication figures for every analysis (one style, journal widths, editable vector text).

Publication figures for every GCEN2 analysis.

All plots share one style (gcen2.plot._style): journal widths (size="single" 89 mm, "onehalf" 120 mm, "double" 183 mm), 5-7 pt sans-serif text kept editable in PDF / SVG, and one colour per module in every figure (WGCNA’s standardColors by default; set_defaults(palette= "okabe-ito")). Each function takes GCEN2 result files or the objects themselves, draws on a new figure (or the given ax), saves it when output is given (a stem: PDF, PNG and SVG; or one file by its extension) and returns the figure.

The figures are also available from the command line (gcen2 plot ...) and in the HTML / PDF report.

gcen2.plot.celltype_networks(directory, size='double', height=None, output=None, formats=None)[source]

Networks of gcen2 celltype: edges and genes per cell type, and the overlap of their edge sets (Jaccard index) between cell types.

gcen2.plot.degree_distribution(network, size='double', height=None, output=None, formats=None)[source]

Degree distribution of a network: histogram of node degrees and the scale-free plot (log10 p(k) against log10 k with the fitted line, R^2 and slope; WGCNA scaleFreePlot). network: an edge-list file (read by the C++ core), a Network, or the degrees.

gcen2.plot.diff_network(diff, top: int = 60, alpha: float = 0.05, seed: int = 0, size='single', height=None, output=None, formats=None)[source]

The top edges with the largest |change| among significant shared edges and one-condition edges: edge colour = gained in B (blue) or lost (orange), width = |change|.

gcen2.plot.diff_overview(diff, alpha: float = 0.05, size='double', height=None, output=None, formats=None)[source]

gcen2 diff at a glance: edges per category, correlation in A against B (point density; edges of one condition only on the axes), and for the shared edges the change in correlation against -log10 p.

gcen2.plot.edge_weights(network, column: str = 'correlation', size='single', height=None, output=None, formats=None)[source]

Distribution of the edge weights (correlations, or another column such as the TOM or a fused score).

gcen2.plot.enrich_bar(table, top: int = 15, size='single', height=None, output=None, formats=None)[source]

The top terms of an enrichment result (gcen2 enrich / one gcen2 annotate file) by p-value: bars of -log10 p, coloured by GO namespace, with the number of genes.

gcen2.plot.enrich_dot(results, modules=None, top: int = 3, max_modules: int = 12, size='double', height=None, output=None, formats=None)[source]

The top terms of each module (hdWGCNA EnrichrDotPlot): a dot per module and term, size = genes in the term, colour = -log10 p (or of the table’s adjusted p-value column, e.g. fdr); modules in their colours along the axis. results: a gcen2 annotate output directory or a dict module -> table.

gcen2.plot.enrich_heatmap(results, top: int = 2, max_modules: int = 12, size='double', height=None, output=None, formats=None)[source]

Modules x terms heatmap of -log10 p (the union of each module’s top terms), to compare modules’ functions at a glance; the colour scale stops at the 95th percentile so that a few extreme p-values do not hide the rest (marked by the arrow on the colour bar).

gcen2.plot.expression_distribution(expr, normalized=None, log: bool = True, max_samples: int = 60, size='double', height=None, output=None, formats=None)[source]

Per-sample expression distributions as boxes (log10(x + 1) with log), and, with normalized, the same after normalization next to them (gcen2 normalize input and output). At most max_samples samples are shown (evenly spaced).

gcen2.plot.extract_overview(network, genes, top: int = 20, size='single', height=None, output=None, formats=None)[source]

The query genes of gcen2 extract: how many are in the network (a Venn diagram of the query genes and the network’s genes), and the degree of the best-connected ones, split into edges to other query genes and to the rest of the network. network: the full network or the extracted subnetwork (it holds every edge of a query gene).

gcen2.plot.fusion_overview(fused, size='double', height=None, output=None, formats=None)[source]

A fused network: edges supported by 1, 2, … layers, edges per layer and the overlap of every pair of layers, and the fused score distribution.

gcen2.plot.mean_variance(expr, kept=None, log: bool = True, size='single', height=None, output=None, formats=None)[source]

Mean against coefficient of variation of every gene (density of points), the genes kept by gcen2 filter (kept: its output or a gene list) in colour.

gcen2.plot.merge_overlap(networks, merged=None, names=None, top: int = 15, size='single', height=None, output=None, formats=None)[source]

Edges shared by the input networks of gcen2 merge: a Venn diagram for 2 or 3 networks (areas not to scale), an UpSet-style bar chart for more; with merged (the merge output), how many edges of each region pass the cutoff on the summed correlation.

gcen2.plot.metacells(members, coords, basis: str = 'X_umap', n_cells=None, size='double', height=None, output=None, formats=None)[source]

Metacells on the cell embedding (hdWGCNA DimPlotMetacells): every cell in grey, each metacell at the mean position of its cells, coloured by cell type; and per cell type the number of metacells and the share of its cells that are in at least one. members: metacell_members.tsv (or a celltype-modules output directory, all cell types); coords as in me_embedding(); n_cells: cells per type (default: from celltypes.tsv of the directory, else not shown).

gcen2.plot.module_size_hist(modules, size='single', height=None, output=None, formats=None)[source]

Sizes of many modules (e.g. Jaccard modules of gcen2 module -i): histogram on a log scale, with the number of modules and genes.

gcen2.plot.moran(table, n_label: int = 8, size='double', height=None, output=None, formats=None)[source]

Spatial autocorrelation of the genes (spatial-build --moran): the distribution of Moran’s I (filtered mode keeps the edges between genes with I > 0), I against mean expression with the most autocorrelated genes named, and, for weighted mode, I before and after the spatial smoothing.

gcen2.plot.network_view(network, genes=None, modules=None, max_nodes: int = 150, weight: str = 'correlation', n_label: int = 12, k_strongest: int = 5, seed: int = 0, size='single', height=None, output=None, formats=None)[source]

A drawing of (part of) a network: the given genes (or the max_nodes best-connected genes) with, for each gene, its k_strongest edges (so dense modules show their structure rather than a solid ball), force-directed layout (networkx), node size by degree, colours by module (modules: modules.tsv), the n_label highest-degree genes named.

gcen2.plot.null_distribution(network, shuffled, metric: str = 'clustering_coefficient', size='single', height=None, output=None, formats=None)[source]

A network statistic (default the clustering coefficient) of the real network against its degree-preserving shuffles (gcen2 shuffle outputs): the shuffles’ values as a histogram, the real value as a line, with the empirical p-value and z-score.

gcen2.plot.rwr_rank(table, seeds=None, top: int = 30, size='single', height=None, output=None, formats=None)[source]

The top genes by random-walk score, seeds marked: a lollipop chart (score on a log axis).

gcen2.plot.rwr_subnetwork(network, table, seeds, top: int = 20, seed: int = 0, size='single', height=None, output=None, formats=None)[source]

The seeds and the top candidates with their edges in network: candidates coloured by score, seeds as diamonds.

gcen2.plot.sample_correlation(expr, method: str = 'pearson', log: bool = True, max_samples: int = 200, size='single', height=None, output=None, formats=None)[source]

Sample-sample correlation heatmap, samples ordered by average-linkage clustering (outliers and batches show up as blocks).

gcen2.plot.trajectory_overview(directory, top: int = 25, size='double', height=None, output=None, formats=None)[source]

Networks along pseudotime: genes and edges per window against the window centre, edges per pattern (stable, gained, lost, transient, intermittent), and the degree of the top most variable genes across the windows (scaled per gene).

gcen2.plot.celltype_overview(table, size='double', height=None, output=None, formats=None)[source]

celltype-modules at a glance: per cell type the cells, metacells, genes, modules and genes in modules (celltypes.tsv), cell types from top to bottom in the order of the table (as in metacells() and the report’s sections).

gcen2.plot.dme_lollipop(dmes, modules=None, alpha: float = 0.05, ncols: int = 3, size='double', height=None, output=None, formats=None)[source]

Differential module eigengenes as a lollipop chart (hdWGCNA PlotDMEsLollipop): fold change per module from 0, dot size = module size (with modules: modules.tsv), crosses for modules not significant at alpha; one panel per group.

gcen2.plot.dme_volcano(dmes, alpha: float = 0.05, ncols: int = 3, size='double', height=None, output=None, formats=None)[source]

Differential module eigengenes (hdWGCNA PlotDMEsVolcano): log2 fold change against -log10 adjusted p-value, modules in their colours and named, one panel per group. dmes: dmes.tsv (or find_dmes / FindDMEs output).

gcen2.plot.me_dotplot(eigengenes, groups, modules=None, scale: bool = True, size='single', height=None, output=None, formats=None)[source]

Eigengenes by group (Seurat DotPlot of the eigengenes, as in the hdWGCNA tutorials): colour = mean eigengene of the group (z-scored across groups with scale), dot size = percentage of the group’s cells with an eigengene above 0. groups: one label per cell (a Series indexed by cell).

gcen2.plot.me_embedding(eigengenes, coords, basis: str = 'X_umap', modules=None, ncols: int = 4, point_size: float | None = None, quantile: float = 0.99, spatial: bool = False, flip_y: bool = True, size='double', height=None, output=None, formats=None)[source]

Eigengene of every cell on an embedding, one panel per module (hdWGCNA ModuleFeaturePlot): symmetric diverging colours around 0, clipped at the quantile of |eigengene|, high |values| drawn on top. eigengenes: cell_eigengenes.tsv (or cell_harmonized_eigengenes.tsv, spot_eigengenes.tsv, projected_eigengenes.tsv); coords: an AnnData / .h5ad (obsm[basis]), a TSV or DataFrame of x, y by cell. spatial: equal axes, y pointing down when flip_y (image coordinates).

gcen2.plot.me_radar(eigengenes, groups, modules=None, ncols: int = 4, size='double', height=None, output=None, formats=None)[source]

Each module’s mean eigengene per group on a radar chart (hdWGCNA ModuleRadarPlot), scaled to 0-1 across the groups.

gcen2.plot.me_violin(eigengenes, groups, modules=None, ncols: int = 3, size='double', height=None, output=None, formats=None)[source]

Distribution of each module’s eigengene by group (violins with the median marked), one panel per module.

gcen2.plot.preservation(z_table, observed=None, size='double', height=None, output=None, formats=None)[source]

Module preservation (hdWGCNA PlotModulePreservation, WGCNA’s preservation figure): Zsummary.pres against module size with the thresholds 2 and 10, and the median rank (with observed: preservation.tsv) against module size; modules in their colours and named, WGCNA’s gold (random) module included as reference.

gcen2.plot.preservation_lollipop(z_table, size='single', height=None, output=None, formats=None)[source]

Zsummary.pres of each module sorted (hdWGCNA PlotModulePreservationLollipop), with the thresholds 2 (moderate) and 10 (strong).

gcen2.plot.set_eigengenes(table, modules=None, ncols: int = 4, size='double', height=None, output=None, formats=None)[source]

Consensus network: each module’s eigengene in the metacells of every set (set_eigengenes.tsv), as boxes per set, to show the module is present in all sets.

gcen2.plot.spatial_me(eigengenes, coords, basis: str = 'spatial', **kwargs)[source]

Spatial maps of spot eigengenes (me_embedding() with equal axes and image coordinates; coords an AnnData with obsm["spatial"] or x, y by spot).

gcen2.plot.dendrogram(tree, show_unmerged: bool = True, size='double', height=None, output=None, formats=None)[source]

Gene dendrogram (average linkage of 1 - TOM) with the module of every gene below it, after and before merging close modules (WGCNA plotDendroAndColors / hdWGCNA PlotDendrogram). tree: dendrogram.json.

gcen2.plot.eigengene_network(eigengenes, traits=None, annotate: bool | None = None, size='single', height=None, output=None, formats=None)[source]

Eigengene network (WGCNA plotEigengeneNetworks / hdWGCNA ModuleCorrelogram): the eigengenes clustered by 1 - correlation (average linkage) above the heatmap of their correlations (values printed for up to 12 modules). traits (samples x numeric traits) are added as extra rows / columns. eigengenes: eigengenes.tsv or cell_eigengenes.tsv.

gcen2.plot.figsize(size='single', height: float | None = None, aspect: float = 0.75)[source]

(width, height) in inches: size “single” (89 mm), “onehalf” (120 mm), “double” (183 mm) or a width in mm; height in mm, else width x aspect (capped at Nature’s 170 mm).

gcen2.plot.get_defaults() → dict[source]
gcen2.plot.hub_network(tom_hubs, kme_table, module, n_inner: int = 10, n_outer: int = 15, edge_prop: float = 0.4, ax=None, size='single', height=None, output=None, formats=None)[source]

Hub genes of one module (hdWGCNA ModuleNetworkPlot): the n_inner genes of highest kME on an inner circle, the next n_outer on an outer one; the strongest edge_prop of their TOM connections drawn, darker and wider for higher TOM. tom_hubs: tom_hubs.tsv (--write-tom / --tom-hubs); kme_table: kme.tsv.

gcen2.plot.hub_network_all(tom_hubs, kme_table, n_hubs: int = 6, n_other: int = 3, edge_prop: float = 0.5, seed: int = 0, size='single', height=None, output=None, formats=None)[source]

Hub genes of all modules in one network (hdWGCNA HubGeneNetworkPlot): the n_hubs top-kME genes and n_other other genes of each module, the strongest edge_prop of their TOM connections, a force-directed layout (networkx); hub genes named.

gcen2.plot.kme(kme_table, modules=None, n_label: int = 5, ncols: int = 4, size='double', height=None, output=None, formats=None)[source]

kME of the genes of each module, sorted (hdWGCNA PlotKMEs), the top n_label hub genes named. kme_table: kme.tsv or cell_kme.tsv (or hdWGCNA’s modules table with kME_<colour> columns).

gcen2.plot.mm_gs(kme_table, gs_table, module, trait, ax=None, size='single', height=None, output=None, formats=None)[source]

Module membership (|kME|) against gene significance (|GS| for a trait) for the genes of one module, with their correlation and p-value (WGCNA verboseScatterplot). gs_table: the file of module -e --gs.

gcen2.plot.module_color(name, palette: str | None = None) → str[source]

The colour of a module in every figure: hdWGCNA / WGCNA colour names are their own colour; GCEN2’s module k (0-based, “ME<k>”) is the (k + 1)-th WGCNA standard colour (turquoise, blue, brown, …), or the k-th Okabe-Ito colour with palette “okabe-ito”; unassigned genes grey, WGCNA’s random module gold.

gcen2.plot.module_label(name) → str[source]

How a module is named in figures: “ME0 (turquoise)” for GCEN2’s numbered modules (with the WGCNA palette), else the name itself, so a module never depends on colour alone.

gcen2.plot.module_sizes(modules, ax=None, size='single', height=None, include_unassigned=False, output=None, formats=None)[source]

Number of genes in each module (bars in the module colours, largest first). modules: modules.tsv (or a gene -> module Series).

gcen2.plot.module_trait(trait_cor, annotate: str = 'p', use_fdr: bool | None = None, group=None, size='single', height=None, output=None, formats=None)[source]

Module-trait correlations (WGCNA labeledHeatmap / hdWGCNA PlotModuleTraitCorrelation): modules x traits coloured by r, each cell printed with r and the p-value (annotate="p") or significance stars ("stars") or nothing ("none"). trait_cor: the table of module -e --trait-cor (module, trait, cor, p, n) or of celltype-modules (group, trait, module, cor, p, fdr, n; one panel per group, or only group). use_fdr: stars / values from the FDR (default: when present).

gcen2.plot.module_umap(tom_hubs, kme_table, n_hubs: int = 10, n_label: int = 3, n_neighbors: int = 15, min_dist: float = 0.1, seed: int = 0, size='single', height=None, output=None, formats=None)[source]

Genes of all modules in two dimensions (hdWGCNA RunModuleUMAP + ModuleUMAPPlot): UMAP of each gene’s TOM with the n_hubs top-kME genes of every module; points in the module colours, sized by kME, the top n_label hubs of each module named. Needs umap-learn (else a PCA of the same values, with a warning).

gcen2.plot.sample_tree(expr, traits=None, cut_height: float | None = None, size='double', height=None, output=None, formats=None)[source]

Clustering of the samples (average linkage, Euclidean distance) to spot outliers, with trait values as colour bars below (WGCNA plotDendroAndColors of the samples); cut_height drawn as a line. expr: genes x samples.

gcen2.plot.save_figure(fig, output, formats=None, close: bool = False) → list[Path][source]

Save fig. output with a known extension (.pdf, .png, .svg, .tiff, .eps) is written as given; without one it is a stem and the figure is written in every format of formats (default: the GCEN2 defaults, PDF, PNG and SVG). Returns the paths written.

gcen2.plot.set_defaults(palette: str | None = None, formats=None) → None[source]

Change the module palette (“wgcna” or “okabe-ito”) and the formats figures are saved in (e.g. (“pdf”, “png”, “svg”)).

gcen2.plot.soft_power(table, r2_cut: float | None = 0.8, size='single', height=None, output=None, formats=None)[source]

Choice of the soft-thresholding power (WGCNA pickSoftThreshold / hdWGCNA PlotSoftPowers): signed scale-free fit R^2 (-sign(slope) x R^2) and mean connectivity for each power, the power used marked; one line per set for a consensus network. table: soft_power.tsv.

gcen2.plot.style()[source]

Use the GCEN2 style inside a with block (the user’s global matplotlib settings are left as they were). Every GCEN2 figure is made inside it, so it also picks the headless backend when none was chosen.

gcen2.plot.tom_heatmap(expr, modules, power: float, signed: bool = True, n_genes: int = 400, seed: int = 0, size='single', height=None, output=None, formats=None)[source]

TOM of a random sample of n_genes genes (WGCNA TOMplot): (1 - TOM)^7 ordered by their average-linkage dendrogram, module colours along both sides. expr: genes x samples (metacells.tsv, the module -e input); power and signed as the network was built.

gcen2.consensus

Consensus modules of several expression sets (WGCNA blockwiseConsensusModules).

Consensus modules of several expression sets (WGCNA blockwiseConsensusModules, as hdWGCNA’s ConstructNetwork(consensus = TRUE) calls it).

consensus_tom_modules() follows WGCNA 1.74 on one block (all genes in one TOM):

  1. the TOM of each set, with its own soft power (power="auto": each set’s power as gcen2.tom_modules.tom_modules() picks it);

  2. calibration (“single quantile”): each set’s TOM is raised to the power that maps its calibration_quantile quantile onto the first set’s (quantile type 8 of calibration_sample_factor / 0.05 entries drawn by R’s sample() after set.seed(calibration_seed), as WGCNA’s consensusTOM: gcen2._rrng);

  3. the consensus TOM: per gene pair the consensus_quantile quantile over the sets (0: the minimum), by WGCNA’s own quantile routine (rowQuantileC), so with its rounding;

  4. average-linkage clustering of 1 - consensus TOM and the dynamic tree cut (as gcen2.tom_modules.tom_modules());

  5. the kME checks on the consensus kME (the consensus_quantile quantile over the sets of each gene’s kME in each set, against that set’s eigengene); WGCNA’s consensus reassignment compares lower-tail chi-square p-values and never moves a gene, so there is none;

  6. mergeCloseModules on the consensus eigengene dissimilarity (per pair of modules, the 1 - consensus_quantile quantile over the sets of 1 - cor of their eigengenes in the set).

The result is a gcen2.tom_modules.TomModules whose samples are the samples of all sets (eigengenes, kME and hub genes on all of them together); metadata has the sets’ names, powers, calibration and eigengenes.

gcen2.consensus.r_quantile7(x: ndarray, p: float, axis: int = 0) → ndarray[source]

R quantile(x, p, type = 7, na.rm = TRUE) along axis (same arithmetic: (1 - h) * x[lo] + h * x[hi]).

gcen2.consensus.r_quantile8(x: ndarray, p: float) → float[source]

R quantile(x, p, type = 8) of a vector without missing values.

gcen2.consensus.consensus_post_process(xs, labels: ndarray, signed: bool, min_size: float, consensus_quantile: float, min_core_kme: float = 0.5, min_kme_to_stay: float = 0.2) → ndarray[source]

blockwiseConsensusModules after cutreeDynamic: the consensus kME checks (xs: genes x samples of each set).

gcen2.consensus.consensus_merge_close_modules(xs, labels: ndarray, cut_height: float, consensus_quantile: float) → ndarray[source]

WGCNA mergeCloseModules on several sets (iterate, relabel by size): modules are merged when the 1 - consensus_quantile quantile over the sets of 1 - cor of their eigengenes is below cut_height (average linkage).

gcen2.consensus.consensus_tom_modules(sets, gene_names=None, set_names=None, sample_names=None, signed: bool = False, power='auto', consensus_quantile: float = 0.0, calibration: str = 'single quantile', calibration_quantile: float = 0.95, sample_for_calibration: bool = True, calibration_sample_factor: float = 1000, calibration_seed: int = 54321, min_size: int = 20, deep_split: int = 2, merge_cut: float = 0.15, detect_cut: float = 0.995, pam_stage: bool = True, min_core_kme: float = 0.5, min_kme_to_stay: float = 0.2, reassign_threshold: float | None = None, power_method: str | None = None, power_r2: float | None = None, min_power: float = 0, powers=None, threads: int = 2) → TomModules[source]

Consensus modules of several expression sets, as WGCNA blockwiseConsensusModules (see the module docstring).

sets: a list (or dict name -> set) of genes x samples matrices (DataFrames, AnnData, or arrays with gene_names) with the same genes; set_names and sample_names (a list per set) name them. power: “auto”, one power for all sets, or one per set; power_method, power_r2, min_power and powers as in gcen2.tom_modules.tom_modules(), applied to each set. consensus_quantile (0: the minimum over the sets), calibration (“single quantile” or “none”), calibration_quantile, sample_for_calibration, calibration_sample_factor and the clustering options are blockwiseConsensusModules’ (minModuleSize 20, deepSplit 2, mergeCutHeight 0.15, minKMEtoStay 0.2); calibration_seed is consensusTOM’s random seed (54321). reassign_threshold is accepted for the options of gcen2.tom_modules.tom_modules() and has no effect (see the module docstring). consensus_tom_modules(sets, **HDWGCNA_CONSENSUS) is hdWGCNA’s ConstructNetwork(consensus = TRUE) with the powers of TestSoftPowersConsensus.

Memory: one genes x genes double matrix plus half of one per set.

gcen2.preservation

Module preservation (WGCNA modulePreservation).

Module preservation (WGCNA modulePreservation, as hdWGCNA’s ModulePreservation calls it): how well the modules of a reference data set hold together in a test data set.

module_preservation() follows WGCNA 1.74 for expression data with one reference and one test set, without interpolation (useInterpolation = FALSE), cluster coefficients or accuracy statistics (the test set has no modules of its own):

  • a “gold” module of min(max_gold_module_size, genes / 2) random genes is added (WGCNA’s baseline), and modules (grey included) with more than max_module_size genes are subsampled;

  • quality (in the reference) and preservation (in the test set) statistics of every module: propVarExplained, meanSignAwareKME, separability, meanSignAwareCorDat, meanAdj and meanMAR (adjacency |r|^6 for “unsigned”, ((1 + r) / 2)^12 for “signed”), and cor.kIM, cor.kME, cor.kMEall, cor.cor and cor.MAR between the sets;

  • n_permutations permutations of the genes; Z = (observed - mean) / sd over the permutations; Zdensity.pres = median Z of propVarExplained, meanSignAwareKME, meanSignAwareCorDat and meanAdj; Zconnectivity.pres = median Z of cor.kIM, cor.kME and cor.cor; Zsummary.pres = their mean (and the median ranks of the observed statistics).

The random draws (the gold genes, the subsampling and the permutations) are those of R’s sample() after set.seed(seed), in WGCNA’s order (gcen2._rrng), so with the same data the statistics are WGCNA’s (to about 1e-8 relative: meanMAR subtracts nearly equal sums, which magnifies last-bit differences of the correlations); the permutations run in parallel. hdWGCNA uses n_permutations = 500, seed = 12345 and an unsigned network (WGCNA’s default).

gcen2.preservation.module_preservation(ref, test, modules, n_permutations: int = 500, seed: int = 12345, network_type: str = 'unsigned', max_gold_module_size: int = 1000, max_module_size: int = 1000, threads: int = 2)[source]

Preservation of the modules of ref in test (see the module docstring), as hdWGCNA’s ModulePreservation.

ref / test: samples (e.g. metacells) x genes DataFrames; the genes they share are used (in the order of ref). modules: the module of every gene of ref (a Series indexed by gene; genes absent or labelled “grey” (or 0) are unassigned). Returns (observed, Z): DataFrames indexed by module (with “gold” and “grey”), WGCNA’s quality and preservation tables side by side (all-missing columns dropped, as WGCNA’s discardInvalidOutput), the Z table with Zsummary.pres.

gcen2.harmony

Harmony batch correction of an embedding (used for harmonized module eigengenes).

Harmony (Korsunsky et al. 2019) batch correction of an embedding, as the R package harmony 2.0.5 runs it (RunHarmony defaults), in double precision.

hdWGCNA’s harmonized module eigengenes (ModuleEigengenes(group.by.vars = ...)) run Harmony on each module’s principal components; see gcen2.single_cell.cell_eigengenes().

The algorithm and every default follow harmony 2.0.5: cosine-normalized cells; nclust = min(round(N / 30), 100) soft clusters, initialized by harmony’s k-means (random distance-weighted seeding, then ten Lloyd steps); each of at most max_iter (10) rounds runs max_iter_cluster (4) passes of the diversity-penalized soft clustering (theta 2, sigma 0.1; cells updated in random blocks of 5%) and then the mixture-of-experts ridge correction (lambda per cluster = alpha (0.2) x the expected number of cells of each batch; batches with less than 1e-5 of a cluster left out of its correction); it stops when the objective improves by less than epsilon_harmony (0.01). R’s harmony computes in single precision and draws its random numbers from R’s generator, so results agree with it closely but not exactly; seed makes this version reproducible.

gcen2.harmony.harmony_integrate(embedding, batches, theta=2.0, sigma: float = 0.1, lambda_=None, nclust: int | None = None, max_iter: int = 10, early_stop: bool = True, alpha: float = 0.2, tau: float = 0.0, block_size: float = 0.05, max_iter_cluster: int = 4, epsilon_cluster: float = 0.001, epsilon_harmony: float = 0.01, batch_prop_cutoff: float = 1e-05, seed: int = 0) → ndarray[source]

Harmony-corrected embedding (cells x dimensions), as R’s RunHarmony(embedding, batches) with harmony 2.0.5’s defaults.

batches: one label per cell, or a list of such vectors (several covariates; theta and lambda_ then one value or one per covariate). lambda_ None estimates it per cluster (alpha x the expected cells of each batch), as harmony 2 does by default. Returns the corrected cells x dimensions array.

gcen2.trajectory

Co-expression networks in sliding windows along pseudotime.

Trajectory co-expression networks: sliding windows along pseudotime.

Cells (or samples of a time course) are ordered by pseudotime and cut into overlapping windows of equal size. One co-expression network is built per window with gcen2.network.build(), and every edge seen in any window is followed across all windows (its correlation in each window, the windows where it passes the cutoffs, and a change pattern).

Requirement §3.6.1 of docs/design/GCEN2_Requirements_Specification.md.

gcen2.trajectory.PATTERNS = ('stable', 'gained', 'lost', 'transient', 'intermittent')

edge patterns of TrajectoryNetworks.dynamics

class gcen2.trajectory.TrajectoryWindow(index: int, start: float, end: float, center: float, n_cells: int, n_samples: int, network: Network)[source]

Bases: object

One pseudotime window and its network.

index: int
start: float
end: float
center: float
n_cells: int
n_samples: int
network: Network
class gcen2.trajectory.TrajectoryNetworks(windows: list[TrajectoryWindow], dynamics: pd.DataFrame, params: dict = <factory>)[source]

Bases: object

Result of build_trajectory().

dynamics has one row per edge present in at least one window: gene_a, gene_b, the correlation in every window (cor_0 …), n_windows (windows where the edge passes the cutoffs), first and last (first / last such window), pattern (see below), cor_change (correlation in the last window minus the first) and trend (Pearson correlation of the edge correlation with the window centre; NaN with fewer than 3 windows or a constant series).

Patterns: stable (all windows), gained (absent from the first window, present in the last), lost (present first, absent last), transient (only in inner windows), intermittent (first and last but not all).

windows: list[TrajectoryWindow]
dynamics: pd.DataFrame
params: dict
window_table() → pd.DataFrame[source]

One row per window: range, sizes and network size.

degree_dynamics() → pd.DataFrame[source]

Gene degree in every window (genes x windows, 0 when absent).

Rows are sorted by the largest degree reached in any window, so the hubs of any stage come first.

write(directory: str | Path) → None[source]

Write window_<i>.network, windows.tsv, edge_dynamics.tsv and degree_dynamics.tsv into directory (created if needed).

gcen2.trajectory.build_trajectory(data: Any, pseudotime: str | Sequence[float] | np.ndarray | pd.Series, window_size: int | float = 0.2, step: int | float | None = None, metacell_size: int = 1, layer: str | None = None, use_highly_variable: bool = False, method: str = 'spearman', cor: float = 0.5, pval: float = 0.001, signed: bool = False, fdr: bool = False, log: str | None = None, threads: int = 2) → TrajectoryNetworks[source]

Build co-expression networks in sliding windows along pseudotime.

Parameters:
  • data – AnnData (cells x genes), or a genes x samples pd.DataFrame (e.g. a bulk time course; ExpressionMatrix is accepted too).

  • pseudotime – For AnnData, the name of an adata.obs column, or one value per cell. For a DataFrame, one value per column, or a pd.Series indexed by column name. Cells with a missing or infinite pseudotime are left out (with a warning).

  • window_size – Cells per window: an int (>= 3), or a float in (0, 1] for a fraction of the ordered cells.

  • step – Shift between window starts, int or fraction as window_size. Default: half the window size. A last window is added at the end when the steps do not reach the last cell, so every cell is in a window.

  • metacell_size – If > 1, consecutive cells (in pseudotime order) of a window are averaged into metacells of this many cells before correlation, which reduces single-cell dropout noise.

  • layer – AnnData layer to use instead of X.

  • use_highly_variable – Subset to adata.var['highly_variable'] genes (AnnData only).

  • method – Passed to gcen2.network.build() for every window.

  • cor – Passed to gcen2.network.build() for every window.

  • pval – Passed to gcen2.network.build() for every window.

  • signed – Passed to gcen2.network.build() for every window.

  • fdr – Passed to gcen2.network.build() for every window.

  • log – Passed to gcen2.network.build() for every window.

  • threads – Passed to gcen2.network.build() for every window.

Return type:

TrajectoryNetworks

gcen2.multilayer

Multi-omics network integration: weighted fusion and multiplex RWR.

Multi-omics network integration: heterogeneous layers over shared genes.

A layer is an undirected gene network of any kind (co-expression, PPI, regulatory, …), given as a Network, a DataFrame or an edge-list file. Its edge weights are |correlation| when the layer has a correlation column, else |weight| when it has a weight column (or the column named by weight_column), else 1.

Two integration strategies (requirement §3.7.1):

  • fuse() — weighted fusion into one network: per edge, the weighted mean of its (normalised) layer weights, an edge absent from a layer counting as 0.

  • rwr_multiplex() — random walk with restart on the multiplex network (RWR-M, Valdeolivas et al., Bioinformatics 2019; by default the transition matrix of their RandomWalkRestartMH): one copy of every gene per layer, walks move within a layer or jump to the same gene in another layer, and the per-layer scores are aggregated per gene.

gcen2.multilayer.read_layer(path: str | Path, weight_column: str | int | None = None, sep: str = '\t') → pd.DataFrame[source]

Read an edge-list file as a layer table gene_a, gene_b, weight.

The first two columns are the genes. A header line is recognised when the file has a third column whose first value is not a number (GCEN network files, STRING protein1 protein2 combined_score files, …). The weight is the column weight_column (name, or 0-based position), else correlation or weight if present, else the third column if it is numeric, else 1.

The C++ extension reads the file when its pandas reading is certain (see read_layer_codes()); the table is the same either way.

gcen2.multilayer.read_layer_codes(path: str | Path, weight_column: str | int | None = None, sep: str = '\t')[source]

read_layer() as (names, a, b, w): gene names (object array), int64 codes of the two gene columns into names and float64 weights.

The first record is read by pandas to decide the header and the weight column; the rows are then read by the C++ extension (_gcen_core.network.read_layer_file), which builds no string per row. Inputs it declines (quotes, a byte order mark, missing values, numbers pandas might parse differently, …) and installs without the extension are read by pandas.

gcen2.multilayer.as_layer(layer: LayerLike) → pd.DataFrame[source]

gene_a, gene_b, weight table of a Network, DataFrame or file.

gcen2.multilayer.fuse(layers: Mapping[str, LayerLike] | list, weights: Mapping[str, float] | None = None, normalize: str = 'max', min_layers: int = 1, min_score: float = 0.0) → Network[source]

Weighted fusion of heterogeneous networks into one network.

Parameters:
  • layers – {name: layer} (or a list, named layer0, layer1, …). Each layer is a Network, a gene_a, gene_b[, weight] DataFrame or an edge-list path (see read_layer()). Edges are undirected; repeated edges within a layer keep their largest weight.

  • weights – Layer importance {name: w >= 0} (default 1 for every layer).

  • normalize – Per-layer edge-weight scaling before fusion: max (divide by the layer’s largest weight, so all layers range up to 1), rank (percentile rank in (0, 1], robust to differently distributed scores) or none.

  • min_layers – Keep edges present in at least this many layers.

  • min_score – Keep edges whose fused score is at least this value.

Returns:

Edges gene_a, gene_b, score, n_layers, layers and one column w_<name> per layer (its normalised weight, 0 when absent). score = sum_l weights[l] * w_l / sum_l weights[l]; gene_a <= gene_b; sorted by score (descending), then gene names.

Return type:

Network

gcen2.multilayer.fuse_to_file(layers: Mapping[str, LayerLike] | list, output: str | Path, weights: Mapping[str, float] | None = None, normalize: str = 'max', min_layers: int = 1, min_score: float = 0.0, threads: int = 4) → dict[source]

fuse() written straight to output (used by gcen2 fuse).

Same file as fuse(...).to_edgelist(output), but the table is written by the C++ extension from gene codes, without building the gene-name columns in Python (falls back to that path without the extension). Returns node_count, edge_count and layer_counts (edges per number of supporting layers).

gcen2.multilayer.rwr_multiplex(layers: Mapping[str, LayerLike] | list, seed_genes: list[str], gamma: float = 0.5, delta: float = 0.5, weighted: bool = False, aggregate: str = 'geometric', prob_cutoff: float = 0.0, transition: str = 'supra', max_iter: int = 1000000, tol: float = 1e-10) → RWRResult[source]

Random walk with restart on a multiplex network (RWR-M).

Every gene of any layer has one node per layer. From a node, the walker restarts with probability gamma (to the seeds, spread equally over the layers); otherwise it moves along the supra-adjacency matrix: the layers’ adjacency matrices scaled by 1 - delta on the diagonal blocks, delta / (L - 1) between the copies of a gene in two layers. How that matrix becomes transition probabilities is transition:

  • supra (default): the whole matrix is column-normalised, as in RandomWalkRestartMH (Valdeolivas et al., the authors’ implementation of RWR-M), whose scores it reproduces. A gene of degree d jumps with probability delta / ((1 - delta) d + delta), so hubs stay in their layer.

  • layer: each layer is column-normalised first, so every gene follows an edge with probability 1 - delta and jumps with probability delta, whatever its degree.

A node without edges in its layer always jumps. With one layer both are gcen2.rwr.predict().

Parameters:
  • layers – {name: layer} or a list, as in fuse().

  • seed_genes – Known genes; those absent from every layer are ignored.

  • gamma – Restart probability, in (0, 1).

  • delta – Weight of the jumps between layers, in [0, 1] (their probability with transition="layer").

  • weighted – Use the layer edge weights (see the module docstring) for intra-layer transitions instead of 1 per edge.

  • aggregate – Per-gene score from its per-layer probabilities: geometric mean (as RWR-M; favours genes supported in every layer), arithmetic mean, or sum (the total probability, summing to 1 over genes).

  • prob_cutoff – Minimum aggregated score of a reported gene.

  • transition – supra or layer, see above.

Returns:

ranked_genes holds gene, probability (the aggregated score) and p_<layer> per layer, seeds excluded, sorted by probability.

Return type:

RWRResult

gcen2.differential

Differential co-expression analysis.

Differential co-expression analysis between two conditions.

gcen2.differential.compare(network_a: Network, network_b: Network, method: str = 'fisher_z', pval: float = 0.05, n_a=None, n_b=None, fdr: bool = False, correlation: str = 'pearson') → DiffCoExResult[source]

Compare two co-expression networks to identify rewired edges.

Uses Fisher’s Z-transformation test to determine whether correlation coefficients are significantly different between conditions: z is the difference of the two atanh(r) divided by its standard error, sqrt(1/(n_a - 3) + 1/(n_b - 3)) for Pearson and sqrt(1.06/(n_a - 3) + 1.06/(n_b - 3)) for Spearman correlations (Fieller et al., Biometrika 1957; as DGCA). The p-values of the edges shared by both networks (the tested pairs) are adjusted by Benjamini-Hochberg into the fdr column.

Parameters:
  • network_a – Network from condition A.

  • network_b – Network from condition B.

  • method – Statistical test method. Currently only ‘fisher_z’ is supported.

  • pval – P-value cutoff for significance.

  • n_a – Number of samples used to build network_a. By default from its metadata: the per-gene effective samples of a metacell network (gene_effective_samples, as gcen2 celltype --diff uses them), else p_value_samples, else n_samples, else 30. Or a mapping (e.g. a pandas.Series) gene → effective number of samples, such as metadata["gene_effective_samples"] of a metacell network (gcen2.single_cell.metacell_effective_samples()): an edge is then tested on the smaller of its two genes’ values, and edges with fewer than 4 get no z or p-value (shared_stable).

  • n_b – Number of samples used to build network_b (or a mapping, as n_a).

  • fdr – Call a shared edge shared_changed when its FDR (instead of its p-value) is at most pval.

  • correlation – How the networks’ correlations were computed: pearson or spearman (sets the standard error of z).

Returns:

results has one row per undirected edge in either network (gene names ordered within the pair), sorted by gene_a, gene_b: gene_a, gene_b, cor_a, cor_b, z_score, p_value, fdr, category (z, p and FDR only for edges in both networks).

Return type:

DiffCoExResult

gcen2.differential.compare_files(path_a, path_b, output, pval: float = 0.05, n_a=None, n_b=None, fdr: bool = False, correlation: str = 'pearson', threads: int = 2) → dict[str, int][source]

compare() from two edge-list files to a result TSV.

Writes the same file as compare(read_network(path_a), read_network(path_b), ...).results.to_csv(output, sep="\t", index=False). The compiled extension reads and joins the edges (_gcen_core.network.diff_edge_files) and writes the table; only the Fisher z test and the FDR of the shared edges run in numpy/scipy (as in compare()), so pandas is never imported. Falls back to that pipeline without the extension or for files whose gene columns are not the first two. The extension reads, sorts and writes with threads threads (the file does not depend on the number). n_a / n_b may be mappings gene → effective samples, as in compare(). Returns the row count of each category present (A_only, B_only, shared_changed, shared_stable).

gcen2.plotting

Visualization functions.

Visualization module for GCEN2.

gcen2.plotting.network_interactive(network: Network, output: str | Path = 'network.html', color_by: str = 'module', modules: ModuleSet | None = None, annotation: dict | None = None) → None[source]

Generate an interactive HTML network visualization using pyvis.

Parameters:
  • network – Input network.

  • output – Output HTML file path.

  • color_by – ‘module’ (requires modules) or ‘degree’.

  • modules – ModuleSet for coloring nodes by module membership.

  • annotation – Optional dict mapping gene → list of top GO terms (for hover tooltips).

gcen2.plotting.network_static(network: Network, output: str | Path | None = None, modules: ModuleSet | None = None, figsize: tuple[int, int] = (12, 10))[source]

Generate a static publication-quality network figure via networkx + matplotlib.

gcen2.plotting.dotplot(enrichment: EnrichmentResult, top_n: int = 20, output: str | Path | None = None, title: str = '', figsize: tuple[int, int] = (8, 8))[source]

Dot plot (bubble plot) for enrichment results.

gcen2.plotting.barplot(enrichment: EnrichmentResult, top_n: int = 20, output: str | Path | None = None, title: str = '', figsize: tuple[int, int] = (8, 8))[source]

Horizontal bar chart for enrichment results.

gcen2.plotting.expression_boxplot(expr: ExpressionMatrix, output=None, figsize=(12, 6))[source]

Box plots comparing expression distributions across samples.

gcen2.plotting.expression_violin(expr: ExpressionMatrix, output=None, figsize=(12, 6))[source]

Violin plots of expression distributions.

gcen2.plotting.heatmap(expr: ExpressionMatrix, modules: ModuleSet, output=None, figsize=(12, 12))[source]

Heatmap (clustermap) of gene expression within modules.

gcen2.plotting.degree_distribution(network: Network, output=None, figsize=(8, 6))[source]

Histogram of node degree distribution.

gcen2.plotting.degree_histogram(degrees, output=None, figsize=(8, 6))[source]

degree_distribution() from the node degrees themselves (any order), e.g. those of gcen2.network.summary_from_file().

gcen2.plotting.eigengene_heatmap(eigengenes, output=None, figsize=None)[source]

Correlations between module eigengenes (WGCNA plotEigengeneNetworks’ heatmap): eigengenes is a samples x eigengenes DataFrame (gcen2 module -e --me; ME_unassigned is left out). Eigengenes are ordered by average-linkage clustering on 1 - r; values are printed for up to 25 modules.

gcen2.plotting.module_trait_heatmap(trait_cor, output=None, figsize=None)[source]

Module-trait relationships (WGCNA labeledHeatmap of the tutorial): trait_cor is the long table of gcen2 module -e --trait-cor (module, trait, cor, p); each cell shows r and its p-value.

gcen2.plotting.spatial_eigengenes(coords, eigengenes, output=None, ncols: int = 4, point_size=None, flip_y: bool = True)[source]

Spatial maps of spot-level module eigengenes (hdWGCNA ModuleFeaturePlot): coords (spots x 2: x, y, e.g. obsm ["spatial"]), eigengenes (spots x modules DataFrame, e.g. gcen2 spatial-modules spot_eigengenes.tsv, rows in the order of coords). Each panel: one module, colour scale symmetric around 0 (clipped at the 1st / 99th percentile of |ME|). flip_y: image coordinates (y down).

gcen2.plotting.diff_network(diff: DiffCoExResult, output=None, figsize=(10, 10))[source]

Visualize differential co-expression network with colored edges.

gcen2.plotting.trajectory_dynamics(traj, top: int = 10, output=None, figsize=(10, 7))[source]

Edges per window (top) and the correlation of the top edges that change most (largest |cor_change|) along pseudotime (bottom).

traj is a gcen2.trajectory.TrajectoryNetworks.

gcen2.report

Automated research report generation.

Automated HTML/PDF research report generation.

gcen2.report.generate(network: Network | NetworkSummary | None = None, modules: ModuleSet | None = None, enrichment: dict[str, EnrichmentResult] | None = None, rwr: RWRResult | None = None, expr: ExpressionMatrix | None = None, output: str | Path = 'report.html', template: str | Path | None = None, wgcna: dict | list | None = None, figures_dir: str | Path | None = None, celltypes: dict | None = None, moran=None, merge: dict | None = None, extract: dict | None = None) → None[source]

Generate a comprehensive HTML research report.

Parameters:
  • network – Co-expression network, or its gcen2.network.NetworkSummary (gcen2.network.summary_from_file()), which gives the same report without the edge table.

  • modules – Identified gene modules.

  • enrichment – Enrichment results dict (gene/module → EnrichmentResult).

  • rwr – RWR prediction results.

  • expr – Expression matrix (for QC section).

  • output – Output file path. Use .pdf extension for PDF output (requires weasyprint).

  • template – Custom Jinja2 template path. Uses the built-in default if None.

  • wgcna – WGCNA-style module results: a section from wgcna_section() (gcen2 module -e outputs) or a list of them (celltype_module_sections()), each shown with its module table and hub genes and the figures its files allow (gcen2.plot: module sizes, soft power, dendrogram, eigengene network, module-trait, kME, hub network, differential eigengenes, consensus sets).

  • figures_dir – Also save every report figure there as PDF, PNG and SVG (named by section and figure), ready for a manuscript.

  • celltypes – celltype_overview() of a celltype-modules directory: cell types at a glance and, with an embedding, the metacells on it.

  • moran – Moran’s I table of spatial-build --moran (path or DataFrame).

  • merge – {"networks": [...], "merged": path or None, "names": [...] or None}: the inputs (and output) of gcen2 merge.

  • extract – {"network": path, "genes": path or list}: the network (or the extracted subnetwork) and query genes of gcen2 extract.

Notes

Figures are embedded as vector SVG (so a PDF report keeps them vector), each with a caption.

gcen2.report.celltype_overview(directory, coords=None, basis: str = 'X_umap') → dict[source]

The cell-type overview of a gcen2 celltype-modules directory for generate() (celltypes): cells, metacells, genes and modules per cell type and, with coords (an AnnData / .h5ad with obsm[basis], or a TSV of x, y by cell), the metacells on that embedding.

gcen2.report.wgcna_section(modules, eigengenes=None, kme=None, hubs=None, trait_cor=None, title: str = 'WGCNA-style modules', n_hubs: int = 10, note: str | None = None, soft_power=None, dendrogram=None, tom_hubs=None, dmes=None, cell_trait_cor=None, set_eigengenes=None) → dict[source]

A report section of gcen2 module -e results (paths or DataFrames): modules (module, gene), and optionally eigengenes (--me), kme (--kme), hubs (--hubs; else the top n_hubs genes by kME when kme is given) and trait_cor (--trait-cor). The files for its figures: soft_power (soft_power.tsv), dendrogram (dendrogram.json), tom_hubs (tom_hubs.tsv), and of celltype-modules dmes (dmes.tsv), cell_trait_cor (trait_cor.tsv) and set_eigengenes (set_eigengenes.tsv).

gcen2.report.celltype_module_sections(directory, n_hubs: int = 10) → list[source]

One wgcna_section() per cell type of a gcen2 celltype-modules output directory (its celltypes.tsv).

gcen2.models

Core data models.

Core domain data models for GCEN2.

class gcen2.models.ExpressionMatrix(data: pd.DataFrame | any, gene_names: np.ndarray, sample_names: np.ndarray, is_single_cell: bool = False, is_normalized: bool = False, normalization_method: str | None = None)[source]

Bases: object

Container for gene expression data (bulk or single-cell).

data: pd.DataFrame | any
gene_names: np.ndarray
sample_names: np.ndarray
is_single_cell: bool = False
is_normalized: bool = False
normalization_method: str | None = None
class gcen2.models.Network(edges: pd.DataFrame, node_count: int = 0, edge_count: int = 0, is_signed: bool = False, method: str = 'spearman', metadata: dict = <factory>)[source]

Bases: object

Gene co-expression network represented as an edge list.

edges: pd.DataFrame
node_count: int = 0
edge_count: int = 0
is_signed: bool = False
method: str = 'spearman'
metadata: dict
to_networkx() → nx.Graph[source]
to_adjacency(weight: str | None = 'correlation', absolute: bool = False, genes: list[str] | None = None) → scipy.sparse.csr_array[source]

Weighted adjacency matrix (symmetric, scipy csr_array).

weight:

Edge column used as the weight: "correlation" (default; the sign is kept), another numeric column such as "tom", or None for an unweighted (0/1) matrix.

absolute:

Use the absolute values (|correlation|, the weights of gcen2.rwr.predict(weighted_network=True)).

genes:

Order of the rows and columns (genes not in the network give empty rows, edges of other genes are left out); default: the genes in order of first appearance in the edge table (the node order of to_networkx()).

Repeated edges between two genes are summed.

to_edgelist(path: str) → None[source]

Write the edges as a tab-separated file with a header line.

Standard networks (gene_a gene_b correlation p_value [fdr] [tom]) are written like GCEN v1 (correlation %f, p-value/FDR/TOM %e, i.e. 6 decimals) by the compiled formatter (pure-Python formatting if the extension is missing); other column layouts are written by pandas.

neighbor_sets() → dict[str, set[str]][source]

Undirected adjacency as {gene: set(neighbors)}.

Vectorised replacement for row-wise iterrows loops; a 3.6M-edge network takes seconds instead of minutes.

sparse_adjacency(genes: list[str] | None = None, weighted: bool = False, directed: bool = False) → scipy.sparse.csr_matrix[source]

Sparse adjacency matrix W with W[i, j] for edge gene_a(i) -> gene_b(j).

Rows/columns follow genes (default: sorted node names). Weights are |correlation| when weighted else 1; parallel edges are summed. Undirected networks get both W[i, j] and W[j, i].

subnetwork(genes: list[str]) → Network[source]
stats() → NetworkStats[source]
class gcen2.models.NetworkStats(node_count: int, edge_count: int, density: float, average_degree: float, max_degree: int, connected_components: int, giant_component_size: int, heterogeneity: float, clustering_coefficient: float, transitivity: float)[source]

Bases: object

Computed statistics for a Network.

node_count: int
edge_count: int
density: float
average_degree: float
max_degree: int
connected_components: int
giant_component_size: int
heterogeneity: float
clustering_coefficient: float
transitivity: float
classmethod compute(network: Network, chunk_size: int = 2000, threads: int = 2) → NetworkStats[source]

Compute statistics with sparse-matrix operations.

Numerically identical to the networkx definitions (undirected simple graph; parallel/reverse duplicate edges collapse; a self-loop adds 2 to the degree but is ignored for clustering/transitivity), but scales to millions of edges. With the compiled extension, degrees, triangles and components come from _gcen_core.network.graph_stats on the adjacency of module._unique_adjacency (nodes in sorted order, as gcen2.network.stats_from_file(), so both give the same values); otherwise triangles are counted in row chunks of the sparse adjacency.

classmethod from_adjacency(indptr, indices, threads: int = 2) → NetworkStats[source]

Statistics of the symmetric CSR adjacency (indptr, indices) (rows sorted and unique, a self-loop is a diagonal entry), as given by module._unique_adjacency or module.read_file_adjacency.

classmethod with_degrees(indptr, indices, threads: int = 2)[source]

from_adjacency() and the node degrees (networkx G.degree values: a self-loop adds 2), in node order, as an int64 array.

class gcen2.models.ModuleSet(modules: list[set[str]], module_count: int = 0, source_network: Network | None = None, similarity_cutoff: float = 0.5)[source]

Bases: object

Collection of gene modules identified from a network.

modules: list[set[str]]
module_count: int = 0
source_network: Network | None = None
similarity_cutoff: float = 0.5
class gcen2.models.EnrichmentResult(results: pd.DataFrame, ontology_type: str, gene_or_module: str, p_cutoff: float = 0.05)[source]

Bases: object

Results of GO or KEGG enrichment analysis.

results: pd.DataFrame
ontology_type: str
gene_or_module: str
p_cutoff: float = 0.05
class gcen2.models.RWRResult(ranked_genes: pd.DataFrame, seed_genes: list[str], gamma: float = 0.5, steps: int = 0)[source]

Bases: object

Results of Random Walk with Restart gene function prediction.

ranked_genes: pd.DataFrame
seed_genes: list[str]
gamma: float = 0.5
steps: int = 0
class gcen2.models.DiffCoExResult(results: pd.DataFrame, network_a_name: str = 'A', network_b_name: str = 'B', method: str = 'fisher_z', p_cutoff: float = 0.05)[source]

Bases: object

Results of differential co-expression analysis between two conditions.

results: pd.DataFrame
network_a_name: str = 'A'
network_b_name: str = 'B'
method: str = 'fisher_z'
p_cutoff: float = 0.05

gcen2.io

File I/O utilities.

File I/O utilities for GCEN2.

gcen2.io.read_tsv(path: str | Path, index_col: int = 0, header: bool | None = None) → ExpressionMatrix[source]

Read a tab-separated expression matrix (genes × samples).

Parameters:
  • path – Path to the TSV file. First column is expected to be gene identifiers.

  • index_col – Column to use as the row index (gene names). Default 0.

  • header – Whether the first line holds sample names. None (default) auto-detects: header-less GCEN v1 matrices (first line is numeric data) are read without losing the first gene. Pass True explicitly if your sample names are purely numeric.

Return type:

ExpressionMatrix

gcen2.io.read_csv(path: str | Path, index_col: int = 0, header: bool | None = None) → ExpressionMatrix[source]

Read a comma-separated expression matrix (genes × samples).

Quoted fields are handled correctly. header behaves as in read_tsv() (auto-detects header-less GCEN v1 matrices).

gcen2.io.read_h5ad(path: str | Path) → ExpressionMatrix[source]

Read an AnnData (.h5ad) file for single-cell data.

gcen2.io.read_network(path: str | Path, genes_only: bool = False) → Network[source]

Read a GCEN-format edge list (TSV: gene_a, gene_b, correlation, p_value).

Compatible with GCEN v1 .network files and GCEN2 network.build() output.

genes_only=True reads just the two gene columns, as categoricals (each gene name is stored once). Enough for annotation and needs much less memory for large networks.

gcen2.io.read_gene_list(path: str | Path) → list[str][source]

Read a gene list file, one gene per line.

GCEN v1 compatible: blank lines and lines starting with # (headers / comments) are skipped, and only the first tab/whitespace-separated column is used, so v1 seed files such as #gene<TAB>probability with GENE<TAB>1.0 rows are read correctly.

gcen2.io.read_modules(path: str | Path) → ModuleSet[source]

Read a module file in GCEN v1 or GCEN2 format.

  • v1 (module_identify): one module per line, genes tab-separated.

  • GCEN2 (gcen2 module): header module<TAB>gene then one module_id<TAB>gene pair per line.

Module order follows the file (v1 numbers annotation output module_<i> by line).

gcen2.io.write_tsv(df: pd.DataFrame, path: str | Path) → None[source]

Write a DataFrame to a tab-separated file.

gcen2.io.write_csv(df: pd.DataFrame, path: str | Path) → None[source]

Write a DataFrame to a comma-separated file.

gcen2.exceptions

Exception hierarchy.

GCEN2 exception hierarchy.

exception gcen2.exceptions.GCENError[source]

Bases: Exception

Base exception for all GCEN2 errors.

exception gcen2.exceptions.GCENInputError[source]

Bases: GCENError

Raised for bad input files or invalid parameters.

exception gcen2.exceptions.GCENComputeError[source]

Bases: GCENError

Raised for numerical failures in C++ kernels.

exception gcen2.exceptions.GCENIOError[source]

Bases: GCENError

Raised for file read/write failures.

gcen2.config

Package configuration.

Global configuration singleton for GCEN2 runtime settings.

class gcen2.config.GCENConfig(n_threads: int = <factory>, random_seed: int = 42, verbosity: int = 1, temp_dir: str | None = None, figure_dpi: int = 300, figure_format: str = 'pdf')[source]

Bases: object

Runtime configuration for GCEN2.

This is a simple dataclass; instantiate it and pass to functions, or modify the module-level default_config to change global defaults.

n_threads: int
random_seed: int = 42
verbosity: int = 1
temp_dir: str | None = None
figure_dpi: int = 300
figure_format: str = 'pdf'
get_temp_dir() → str[source]
gcen2.config.default_config = GCENConfig(n_threads=2, random_seed=42, verbosity=1, temp_dir=None, figure_dpi=300, figure_format='pdf')

Module-level default configuration used when no config is explicitly passed.