xchroma 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 (53) hide show
  1. xchroma-0.1.0/LICENSE +21 -0
  2. xchroma-0.1.0/PACKAGE.md +63 -0
  3. xchroma-0.1.0/PKG-INFO +100 -0
  4. xchroma-0.1.0/README.md +95 -0
  5. xchroma-0.1.0/pyproject.toml +64 -0
  6. xchroma-0.1.0/setup.cfg +4 -0
  7. xchroma-0.1.0/xatac/__init__.py +3 -0
  8. xchroma-0.1.0/xatac/config.json +29 -0
  9. xchroma-0.1.0/xatac/data.py +119 -0
  10. xchroma-0.1.0/xatac/io.py +59 -0
  11. xchroma-0.1.0/xatac/loss.py +106 -0
  12. xchroma-0.1.0/xatac/model.py +123 -0
  13. xchroma-0.1.0/xatac/predict.py +111 -0
  14. xchroma-0.1.0/xatac/sites.py +135 -0
  15. xchroma-0.1.0/xatac/train.py +256 -0
  16. xchroma-0.1.0/xatac/windows.py +97 -0
  17. xchroma-0.1.0/xbench/__init__.py +1 -0
  18. xchroma-0.1.0/xbench/metrics/__init__.py +27 -0
  19. xchroma-0.1.0/xbench/metrics/_pollard.py +46 -0
  20. xchroma-0.1.0/xbench/metrics/contact_directionality.py +23 -0
  21. xchroma-0.1.0/xbench/metrics/distance_enrichment.py +23 -0
  22. xchroma-0.1.0/xbench/metrics/eigenvector.py +35 -0
  23. xchroma-0.1.0/xbench/metrics/fine_structure.py +21 -0
  24. xchroma-0.1.0/xbench/metrics/insulation.py +28 -0
  25. xchroma-0.1.0/xbench/metrics/loop_strength.py +67 -0
  26. xchroma-0.1.0/xbench/metrics/mse.py +10 -0
  27. xchroma-0.1.0/xbench/metrics/pearson.py +16 -0
  28. xchroma-0.1.0/xbench/metrics/scc.py +10 -0
  29. xchroma-0.1.0/xbench/metrics/spearman.py +10 -0
  30. xchroma-0.1.0/xbench/metrics/ssim.py +15 -0
  31. xchroma-0.1.0/xbench/metrics/vendor/pollard/NOTICE.md +10 -0
  32. xchroma-0.1.0/xbench/metrics/vendor/pollard/hicrep.py +84 -0
  33. xchroma-0.1.0/xbench/metrics/vendor/pollard/scoring.py +732 -0
  34. xchroma-0.1.0/xchroma/__init__.py +14 -0
  35. xchroma-0.1.0/xchroma/__main__.py +4 -0
  36. xchroma-0.1.0/xchroma/cli.py +37 -0
  37. xchroma-0.1.0/xchroma.egg-info/PKG-INFO +100 -0
  38. xchroma-0.1.0/xchroma.egg-info/SOURCES.txt +51 -0
  39. xchroma-0.1.0/xchroma.egg-info/dependency_links.txt +1 -0
  40. xchroma-0.1.0/xchroma.egg-info/entry_points.txt +2 -0
  41. xchroma-0.1.0/xchroma.egg-info/requires.txt +16 -0
  42. xchroma-0.1.0/xchroma.egg-info/top_level.txt +4 -0
  43. xchroma-0.1.0/xtrain/checkpoints/current_model.json +115 -0
  44. xchroma-0.1.0/xtrain/checkpoints/verify.py +75 -0
  45. xchroma-0.1.0/xtrain/data.py +207 -0
  46. xchroma-0.1.0/xtrain/inputs.py +254 -0
  47. xchroma-0.1.0/xtrain/licenses/Selene.txt +32 -0
  48. xchroma-0.1.0/xtrain/model.py +280 -0
  49. xchroma-0.1.0/xtrain/predict.py +153 -0
  50. xchroma-0.1.0/xtrain/preprocess/atac/bigwig_to_memmap.py +74 -0
  51. xchroma-0.1.0/xtrain/preprocess/atac/scatac_pipeline.sh +75 -0
  52. xchroma-0.1.0/xtrain/train.py +243 -0
  53. xchroma-0.1.0/xtrain/x_utils.py +298 -0
xchroma-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hansen lab at MIT
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,63 @@
1
+ # XChroma
2
+
3
+ XChroma predicts cell-type-specific 3D genome contacts at 1-kb resolution from
4
+ DNA and chromatin accessibility. DNA-only prediction first uses a cell-specific
5
+ xATAC model to supply the accessibility input.
6
+
7
+ This package runs on your own computer or GPU server. It does not send DNA to
8
+ xchroma.ai. Model checkpoints are downloaded separately from the official
9
+ [GitHub Releases](https://github.com/ahansenlab/XChroma/releases).
10
+
11
+ ## Install
12
+
13
+ Python 3.10–3.12 is supported. For GPU use, install the PyTorch build appropriate
14
+ for your CUDA platform before installing XChroma.
15
+
16
+ ```bash
17
+ python -m pip install xchroma
18
+ xchroma --version
19
+ xchroma --help
20
+ ```
21
+
22
+ For data preparation or scoring, optional dependencies can be installed with
23
+ `python -m pip install 'xchroma[prepare]'` or `python -m pip install 'xchroma[metrics]'`.
24
+ To install from a source checkout instead, run `python -m pip install .` in the repository root.
25
+
26
+ ## Predict a 3D genome map
27
+
28
+ Download the ten contact-model checkpoints from the official release and verify
29
+ them before prediction:
30
+
31
+ ```bash
32
+ xchroma weights --weights-dir weights
33
+ xchroma predict \
34
+ --genome-fa /path/to/hg38.fa \
35
+ --atac-dir /path/to/cell_atac \
36
+ --assembly hg38 \
37
+ --region chr8:127000000-128000000 \
38
+ --weights-dir weights \
39
+ --device cuda \
40
+ --out outputs/MYC.dna-atac
41
+ ```
42
+
43
+ The output is a 1,000 × 1,000 matrix in `prediction.npz`, with a provenance
44
+ manifest. Replace `--device cuda` with `--device cpu --threads 8` to use a CPU.
45
+ Input coordinates are 0-based and half-open; an interval spans exactly 1 Mb.
46
+
47
+ For DNA-only inference, `xchroma atac` runs the existing cell-specific xATAC
48
+ predictor. Pass its normalized NPZ to `xchroma predict --atac-npz` as described
49
+ in the [DNA-only guide](https://github.com/ahansenlab/XChroma#predict-a-contact-map-from-dna-only).
50
+ Cell-specific checkpoints and their registered calibration are required.
51
+
52
+ ## Existing interfaces
53
+
54
+ The package retains `python -m xtrain.predict`, `python -m xatac.predict`,
55
+ `python -m xtrain.checkpoints.verify` and the `xbench.metrics` modules. The
56
+ `xchroma` command is a thin dispatcher to those same implementations. It does
57
+ not change the published ten-checkpoint ensemble to the website's fast profile.
58
+
59
+ Training workflows remain documented for source checkouts in the
60
+ [repository](https://github.com/ahansenlab/XChroma); this package's command-line
61
+ entry points cover inference and weight verification.
62
+
63
+ Source code and license: [ahansenlab/XChroma](https://github.com/ahansenlab/XChroma).
xchroma-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: xchroma
3
+ Version: 0.1.0
4
+ Summary: Cell-type-specific 3D genome prediction from DNA and chromatin accessibility
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://xchroma.ai
7
+ Project-URL: Source, https://github.com/ahansenlab/XChroma
8
+ Project-URL: Documentation, https://github.com/ahansenlab/XChroma#readme
9
+ Project-URL: Issues, https://github.com/ahansenlab/XChroma/issues
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
17
+ Requires-Python: <3.13,>=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ License-File: xtrain/licenses/Selene.txt
21
+ License-File: xbench/metrics/vendor/pollard/NOTICE.md
22
+ Requires-Dist: numpy<3,>=1.24
23
+ Requires-Dist: torch<3,>=2.2
24
+ Requires-Dist: zstandard>=0.19
25
+ Requires-Dist: pysam>=0.22
26
+ Provides-Extra: prepare
27
+ Requires-Dist: pyBigWig>=0.3.22; extra == "prepare"
28
+ Provides-Extra: metrics
29
+ Requires-Dist: numpy<3,>=1.26; extra == "metrics"
30
+ Requires-Dist: scipy<2,>=1.12; extra == "metrics"
31
+ Requires-Dist: pandas<3,>=2.1; extra == "metrics"
32
+ Requires-Dist: scikit-image<1,>=0.22; extra == "metrics"
33
+ Requires-Dist: scikit-learn<2,>=1.3; extra == "metrics"
34
+ Requires-Dist: matplotlib<4,>=3.8; extra == "metrics"
35
+ Requires-Dist: cooltools==0.7.1; extra == "metrics"
36
+ Dynamic: license-file
37
+
38
+ # XChroma
39
+
40
+ XChroma predicts cell-type-specific 3D genome contacts at 1-kb resolution from
41
+ DNA and chromatin accessibility. DNA-only prediction first uses a cell-specific
42
+ xATAC model to supply the accessibility input.
43
+
44
+ This package runs on your own computer or GPU server. It does not send DNA to
45
+ xchroma.ai. Model checkpoints are downloaded separately from the official
46
+ [GitHub Releases](https://github.com/ahansenlab/XChroma/releases).
47
+
48
+ ## Install
49
+
50
+ Python 3.10–3.12 is supported. For GPU use, install the PyTorch build appropriate
51
+ for your CUDA platform before installing XChroma.
52
+
53
+ ```bash
54
+ python -m pip install xchroma
55
+ xchroma --version
56
+ xchroma --help
57
+ ```
58
+
59
+ For data preparation or scoring, optional dependencies can be installed with
60
+ `python -m pip install 'xchroma[prepare]'` or `python -m pip install 'xchroma[metrics]'`.
61
+ To install from a source checkout instead, run `python -m pip install .` in the repository root.
62
+
63
+ ## Predict a 3D genome map
64
+
65
+ Download the ten contact-model checkpoints from the official release and verify
66
+ them before prediction:
67
+
68
+ ```bash
69
+ xchroma weights --weights-dir weights
70
+ xchroma predict \
71
+ --genome-fa /path/to/hg38.fa \
72
+ --atac-dir /path/to/cell_atac \
73
+ --assembly hg38 \
74
+ --region chr8:127000000-128000000 \
75
+ --weights-dir weights \
76
+ --device cuda \
77
+ --out outputs/MYC.dna-atac
78
+ ```
79
+
80
+ The output is a 1,000 × 1,000 matrix in `prediction.npz`, with a provenance
81
+ manifest. Replace `--device cuda` with `--device cpu --threads 8` to use a CPU.
82
+ Input coordinates are 0-based and half-open; an interval spans exactly 1 Mb.
83
+
84
+ For DNA-only inference, `xchroma atac` runs the existing cell-specific xATAC
85
+ predictor. Pass its normalized NPZ to `xchroma predict --atac-npz` as described
86
+ in the [DNA-only guide](https://github.com/ahansenlab/XChroma#predict-a-contact-map-from-dna-only).
87
+ Cell-specific checkpoints and their registered calibration are required.
88
+
89
+ ## Existing interfaces
90
+
91
+ The package retains `python -m xtrain.predict`, `python -m xatac.predict`,
92
+ `python -m xtrain.checkpoints.verify` and the `xbench.metrics` modules. The
93
+ `xchroma` command is a thin dispatcher to those same implementations. It does
94
+ not change the published ten-checkpoint ensemble to the website's fast profile.
95
+
96
+ Training workflows remain documented for source checkouts in the
97
+ [repository](https://github.com/ahansenlab/XChroma); this package's command-line
98
+ entry points cover inference and weight verification.
99
+
100
+ Source code and license: [ahansenlab/XChroma](https://github.com/ahansenlab/XChroma).
@@ -0,0 +1,95 @@
1
+ # XChroma
2
+
3
+ High-resolution, cell-type-specific 3D genome prediction and in silico mutagenesis.
4
+
5
+ XChroma predicts a 1-Mb contact map at 1-kb resolution from DNA sequence and chromatin accessibility. The same contact model can be applied to new cell types without retraining.
6
+
7
+ **DNA-only prediction and in silico mutagenesis.** [xatac](xatac/) learns sequence-to-accessibility mappings from experimental ATAC-seq, with one model per cell type. Its predicted accessibility, together with the DNA sequence, supplies the frozen XChroma model to predict how sequence edits alter genome folding in that cellular context.
8
+
9
+ ## Zero-shot prediction across human cell types
10
+
11
+ <p align="center">
12
+ <img src="zero-shot-predictions.png" alt="XChroma training and cell-type-specific DNA-only prediction. The same contact-model weights are reused with cell-specific predicted accessibility. Four MYC examples show ENCODE Hi-C (2026) in the upper-right triangle and XChroma DNA-only predictions in the lower-left at 1-kb resolution." width="960">
13
+ </p>
14
+
15
+ These DNA-only examples use cell-specific predicted ATAC-seq with the same frozen XChroma contact model across four human cell types. They show a **1-Mb interval at the MYC locus** at native **1-kb resolution**, with **ENCODE Hi-C (2026)** contacts above the diagonal and **XChroma DNA-only** predictions below it.
16
+
17
+ ## Install
18
+
19
+ Python 3.10–3.12 is supported. For GPU inference, install the PyTorch build for
20
+ your CUDA platform first.
21
+
22
+ ```bash
23
+ python -m pip install xchroma
24
+ xchroma --version
25
+ xchroma --help
26
+ ```
27
+
28
+ Model checkpoints are downloaded separately. The package runs locally on your
29
+ CPU or GPU and retains the existing `xtrain` and `xatac` interfaces below. See
30
+ the [package guide](PACKAGE.md) for the `xchroma` commands and optional dependencies.
31
+
32
+ ## Predict a contact map from DNA and ATAC
33
+
34
+ After installing XChroma, download the ten contact-model checkpoint files from the [model release](https://github.com/ahansenlab/XChroma/releases/tag/main-model-avg10-30500-35000) into `weights/`:
35
+
36
+ ```bash
37
+ python -m xtrain.checkpoints.verify --weights-dir weights
38
+ ```
39
+
40
+ Supply a matching reference genome and chromatin-accessibility input:
41
+
42
+ ```bash
43
+ python -m xtrain.predict \
44
+ --genome-fa /path/to/hg38.fa \
45
+ --atac-dir /path/to/cell_atac \
46
+ --assembly hg38 \
47
+ --region chr8:127000000-128000000 \
48
+ --weights-dir weights \
49
+ --device cuda \
50
+ --out outputs/MYC.dna-atac
51
+ ```
52
+
53
+ The output is a 1,000 × 1,000 contact map in `prediction.npz`, at 1-kb resolution. Use `--device cpu` for CPU inference. See the [inference guide](xtrain/GETTING_STARTED.md) for input formats and output values.
54
+
55
+ ## Predict a contact map from DNA only
56
+
57
+ Use a cell-specific **xatac** model to predict accessibility, then pass its output
58
+ and the same DNA sequence to **XChroma**. The contact model and weights are the same
59
+ as above.
60
+
61
+ Download the ten GM12878 xATAC checkpoints, `xatac_models.json` and `SHA256SUMS`
62
+ from the [xATAC release](https://github.com/ahansenlab/XChroma/releases/tag/xatac-avg10-20261102)
63
+ into `weights/xatac/gm12878`, then predict accessibility with the fixed training
64
+ calibration. Use the matching indexed hg38 reference FASTA. See the
65
+ [xatac guide](xatac/README.md#pretrained-ensembles) for checksum verification,
66
+ other cell types and the scope of each calibration.
67
+
68
+ ```bash
69
+ python -m xatac.predict \
70
+ --checkpoint weights/xatac/gm12878/XChroma_xATAC_gm12878_step*.pt \
71
+ --fasta /path/to/hg38.fa --assembly hg38 --chrom chr8 \
72
+ --start 127000000 --end 128000000 \
73
+ --xchroma-scale 1062.9903291441547 --gp99 6.207031 \
74
+ --device cuda --output outputs/MYC.atac.npz
75
+ ```
76
+
77
+ Then predict the contact map:
78
+
79
+ ```bash
80
+ python -m xtrain.predict \
81
+ --genome-fa /path/to/hg38.fa \
82
+ --atac-npz outputs/MYC.atac.npz \
83
+ --assembly hg38 \
84
+ --region chr8:127000000-128000000 \
85
+ --weights-dir weights \
86
+ --device cuda \
87
+ --out outputs/MYC.dna-only
88
+ ```
89
+
90
+ The DNA-only map is saved as `outputs/MYC.dna-only/prediction.npz`. The predicted
91
+ accessibility is already normalized for XChroma; this command uses it directly.
92
+
93
+ For CPU inference, replace `--device cuda` with `--device cpu --threads 8`
94
+ in both commands. Verified 1-Mb DNA-only examples took 6.0–6.4 min
95
+ with eight CPU threads on Linux, after reference-context preparation.
@@ -0,0 +1,64 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "xchroma"
7
+ version = "0.1.0"
8
+ description = "Cell-type-specific 3D genome prediction from DNA and chromatin accessibility"
9
+ readme = "PACKAGE.md"
10
+ requires-python = ">=3.10,<3.13"
11
+ license = "MIT"
12
+ license-files = ["LICENSE", "xtrain/licenses/Selene.txt", "xbench/metrics/vendor/pollard/NOTICE.md"]
13
+ dependencies = [
14
+ "numpy>=1.24,<3",
15
+ "torch>=2.2,<3",
16
+ "zstandard>=0.19",
17
+ "pysam>=0.22",
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 3 - Alpha",
21
+ "Intended Audience :: Science/Research",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://xchroma.ai"
31
+ Source = "https://github.com/ahansenlab/XChroma"
32
+ Documentation = "https://github.com/ahansenlab/XChroma#readme"
33
+ Issues = "https://github.com/ahansenlab/XChroma/issues"
34
+
35
+ [project.optional-dependencies]
36
+ prepare = ["pyBigWig>=0.3.22"]
37
+ metrics = [
38
+ "numpy>=1.26,<3",
39
+ "scipy>=1.12,<2",
40
+ "pandas>=2.1,<3",
41
+ "scikit-image>=0.22,<1",
42
+ "scikit-learn>=1.3,<2",
43
+ "matplotlib>=3.8,<4",
44
+ "cooltools==0.7.1",
45
+ ]
46
+
47
+ [project.scripts]
48
+ xchroma = "xchroma.cli:main"
49
+
50
+ # Explicitly include the existing namespace packages, without tests or private data.
51
+ [tool.setuptools]
52
+ include-package-data = false
53
+ packages = [
54
+ "xchroma", "xtrain", "xtrain.checkpoints", "xtrain.preprocess",
55
+ "xtrain.preprocess.atac", "xatac", "xbench", "xbench.metrics",
56
+ "xbench.metrics.vendor", "xbench.metrics.vendor.pollard",
57
+ ]
58
+
59
+ [tool.setuptools.package-data]
60
+ xtrain = ["licenses/*.txt"]
61
+ "xtrain.checkpoints" = ["current_model.json"]
62
+ "xtrain.preprocess.atac" = ["*.sh"]
63
+ xatac = ["config.json"]
64
+ "xbench.metrics.vendor.pollard" = ["NOTICE.md"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """Cell-specific DNA-to-ATAC prediction used with XChroma."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,29 @@
1
+ {
2
+ "model": {
3
+ "seq_len": 1048576,
4
+ "width": 512,
5
+ "n_dilated": 13,
6
+ "dilation_cycles": 1,
7
+ "pool_factors": [5, 5, 5, 1, 1, 1],
8
+ "up_factors": [5, 5, 5],
9
+ "up_channels": [128, 64, 32],
10
+ "grad_checkpoint": true
11
+ },
12
+ "batch_size": 8,
13
+ "max_steps": 50000,
14
+ "lr": 0.0002,
15
+ "min_lr": 0.00002,
16
+ "warmup": 250,
17
+ "weight_decay": 0.01,
18
+ "grad_clip": 1.0,
19
+ "shift_bp": 1000,
20
+ "reverse_complement_probability": 0.5,
21
+ "seed": 42,
22
+ "val_seed": 42,
23
+ "val_windows": 20,
24
+ "validate_every": 500,
25
+ "save_every": 100,
26
+ "loader_workers": 4,
27
+ "threads": 4,
28
+ "precision": "bf16"
29
+ }
@@ -0,0 +1,119 @@
1
+ """Compact site-label records and deterministic paired shift/RC augmentation."""
2
+ from functools import lru_cache
3
+ import hashlib
4
+ import io
5
+ import json
6
+ from pathlib import Path, PurePosixPath
7
+
8
+ import numpy as np
9
+ import torch
10
+
11
+ from .io import DNA_LUT, decode_bf16, fingerprint, sha256
12
+
13
+
14
+ def read_dataset(root):
15
+ root = Path(root).resolve()
16
+ meta_path = root / "dataset.json"
17
+ if not meta_path.exists():
18
+ meta_path = root / "READY.json" # Original experimental-target record caches.
19
+ metadata = json.loads(meta_path.read_text())
20
+ if metadata.get("status") != "PASS" or metadata.get("fixture", False):
21
+ raise ValueError("Dataset is incomplete or marked as a fixture")
22
+ known_sites = (metadata.get("signal") == "tn5_insertion_sites"
23
+ or metadata.get("data_source") == "official_experimental_ATAC_TFRecords"
24
+ or "ChromBPNet insertion counts" in metadata.get("label_source", ""))
25
+ if not known_sites:
26
+ raise ValueError("Dataset metadata does not identify insertion-site ATAC labels")
27
+ if not np.isfinite(metadata["track_mean"]) or metadata["track_mean"] <= 0:
28
+ raise ValueError("Dataset requires a positive nonzero-base track mean")
29
+ records_path = root / "records.json"
30
+ records_hash = sha256(records_path)
31
+ if records_hash != metadata["records_sha256"]:
32
+ raise ValueError("Dataset record manifest changed")
33
+ rows = json.loads(records_path.read_text())
34
+ for row in rows:
35
+ path = PurePosixPath(row["path"])
36
+ if path.is_absolute() or ".." in path.parts:
37
+ raise ValueError(f"Invalid record path: {path}")
38
+ if row["subset"] not in {"TRAIN", "VALID", "TEST"}:
39
+ raise ValueError("Unknown data split")
40
+ length, target_length = row["length"], row["target_length"]
41
+ if not 0 < target_length <= length or (length - target_length) % 2:
42
+ raise ValueError("Targets must be centered within the DNA context")
43
+ if row["target_offset"] != (length - target_length) // 2:
44
+ raise ValueError("Incorrect target offset")
45
+ dataset_id = fingerprint({"metadata": metadata, "records_sha256": records_hash})
46
+ return metadata, rows, dataset_id
47
+
48
+
49
+ @lru_cache(maxsize=48)
50
+ def read_record(path, expected_bytes=None, expected_sha256=None):
51
+ payload = Path(path).read_bytes()
52
+ if expected_bytes is not None and len(payload) != expected_bytes:
53
+ raise ValueError(f"Truncated or replaced record: {path}")
54
+ if expected_sha256 is not None and hashlib.sha256(payload).hexdigest() != expected_sha256:
55
+ raise ValueError(f"Record content changed: {path}")
56
+ with np.load(io.BytesIO(payload), allow_pickle=False) as record:
57
+ code, bits = record["sequence_code"], record["atac_bf16"]
58
+ if code.dtype != np.uint8 or code.ndim != 1 or (code > 4).any():
59
+ raise ValueError("DNA encoding must be A=0,C=1,G=2,T=3,unknown=4")
60
+ if bits.dtype != np.uint16 or bits.ndim != 1:
61
+ raise ValueError("ATAC must be a one-dimensional bfloat16 bit array")
62
+ return code, bits
63
+
64
+
65
+ def example(root, row, seq_len, shift=0, reverse=False):
66
+ code, bits = read_record(str(Path(root) / row["path"]), row.get("bytes"), row.get("sha256"))
67
+ if len(code) != row["length"] or len(bits) != row["target_length"]:
68
+ raise ValueError("Record dimensions differ from manifest")
69
+ crop = (len(code) - seq_len) // 2 + shift
70
+ end = crop + seq_len
71
+ if crop < 0 or end > len(code):
72
+ raise ValueError("Requested shift exceeds the stored DNA flanks")
73
+ offset = row["target_offset"]
74
+ left, right = max(crop, offset), min(end, offset + len(bits))
75
+ if left >= right:
76
+ raise ValueError("Crop does not intersect observed targets")
77
+ dna = DNA_LUT[code[crop:end]].copy()
78
+ counts = decode_bf16(bits[left - offset:right - offset])[:, None]
79
+ target_slice = (left - crop, right - crop)
80
+ if not np.isfinite(counts).all() or (counts < 0).any():
81
+ raise ValueError("Invalid ATAC target values")
82
+ if reverse:
83
+ dna, counts = dna[::-1, ::-1].copy(), counts[::-1].copy()
84
+ target_slice = (seq_len - target_slice[1], seq_len - target_slice[0])
85
+ return dna, counts, target_slice
86
+
87
+
88
+ class TrainingBatches(torch.utils.data.Dataset):
89
+ """One optimizer step per item; sample order survives resume and worker changes."""
90
+ def __init__(self, root, rows, config, first_step, last_step):
91
+ self.root, self.rows, self.config = str(root), rows, config
92
+ self.first_step, self.last_step = first_step, last_step
93
+ n, shift = config["model"]["seq_len"], config["shift_bp"]
94
+ if not rows or any(row["subset"] != "TRAIN" for row in rows):
95
+ raise ValueError("Training requires TRAIN records")
96
+ for row in rows:
97
+ if row["target_length"] < n + 2 * shift:
98
+ raise ValueError("TRAIN labels lack sufficient flanks for the requested shift")
99
+
100
+ def __len__(self):
101
+ return max(0, self.last_step - self.first_step + 1)
102
+
103
+ def __getitem__(self, index):
104
+ step = self.first_step + index
105
+ c = self.config
106
+ rng = np.random.default_rng(np.random.SeedSequence([c["seed"], step]))
107
+ dna, counts, indices, shifts, reverses = [], [], [], [], []
108
+ for _ in range(c["batch_size"]):
109
+ ri = int(rng.integers(len(self.rows)))
110
+ shift = int(rng.integers(-c["shift_bp"], c["shift_bp"] + 1))
111
+ reverse = rng.random() < c["reverse_complement_probability"]
112
+ x, y, observed = example(self.root, self.rows[ri], c["model"]["seq_len"], shift, reverse)
113
+ if observed != (0, c["model"]["seq_len"]):
114
+ raise ValueError("TRAIN crop is not fully supervised")
115
+ dna.append(x); counts.append(y)
116
+ indices.append(ri); shifts.append(shift); reverses.append(reverse)
117
+ return dict(step=step, x=torch.from_numpy(np.stack(dna)),
118
+ raw=torch.from_numpy(np.stack(counts)), indices=indices,
119
+ shifts=shifts, reverses=reverses)
@@ -0,0 +1,59 @@
1
+ """Sequence encoding, checksums and atomic output writes."""
2
+ import hashlib
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+
9
+ def sha256(path):
10
+ digest = hashlib.sha256()
11
+ with open(path, "rb") as stream:
12
+ for block in iter(lambda: stream.read(4 << 20), b""):
13
+ digest.update(block)
14
+ return digest.hexdigest()
15
+
16
+
17
+ def fingerprint(value):
18
+ return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
19
+
20
+
21
+ def write_json(path, value):
22
+ path = Path(path)
23
+ path.parent.mkdir(parents=True, exist_ok=True)
24
+ tmp = path.with_name(path.name + ".partial")
25
+ tmp.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")
26
+ tmp.replace(path)
27
+
28
+
29
+ def write_npz(path, **arrays):
30
+ path = Path(path)
31
+ path.parent.mkdir(parents=True, exist_ok=True)
32
+ tmp = path.with_name(path.name + ".partial")
33
+ with tmp.open("wb") as stream:
34
+ np.savez_compressed(stream, **arrays)
35
+ tmp.replace(path)
36
+
37
+
38
+ def encode_dna(sequence):
39
+ table = np.full(256, 4, np.uint8)
40
+ for i, base in enumerate(b"ACGT"):
41
+ table[base] = i
42
+ return table[np.frombuffer(sequence.upper().encode(), np.uint8)]
43
+
44
+
45
+ DNA_LUT = np.vstack((np.eye(4, dtype=np.float32), np.zeros((1, 4), np.float32)))
46
+
47
+
48
+ def encode_bf16(values):
49
+ values = np.asarray(values, dtype=np.float32)
50
+ if not np.isfinite(values).all() or (values < 0).any():
51
+ raise ValueError("Site labels must be finite and nonnegative")
52
+ bits = values.view(np.uint32)
53
+ return ((bits + np.uint32(0x7FFF) + ((bits >> 16) & 1)) >> 16).astype(np.uint16)
54
+
55
+
56
+ def decode_bf16(bits):
57
+ if bits.dtype != np.uint16:
58
+ raise ValueError("Expected uint16 bfloat16 bit patterns")
59
+ return (bits.astype(np.uint32) << 16).view(np.float32)
@@ -0,0 +1,106 @@
1
+ """Accessibility scaling and mean-reduced count/profile losses.
2
+
3
+ Tensors use batch, sequence, track order.
4
+ """
5
+
6
+ from collections.abc import Sequence
7
+
8
+ import torch
9
+ from torch import Tensor
10
+
11
+
12
+ def targets_scaling(counts: Tensor, track_mean: Tensor) -> Tensor:
13
+ """Normalize counts and smoothly compress normalized values above ten."""
14
+ normalized = counts.float() / track_mean
15
+ # Clamping only the inactive curved branch avoids sqrt'(0) in backprop.
16
+ curved = 2 * torch.sqrt(10 * normalized.clamp_min(10)) - 10
17
+ return torch.where(normalized <= 10, normalized, curved)
18
+
19
+
20
+ def predictions_scaling(values: Tensor, track_mean: Tensor) -> Tensor:
21
+ """Invert the target transform and restore the count scale."""
22
+ values = values.float()
23
+ normalized = torch.where(values <= 10, values, (values + 10).square() / 40)
24
+ return normalized * track_mean
25
+
26
+
27
+ def pool128(counts: Tensor) -> Tensor:
28
+ """Sum successive, non-overlapping groups of 128 sequence positions."""
29
+ if counts.ndim != 3 or counts.shape[1] % 128:
30
+ raise ValueError("counts must have shape (batch, length, tracks), with length divisible by 128")
31
+ batch, length, tracks = counts.shape
32
+ return counts.reshape(batch, length // 128, 128, tracks).sum(dim=2)
33
+
34
+
35
+ def multinomial_loss(
36
+ prediction: Tensor, target: Tensor, segment_length: int
37
+ ) -> tuple[Tensor, Tensor, Tensor]:
38
+ """Return combined, mass, and profile losses for contiguous segments.
39
+
40
+ The mass term is a Poisson deviance without its factor of two, divided by
41
+ segment length. The profile term is the average negative target-weighted
42
+ log probability. Both inputs enter the calculation as float32 tensors;
43
+ target values below zero are treated as zero.
44
+ """
45
+ if prediction.ndim != 3 or prediction.shape != target.shape:
46
+ raise ValueError("prediction and target must share shape (batch, length, tracks)")
47
+ if not isinstance(segment_length, int) or segment_length <= 0:
48
+ raise ValueError("segment_length must be a positive integer")
49
+ batch, length, tracks = prediction.shape
50
+ if length == 0 or length % segment_length:
51
+ raise ValueError("sequence length must be nonzero and divisible by segment_length")
52
+
53
+ shape = (batch, length // segment_length, segment_length, tracks)
54
+ predicted = prediction.float().reshape(shape)
55
+ observed = target.float().clamp_min(0).reshape(shape)
56
+ predicted_mass = predicted.sum(dim=2, keepdim=True)
57
+ observed_mass = observed.sum(dim=2, keepdim=True)
58
+ epsilon = 1e-7
59
+
60
+ total = (
61
+ predicted_mass
62
+ - observed_mass * torch.log(predicted_mass + epsilon)
63
+ - (observed_mass - observed_mass * torch.log(observed_mass + epsilon))
64
+ ).mean() / segment_length
65
+ positional = -(observed * torch.log(predicted / (predicted_mass + epsilon) + epsilon)).mean()
66
+ return total + 5 * positional, total, positional
67
+
68
+
69
+ def atac_loss(
70
+ predictions: Sequence[Tensor],
71
+ counts: Tensor,
72
+ track_mean: Tensor,
73
+ target_slice: tuple[int, int] | None = None,
74
+ ) -> tuple[Tensor, dict[str, Tensor]]:
75
+ """Combine full-resolution and 128-base accessibility losses.
76
+
77
+ ``counts`` contains the cropped target. ``target_slice`` identifies that
78
+ crop within both prediction tensors in full-resolution coordinates. Each
79
+ resolution uses eight sequence segments over the cropped interval.
80
+ """
81
+ if len(predictions) != 2:
82
+ raise ValueError("predictions must contain full-resolution and 128-base tensors")
83
+ if counts.ndim != 3 or any(value.ndim != 3 for value in predictions):
84
+ raise ValueError("counts and predictions must have shape (batch, length, tracks)")
85
+ left, right = (0, predictions[0].shape[1]) if target_slice is None else target_slice
86
+ if not isinstance(left, int) or not isinstance(right, int):
87
+ raise ValueError("target_slice endpoints must be integer base coordinates")
88
+ length = right - left
89
+ if left < 0 or right > predictions[0].shape[1] or length <= 0:
90
+ raise ValueError("target_slice must identify a nonempty interval within the predictions")
91
+ if left % 128 or right % 128 or length % 1024:
92
+ raise ValueError("slice endpoints must be divisible by 128 and cropped length by 1024")
93
+ if counts.shape[1] != length:
94
+ raise ValueError("counts length must equal the selected prediction interval")
95
+
96
+ selected = (predictions[0][:, left:right], predictions[1][:, left // 128:right // 128])
97
+ targets = (targets_scaling(counts, track_mean), targets_scaling(pool128(counts), track_mean * 128))
98
+ result: dict[str, Tensor] = {}
99
+ losses = []
100
+ for resolution, predicted, observed in zip((1, 128), selected, targets):
101
+ loss, total, positional = multinomial_loss(predicted, observed, length // 8 // resolution)
102
+ result[f"loss_{resolution}bp"] = loss
103
+ result[f"total_{resolution}bp"] = total
104
+ result[f"positional_{resolution}bp"] = positional
105
+ losses.append(loss)
106
+ return losses[0] + losses[1], result