smallregnet 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. smallregnet-0.1.0/LICENSE +133 -0
  2. smallregnet-0.1.0/MANIFEST.in +11 -0
  3. smallregnet-0.1.0/PKG-INFO +201 -0
  4. smallregnet-0.1.0/README.md +168 -0
  5. smallregnet-0.1.0/examples/quickstart.py +91 -0
  6. smallregnet-0.1.0/pyproject.toml +59 -0
  7. smallregnet-0.1.0/setup.cfg +4 -0
  8. smallregnet-0.1.0/src/smallregnet/__init__.py +61 -0
  9. smallregnet-0.1.0/src/smallregnet/adaptation.py +206 -0
  10. smallregnet-0.1.0/src/smallregnet/cohorts.py +90 -0
  11. smallregnet-0.1.0/src/smallregnet/diagnostics.py +27 -0
  12. smallregnet-0.1.0/src/smallregnet/metrics.py +61 -0
  13. smallregnet-0.1.0/src/smallregnet/model.py +823 -0
  14. smallregnet-0.1.0/src/smallregnet/netrex.py +196 -0
  15. smallregnet-0.1.0/src/smallregnet/network_inputs.py +116 -0
  16. smallregnet-0.1.0/src/smallregnet/node_universe.py +33 -0
  17. smallregnet-0.1.0/src/smallregnet/pairs_cap.py +75 -0
  18. smallregnet-0.1.0/src/smallregnet/pilot.py +31 -0
  19. smallregnet-0.1.0/src/smallregnet/provenance.py +28 -0
  20. smallregnet-0.1.0/src/smallregnet/reference_models.py +337 -0
  21. smallregnet-0.1.0/src/smallregnet/reference_registry.py +32 -0
  22. smallregnet-0.1.0/src/smallregnet/refitting.py +35 -0
  23. smallregnet-0.1.0/src/smallregnet/tuning.py +72 -0
  24. smallregnet-0.1.0/src/smallregnet/validation.py +62 -0
  25. smallregnet-0.1.0/src/smallregnet/workflow.py +9 -0
  26. smallregnet-0.1.0/src/smallregnet.egg-info/PKG-INFO +201 -0
  27. smallregnet-0.1.0/src/smallregnet.egg-info/SOURCES.txt +34 -0
  28. smallregnet-0.1.0/src/smallregnet.egg-info/dependency_links.txt +1 -0
  29. smallregnet-0.1.0/src/smallregnet.egg-info/requires.txt +13 -0
  30. smallregnet-0.1.0/src/smallregnet.egg-info/top_level.txt +1 -0
  31. smallregnet-0.1.0/tests/test_adaptation.py +86 -0
  32. smallregnet-0.1.0/tests/test_diagnostics.py +22 -0
  33. smallregnet-0.1.0/tests/test_reference_models.py +226 -0
  34. smallregnet-0.1.0/tests/test_smallregnet_package.py +360 -0
  35. smallregnet-0.1.0/tests/test_tuning.py +36 -0
  36. smallregnet-0.1.0/tests/test_validation.py +39 -0
@@ -0,0 +1,133 @@
1
+ # PolyForm Noncommercial License 1.0.0
2
+
3
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
4
+
5
+ ## Acceptance
6
+
7
+ In order to get any license under these terms, you must agree
8
+ to them as both strict obligations and conditions to all
9
+ your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the
14
+ software to do everything you might do with the software
15
+ that would otherwise infringe the licensor's copyright
16
+ in it for any permitted purpose. However, you may
17
+ only distribute the software according to [Distribution
18
+ License](#distribution-license) and make changes or new works
19
+ based on the software according to [Changes and New Works
20
+ License](#changes-and-new-works-license).
21
+
22
+ ## Distribution License
23
+
24
+ The licensor grants you an additional copyright license
25
+ to distribute copies of the software. Your license
26
+ to distribute covers distributing the software with
27
+ changes and new works permitted by [Changes and New Works
28
+ License](#changes-and-new-works-license).
29
+
30
+ ## Notices
31
+
32
+ You must ensure that anyone who gets a copy of any part of
33
+ the software from you also gets a copy of these terms or the
34
+ URL for them above, as well as copies of any plain-text lines
35
+ beginning with `Required Notice:` that the licensor provided
36
+ with the software. For example:
37
+
38
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
39
+
40
+ ## Changes and New Works License
41
+
42
+ The licensor grants you an additional copyright license to
43
+ make changes and new works based on the software for any
44
+ permitted purpose.
45
+
46
+ ## Patent License
47
+
48
+ The licensor grants you a patent license for the software that
49
+ covers patent claims the licensor can license, or becomes able
50
+ to license, that you would infringe by using the software.
51
+
52
+ ## Noncommercial Purposes
53
+
54
+ Any noncommercial purpose is a permitted purpose.
55
+
56
+ ## Personal Uses
57
+
58
+ Personal use for research, experiment, and testing for
59
+ the benefit of public knowledge, personal study, private
60
+ entertainment, hobby projects, amateur pursuits, or religious
61
+ observance, without any anticipated commercial application,
62
+ is use for a permitted purpose.
63
+
64
+ ## Noncommercial Organizations
65
+
66
+ Use by any charitable organization, educational institution,
67
+ public research organization, public safety or health
68
+ organization, environmental protection organization,
69
+ or government institution is use for a permitted purpose
70
+ regardless of the source of funding or obligations resulting
71
+ from the funding.
72
+
73
+ ## Fair Use
74
+
75
+ You may have "fair use" rights for the software under the
76
+ law. These terms do not limit them.
77
+
78
+ ## No Other Rights
79
+
80
+ These terms do not allow you to sublicense or transfer any of
81
+ your licenses to anyone else, or prevent the licensor from
82
+ granting licenses to anyone else. These terms do not imply
83
+ any other licenses.
84
+
85
+ ## Patent Defense
86
+
87
+ If you make any written claim that the software infringes or
88
+ contributes to infringement of any patent, your patent license
89
+ for the software granted under these terms ends immediately. If
90
+ your company makes such a claim, your patent license ends
91
+ immediately for work on behalf of your company.
92
+
93
+ ## Violations
94
+
95
+ The first time you are notified in writing that you have
96
+ violated any of these terms, or done anything with the software
97
+ not covered by your licenses, your licenses can nonetheless
98
+ continue if you come into full compliance with these terms,
99
+ and take practical steps to correct past violations, within
100
+ 32 days of receiving notice. Otherwise, all your licenses
101
+ end immediately.
102
+
103
+ ## No Liability
104
+
105
+ ***As far as the law allows, the software comes as is, without
106
+ any warranty or condition, and the licensor will not be liable
107
+ to you for any damages arising out of these terms or the use
108
+ or nature of the software, under any kind of legal claim.***
109
+
110
+ ## Definitions
111
+
112
+ The **licensor** is the individual or entity offering these
113
+ terms, and the **software** is the software the licensor makes
114
+ available under these terms.
115
+
116
+ **You** refers to the individual or entity agreeing to these
117
+ terms.
118
+
119
+ **Your company** is any legal entity, sole proprietorship,
120
+ or other kind of organization that you work for, plus all
121
+ organizations that have control over, are under the control of,
122
+ or are under common control with that organization. **Control**
123
+ means ownership of substantially all the assets of an entity,
124
+ or the power to direct its management and policies by vote,
125
+ contract, or otherwise. Control can be direct or indirect.
126
+
127
+ **Your licenses** are all the licenses granted to you for the
128
+ software under these terms.
129
+
130
+ **Use** means anything you do with the software requiring one
131
+ of your licenses.
132
+
133
+ Required Notice: Copyright 2026 Wajdi Dhifli, and SmallRegNet contributors
@@ -0,0 +1,11 @@
1
+ include LICENSE README.md pyproject.toml
2
+ recursive-include src *.py
3
+ recursive-include examples *.py
4
+ exclude tests/*
5
+ include tests/test_adaptation.py
6
+ include tests/test_diagnostics.py
7
+ include tests/test_reference_models.py
8
+ include tests/test_smallregnet_package.py
9
+ include tests/test_tuning.py
10
+ include tests/test_validation.py
11
+ global-exclude *.pyc __pycache__ .DS_Store
@@ -0,0 +1,201 @@
1
+ Metadata-Version: 2.4
2
+ Name: smallregnet
3
+ Version: 0.1.0
4
+ Summary: Prior-guided conditional VAE framework for gene regulatory network adaptation in small transcriptomic cohorts
5
+ Author-email: Wajdi Dhifli <wajdi.dhifli@univ-lille.fr>, Ali Assi <ali.assi@rit.edu>, Allan De Clercq <allan.de-clercq@chu-lyon.fr>, Quentin Kalinka <q.kalinka@genesdiffusion.com>, Nour Elislem Karabadji <n.karabadji@ensti-annaba.dz>, Mohamed Elati <mohamed.elati@univ-lille.fr>
6
+ License-Expression: PolyForm-Noncommercial-1.0.0
7
+ Project-URL: Homepage, https://github.com/wajdidhifli/SmallRegNet
8
+ Project-URL: Repository, https://github.com/wajdidhifli/SmallRegNet
9
+ Project-URL: Issues, https://github.com/wajdidhifli/SmallRegNet/issues
10
+ Keywords: gene-regulatory-networks,variational-autoencoder,transfer-learning,transcriptomics,bioinformatics
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: numpy<3,>=1.24
22
+ Requires-Dist: pandas>=2
23
+ Requires-Dist: scipy>=1.10
24
+ Requires-Dist: scikit-learn>=1.3
25
+ Requires-Dist: torch>=2.2
26
+ Provides-Extra: inference
27
+ Requires-Dist: pyhlicorn>=0.1.3; extra == "inference"
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=8; extra == "dev"
30
+ Requires-Dist: build>=1; extra == "dev"
31
+ Requires-Dist: twine>=5; extra == "dev"
32
+ Dynamic: license-file
33
+
34
+ # SmallRegNet
35
+
36
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
37
+ [![License: PolyForm Noncommercial 1.0.0](https://img.shields.io/badge/License-PolyForm%20Noncommercial%201.0.0-orange.svg)](LICENSE)
38
+
39
+ **SmallRegNet** is a Python package and reproducible study repository for **gene regulatory network (GRN) adaptation in small transcriptomic cohorts** using conditional variational autoencoders (CVAEs) and prior-guided learning.
40
+
41
+ ---
42
+
43
+ ## Method Overview
44
+
45
+ When adapting a tissue-matched reference GRN $W_0 \in \mathbb{R}^{g \times p}$ ($g$ target genes, $p$ transcription factors) to a small target cohort of $N \ll p$ donors, SmallRegNet combines:
46
+
47
+ 1. **Reference Conditional VAE ($D_0$):** A conditional Gaussian prior $p(z \mid r) = \mathcal{N}(r, \tau^2 I_p)$ ($\tau^2 = 0.1$) centered on measured TF expression $r$, paired with a linear Gaussian decoder $p_\theta(x \mid z) = \mathcal{N}(W_{\mathrm{dec}} z, \sigma^2 I_g)$ constrained to the reference network support mask $M_{ij} = \mathbf{1}\{|W_{0,ij}| > 10^{-6}\}$.
48
+ 2. **Probabilistic Discrepancy Scoring:** Marginalizing $z$ yields the gene-level predictive variance $v_i = \tau^2 \|W_{\mathrm{dec}, i:}\|_2^2 + \sigma^2$ and normalized target discrepancy score $S_i = \frac{1}{N v_i}\sum_{a=1}^N [x_{ai} - (W_{\mathrm{dec}} r_a)_i]^2$.
49
+ 3. **Prior-Anchored Adaptation with Unpenalized Intercept:** For each target gene $i$, SmallRegNet solves the weighted quadratic objective around $w_{0i} = W_{0,i:}^\top$:
50
+
51
+ $$\min_{\delta_i, \alpha_i} \frac{\|e_i - \alpha_i \mathbf{1}_N - R\delta_i\|_2^2}{Ng} + \frac{\mu_i}{2}\delta_i^\top D_i \delta_i, \qquad e_i = X_{:i} - R w_{0i}$$
52
+
53
+ with $\mu_i = \mu_0 / (\log(1 + S_i) + \epsilon)$ (or constant $\mu_i = \mu_0$ for the **VAE-free uniform-anchor variant**) and $D_{i,jj} = (|W_{0,ij}|^{1/2} + \epsilon)^{-1}$.
54
+ 4. **Exact Patient-Space Optimization:** Using the centering matrix $H = I_N - \mathbf{1}_N \mathbf{1}_N^\top / N$ and Woodbury matrix identity, the $p$-dimensional linear system reduces exactly to an $N \times N$ patient-space solve per target batch, with $\mu_0$ selected via 3-fold stratified masked-gene cross-validation within the adaptation cohort.
55
+
56
+ ---
57
+
58
+ ## Installation
59
+
60
+ Install the core package from PyPI:
61
+
62
+ ```bash
63
+ pip install smallregnet
64
+ ```
65
+
66
+ Optional extras:
67
+
68
+ - **Reference / silver-standard inference via [pyHLicorn](https://pypi.org/project/pyhlicorn/)** (GPL-3.0-or-later):
69
+ ```bash
70
+ pip install "smallregnet[inference]"
71
+ ```
72
+ - **Development and testing tools**:
73
+ ```bash
74
+ pip install "smallregnet[dev]"
75
+ ```
76
+
77
+ From a local clone of this repository:
78
+
79
+ ```bash
80
+ git clone https://github.com/wajdidhifli/SmallRegNet.git
81
+ cd SmallRegNet
82
+ pip install -e ".[dev]"
83
+ ```
84
+
85
+ ---
86
+
87
+ ## Quickstart
88
+
89
+ **Shape conventions:**
90
+ - `prior_weights`: shape `(n_targets, n_regulators)` ($W_0 \in \mathbb{R}^{g \times p}$)
91
+ - `regulators`: shape `(n_samples, n_regulators)` ($R \in \mathbb{R}^{N \times p}$)
92
+ - `targets`: shape `(n_samples, n_targets)` ($X \in \mathbb{R}^{N \times g}$)
93
+
94
+ ### 1. Primary SmallRegNet (CVAE Discrepancy + Unpenalized Intercept)
95
+
96
+ ```python
97
+ import numpy as np
98
+ from smallregnet import SmallRegNet
99
+
100
+ # Fits ReferenceVAE on the reference cohort (r_ref, x_ref), selects mu0 via
101
+ # 3-fold masked-gene CV on (r_adapt, x_adapt), and solves the exact patient-space system.
102
+ model = SmallRegNet(scoring="vae", intercept=True, gated=False)
103
+ model.fit(prior_weights, r_ref, x_ref, r_adapt, x_adapt)
104
+
105
+ # Inspect adapted network, per-gene offsets, discrepancy scores, and held-out predictions
106
+ w_hat = model.weights_ # W0 + delta
107
+ delta = model.delta_ # quantitative regulatory weight changes
108
+ offsets = model.intercept_ # gene-specific intercepts alpha_i
109
+ scores = model.discrepancy_scores_ # gene-level discrepancy scores S_i
110
+ x_pred = model.predict(r_eval) # alpha_i + R_eval @ W_hat^T
111
+ w_thr = model.thresholded_weights(cutoff=1e-4)
112
+ ```
113
+
114
+ Using a pre-trained frozen `ReferenceVAE` checkpoint directly:
115
+
116
+ ```python
117
+ est = SmallRegNet.from_reference_model(trained_vae, prior_weights=prior_df)
118
+ est.fit_adaptation(r_adapt_df, x_adapt_df, sex=donor_sex)
119
+ top_shifts = est.top_edge_changes(n=20)
120
+ metrics = est.evaluate_ranking(silver_df)
121
+ ```
122
+
123
+ ### 2. VAE-Free Uniform-Anchor Variant (`scoring="uniform"`)
124
+
125
+ Replaces gene-specific discrepancy weighting with a uniform regularization strength $\mu_i = \mu_0$ while retaining the same edge penalties $D_i$, unpenalized intercept $\alpha_i$, and patient-space Woodbury solver:
126
+
127
+ ```python
128
+ uniform = SmallRegNet(scoring="uniform", intercept=True, gated=False)
129
+ uniform.fit_adaptation(r_adapt, x_adapt, prior_weights=prior_weights)
130
+ ```
131
+
132
+ ### 3. Exporting the Adapted Network & PyHLicorn Interoperability
133
+
134
+ `SmallRegNet` reads `PyHLicorn` GRNs (`network.json`, `network.json.gz`, or `pyhlicorn.Network`) via `load_pyhlicorn_prior(...)` (or directly as `prior_weights`) and exports the adapted network in matrix, edge-list, summary, and `PyHLicorn`-compatible JSON formats:
135
+
136
+ ```python
137
+ # Export full weight matrix, filtered edge list (|w| > 1e-6), gene summary, and network.json.gz
138
+ files = model.export_network("results/adapted_brca", cutoff=1e-6, prefix="tumor")
139
+
140
+ # Individual in-memory or standalone exports
141
+ edges_df = model.to_edge_list(cutoff=1e-4)
142
+ gene_df = model.gene_summary(cutoff=1e-4)
143
+ model.export_pyhlicorn_json("results/adapted_network.json.gz", cutoff=1e-6)
144
+ net = model.to_pyhlicorn_network(cutoff=1e-6) # requires smallregnet[inference]
145
+ ```
146
+
147
+ ### 4. Supported Manuscript Variants & Solvers
148
+
149
+ All methodological variants evaluated in Table 2 of the manuscript are available directly through `SmallRegNet(...)`:
150
+
151
+ | Manuscript Formulation | `scoring` | `intercept` | `gated` |
152
+ |---|---|---|---|
153
+ | **Ungated VAE (Primary SmallRegNet)** | `"vae"` | `True` | `False` |
154
+ | **Uniform anchor (VAE-free)** | `"uniform"` | `True` | `False` |
155
+ | Raw residual | `"raw"` | `True` | `False` |
156
+ | Gated VAE | `"vae"` | `True` | `True` |
157
+ | Gated reference residual | `"reference_residual"` | `True` | `True` |
158
+ | Any variant without intercept ($\alpha_i = 0$) | any above | `False` | `False` / `True` |
159
+
160
+ For low-level direct optimization with precomputed $\mu_i$, use `solve_anchored_weights(...)` (or `anchored_l2(...)` for the original no-intercept active-mask API).
161
+
162
+ See [examples/quickstart.py](examples/quickstart.py) for a complete runnable script on DataFrames.
163
+
164
+ ---
165
+
166
+ ## Running Tests
167
+
168
+ ```bash
169
+ OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 pytest
170
+ ```
171
+
172
+ In the full research repository (with frozen local transcriptomic caches and checkpoints under `data/` and `outputs/`), `tests/test_smallregnet_package.py` also verifies bit-level reproduction (`1e-12` weight tolerance) of the published `N = 35` BRCA and LUAD adaptation weights and Table 2 normalized average precision (`nAP`) values. In clean standalone package installs without local study archives, those data-dependent checks are skipped automatically while all unit and solver-equivalence tests run.
173
+
174
+ ---
175
+
176
+ ## Reproducing the Manuscript Experiments
177
+
178
+ All study manifests (`manifests/`), frozen configuration files (`configs/`), evaluation scripts (`scripts/`), public data source URLs, and step-by-step reproduction commands are documented in [docs/REPRODUCIBILITY.md](docs/REPRODUCIBILITY.md).
179
+
180
+ - **Expression data:** UCSC Xena Toil RNA-seq Recompute hub (<https://xenabrowser.net/datapages/?host=https%3A%2F%2Ftoil.xenahubs.net>)
181
+ - **Curated interactions:** CollecTRI v2.0 (<https://zenodo.org/records/8192729>)
182
+ - **Cooperative reference/de novo inference:** [pyHLicorn](https://github.com/wajdidhifli/PyHLicorn) (`pip install pyhlicorn`)
183
+ - **Comparator:** [NetREX](https://github.com/ncbi/NetREX)
184
+
185
+ ---
186
+
187
+ ## Authors & Citation
188
+
189
+ Wajdi Dhifli, Ali Assi, Allan De Clercq, Quentin Kalinka, Nour Elislem Karabadji, and Mohamed Elati.
190
+
191
+ > *SmallRegNet: gene regulatory network adaptation in small transcriptomic cohorts using variational autoencoders and prior-guided learning*
192
+
193
+ ---
194
+
195
+ ## License
196
+
197
+ `smallregnet` is distributed under the [PolyForm Noncommercial License 1.0.0](LICENSE) (`PolyForm-Noncommercial-1.0.0`), permitting any noncommercial purpose including academic, educational, and public research use.
198
+
199
+ > Required Notice: Copyright 2026 Wajdi Dhifli, and SmallRegNet contributors
200
+
201
+ Note that optional cooperative GRN inference via `pyhlicorn` (`smallregnet[inference]`) is distributed separately under `GPL-3.0-or-later` and is not bundled with the core `smallregnet` distribution.
@@ -0,0 +1,168 @@
1
+ # SmallRegNet
2
+
3
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
4
+ [![License: PolyForm Noncommercial 1.0.0](https://img.shields.io/badge/License-PolyForm%20Noncommercial%201.0.0-orange.svg)](LICENSE)
5
+
6
+ **SmallRegNet** is a Python package and reproducible study repository for **gene regulatory network (GRN) adaptation in small transcriptomic cohorts** using conditional variational autoencoders (CVAEs) and prior-guided learning.
7
+
8
+ ---
9
+
10
+ ## Method Overview
11
+
12
+ When adapting a tissue-matched reference GRN $W_0 \in \mathbb{R}^{g \times p}$ ($g$ target genes, $p$ transcription factors) to a small target cohort of $N \ll p$ donors, SmallRegNet combines:
13
+
14
+ 1. **Reference Conditional VAE ($D_0$):** A conditional Gaussian prior $p(z \mid r) = \mathcal{N}(r, \tau^2 I_p)$ ($\tau^2 = 0.1$) centered on measured TF expression $r$, paired with a linear Gaussian decoder $p_\theta(x \mid z) = \mathcal{N}(W_{\mathrm{dec}} z, \sigma^2 I_g)$ constrained to the reference network support mask $M_{ij} = \mathbf{1}\{|W_{0,ij}| > 10^{-6}\}$.
15
+ 2. **Probabilistic Discrepancy Scoring:** Marginalizing $z$ yields the gene-level predictive variance $v_i = \tau^2 \|W_{\mathrm{dec}, i:}\|_2^2 + \sigma^2$ and normalized target discrepancy score $S_i = \frac{1}{N v_i}\sum_{a=1}^N [x_{ai} - (W_{\mathrm{dec}} r_a)_i]^2$.
16
+ 3. **Prior-Anchored Adaptation with Unpenalized Intercept:** For each target gene $i$, SmallRegNet solves the weighted quadratic objective around $w_{0i} = W_{0,i:}^\top$:
17
+
18
+ $$\min_{\delta_i, \alpha_i} \frac{\|e_i - \alpha_i \mathbf{1}_N - R\delta_i\|_2^2}{Ng} + \frac{\mu_i}{2}\delta_i^\top D_i \delta_i, \qquad e_i = X_{:i} - R w_{0i}$$
19
+
20
+ with $\mu_i = \mu_0 / (\log(1 + S_i) + \epsilon)$ (or constant $\mu_i = \mu_0$ for the **VAE-free uniform-anchor variant**) and $D_{i,jj} = (|W_{0,ij}|^{1/2} + \epsilon)^{-1}$.
21
+ 4. **Exact Patient-Space Optimization:** Using the centering matrix $H = I_N - \mathbf{1}_N \mathbf{1}_N^\top / N$ and Woodbury matrix identity, the $p$-dimensional linear system reduces exactly to an $N \times N$ patient-space solve per target batch, with $\mu_0$ selected via 3-fold stratified masked-gene cross-validation within the adaptation cohort.
22
+
23
+ ---
24
+
25
+ ## Installation
26
+
27
+ Install the core package from PyPI:
28
+
29
+ ```bash
30
+ pip install smallregnet
31
+ ```
32
+
33
+ Optional extras:
34
+
35
+ - **Reference / silver-standard inference via [pyHLicorn](https://pypi.org/project/pyhlicorn/)** (GPL-3.0-or-later):
36
+ ```bash
37
+ pip install "smallregnet[inference]"
38
+ ```
39
+ - **Development and testing tools**:
40
+ ```bash
41
+ pip install "smallregnet[dev]"
42
+ ```
43
+
44
+ From a local clone of this repository:
45
+
46
+ ```bash
47
+ git clone https://github.com/wajdidhifli/SmallRegNet.git
48
+ cd SmallRegNet
49
+ pip install -e ".[dev]"
50
+ ```
51
+
52
+ ---
53
+
54
+ ## Quickstart
55
+
56
+ **Shape conventions:**
57
+ - `prior_weights`: shape `(n_targets, n_regulators)` ($W_0 \in \mathbb{R}^{g \times p}$)
58
+ - `regulators`: shape `(n_samples, n_regulators)` ($R \in \mathbb{R}^{N \times p}$)
59
+ - `targets`: shape `(n_samples, n_targets)` ($X \in \mathbb{R}^{N \times g}$)
60
+
61
+ ### 1. Primary SmallRegNet (CVAE Discrepancy + Unpenalized Intercept)
62
+
63
+ ```python
64
+ import numpy as np
65
+ from smallregnet import SmallRegNet
66
+
67
+ # Fits ReferenceVAE on the reference cohort (r_ref, x_ref), selects mu0 via
68
+ # 3-fold masked-gene CV on (r_adapt, x_adapt), and solves the exact patient-space system.
69
+ model = SmallRegNet(scoring="vae", intercept=True, gated=False)
70
+ model.fit(prior_weights, r_ref, x_ref, r_adapt, x_adapt)
71
+
72
+ # Inspect adapted network, per-gene offsets, discrepancy scores, and held-out predictions
73
+ w_hat = model.weights_ # W0 + delta
74
+ delta = model.delta_ # quantitative regulatory weight changes
75
+ offsets = model.intercept_ # gene-specific intercepts alpha_i
76
+ scores = model.discrepancy_scores_ # gene-level discrepancy scores S_i
77
+ x_pred = model.predict(r_eval) # alpha_i + R_eval @ W_hat^T
78
+ w_thr = model.thresholded_weights(cutoff=1e-4)
79
+ ```
80
+
81
+ Using a pre-trained frozen `ReferenceVAE` checkpoint directly:
82
+
83
+ ```python
84
+ est = SmallRegNet.from_reference_model(trained_vae, prior_weights=prior_df)
85
+ est.fit_adaptation(r_adapt_df, x_adapt_df, sex=donor_sex)
86
+ top_shifts = est.top_edge_changes(n=20)
87
+ metrics = est.evaluate_ranking(silver_df)
88
+ ```
89
+
90
+ ### 2. VAE-Free Uniform-Anchor Variant (`scoring="uniform"`)
91
+
92
+ Replaces gene-specific discrepancy weighting with a uniform regularization strength $\mu_i = \mu_0$ while retaining the same edge penalties $D_i$, unpenalized intercept $\alpha_i$, and patient-space Woodbury solver:
93
+
94
+ ```python
95
+ uniform = SmallRegNet(scoring="uniform", intercept=True, gated=False)
96
+ uniform.fit_adaptation(r_adapt, x_adapt, prior_weights=prior_weights)
97
+ ```
98
+
99
+ ### 3. Exporting the Adapted Network & PyHLicorn Interoperability
100
+
101
+ `SmallRegNet` reads `PyHLicorn` GRNs (`network.json`, `network.json.gz`, or `pyhlicorn.Network`) via `load_pyhlicorn_prior(...)` (or directly as `prior_weights`) and exports the adapted network in matrix, edge-list, summary, and `PyHLicorn`-compatible JSON formats:
102
+
103
+ ```python
104
+ # Export full weight matrix, filtered edge list (|w| > 1e-6), gene summary, and network.json.gz
105
+ files = model.export_network("results/adapted_brca", cutoff=1e-6, prefix="tumor")
106
+
107
+ # Individual in-memory or standalone exports
108
+ edges_df = model.to_edge_list(cutoff=1e-4)
109
+ gene_df = model.gene_summary(cutoff=1e-4)
110
+ model.export_pyhlicorn_json("results/adapted_network.json.gz", cutoff=1e-6)
111
+ net = model.to_pyhlicorn_network(cutoff=1e-6) # requires smallregnet[inference]
112
+ ```
113
+
114
+ ### 4. Supported Manuscript Variants & Solvers
115
+
116
+ All methodological variants evaluated in Table 2 of the manuscript are available directly through `SmallRegNet(...)`:
117
+
118
+ | Manuscript Formulation | `scoring` | `intercept` | `gated` |
119
+ |---|---|---|---|
120
+ | **Ungated VAE (Primary SmallRegNet)** | `"vae"` | `True` | `False` |
121
+ | **Uniform anchor (VAE-free)** | `"uniform"` | `True` | `False` |
122
+ | Raw residual | `"raw"` | `True` | `False` |
123
+ | Gated VAE | `"vae"` | `True` | `True` |
124
+ | Gated reference residual | `"reference_residual"` | `True` | `True` |
125
+ | Any variant without intercept ($\alpha_i = 0$) | any above | `False` | `False` / `True` |
126
+
127
+ For low-level direct optimization with precomputed $\mu_i$, use `solve_anchored_weights(...)` (or `anchored_l2(...)` for the original no-intercept active-mask API).
128
+
129
+ See [examples/quickstart.py](examples/quickstart.py) for a complete runnable script on DataFrames.
130
+
131
+ ---
132
+
133
+ ## Running Tests
134
+
135
+ ```bash
136
+ OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 pytest
137
+ ```
138
+
139
+ In the full research repository (with frozen local transcriptomic caches and checkpoints under `data/` and `outputs/`), `tests/test_smallregnet_package.py` also verifies bit-level reproduction (`1e-12` weight tolerance) of the published `N = 35` BRCA and LUAD adaptation weights and Table 2 normalized average precision (`nAP`) values. In clean standalone package installs without local study archives, those data-dependent checks are skipped automatically while all unit and solver-equivalence tests run.
140
+
141
+ ---
142
+
143
+ ## Reproducing the Manuscript Experiments
144
+
145
+ All study manifests (`manifests/`), frozen configuration files (`configs/`), evaluation scripts (`scripts/`), public data source URLs, and step-by-step reproduction commands are documented in [docs/REPRODUCIBILITY.md](docs/REPRODUCIBILITY.md).
146
+
147
+ - **Expression data:** UCSC Xena Toil RNA-seq Recompute hub (<https://xenabrowser.net/datapages/?host=https%3A%2F%2Ftoil.xenahubs.net>)
148
+ - **Curated interactions:** CollecTRI v2.0 (<https://zenodo.org/records/8192729>)
149
+ - **Cooperative reference/de novo inference:** [pyHLicorn](https://github.com/wajdidhifli/PyHLicorn) (`pip install pyhlicorn`)
150
+ - **Comparator:** [NetREX](https://github.com/ncbi/NetREX)
151
+
152
+ ---
153
+
154
+ ## Authors & Citation
155
+
156
+ Wajdi Dhifli, Ali Assi, Allan De Clercq, Quentin Kalinka, Nour Elislem Karabadji, and Mohamed Elati.
157
+
158
+ > *SmallRegNet: gene regulatory network adaptation in small transcriptomic cohorts using variational autoencoders and prior-guided learning*
159
+
160
+ ---
161
+
162
+ ## License
163
+
164
+ `smallregnet` is distributed under the [PolyForm Noncommercial License 1.0.0](LICENSE) (`PolyForm-Noncommercial-1.0.0`), permitting any noncommercial purpose including academic, educational, and public research use.
165
+
166
+ > Required Notice: Copyright 2026 Wajdi Dhifli, and SmallRegNet contributors
167
+
168
+ Note that optional cooperative GRN inference via `pyhlicorn` (`smallregnet[inference]`) is distributed separately under `GPL-3.0-or-later` and is not bundled with the core `smallregnet` distribution.
@@ -0,0 +1,91 @@
1
+ """Self-contained quickstart illustrating SmallRegNet and its uniform-anchor variant.
2
+
3
+ Both matrices follow the package convention:
4
+ - prior_weights: shape (n_targets, n_regulators)
5
+ - expression matrices (regulators, targets): shape (n_samples, n_features)
6
+ """
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+ from smallregnet import SmallRegNet
11
+
12
+
13
+ def make_synthetic_cohort():
14
+ rng = np.random.default_rng(42)
15
+ n_tfs, n_targets = 40, 24
16
+ tfs = [f"TF_{i:02d}" for i in range(n_tfs)]
17
+ targets = [f"GENE_{i:02d}" for i in range(n_targets)]
18
+
19
+ # Sparse reference network W0 (targets x regulators)
20
+ w0 = rng.normal(scale=0.5, size=(n_targets, n_tfs)) * (rng.uniform(size=(n_targets, n_tfs)) > 0.85)
21
+ prior_df = pd.DataFrame(w0, index=targets, columns=tfs)
22
+
23
+ # Normal reference cohort (large sample size n0 = 120)
24
+ r_ref = pd.DataFrame(rng.normal(size=(120, n_tfs)), columns=tfs)
25
+ x_ref = pd.DataFrame(
26
+ r_ref.to_numpy() @ w0.T + rng.normal(scale=0.15, size=(120, n_targets)),
27
+ columns=targets,
28
+ )
29
+
30
+ # Target disease network W_tumor = W0 + selective rewiring + systematic expression offsets
31
+ w_tumor = w0.copy()
32
+ mask = np.abs(w0) > 1e-6
33
+ w_tumor[mask] += rng.normal(scale=0.35, size=int(mask.sum()))
34
+ offsets = rng.normal(loc=0.8, scale=0.4, size=n_targets)
35
+
36
+ # Small adaptation cohort (N = 20 < n_tfs = 40) and held-out test donors (N_eval = 50)
37
+ r_adapt = pd.DataFrame(rng.normal(size=(20, n_tfs)), index=[f"ADAPT_{i:02d}" for i in range(20)], columns=tfs)
38
+ x_adapt = pd.DataFrame(
39
+ r_adapt.to_numpy() @ w_tumor.T + offsets + rng.normal(scale=0.15, size=(20, n_targets)),
40
+ index=r_adapt.index,
41
+ columns=targets,
42
+ )
43
+ r_eval = pd.DataFrame(rng.normal(size=(50, n_tfs)), index=[f"EVAL_{i:02d}" for i in range(50)], columns=tfs)
44
+ x_eval = pd.DataFrame(
45
+ r_eval.to_numpy() @ w_tumor.T + offsets + rng.normal(scale=0.15, size=(50, n_targets)),
46
+ index=r_eval.index,
47
+ columns=targets,
48
+ )
49
+ silver_df = pd.DataFrame(w_tumor, index=targets, columns=tfs)
50
+ return prior_df, r_ref, x_ref, r_adapt, x_adapt, r_eval, x_eval, silver_df
51
+
52
+
53
+ def main():
54
+ prior_df, r_ref, x_ref, r_adapt, x_adapt, r_eval, x_eval, silver_df = make_synthetic_cohort()
55
+
56
+ # 1. Primary manuscript SmallRegNet: CVAE predictive-variance discrepancy + intercept (fast demo steps)
57
+ vae_model = SmallRegNet(
58
+ scoring="vae",
59
+ intercept=True,
60
+ gated=False,
61
+ reference_steps=400,
62
+ warmup_steps=50,
63
+ )
64
+ vae_model.fit(prior_df, r_ref, x_ref, r_adapt, x_adapt)
65
+ vae_eval = vae_model.evaluate_ranking(silver_df)
66
+ vae_mse = float(np.square(x_eval - vae_model.predict(r_eval)).to_numpy().mean())
67
+
68
+ # 2. VAE-free Uniform-Anchor ablation: constant mu_i = mu_0 across target genes + intercept
69
+ uniform_model = SmallRegNet(scoring="uniform", intercept=True, gated=False)
70
+ uniform_model.fit_adaptation(r_adapt, x_adapt, prior_weights=prior_df)
71
+ uni_eval = uniform_model.evaluate_ranking(silver_df)
72
+ uni_mse = float(np.square(x_eval - uniform_model.predict(r_eval)).to_numpy().mean())
73
+
74
+ print("=== SmallRegNet (VAE discrepancy + intercept) ===")
75
+ print(f"Selected mu0={vae_model.selected_strength_:g}, nAP={vae_eval['nAP']:.4f}, held-out MSE={vae_mse:.4f}")
76
+ print("\nTop 5 adapted edge changes (|delta_ij|):")
77
+ print(vae_model.top_edge_changes(5).to_string(index=False))
78
+ print("\nTop 5 adapted edges in edge-list export (|weight| > 1e-6):")
79
+ print(vae_model.to_edge_list(cutoff=1e-6).head(5).to_string(index=False))
80
+
81
+ import tempfile
82
+ with tempfile.TemporaryDirectory() as tmpdir:
83
+ exported = vae_model.export_network(tmpdir, cutoff=1e-6, prefix="demo")
84
+ print("\nExported artifacts:", {k: v.name for k, v in exported.items()})
85
+
86
+ print("\n=== Uniform Anchor (VAE-free + intercept) ===")
87
+ print(f"Selected mu0={uniform_model.selected_strength_:g}, nAP={uni_eval['nAP']:.4f}, held-out MSE={uni_mse:.4f}")
88
+
89
+
90
+ if __name__ == "__main__":
91
+ main()
@@ -0,0 +1,59 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "smallregnet"
7
+ version = "0.1.0"
8
+ description = "Prior-guided conditional VAE framework for gene regulatory network adaptation in small transcriptomic cohorts"
9
+ readme = "README.md"
10
+ license = "PolyForm-Noncommercial-1.0.0"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ authors = [
14
+ { name = "Wajdi Dhifli", email = "wajdi.dhifli@univ-lille.fr" },
15
+ { name = "Ali Assi", email = "ali.assi@rit.edu" },
16
+ { name = "Allan De Clercq", email = "allan.de-clercq@chu-lyon.fr" },
17
+ { name = "Quentin Kalinka", email = "q.kalinka@genesdiffusion.com" },
18
+ { name = "Nour Elislem Karabadji", email = "n.karabadji@ensti-annaba.dz" },
19
+ { name = "Mohamed Elati", email = "mohamed.elati@univ-lille.fr" },
20
+ ]
21
+ keywords = [
22
+ "gene-regulatory-networks",
23
+ "variational-autoencoder",
24
+ "transfer-learning",
25
+ "transcriptomics",
26
+ "bioinformatics",
27
+ ]
28
+ classifiers = [
29
+ "Development Status :: 4 - Beta",
30
+ "Intended Audience :: Science/Research",
31
+ "Programming Language :: Python :: 3",
32
+ "Programming Language :: Python :: 3.11",
33
+ "Programming Language :: Python :: 3.12",
34
+ "Programming Language :: Python :: 3.13",
35
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
36
+ ]
37
+ dependencies = [
38
+ "numpy>=1.24,<3",
39
+ "pandas>=2",
40
+ "scipy>=1.10",
41
+ "scikit-learn>=1.3",
42
+ "torch>=2.2",
43
+ ]
44
+
45
+ [project.optional-dependencies]
46
+ inference = ["pyhlicorn>=0.1.3"]
47
+ dev = ["pytest>=8", "build>=1", "twine>=5"]
48
+
49
+ [project.urls]
50
+ Homepage = "https://github.com/wajdidhifli/SmallRegNet"
51
+ Repository = "https://github.com/wajdidhifli/SmallRegNet"
52
+ Issues = "https://github.com/wajdidhifli/SmallRegNet/issues"
53
+
54
+ [tool.setuptools.packages.find]
55
+ where = ["src"]
56
+
57
+ [tool.pytest.ini_options]
58
+ testpaths = ["tests"]
59
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+