Skip to main content

GSNetAct

Network-weighted gene-set activity for single-cell data.

GSNetAct scores a gene set in a cell as a weighted sum of its members' expression, where the weights come from the interactions between those genes in STRING. The idea is that a gene wired into the programme should count for more than a gene that merely appears in the list.

Version 0.1.0 changes the default weighting. The old scheme weighted a gene by its neighbours' degrees, which in practice reproduced STRING degree — a proxy for how much a gene has been studied — and made gene-set scores collinear. The new default damps connectivity instead of amplifying it, and restricts the prior network to genes actually detected in the data. On the GSNetAct benchmark this is the difference between falling behind unweighted aggregation and beating it. See CHANGELOG.md for the argument, the numbers, and the bugs fixed along the way. weights="legacy" reproduces 0.0.x exactly.

Install

pip install gsnetact

or from source:

git clone https://github.com/BMGLab/GSNetAct
cd GSNetAct
pip install -e .

Requires Python 3.9+, NumPy, SciPy, AnnData, scikit-learn and Requests.

Usage

import scanpy as sc
from gsnetact import pjson, runGSNA

adata = sc.read_h5ad("pbmc.h5ad")     # var_names must be HGNC symbols
network = pjson("geneSets.json")      # see "Building the network" below

activity = runGSNA(adata, network, layer="lognorm")

activity is an AnnData of cells × gene sets. Pass the log-normalised layer explicitly — a weighted sum of raw counts is dominated by library size.

The result carries its own provenance:

activity.var                       # per-set QC, one row per gene set
activity.uns["gsnetact"]           # the parameters this run used
activity.uns["gsnetact_gene_weights"]["HALLMARK_INFLAMMATORY_RESPONSE"]
activity.layers["raw_activity"]    # scores before standardisation

var reports, for every set: how many members it has, how many are in your data, how many edges survived, how many members ended up isolated and what share of the weight they hold, the weight Gini, the largest-component fraction, whether the set fell back to uniform weighting, and its top-weighted gene. A score you cannot trace to network evidence is a score you should not trust.

Which genes is a score reading?

from gsnetact import GeneSetGraph, NetworkGeneWeights

graph = GeneSetGraph(network["HALLMARK_INTERFERON_ALPHA_RESPONSE"])
weights = NetworkGeneWeights(graph)
weights.top(10)          # the ten genes carrying most of the set's weight
weights.stats            # the same QC as in var

Options

runGSNA(
    adata, network,
    weights="diffusion",        # "legacy" | "uniform" | "strength" | "pagerank"
    layer="lognorm",
    min_detection=0.05,         # edges need both partners detected this often
    restrict_to_context=True,
    normalize="set",            # "cell" | None
    weight_options={"alpha": 0.5, "steps": 2},
)

Reproducing the GSNetAct paper. The default (alpha=0.5, min_detection=0.05) was fit for cell-identity scoring. For coordinated condition/state programmes — the regime the paper focuses on (e.g. interferon stimulation) — the tuned configuration is stronger hub damping and a stricter context filter:

runGSNA(adata, network, weights="diffusion", layer="lognorm",
        min_detection=0.2, weight_options={"alpha": 1.0, "steps": 2})

alpha is a genuine tuning knob, not a universal constant; sweep it for your signal rather than assuming the identity-fit default (see CHANGELOG).

weights — "diffusion" (default) weights a gene by (D^-0.5 A D^-0.5)^2 · 1. sqrt(strength) is the leading eigenvector of that operator, so influence grows with the square root of the interaction evidence rather than with the evidence times the neighbours' evidence. "uniform" ignores the network entirely and is the control any network claim has to beat. "legacy" is the pre-0.1.0 formula.

min_detection — STRING asserts that two proteins associate somewhere in the organism, not that the interaction is available in the cells you are scoring. Edges between genes not transcribed here are dropped. Members are never dropped, only their edges. A set that loses every edge falls back to uniform weighting, which is the honest treatment of a gene set with no context-supported network evidence.

normalize — "set" (default) robust-z-scores each gene set across cells. "cell" is the pre-0.1.0 within-cell transform: it makes activities comparable within a cell but forces every cell to the same distribution of pathway activity, so a globally quiescent cell cannot look quiescent. Use "cell" for within-cell comparisons, "set" for clustering and differential testing.

Building the network

makeGeneSets --geneSymbols h.all.v2026.1.Hs.symbols.gmt --fileType gmt -o geneSets.json

or

from gsnetact import makeJson

makeJson("h.all.v2026.1.Hs.symbols.gmt", "gmt", "geneSets.json",
         required_score=400,
         channels=["experiments", "database"])   # optional

required_score is STRING's confidence floor on a 0–1000 scale: 150 low, 400 medium (the default), 700 high, 900 highest. The pre-0.1.0 default was 100, STRING's lowest possible cut, which admits links more likely wrong than right.

channels restricts the score to chosen evidence channels, recombined with STRING's own independence formula. ["experiments", "database"] gives a network free of expression-derived and text-mined evidence — worth using when the downstream analysis is itself expression-based, since STRING's coexpression and textmining channels partly encode the co-expression structure the method is then credited with finding.

Network JSON format

{
  "GeneSet1": {
    "Gene1": {"Gene2": 0.35, "Gene3": 0.77},
    "Gene2": {"Gene1": 0.35, "Gene3": 0.51},
    "Gene3": {"Gene1": 0.77, "Gene2": 0.51},
    "Gene4": {}
  }
}

Scores are STRING combined scores in [0, 1]. The graph is undirected; both directions may be listed and are merged with max. A member with no within-set partner is written with an empty dict — it stays in the gene set and receives no network weight.

Graph for GeneSet1

Choosing a weighting

The weighting is a per-task choice, not a global default. Two modes ship with the package:

from gsnetact import mode_options, recommend_mode, runGSNA

rec = recommend_mode(adata, sets, layer="lognorm")   # measures the data
print(rec)
activity = runGSNA(adata, sets, layer="lognorm", **mode_options(rec.mode))
mode weighting context use when
"programme" diffusion, α=1.0, t=2 min_detection=0.2 the contrast is a broad coordinated response (interferon programme, hypoxia shift)
"marker" legacy degree off the contrast rests on a few genes (CD4 vs CD8 T cells: CD4, CD8A, CD8B)

On PBMC benchmarks with an identical downstream pipeline, "programme" beats degree weighting by +0.306 condition NMI on the Kang IFN-β state (donor-bootstrap [+0.279, +0.328], n = 8 donors), while on a curated PBMC identity library across 8 donors "programme" falls 0.020 ARI below "marker" and 0.018 below the unweighted mean of identical sets — both donor-bootstrap intervals excluding zero, with 0 of 8 donors favouring it.

"marker" is recommended for identity because "programme" is harmful there, not because degree weighting beats unweighted aggregation: across those donors that difference is +0.003 ARI [−0.001, +0.006], indistinguishable from zero. An earlier single-donor figure of +0.072 did not replicate and is withdrawn.

The axis is how concentrated the discriminating signal is, not "state vs cell type"; those correlate but are not the same. Two mechanisms contribute about equally: hub damping disperses weight a lineage signature had concentrated on its defining genes, and the detection floor disconnects markers of any class rarer than the floor (a perfectly class-specific marker cannot be detected in more cells than its class occupies).

recommend_mode() is a one-sided guard, not a classifier. It detects only the detection-floor risk, which is measurable without labels. Whether hub damping will disperse your discriminating genes depends on labels that do not exist at scoring time, so a "programme" result means "the floor is not obviously destructive here" — never "the programme mode is right for your question". If you know your contrast rests on a few markers, pass "marker".

Both arms have 8 donors, but differ in cohort quality: "programme" comes from a paired design (condition NMI ~50× donor NMI), "marker" from a reference whose labels are WNN calls derived from RNA and protein jointly. When unsure, "marker" is the conservative choice — "programme" is best on one task and worst on the other.

Weighting schemes

Measured across 752 STRING gene-set subgraphs (≥20 genes, ≥20 edges):

scheme weight Gini ρ(weight, degree) top-10% weight share
legacy 0.666 0.93 39%
strength 0.618 0.97 37%
pagerank 0.452 0.86 28%
diffusion 0.403 0.79 21%

Lower is less hub-dominated. Clustering benchmarks for each are in CHANGELOG.md.

Tests

pip install -e ".[test]"
pytest

Limitations

  • Weights are unsigned. A gene set mixes activators and repressors, and a negative-feedback gene induced by pathway activity counts toward activity as if it were an effector.
  • Genes with no within-set STRING partner get weight zero, so poorly annotated genes are invisible to the weighting. var["n_isolated_genes"] reports how many members that affects per set.
  • Context restriction uses detection rate, which is confounded with expression level. It is a deliberately weak filter, not a claim about which interactions are physically occurring.
  • STRING is context-agnostic even after restriction: a benefit from the topology is evidence for informative prior structure, not for tissue-specific causality.

Citation

Please cite this repository if you use this code in your work.

Metadata

Release files for gsnetact 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gsnetact 0.1.0
File Size Uploaded Provenance Actions
gsnetact-0.1.0.tar.gz 55.8 kB Without provenance Details for gsnetact-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for gsnetact 0.1.0
File Interpreter ABI Platform Actions
gsnetact-0.1.0-py3-none-any.whl Python 3 none any Details for gsnetact-0.1.0-py3-none-any.whl

Total release size: 108.0 kB

Release files / gsnetact-0.1.0.tar.gz

Download URL gsnetact-0.1.0.tar.gz
Size 55.8 kB
Tags Source
SHA-256 checksum
How to use checksums
ee47d811c7b56c13a679aae1bbb5909bee9453286fcbeac09b853d26bf9cc631
BLAKE2b-256 checksum
How to use checksums
f89163b3f6c8a7f306fb270e106f8dcc449133ea5c5b3820f3312e987c5453a1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.9

Release files / gsnetact-0.1.0-py3-none-any.whl

Download URL gsnetact-0.1.0-py3-none-any.whl
Size 52.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
84c32c5d6993c8e209e3322812e797592fdb38df1dea69daeb2295d4c41e0dbf
BLAKE2b-256 checksum
How to use checksums
734b8a997e48d310162f8fbed43857a5155e82e646866169e21c9df1e1adc2cc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.9

Security for gsnetact 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page