altar-legnet 0.2.0__py3-none-any.whl

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.
@@ -0,0 +1,25 @@
1
+ # Copyright 2026 Riya Sinha
2
+ """LegNet model binding for Altar."""
3
+
4
+ from altar_legnet.plugin import (
5
+ CONTEXT_LENGTH,
6
+ DEFAULT_IMAGE,
7
+ KIND_SCORING,
8
+ MODEL_INPUT_LENGTH,
9
+ LegNetConfiguration,
10
+ LegNetPlugin,
11
+ LegNetRunInputs,
12
+ LegNetShardKind,
13
+ )
14
+
15
+
16
+ __all__ = [
17
+ "CONTEXT_LENGTH",
18
+ "DEFAULT_IMAGE",
19
+ "KIND_SCORING",
20
+ "MODEL_INPUT_LENGTH",
21
+ "LegNetConfiguration",
22
+ "LegNetPlugin",
23
+ "LegNetRunInputs",
24
+ "LegNetShardKind",
25
+ ]
altar_legnet/plugin.py ADDED
@@ -0,0 +1,202 @@
1
+ # Copyright 2026 Riya Sinha
2
+ """Backend-neutral LegNet binding for MPRA activity variant effects."""
3
+
4
+ from __future__ import annotations
5
+ import enum
6
+ from typing import TYPE_CHECKING, Annotated, Any, cast
7
+
8
+ from altar.execution import ResourceRequest
9
+ from altar.models import (
10
+ ApiVersionRange,
11
+ ContainerImageDigest,
12
+ ContainerScoringPlan,
13
+ ModelConfiguration,
14
+ ModelPlugin,
15
+ OutputSelection,
16
+ PluginCapability,
17
+ PluginKind,
18
+ PluginManifest,
19
+ PrioritizationPolicy,
20
+ ReferenceGenomeRunInputs,
21
+ ResourceReference,
22
+ ResultField,
23
+ ResultSchema,
24
+ RuntimeIdentityPolicy,
25
+ RuntimeKind,
26
+ RuntimeRequirement,
27
+ ScoringRequest,
28
+ VariantClass,
29
+ VariantEligibility,
30
+ require_resource_digests,
31
+ resource_transfer,
32
+ single_container_plan,
33
+ )
34
+ from altar.predicates import Abs, Col, Ge, Lit, Predicate
35
+ from pydantic import Field, model_validator
36
+
37
+ from altar_legnet.resources import manifest_resources
38
+
39
+
40
+ if TYPE_CHECKING:
41
+ import os
42
+
43
+
44
+ CONTEXT_LENGTH = 200
45
+ MODEL_INPUT_LENGTH = 230
46
+ LEFT_MPRA_FLANK = "AGGACCGGATCAACT"
47
+ RIGHT_MPRA_FLANK = "CATTGCGTGAACCGA"
48
+ DEFAULT_IMAGE = "riyavsinha/altar-legnet@sha256:43a4000583f5ebda33554a21a6b627f071a43a65da76c77c625eb1c4f3d50d0d"
49
+
50
+
51
+ class LegNetShardKind(enum.StrEnum):
52
+ """Stable execution kind emitted by :class:`LegNetPlugin`."""
53
+
54
+ SCORING = "legnet_scoring"
55
+
56
+
57
+ KIND_SCORING = LegNetShardKind.SCORING
58
+ _SCORE_RESOURCES = ResourceRequest(memory_gb=4)
59
+ _ACTIVITY_DELTA_THRESHOLD = 0.5
60
+
61
+
62
+ class LegNetConfiguration(ModelConfiguration):
63
+ """Immutable human LegNet checkpoint and MPRA scoring settings."""
64
+
65
+ weights: ResourceReference
66
+ training_config: ResourceReference
67
+ cell_type: Annotated[str, Field(min_length=1)]
68
+ assay: Annotated[str, Field(min_length=1)] = "LentiMPRA"
69
+ average_reverse: bool = True
70
+ image: ContainerImageDigest = DEFAULT_IMAGE
71
+
72
+ @model_validator(mode="after")
73
+ def validate_resources(self) -> LegNetConfiguration:
74
+ require_resource_digests(self, owner="LegNet")
75
+ return self
76
+
77
+ @classmethod
78
+ def from_resource_manifest(
79
+ cls, path: str | os.PathLike[str], *, base_uri: str | None = None, **settings: Any
80
+ ) -> LegNetConfiguration:
81
+ """Build a configuration from the ``legnet.resources.json`` that ``legnet-resources`` wrote.
82
+
83
+ ``settings`` are the remaining configuration fields: ``assay``, ``average_reverse`` and ``image``, and
84
+ ``cell_type`` to override the one the manifest records for the checkpoint. See
85
+ :func:`altar_legnet.resources.manifest_resources` for how ``base_uri`` locates the files.
86
+ """
87
+ resources = manifest_resources(path, base_uri=base_uri)
88
+ settings.setdefault("cell_type", resources.cell_type)
89
+ return cls(weights=resources.weights, training_config=resources.training_config, **settings)
90
+
91
+
92
+ class LegNetRunInputs(ReferenceGenomeRunInputs):
93
+ """Per-run inputs for the published human MPRA checkpoints."""
94
+
95
+ supported_genome_builds = frozenset({"hg38"})
96
+
97
+
98
+ class LegNetPlugin(ModelPlugin):
99
+ """Human LegNet sequence-to-MPRA activity semantics and scalable batch plan."""
100
+
101
+ model_type = "LEGNET"
102
+ manifest = PluginManifest(
103
+ plugin_id="org.kundajelab.altar.model.legnet",
104
+ kind=PluginKind.MODEL,
105
+ capabilities=frozenset({PluginCapability.SCORE, PluginCapability.MATERIALIZE_RESULTS}),
106
+ architecture="LegNet",
107
+ plugin_version="0.0.1",
108
+ altar_api=ApiVersionRange("0.1.0", "0.2.0"),
109
+ configuration_schema_version="0.0.1",
110
+ result_schema=ResultSchema(
111
+ version="0.0.1",
112
+ fields=(
113
+ ResultField("ref_activity", "float", "Reference Activity", "Predicted reference MPRA activity"),
114
+ ResultField("alt_activity", "float", "Alternate Activity", "Predicted alternate MPRA activity"),
115
+ ResultField(
116
+ "activity_delta",
117
+ "float",
118
+ "Activity Delta",
119
+ "Signed alternate-minus-reference predicted MPRA activity",
120
+ ),
121
+ ),
122
+ ),
123
+ # The LegNet runtime substitutes one reference base; batch preparation filters out indels and MNVs.
124
+ variant_eligibility=VariantEligibility(frozenset({VariantClass.SNV})),
125
+ prioritization=PrioritizationPolicy(name="legnet-activity-delta-v1", version="0.0.1"),
126
+ runtimes=(
127
+ RuntimeRequirement(
128
+ name="model_runtime",
129
+ kind=RuntimeKind.CONTAINER_IMAGE,
130
+ policy=RuntimeIdentityPolicy.DIGEST_REQUIRED,
131
+ ),
132
+ ),
133
+ )
134
+ configuration_schema_id = "org.kundajelab.altar.model.legnet.configuration"
135
+ configuration_model = LegNetConfiguration
136
+ run_input_model = LegNetRunInputs
137
+ default_output = OutputSelection(outputs=("scores",), reducer="alt_minus_ref_activity_v1")
138
+
139
+ def build_scoring_plan(self, request: ScoringRequest) -> ContainerScoringPlan:
140
+ configuration = self.parse_configuration_as(request.configuration, LegNetConfiguration)
141
+ run_inputs = self.parse_run_inputs_as(request.run_inputs, LegNetRunInputs)
142
+ layout, resolver = request.layout, request.resolver
143
+ weights_logical = layout.model_resource_file(request.model_id, "legnet.weights.ckpt")
144
+ config_logical = layout.model_resource_file(request.model_id, "legnet.config.json")
145
+ genome_logical = layout.genome_fasta(request.genome_label)
146
+ variants_logical = layout.model_variants_file(request.job_id, request.model_id, request.scoring_batch)
147
+ output_logical = layout.scoring_result_file(request.job_id, request.model_id, request.scoring_batch)
148
+ command = [
149
+ "legnet-score",
150
+ "score",
151
+ "--weights",
152
+ resolver.resolve(weights_logical),
153
+ "--weights-digest",
154
+ cast("str", configuration.weights.digest),
155
+ "--model-config",
156
+ resolver.resolve(config_logical),
157
+ "--model-config-digest",
158
+ cast("str", configuration.training_config.digest),
159
+ "--cell-type",
160
+ configuration.cell_type,
161
+ "--assay",
162
+ configuration.assay,
163
+ "--genome",
164
+ resolver.resolve(genome_logical),
165
+ "--genome-digest",
166
+ cast("str", run_inputs.genome.digest),
167
+ "--variants",
168
+ resolver.resolve(variants_logical),
169
+ "--output",
170
+ resolver.resolve(output_logical),
171
+ ]
172
+ if configuration.average_reverse:
173
+ command.append("--average-reverse")
174
+ return single_container_plan(
175
+ self,
176
+ request,
177
+ kind=KIND_SCORING,
178
+ image=configuration.image,
179
+ command=command,
180
+ resources=_SCORE_RESOURCES,
181
+ inputs=[
182
+ resource_transfer(configuration.weights, weights_logical, locality_key=request.model_id),
183
+ resource_transfer(configuration.training_config, config_logical, locality_key=request.model_id),
184
+ resource_transfer(run_inputs.genome, genome_logical),
185
+ ],
186
+ )
187
+
188
+ def prioritize_predicate(self) -> Predicate:
189
+ return Ge(Abs(Col("activity_delta")), Lit(_ACTIVITY_DELTA_THRESHOLD))
190
+
191
+
192
+ __all__ = [
193
+ "CONTEXT_LENGTH",
194
+ "KIND_SCORING",
195
+ "LEFT_MPRA_FLANK",
196
+ "MODEL_INPUT_LENGTH",
197
+ "RIGHT_MPRA_FLANK",
198
+ "LegNetConfiguration",
199
+ "LegNetPlugin",
200
+ "LegNetRunInputs",
201
+ "LegNetShardKind",
202
+ ]
altar_legnet/py.typed ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,84 @@
1
+ # Copyright 2026 Riya Sinha
2
+ """The manifest ``legnet-resources`` writes beside a prepared LegNet checkpoint, read back into references.
3
+
4
+ The LegNet runtime's ``legnet-resources`` command (``altar_legnet_runtime.resources``) validates a checkpoint by
5
+ loading it with PyTorch, copies it and its training configuration under stable names, and writes
6
+ ``legnet.resources.json`` beside them with each file's SHA-256 digest and the checkpoint's cell type. The
7
+ preparer stays in the runtime because loading the checkpoint needs torch; this module knows only the manifest
8
+ it writes, so ``LegNetConfiguration.from_resource_manifest`` turns it into content-addressed
9
+ ``ResourceReference`` values without anyone copying digests by hand.
10
+
11
+ Provider locations never enter the manifest. A reference's ``uri`` names the file beside the manifest, or
12
+ ``base_uri`` joined with the recorded filename when the prepared directory was copied elsewhere; the storage
13
+ adapter that stages a reference decides where the bytes come from and verifies them against the digest.
14
+ """
15
+
16
+ from __future__ import annotations
17
+ import json
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from typing import TYPE_CHECKING, Any
21
+
22
+ from altar.models import ResourceReference
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ import os
27
+
28
+
29
+ ARCHITECTURE = "human LegNet"
30
+ MANIFEST_SCHEMA_VERSION = "0.0.1"
31
+ MANIFEST_FILENAME = "legnet.resources.json"
32
+ # The manifest's resource keys; the runtime records the training configuration as ``model_config``.
33
+ _WEIGHTS_RESOURCE = "weights"
34
+ _CONFIG_RESOURCE = "model_config"
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class ManifestResources:
39
+ """Location-neutral references and the checkpoint's cell type, read from one ``legnet.resources.json``."""
40
+
41
+ weights: ResourceReference
42
+ training_config: ResourceReference
43
+ cell_type: str
44
+
45
+
46
+ def manifest_resources(path: str | os.PathLike[str], *, base_uri: str | None = None) -> ManifestResources:
47
+ """Read the manifest the runtime's preparer writes into the weights and training-configuration references.
48
+
49
+ Each reference's ``uri`` names the file beside the manifest, or ``base_uri`` joined with the recorded
50
+ filename when the prepared directory was copied elsewhere, such as an object-storage prefix. The digests
51
+ are the manifest's; the storage adapter that stages a reference verifies the bytes against them. Raises
52
+ ``ValueError`` for a manifest of another architecture or schema, or one that lacks a resource or the
53
+ checkpoint's cell type.
54
+ """
55
+ manifest_path = Path(path)
56
+ manifest: dict[str, Any] = json.loads(manifest_path.read_text())
57
+ if manifest.get("architecture") != ARCHITECTURE or manifest.get("schema_version") != MANIFEST_SCHEMA_VERSION:
58
+ msg = f"{str(manifest_path)!r} is not a {ARCHITECTURE} resource manifest with schema {MANIFEST_SCHEMA_VERSION}"
59
+ raise ValueError(msg)
60
+ records = manifest.get("resources", {})
61
+ missing = [name for name in (_CONFIG_RESOURCE, _WEIGHTS_RESOURCE) if name not in records]
62
+ if missing:
63
+ msg = f"{str(manifest_path)!r} is missing resources {missing}"
64
+ raise ValueError(msg)
65
+ cell_type = manifest.get("cell_type")
66
+ if not isinstance(cell_type, str) or not cell_type:
67
+ msg = f"{str(manifest_path)!r} does not record the checkpoint's cell_type"
68
+ raise ValueError(msg)
69
+
70
+ def reference(name: str) -> ResourceReference:
71
+ record = records[name]
72
+ return ResourceReference(
73
+ uri=_resource_uri(manifest_path.parent, record["filename"], base_uri), digest=record["digest"]
74
+ )
75
+
76
+ return ManifestResources(
77
+ weights=reference(_WEIGHTS_RESOURCE), training_config=reference(_CONFIG_RESOURCE), cell_type=cell_type
78
+ )
79
+
80
+
81
+ def _resource_uri(directory: Path, filename: str, base_uri: str | None) -> str:
82
+ if base_uri is None:
83
+ return str(directory / filename)
84
+ return f"{base_uri.rstrip('/')}/{filename}"
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.5
2
+ Name: altar-legnet
3
+ Version: 0.2.0
4
+ Summary: LegNet model binding for large-scale Altar MPRA variant scoring
5
+ Project-URL: Documentation, https://kundajelab.github.io/altar/
6
+ Author: Riya Sinha
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.12
18
+ Requires-Dist: altar<0.3,>=0.2.0
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
21
+ Requires-Dist: pytest>=8; extra == 'test'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # Altar LegNet binding
25
+
26
+ `altar-legnet` is the lightweight control-plane binding for large-scale human LegNet MPRA activity
27
+ variant scoring. It produces backend-neutral container plans and does not import PyTorch.
28
+
29
+ The binding scores hg38 SNVs in independently retryable Altar variant batches. Each variant contributes a
30
+ 200 bp genomic context with the SNV at index 100; the runtime adds the published 5′ and 3′ 15 bp LentiMPRA
31
+ adapters before the 230 bp model inference. The stable scalar effect is signed `alt_activity - ref_activity`.
32
+
33
+ Checkpoint bytes and the matching training configuration are independent, content-addressed resources.
34
+ This supports the upstream K562, HepG2, and WTC11 models as well as compatible checkpoints without tying
35
+ Altar to Zenodo, Hugging Face, Chorus, or another provider. The isolated executor is in `runtimes/legnet`.
36
+ `LegNetConfiguration` uses the digest-pinned runtime tested with the binding by default; callers can override
37
+ it with another immutable image reference.
@@ -0,0 +1,9 @@
1
+ altar_legnet/__init__.py,sha256=8DEOfgeanNhzgWezaa6asx9a7UcdqguAf8YzONjZa6I,467
2
+ altar_legnet/plugin.py,sha256=dk_vf3yaz_HfdTV4lMGCBYRaJnuZpIM1bpiSbtL44Ws,7492
3
+ altar_legnet/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
4
+ altar_legnet/resources.py,sha256=SoQDKIPrE7WUfYG-nkSVtI7MdBOQ64ehBYDjmxo2iCc,3891
5
+ altar_legnet-0.2.0.dist-info/METADATA,sha256=gEAP1z_CVBQj_846WifQDbQ50hwTxGgL0V11oqqisj8,1868
6
+ altar_legnet-0.2.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
7
+ altar_legnet-0.2.0.dist-info/entry_points.txt,sha256=lGj3U419S27pfGPssbvw6OK5mwMRcdDYNO4AeyCUzew,57
8
+ altar_legnet-0.2.0.dist-info/licenses/LICENSE,sha256=WXdDrQ5KT8NmZrPwFTmbpTbvtOUy9dCL9er44qckaj0,1067
9
+ altar_legnet-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [altar.model_plugins]
2
+ LEGNET = altar_legnet:LegNetPlugin
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Riya Sinha
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.