ahcore 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 (91) hide show
  1. ahcore-0.1.0/.gitignore +19 -0
  2. ahcore-0.1.0/LICENSE +201 -0
  3. ahcore-0.1.0/PKG-INFO +118 -0
  4. ahcore-0.1.0/README.md +63 -0
  5. ahcore-0.1.0/ahcore/__init__.py +27 -0
  6. ahcore-0.1.0/ahcore/augmentations/__init__.py +26 -0
  7. ahcore-0.1.0/ahcore/augmentations/adapter_augmentation.py +35 -0
  8. ahcore-0.1.0/ahcore/augmentations/interfaces.py +25 -0
  9. ahcore-0.1.0/ahcore/augmentations/tile_features.py +104 -0
  10. ahcore-0.1.0/ahcore/augmentations/tile_mask_pair.py +255 -0
  11. ahcore-0.1.0/ahcore/data/__init__.py +26 -0
  12. ahcore-0.1.0/ahcore/data/adapters/__init__.py +33 -0
  13. ahcore-0.1.0/ahcore/data/adapters/cached_tile_features.py +848 -0
  14. ahcore-0.1.0/ahcore/data/adapters/patient_label.py +148 -0
  15. ahcore-0.1.0/ahcore/data/adapters/rna_expression.py +80 -0
  16. ahcore-0.1.0/ahcore/data/adapters/tile_mask_pair.py +50 -0
  17. ahcore-0.1.0/ahcore/data/collate.py +107 -0
  18. ahcore-0.1.0/ahcore/data/interfaces.py +85 -0
  19. ahcore-0.1.0/ahcore/data/mm_dataset.py +382 -0
  20. ahcore-0.1.0/ahcore/data/slide_view.py +173 -0
  21. ahcore-0.1.0/ahcore/data/stores/__init__.py +24 -0
  22. ahcore-0.1.0/ahcore/data/stores/base.py +66 -0
  23. ahcore-0.1.0/ahcore/data/stores/per_file_h5.py +212 -0
  24. ahcore-0.1.0/ahcore/data/tile_dataset.py +342 -0
  25. ahcore-0.1.0/ahcore/data/tile_view.py +65 -0
  26. ahcore-0.1.0/ahcore/feature_extractors/__init__.py +17 -0
  27. ahcore-0.1.0/ahcore/feature_extractors/feature_extractor.py +40 -0
  28. ahcore-0.1.0/ahcore/feature_extractors/from_pack.py +69 -0
  29. ahcore-0.1.0/ahcore/feature_extractors/interfaces.py +39 -0
  30. ahcore-0.1.0/ahcore/manifest/__init__.py +64 -0
  31. ahcore-0.1.0/ahcore/manifest/description.py +87 -0
  32. ahcore-0.1.0/ahcore/manifest/manager.py +659 -0
  33. ahcore-0.1.0/ahcore/manifest/models.py +210 -0
  34. ahcore-0.1.0/ahcore/metrics/__init__.py +20 -0
  35. ahcore-0.1.0/ahcore/metrics/metrics.py +128 -0
  36. ahcore-0.1.0/ahcore/mm_lit_module.py +155 -0
  37. ahcore-0.1.0/ahcore/models/__init__.py +16 -0
  38. ahcore-0.1.0/ahcore/models/base_jit_model.py +76 -0
  39. ahcore-0.1.0/ahcore/models/classifiers/__init__.py +19 -0
  40. ahcore-0.1.0/ahcore/models/classifiers/ab_mil.py +156 -0
  41. ahcore-0.1.0/ahcore/models/classifiers/linear.py +49 -0
  42. ahcore-0.1.0/ahcore/models/classifiers/mean_mil.py +127 -0
  43. ahcore-0.1.0/ahcore/models/classifiers/mlp.py +79 -0
  44. ahcore-0.1.0/ahcore/models/encoders/__init__.py +18 -0
  45. ahcore-0.1.0/ahcore/models/encoders/abmil_encoder.py +156 -0
  46. ahcore-0.1.0/ahcore/models/encoders/mean_encoder.py +106 -0
  47. ahcore-0.1.0/ahcore/models/encoders/mlp_encoder.py +61 -0
  48. ahcore-0.1.0/ahcore/models/fusion/__init__.py +16 -0
  49. ahcore-0.1.0/ahcore/models/fusion/fusion_mil.py +192 -0
  50. ahcore-0.1.0/ahcore/models/interfaces.py +94 -0
  51. ahcore-0.1.0/ahcore/models/layers/__init__.py +17 -0
  52. ahcore-0.1.0/ahcore/models/layers/attention.py +106 -0
  53. ahcore-0.1.0/ahcore/models/layers/mlp.py +113 -0
  54. ahcore-0.1.0/ahcore/models/segmentation/__init__.py +16 -0
  55. ahcore-0.1.0/ahcore/models/segmentation/monai_wrapper.py +47 -0
  56. ahcore-0.1.0/ahcore/py.typed +0 -0
  57. ahcore-0.1.0/ahcore/readers.py +465 -0
  58. ahcore-0.1.0/ahcore/tasks/__init__.py +22 -0
  59. ahcore-0.1.0/ahcore/tasks/interfaces.py +90 -0
  60. ahcore-0.1.0/ahcore/tasks/task.py +43 -0
  61. ahcore-0.1.0/ahcore/tools/__init__.py +19 -0
  62. ahcore-0.1.0/ahcore/tools/config.yaml +87 -0
  63. ahcore-0.1.0/ahcore/tools/fomo_pack.py +213 -0
  64. ahcore-0.1.0/ahcore/transforms/__init__.py +16 -0
  65. ahcore-0.1.0/ahcore/transforms/tile.py +169 -0
  66. ahcore-0.1.0/ahcore/utils/__init__.py +13 -0
  67. ahcore-0.1.0/ahcore/utils/cache_keys.py +162 -0
  68. ahcore-0.1.0/ahcore/utils/debug_utils.py +52 -0
  69. ahcore-0.1.0/ahcore/utils/features_manifest.py +62 -0
  70. ahcore-0.1.0/ahcore/utils/image.py +39 -0
  71. ahcore-0.1.0/ahcore/utils/io.py +120 -0
  72. ahcore-0.1.0/ahcore/utils/types.py +68 -0
  73. ahcore-0.1.0/ahcore/writers.py +478 -0
  74. ahcore-0.1.0/pyproject.toml +122 -0
  75. ahcore-0.1.0/tests/python/cache_keys_test.py +79 -0
  76. ahcore-0.1.0/tests/python/cached_adapters_test.py +177 -0
  77. ahcore-0.1.0/tests/python/collate_test.py +147 -0
  78. ahcore-0.1.0/tests/python/features_manifest_test.py +94 -0
  79. ahcore-0.1.0/tests/python/from_pack_test.py +109 -0
  80. ahcore-0.1.0/tests/python/fusion_test.py +69 -0
  81. ahcore-0.1.0/tests/python/manifest_test.py +347 -0
  82. ahcore-0.1.0/tests/python/mean_mil_test.py +93 -0
  83. ahcore-0.1.0/tests/python/metrics_test.py +107 -0
  84. ahcore-0.1.0/tests/python/mm_dataset_test.py +47 -0
  85. ahcore-0.1.0/tests/python/patient_label_adapter_test.py +110 -0
  86. ahcore-0.1.0/tests/python/per_file_h5_store_test.py +133 -0
  87. ahcore-0.1.0/tests/python/precompute_features_test.py +506 -0
  88. ahcore-0.1.0/tests/python/readers_test.py +382 -0
  89. ahcore-0.1.0/tests/python/tile_mask_pair_augmentation_test.py +71 -0
  90. ahcore-0.1.0/tests/python/tile_transforms_ignore_mask_test.py +49 -0
  91. ahcore-0.1.0/tests/python/writers_test.py +186 -0
@@ -0,0 +1,19 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+ build/
7
+ dist/
8
+
9
+ # Tooling caches
10
+ .pytest_cache/
11
+ .ruff_cache/
12
+ .mypy_cache/
13
+
14
+ # Environments
15
+ .venv/
16
+ venv/
17
+
18
+ # OS / editor
19
+ .DS_Store
ahcore-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
ahcore-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.5
2
+ Name: ahcore
3
+ Version: 0.1.0
4
+ Summary: Core building blocks for whole-slide-image deep learning pipelines
5
+ Project-URL: Homepage, https://github.com/NKI-AI/ahcore
6
+ Project-URL: Repository, https://github.com/NKI-AI/ahcore
7
+ Project-URL: Issues, https://github.com/NKI-AI/ahcore/issues
8
+ Author-email: Jonas Teuwen <j.teuwen@nki.nl>, Joren Brunekreef <j.brunekreef@nki.nl>
9
+ Maintainer-email: AI for Oncology <j.teuwen@nki.nl>
10
+ License: Apache-2.0
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Healthcare Industry
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
21
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: dlup>=0.9.4
24
+ Requires-Dist: filelock>=3.12
25
+ Requires-Dist: h5py>=3.12
26
+ Requires-Dist: imageio>=2.37
27
+ Requires-Dist: kornia>=0.8
28
+ Requires-Dist: lightning>=2.6
29
+ Requires-Dist: numcodecs>=0.13
30
+ Requires-Dist: numpy>=2.0
31
+ Requires-Dist: omegaconf>=2.3
32
+ Requires-Dist: pandas>=2.0
33
+ Requires-Dist: pillow>=10.0
34
+ Requires-Dist: pydantic>=2.10
35
+ Requires-Dist: rich>=13
36
+ Requires-Dist: sqlalchemy>=2.0
37
+ Requires-Dist: torch>=2.6
38
+ Requires-Dist: tqdm>=4.66
39
+ Requires-Dist: typing-extensions>=4.10
40
+ Requires-Dist: zarr>=3.0
41
+ Provides-Extra: dev
42
+ Requires-Dist: mypy; extra == 'dev'
43
+ Requires-Dist: pytest-mock; extra == 'dev'
44
+ Requires-Dist: pytest>=7.0; extra == 'dev'
45
+ Requires-Dist: ruff; extra == 'dev'
46
+ Provides-Extra: logging
47
+ Requires-Dist: mlflow>=3.4; extra == 'logging'
48
+ Requires-Dist: tensorboard>=2.19; extra == 'logging'
49
+ Provides-Extra: tracing
50
+ Requires-Dist: huggingface-hub; extra == 'tracing'
51
+ Requires-Dist: pyyaml; extra == 'tracing'
52
+ Requires-Dist: timm; extra == 'tracing'
53
+ Requires-Dist: transformers; extra == 'tracing'
54
+ Description-Content-Type: text/markdown
55
+
56
+ # ahcore
57
+
58
+ `ahcore` is the AI for Oncology core toolkit for computational-pathology pipelines: the reusable building
59
+ blocks that sit between whole-slide images and a training run. It is a pure-Python library, meant to be
60
+ composed inside a larger pipeline rather than run on its own.
61
+
62
+ This repository is automatically synced from the AI for Oncology monorepo.
63
+
64
+ ## What ahcore offers
65
+
66
+ `ahcore` is a toolkit of composable building blocks for whole-slide-image deep learning, not an end-to-end
67
+ application. A consumer pipeline assembles these pieces and owns the experiment logic. It decides how data
68
+ is split, whether to cross-validate, and how runs are orchestrated. `ahcore` provides the parts.
69
+
70
+ - **A data catalog.** A SQLAlchemy-backed manifest of patients, slides, masks, labels, and named splits,
71
+ queried through a `DataManager`. `ahcore` _stores and serves_ splits (e.g. fit/validate/test membership,
72
+ or membership supplied in memory). How you _draw_ them is up to you.
73
+ - **Views and adapters.** Lazy per-slide and per-tile accessors over the catalog, plus an adapter seam
74
+ (`view → AdapterBundle`) that turns them into named, model-ready tensors. Ships adapters for
75
+ foundation-model tile features, patient labels, bulk RNA expression, and image+mask pairs. Adapters are
76
+ the main extension point.
77
+ - **Feature extraction and caching.** Run a packaged foundation-model encoder over a slide's tiles and
78
+ persist the per-slide features to HDF5, keyed deterministically. This is a distinct precompute step: at
79
+ training time the feature adapters read from that cache, they do not extract on the fly (doing so would
80
+ be too slow for a realistic training run).
81
+ - **Datamodules and models.** PyTorch Lightning datamodules that assemble batches from adapters (single-
82
+ or multi-modal), plus model heads: attention-based MIL (ABMIL), mean-pool MIL (MeanMIL), encoders, a
83
+ concatenation fusion head, and segmentation wrappers.
84
+ - **Task and training scaffolding.** A `Task` protocol (choose inputs and targets, compute loss and
85
+ metrics) and a thin `MultiModalLightningModule` that runs training/validation/test by delegating to the
86
+ task. You supply the concrete tasks.
87
+ - **Slide-sized raster I/O.** Stream model outputs (segmentation masks, attention or probability maps)
88
+ tile-by-tile into a chunked Zarr store, then read arbitrary regions back like a slide, to stitch,
89
+ overlay, or export to a pyramidal TIFF.
90
+ - **Transforms and augmentations.** Tile transforms (including polygon-to-mask) and feature-space
91
+ augmentations.
92
+
93
+ `ahcore` ships no end-to-end command-line application; it is a library.
94
+
95
+ ## Installation
96
+
97
+ ```bash
98
+ pip install ahcore
99
+ ```
100
+
101
+ Requires Python ≥ 3.11. The training stack (PyTorch Lightning) is a core dependency. `ahcore` is a
102
+ training-scaffolding library, not an optional add-on.
103
+
104
+ ## Development
105
+
106
+ `ahcore` is developed in the AI for Oncology monorepo and synced to this repository. To work on it here,
107
+ standalone:
108
+
109
+ ```bash
110
+ pip install -e ".[dev]"
111
+ pytest
112
+ ```
113
+
114
+ Inside the monorepo it is built and tested with Bazel (`bazelisk test //aifo/ahcore/tests/...`).
115
+
116
+ ## License
117
+
118
+ Apache 2.0 — see [LICENSE](LICENSE).
ahcore-0.1.0/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # ahcore
2
+
3
+ `ahcore` is the AI for Oncology core toolkit for computational-pathology pipelines: the reusable building
4
+ blocks that sit between whole-slide images and a training run. It is a pure-Python library, meant to be
5
+ composed inside a larger pipeline rather than run on its own.
6
+
7
+ This repository is automatically synced from the AI for Oncology monorepo.
8
+
9
+ ## What ahcore offers
10
+
11
+ `ahcore` is a toolkit of composable building blocks for whole-slide-image deep learning, not an end-to-end
12
+ application. A consumer pipeline assembles these pieces and owns the experiment logic. It decides how data
13
+ is split, whether to cross-validate, and how runs are orchestrated. `ahcore` provides the parts.
14
+
15
+ - **A data catalog.** A SQLAlchemy-backed manifest of patients, slides, masks, labels, and named splits,
16
+ queried through a `DataManager`. `ahcore` _stores and serves_ splits (e.g. fit/validate/test membership,
17
+ or membership supplied in memory). How you _draw_ them is up to you.
18
+ - **Views and adapters.** Lazy per-slide and per-tile accessors over the catalog, plus an adapter seam
19
+ (`view → AdapterBundle`) that turns them into named, model-ready tensors. Ships adapters for
20
+ foundation-model tile features, patient labels, bulk RNA expression, and image+mask pairs. Adapters are
21
+ the main extension point.
22
+ - **Feature extraction and caching.** Run a packaged foundation-model encoder over a slide's tiles and
23
+ persist the per-slide features to HDF5, keyed deterministically. This is a distinct precompute step: at
24
+ training time the feature adapters read from that cache, they do not extract on the fly (doing so would
25
+ be too slow for a realistic training run).
26
+ - **Datamodules and models.** PyTorch Lightning datamodules that assemble batches from adapters (single-
27
+ or multi-modal), plus model heads: attention-based MIL (ABMIL), mean-pool MIL (MeanMIL), encoders, a
28
+ concatenation fusion head, and segmentation wrappers.
29
+ - **Task and training scaffolding.** A `Task` protocol (choose inputs and targets, compute loss and
30
+ metrics) and a thin `MultiModalLightningModule` that runs training/validation/test by delegating to the
31
+ task. You supply the concrete tasks.
32
+ - **Slide-sized raster I/O.** Stream model outputs (segmentation masks, attention or probability maps)
33
+ tile-by-tile into a chunked Zarr store, then read arbitrary regions back like a slide, to stitch,
34
+ overlay, or export to a pyramidal TIFF.
35
+ - **Transforms and augmentations.** Tile transforms (including polygon-to-mask) and feature-space
36
+ augmentations.
37
+
38
+ `ahcore` ships no end-to-end command-line application; it is a library.
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ pip install ahcore
44
+ ```
45
+
46
+ Requires Python ≥ 3.11. The training stack (PyTorch Lightning) is a core dependency. `ahcore` is a
47
+ training-scaffolding library, not an optional add-on.
48
+
49
+ ## Development
50
+
51
+ `ahcore` is developed in the AI for Oncology monorepo and synced to this repository. To work on it here,
52
+ standalone:
53
+
54
+ ```bash
55
+ pip install -e ".[dev]"
56
+ pytest
57
+ ```
58
+
59
+ Inside the monorepo it is built and tested with Bazel (`bazelisk test //aifo/ahcore/tests/...`).
60
+
61
+ ## License
62
+
63
+ Apache 2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,27 @@
1
+ # Copyright 2025 Jonas Teuwen & Joren Brunekreef. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """ahcore: reusable building blocks for whole-slide-image deep learning pipelines.
15
+
16
+ A manifest-backed data catalog, pluggable adapters, a foundation-model feature store, MIL / encoder /
17
+ fusion and segmentation model heads, a Task-driven PyTorch-Lightning module, and Zarr tile readers /
18
+ writers. Import the pieces from their subpackages (e.g. ``ahcore.models``, ``ahcore.data``,
19
+ ``ahcore.tasks``, ``ahcore.readers``).
20
+ """
21
+
22
+ # Single source of truth for the version; pyproject.toml reads it via hatch's version hook.
23
+ __version__ = "0.1.0"
24
+
25
+ import ahcore.writers as writers
26
+
27
+ __all__ = ["writers"]
@@ -0,0 +1,26 @@
1
+ # Copyright 2025 Joren Brunekreef. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from .adapter_augmentation import AdapterAugmentation
15
+ from .interfaces import AdapterAugmentor
16
+ from .tile_features import SelectRandomTiles, TileFeaturesAugmentation
17
+ from .tile_mask_pair import HEDColorAugmentation, TileMaskPairAugmentation
18
+
19
+ __all__ = [
20
+ "AdapterAugmentation",
21
+ "AdapterAugmentor",
22
+ "HEDColorAugmentation",
23
+ "SelectRandomTiles",
24
+ "TileFeaturesAugmentation",
25
+ "TileMaskPairAugmentation",
26
+ ]
@@ -0,0 +1,35 @@
1
+ # Copyright 2025 Joren Brunekreef. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import torch.nn as nn
17
+
18
+ from ahcore.augmentations.interfaces import AdapterAugmentor
19
+ from ahcore.data.interfaces import AdapterBundle
20
+
21
+
22
+ class AdapterAugmentation(nn.Module):
23
+ """Composes an ordered list of :class:`AdapterAugmentor` modules into one bundle-to-bundle transform.
24
+
25
+ ``forward`` threads the ``AdapterBundle`` through each augmentor in turn and returns the result.
26
+ """
27
+
28
+ def __init__(self, augmentors: list[AdapterAugmentor]) -> None:
29
+ super().__init__()
30
+ self._augmentors = nn.ModuleList(augmentors)
31
+
32
+ def forward(self, bundle: AdapterBundle) -> AdapterBundle:
33
+ for augmentor in self._augmentors:
34
+ bundle = augmentor(bundle)
35
+ return bundle
@@ -0,0 +1,25 @@
1
+ # Copyright 2025 Joren Brunekreef. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import torch.nn as nn
17
+
18
+ from ahcore.data.interfaces import AdapterBundle
19
+
20
+
21
+ class AdapterAugmentor(nn.Module):
22
+ """Interface for an augmentor that maps an :class:`AdapterBundle` to an augmented ``AdapterBundle``."""
23
+
24
+ def __call__(self, bundle: AdapterBundle) -> AdapterBundle:
25
+ raise NotImplementedError
@@ -0,0 +1,104 @@
1
+ # Copyright 2025 Joren Brunekreef. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ from typing import Callable
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from ahcore.data.interfaces import AdapterBundle
23
+
24
+
25
+ class TileFeaturesAugmentation(nn.Module):
26
+ """Runs an ordered list of bundle-to-bundle transforms over a tile-features :class:`AdapterBundle`.
27
+
28
+ Each transform maps an ``AdapterBundle`` to an ``AdapterBundle``; ``forward`` applies them in order.
29
+ Use :meth:`for_classification` for the default tile-subsampling pipeline.
30
+ """
31
+
32
+ def __init__(self, transforms: list[Callable[[AdapterBundle], AdapterBundle]]) -> None:
33
+ super().__init__()
34
+ self._transforms = transforms
35
+
36
+ @classmethod
37
+ def for_classification(
38
+ cls, num_tiles: int = 1000, seed: int | None = None, per_sample: bool = False, meta_key: str = "slide_id"
39
+ ) -> TileFeaturesAugmentation:
40
+ transforms: list[Callable[[AdapterBundle], AdapterBundle]] = [
41
+ SelectRandomTiles(num_tiles=num_tiles, seed=seed, per_sample=per_sample, meta_key=meta_key),
42
+ ]
43
+ return TileFeaturesAugmentation(transforms)
44
+
45
+ def forward(self, data: AdapterBundle) -> AdapterBundle:
46
+ for transform in self._transforms:
47
+ data = transform(data)
48
+ return data
49
+
50
+
51
+ class SelectRandomTiles(nn.Module):
52
+ """Randomly subsample a fixed number of tiles from a bundle, keeping all per-tile tensors aligned.
53
+
54
+ Samples ``num_tiles`` rows without replacement (with replacement if the bag is smaller) and applies
55
+ the same indices to every per-tile tensor in ``bundle.data`` so features/coords stay row-aligned.
56
+ With ``seed`` set the choice is deterministic; ``per_sample=True`` derives the seed from
57
+ ``bundle.meta[meta_key]`` so each slide gets its own reproducible selection.
58
+ """
59
+
60
+ def __init__(
61
+ self, num_tiles: int, seed: int | None = None, per_sample: bool = False, meta_key: str = "slide_id"
62
+ ) -> None:
63
+ super().__init__()
64
+ self._num_tiles = num_tiles
65
+ self._seed = seed
66
+ self._per_sample = per_sample
67
+ self._meta_key = meta_key
68
+
69
+ def _make_generator(self, bundle: AdapterBundle, device: torch.device | str) -> torch.Generator | None:
70
+ if self._seed is None:
71
+ return None
72
+ derived_seed = self._seed
73
+ if (
74
+ self._per_sample
75
+ and hasattr(bundle, "meta")
76
+ and isinstance(bundle.meta, dict)
77
+ and self._meta_key in bundle.meta
78
+ ):
79
+ key = str(bundle.meta[self._meta_key])
80
+ digest = hashlib.sha256(f"{self._seed}:{key}".encode("utf-8")).digest()
81
+ derived_seed = int.from_bytes(digest[:8], "little", signed=False)
82
+ gen = torch.Generator(device=device)
83
+ gen.manual_seed(derived_seed)
84
+ return gen
85
+
86
+ def forward(self, bundle: AdapterBundle) -> AdapterBundle:
87
+ features = bundle.data["features"]
88
+ num_features = features.shape[0]
89
+
90
+ gen = self._make_generator(bundle, features.device)
91
+
92
+ if num_features < self._num_tiles:
93
+ # If there are fewer features than num_tiles, we sample with replacement.
94
+ indices = torch.randint(0, num_features, (self._num_tiles,), device=features.device, generator=gen)
95
+ else:
96
+ # Otherwise, we sample without replacement.
97
+ indices = torch.randperm(num_features, device=features.device, generator=gen)[: self._num_tiles]
98
+
99
+ # Subsample every per-tile tensor by the same indices so features / coords / (future)
100
+ # patch_tokens stay row-aligned — no per-key hardcoding.
101
+ for key, value in bundle.data.items():
102
+ if isinstance(value, torch.Tensor) and value.shape[0] == num_features:
103
+ bundle.data[key] = value[indices]
104
+ return bundle