API reference¶
Generated from the docstrings in the source. The top-level neorx
package re-exports the pipeline entry points, so
from neorx import run_pipeline and
from neorx.core.pipeline import run_pipeline are equivalent.
>>> import neorx
>>> "run_pipeline" in neorx.__all__ and "identify_causal_targets" in neorx.__all__
True
causalphylo — admissibility and identification¶
Edge admissibility and Pearl's backdoor criterion are not in this package. They depend on nothing but NetworkX, so they live in CausalPhylo, which NeoRx imports them from. The narrative pages that use them are Which edges earn an arrow and Identification.
They are not re-documented here. Duplicating another package's API reference means two copies that drift, and the authoritative one is CausalPhylo's own API reference.
Everything both modules make public is re-exported from the top level, so a single import reaches all of it:
>>> from causalphylo import (
... is_causal_admissible, causal_subgraph, cyclic_components,
... acyclic_core, AcyclicCore,
... CAUSAL_EDGE_TYPES, GENETIC_EVIDENCE_CLASSES,
... find_adjustment_set, Identification, IdentificationReason,
... satisfies_backdoor, mutilated_graph, confounding_sensitivity,
... MAX_ADJUSTMENT_SET_SIZE, MAX_CANDIDATE_POOL,
... )
The submodule paths causalphylo.graph_semantics and
causalphylo.backdoor also work, and are what the CausalPhylo reference
is organised by.
neorx.core.causal.identifier¶
Candidate evaluation and ranking. See From verdict to target.
Causal Target Identifier¶
This is the NOVEL core of NeoRx. While every other drug-discovery pipeline ranks targets by association scores (correlation), we apply Pearl's causal inference framework to distinguish genuine causal drivers from correlational bystanders.
The Fundamental Problem
Gene–disease association databases (Monarch Initiative, Open Targets) report that TNF-α is strongly associated with HIV. Indeed, TNF-α levels are elevated during HIV infection. But TNF-α elevation is a consequence of immune activation — it is downstream of the infection. Inhibiting TNF-α does not treat HIV; it makes it worse by suppressing immune defence.
Conversely, CCR5 is the HIV-1 co-receptor. A loss-of-function mutation (CCR5-Δ32) confers near-complete resistance to HIV-1. Maraviroc, which blocks CCR5, is an approved antiretroviral. CCR5 is a causal target.
Our Method
-
Graph → Causal Model: Convert the disease knowledge graph into a DAG suitable for DoWhy. Each edge encodes a potential causal direction.
-
Backdoor Criterion: For each candidate target, check whether the causal effect on the disease outcome is identifiable — i.e. whether there exists a valid adjustment set that blocks all confounding paths.
-
Effect Estimation: Estimate the Average Treatment Effect (ATE) of intervening on the target. We use linear regression (for interpretability) and inverse propensity weighting (for robustness).
-
Sensitivity Analysis: Apply DoWhy's refutation tests:
random_common_cause: Add a random confounder.placebo_treatment: Shuffle the treatment variable.-
data_subset: Re-estimate on random subsets. If the estimate is fragile, the target may be correlational. -
Classification: Combine causal effect, robustness, graph topology (in-degree, pathway membership), and druggability into a final classification:
- Causal: High effect + robust + identifiable
- Correlational: High association but fragile/unidentifiable
- Inconclusive: Insufficient evidence
identify_causal_targets ¶
identify_causal_targets(graph: DiseaseGraph, top_n: int = 10, min_causal_confidence: float = 0.3, frame: frozenset[str] | None = None) -> list[NeoRxResult]
Identify and rank causal drug targets from a disease graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
DiseaseGraph
|
The assembled disease causal graph. |
required |
top_n
|
int
|
Maximum number of targets to return. |
10
|
min_causal_confidence
|
float
|
Minimum causal confidence threshold. |
0.3
|
frame
|
frozenset[str] | None
|
The population a dated run may evaluate -- gene symbols the pinned
release associated with this disease on genetic evidence (see
|
None
|
Returns:
| Type | Description |
|---|---|
list[NeoRxResult]
|
Ranked list of causal target assessments, best first. |
Any statistic *about the evaluation* -- an identifiability rate, a
|
|
failure breakdown -- belongs on ``evaluate_all_targets`` instead:
|
|
this list is ranked by ``causal_confidence``, which itself rewards
|
|
identifiability, so a rate measured over it is measured on a sample
|
|
the rate selected.
|
|
Source code in src/neorx/core/causal/identifier.py
evaluate_all_targets ¶
Evaluate every candidate target in the graph, filtering nothing.
This is the population identify_causal_targets then ranks and
truncates, and what any statistic describing the identification
procedure has to be computed over -- compute_causal_confidence
awards a bonus for being identifiable, so the top-N is a sample
selected partly by the property such a statistic measures.
frame, when given, restricts candidates to the population a dated
run may evaluate (see identify_causal_targets). Exclusions are
logged rather than raised: Monarch and ChEMBL legitimately contribute
genes OpenTargets did not, so refusing on an out-of-frame gene would
fail every dated run for an entirely normal condition. The log line,
with the disease name and the count, is what keeps that filtering
honest -- a run that suddenly excludes far more than it used to has
had something change upstream, and that must be visible.
Sorted by causal_confidence descending: ordering only, nothing
dropped.
Source code in src/neorx/core/causal/identifier.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | |
Which evaluated targets get reported.
identifier.evaluate_all_targets evaluates every candidate in the
disease graph; this module decides which of them the pipeline reports.
The two are separate because they answer different questions, and
conflating them corrupts any statistic about the evaluation: ranking is
by causal_confidence, which awards a bonus for being identifiable,
so the reported slice is a sample selected partly by a property one
might want to measure over the candidates.
rank_causal_targets ¶
rank_causal_targets(results: list[NeoRxResult], top_n: int = 10, min_causal_confidence: float = 0.3) -> list[NeoRxResult]
Filter and rank evaluated targets down to the reported top-N.
results is what evaluate_all_targets returned. Kept separate
from that evaluation so the full list stays reachable: the survivors
are not a representative sample of what was evaluated.
Source code in src/neorx/core/causal/ranking.py
Turning evidence into a ranked, labelled target.
Druggability, the combined causal confidence, and the final causal-versus-correlational classification. These are weighted heuristics over the evidence counts, and they are named as such: nothing here estimates a causal effect.
compute_causal_confidence ¶
compute_causal_confidence(effect: float, robustness: float, is_identifiable: bool, n_pathways: int, n_interactions: int, source_scores: dict[str, float], druggability: float, n_active_sources: int = 4, n_associated_diseases: int = 0) -> float
Compute composite causal confidence score.
Weights: - Causal effect magnitude: 30% - Robustness (sensitivity analysis): 25% - Identifiability (backdoor criterion): 15% - Multi-source consensus: 10% - Disease specificity: 10% - Druggability: 10%
Disease specificity replaces the former "network centrality" weight. Hub genes (TP53, AKT1) are associated with thousands of diseases — they are generic, not specific. Specificity rewards targets that are uniquely linked to the disease under study, penalising promiscuous hubs.
Formula: specificity = 1 / log2(n_diseases + 2) - Gene linked to 1 disease: specificity = 1.0 - Gene linked to 10 diseases: specificity = 0.29 - Gene linked to 100: specificity = 0.15 - Gene linked to 1000: specificity = 0.10
Source code in src/neorx/core/causal/scoring.py
classify_target ¶
classify_target(gene_name: str, causal_confidence: float, robustness: float, is_identifiable: bool, n_pathways: int, druggability: float, target_type: TargetType = TargetType.CORRELATIONAL, tissue_relevant: bool = True, evidence_streams: int = 0) -> tuple[TargetClassification, str]
Classify a target as causal, correlational, or inconclusive.
Classification rules:
Automatic demotion (overrides confidence scores): - HOST_SYMPTOM targets → always CORRELATIONAL - tissue_relevant=False → always CORRELATIONAL
Tissue gate (boolean, not a modifier): - tissue_relevant is True/False from the tissue filter. - True = gene is expressed in a disease-relevant tissue (or expression unknown → pass). - False = gene is only expressed in irrelevant tissues → demoted to CORRELATIONAL regardless of confidence. - The gate NEVER modifies causal_confidence. Confidence stays pure — it measures causal evidence quality, not tissue expression.
Evidence triangulation (for CAUSAL status): - Must have ≥2 independent evidence streams - causal_confidence ≥ 0.6 AND robust AND identifiable
Standard rules: - Correlational: confidence < 0.4 OR not robust - Inconclusive: everything in between
Source code in src/neorx/core/causal/scoring.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | |
assess_druggability ¶
Score druggability based on available evidence.
Uses Open Targets tractability data when available, structural information, and protein family heuristics.
Source code in src/neorx/core/causal/scoring.py
organism_disease_relevance ¶
Score how relevant a pathogen organism is to a disease.
Returns 1.0 if the organism matches the primary pathogen, 0.3 for generic/unrelated organisms, enabling the confidence formula to demote off-target pathogens.
For non-infectious diseases (cancer, neurological, metabolic), ALL pathogen targets get 0.0 — these diseases have no causative pathogen, so any pathogen target in ChEMBL is from co-prescribed medications (e.g. antibiotics for Alzheimer's patients) and should not be ranked.
Source code in src/neorx/core/causal/scoring.py
evaluate_pathogen_target ¶
evaluate_pathogen_target(G: DiGraph, target_id: str, disease_id: str, graph: DiseaseGraph, *, causal_pathway: list[str], n_active_sources: int = 4, disease_name: str = '') -> NeoRxResult
Evaluate a pathogen target from ChEMBL.
Pathogen targets (e.g. PfDHFR-TS, HIV-1 protease) are validated by existing drugs. Their confidence is based on drug evidence rather than causal graph analysis:
- Clinical phase = highest weight (Phase 4 approved drug = maximum confidence)
- Number of drugs targeting this protein
- Mechanism-of-action diversity
They bypass: - Biological classifier (not host genes) - Tissue filter (pathogen proteins don't express in human tissue) - Causal path analysis (they're direct drug targets)
causal_pathway is computed by the caller (identifier.py still
owns _find_causal_pathway, which stays there for the tests that
exercise it directly) and threaded through here rather than
recomputed, so this function only needs the graph for node lookups.
Source code in src/neorx/core/causal/scoring.py
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 | |
Counting the evidence behind a candidate target.
How many pathways mention it, how many proteins it interacts with, how many independent databases report it, and how strongly the graph's edge weights connect it to the disease. None of this is causal inference -- it is the bookkeeping that ranks candidates once identification has said which claims are admissible.
collect_source_scores ¶
Collect per-source association scores for a gene.
Source code in src/neorx/core/causal/evidence.py
count_evidence_streams ¶
count_evidence_streams(source_scores: dict[str, float], n_pathways: int, n_interactions: int, node_data: dict[str, Any]) -> int
Count independent evidence streams supporting a target.
Evidence streams: 1. Gene-disease association databases (Monarch, OpenTargets) 2. Pathway membership (KEGG, Reactome) 3. Protein-protein interactions (STRING) 4. Structural data (PDB) 5. Druggability / functional annotation (UniProt) 6. Drug evidence (ChEMBL — validated drug targets)
Each counts as ONE stream even if multiple sources within the category confirm it (e.g. both KEGG and Reactome = 1 pathway stream, not 2).
Source code in src/neorx/core/causal/evidence.py
count_pathway_connections ¶
Count how many pathways this gene participates in.
Source code in src/neorx/core/causal/evidence.py
count_protein_interactions ¶
Count protein–protein interactions for this node.
Source code in src/neorx/core/causal/evidence.py
compute_path_strength ¶
Compute causal path strength from edge weights.
Shorter paths with higher-weight edges indicate stronger causal mechanisms.
Source code in src/neorx/core/causal/evidence.py
corroboration_factor ¶
Multi-source corroboration, counted over primary evidence.
An aggregator is not a source. OmniPath re-reports interactions
STRING also reports, so counting source_db values would let one
curated interaction inflate the factor twice. Where an edge names its
primary_sources, those are counted instead of the aggregator.
Source code in src/neorx/core/causal/evidence.py
neorx.core.graph¶
Graph assembly and persistence. See The graph and its sources.
Disease Causal Graph Builder¶
The graph builder is the first major step in the NeoRx pipeline. It queries all 8 biomedical data sources and assembles a unified causal knowledge graph for a specific disease.
Architecture
- Query gene–disease associations (Monarch Initiative, Open Targets) 1b. Query validated drug targets (ChEMBL — human + pathogen)
- Query pathway memberships (KEGG, Reactome)
- Query protein–protein interactions (STRING)
- Enrich proteins with UniProt metadata (function, PDB IDs)
- Query PDB structures for docking targets
- Merge duplicate nodes by gene symbol
- Build a NetworkX DiGraph ready for DoWhy causal inference
Node merging
Monarch might call it "CCR5" while Open Targets uses "ENSG00000160791". We normalise to gene symbols and merge, keeping the highest confidence score and union of all metadata.
Edge semantics
ASSOCIATED_WITH→ gene ↔ disease (from Monarch, OT)PARTICIPATES_IN→ gene → pathway (from KEGG, Reactome)INTERACTS_WITH→ protein ↔ protein (from STRING)CAUSES→ the disease node → disease outcome
The causal identifier (next stage) then tests whether each gene's path to the disease outcome is causal or merely correlational using do-calculus.
build_disease_graph ¶
build_disease_graph(disease: str, *, max_genes: int = 20, string_min_score: int = 400, use_cache: bool = True, allow_mocks: bool = False, as_of: str | None = None, resolver: SourceResolver | None = None, disease_id: str | None = None) -> DiseaseGraph
Build a comprehensive causal knowledge graph for a disease.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
disease
|
str
|
Disease name (e.g. "HIV", "Type 2 Diabetes"). |
required |
max_genes
|
int
|
Cap on number of genes to include. |
20
|
string_min_score
|
int
|
STRING combined score threshold (0–1000). |
400
|
use_cache
|
bool
|
Check/store results in the cache layer. |
True
|
allow_mocks
|
bool
|
If True, data source clients may fall back to curated
mock data when a live API call fails. If False
(default), failed API calls produce empty results. Refused
outright together with |
False
|
as_of
|
str | None
|
A release date for a dated build. |
None
|
resolver
|
SourceResolver | None
|
Resolves |
None
|
disease_id
|
str | None
|
EFO disease id. Required when |
None
|
Returns:
| Type | Description |
|---|---|
DiseaseGraph
|
Assembled graph with merged nodes and unified edges. |
Dated builds and live builds are not interchangeable
On a live build a gene node's score is OpenTargets' overall
association score: a harmonic sum over datasources, published by the
platform. On a dated build it is the maximum genetic-evidence
score in the pinned release, because the derived extract carries one
row per datatype and does not carry the overall score -- and
reconstructing it would mean putting a computed quantity where a
measurement belongs. Both are real numbers from Open Targets, but
they are different quantities: they must not be placed in the same
column of a table, ranked against each other, or pooled. The full
per-datatype breakdown is on both, in
metadata["datatype_scores"]. See
neorx.core.sources.snapshot_sources.
The gene node population of a dated build is the frame
The unpinned sources stay live on a dated build, because their edges
are not causal-admissible and identification filters them out. Their
nodes are another matter, and on a dated build they are restricted
to the pinned release's own gene population -- they may enrich a node
the release put in the graph, never introduce one, never overwrite a
pinned score or a pinned node's metadata, and never take a place in
the max_genes cap. See neorx.core.graph.dated_frame for what
each of those channels does when it is left open.
Source code in src/neorx/core/graph/graph_builder.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 | |
disease_graph_to_networkx ¶
Convert a DiseaseGraph to a NetworkX directed graph.
This is needed by DoWhy for causal inference. Node attributes
include node_type, score, uniprot_id, etc. Edge
attributes include edge_type, weight, source_db.
Source code in src/neorx/core/graph/graph_builder.py
Graph Persistence & Export¶
Save and load DiseaseGraph objects for reproducibility
and external analysis.
Formats
- JSON (native): Full-fidelity serialisation of DiseaseGraph
- GraphML: For Cytoscape, yEd, and NetworkX interop
- GEXF: For Gephi
- Cytoscape JSON (.cyjs): For Cytoscape web/desktop
Database
When PostgreSQL is available (Docker deployment), graphs are
also persisted to the disease_graphs table for querying
and sharing.
save_graph ¶
Save a DiseaseGraph to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
DiseaseGraph
|
The graph to save. |
required |
output_dir
|
Path
|
Defaults to |
None
|
fmt
|
str
|
|
'json'
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the saved file. |
Source code in src/neorx/core/graph/persistence.py
load_graph ¶
Load a DiseaseGraph from a JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str or Path
|
Path to a |
required |
Returns:
| Type | Description |
|---|---|
DiseaseGraph
|
|
Source code in src/neorx/core/graph/persistence.py
list_saved_graphs ¶
List saved graph files with metadata.
Returns:
| Type | Description |
|---|---|
list[dict]
|
Each dict has |
Source code in src/neorx/core/graph/persistence.py
neorx.core.graph.models¶
The data model shared by every stage.
NeoRx Data Models¶
Pydantic models for the causal drug-discovery pipeline.
The hierarchy:
1. GeneNode / ProteinNode / PathwayNode — graph entities
2. DiseaseGraph — the assembled causal knowledge graph
3. NeoRxResult — a protein evaluated as a potential target
4. ScoredCandidate — a drug candidate with composite score
5. PipelineResult — the full output of a pipeline run
Why causal reasoning matters
Most drug-discovery pipelines rank targets by correlation — which genes are differentially expressed in disease tissue? But correlation ≠ causation:
- TNF-α is highly correlated with HIV progression, but targeting it does not treat HIV. It is a downstream consequence, not a cause.
- HIV protease is causally upstream — inhibiting it blocks viral replication. Protease inhibitors work.
NeoRx applies Pearl's do-calculus to distinguish genuine
causal targets from correlational bystanders. The
NeoRxResult.is_causal_target flag captures this
distinction, and the composite scorer weights causal confidence
above binding affinity.
NodeType ¶
Bases: str, Enum
Types of nodes in the disease causal graph.
Source code in src/neorx/core/graph/models.py
EdgeType ¶
Bases: str, Enum
Types of biological relationships (edges) in the graph.
Source code in src/neorx/core/graph/models.py
TargetClassification ¶
JobStatus ¶
Bases: str, Enum
Pipeline execution status.
Source code in src/neorx/core/graph/models.py
GraphNode ¶
Bases: BaseModel
A node in the disease causal graph.
Every entity (gene, protein, pathway, phenotype) is represented as a node with a unique ID, a human-readable name, and metadata from the source database.
Source code in src/neorx/core/graph/models.py
GraphEdge ¶
Bases: BaseModel
An edge (relationship) in the disease causal graph.
Each edge represents a biological relationship with a confidence score and provenance.
Source code in src/neorx/core/graph/models.py
DiseaseGraph ¶
Bases: BaseModel
A causal knowledge graph for a specific disease.
Assembled from multiple databases (Monarch Initiative, Open Targets, KEGG, Reactome, STRING, UniProt). The graph captures known biological relationships: which genes cause the disease, which proteins interact, which pathways are disrupted.
The graph is stored both as:
- A networkx DiGraph (for DoWhy compatibility)
- A list of nodes and edges (for serialisation)
Source code in src/neorx/core/graph/models.py
NeoRxResult ¶
Bases: BaseModel
Result of causal analysis for a single protein target.
This is the core output of the causal reasoning layer. For each protein in the disease graph, we ask: "If we intervene on this protein (i.e. inhibit/activate it with a drug), does it causally affect the disease outcome?"
We answer this using Pearl's do-calculus via DoWhy:
-
Identifiability — Can we estimate the causal effect? The backdoor criterion checks if there is a valid set of variables to condition on that blocks all spurious paths.
-
Evidence aggregation — How much independent support does this target have? Reported as
evidence_score, not as a causal effect size: no interventional data enters it. -
Sensitivity analysis — Is the finding robust to removing any single source? Leave-one-source-out stability.
-
Classification — Combine all evidence to label the protein as a genuine causal target or a correlational bystander.
Source code in src/neorx/core/graph/models.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 | |
ScoredCandidate ¶
Bases: BaseModel
A drug candidate scored across multiple dimensions.
The composite score integrates: - Causal confidence (weight 0.30) — Is the target genuine? - Binding affinity (weight 0.25) — How tightly does it bind? - Drug-likeness (QED) (weight 0.15) — Is it drug-like? - Synthetic accessibility (weight 0.10) — Can it be made? - ADMET (weight 0.10) — Predicted pharmacokinetics - Novelty (weight 0.10) — Structural novelty vs known drugs
The key design decision: causal confidence has the HIGHEST weight. A moderately-binding molecule against a validated causal target ranks above a strongly-binding molecule against a correlational bystander.
Source code in src/neorx/core/graph/models.py
PipelineJob ¶
Bases: BaseModel
Tracks a pipeline execution job.
Source code in src/neorx/core/graph/models.py
PipelineResult ¶
Bases: BaseModel
Complete output of a NeoRx pipeline run.
Contains everything needed to understand why specific drug candidates were recommended: the disease graph, the causal reasoning for each target, and the scored candidates.
Source code in src/neorx/core/graph/models.py
top_candidates
property
¶
Top 10 candidates by composite score.
neorx.core.pipeline¶
NeoRx Pipeline¶
The pipeline orchestrates the full causal drug-discovery workflow:
- Build Graph → query 7 databases, assemble causal knowledge graph
- Identify Targets → apply do-calculus to find causal targets
- Generate Candidates → use GenMol VAE to create novel molecules
- Screen Candidates → MolScreen (drug-likeness) + DockBot (binding)
- Score & Rank → composite scorer with causal confidence weighting
- Report → generate HTML report with interactive visualisations
Integration Points
graph_builder.build_disease_graph()→ DiseaseGraphidentifier.identify_causal_targets()→ list[NeoRxResult]neorx.genmol.generate.generate()→ list[str]neorx.molscreen.properties.calculate_properties()→ MolecularPropertiesneorx.molscreen.accessibility.qed_score()/sa_score()neorx.molscreen.filters.run_all_filters()→ list[FilterResult]neorx.molscreen.similarity.find_similar_drugs()→ noveltyneorx.dockbot.protein_prep.prepare_protein()→ ProteinInfoneorx.dockbot.ligand_prep.prepare_ligand_pdbqt()→ (Mol, pdbqt)neorx.dockbot.docker.dock()→ DockingResultscorer.score_candidate()→ ScoredCandidate
Error Handling
Degradation is allowed only where the degraded result is still an
honest one. If DockBot fails we score without binding affinity, and
say so. Generation is not like that: a candidate list is either the
model's output or it is not, and nothing downstream can tell the
difference, so _generate_for_target raises rather than substituting
anything for the trained model. A failure there fails the job, which
is recorded on the PipelineJob.
run_pipeline ¶
run_pipeline(disease: str, top_n_targets: int = 5, candidates_per_target: int = 100, *, generate_molecules: bool = True, run_docking: bool = True, generate_report: bool = True, prebuilt_graph: DiseaseGraph | None = None, allow_mocks: bool = False) -> PipelineResult
Run the full NeoRx pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
disease
|
str
|
Disease name (e.g. "HIV", "Type 2 Diabetes"). |
required |
top_n_targets
|
int
|
Number of top causal targets to pursue. |
5
|
candidates_per_target
|
int
|
Molecules to generate per target. |
100
|
generate_molecules
|
bool
|
Whether to run GenMol generation. |
True
|
run_docking
|
bool
|
Whether to run DockBot docking. |
True
|
generate_report
|
bool
|
Whether to generate HTML report. |
True
|
prebuilt_graph
|
DiseaseGraph
|
Pre-built disease graph. If provided, Step 1 is skipped and this graph is used directly. Useful for testing and for interactive workflows where the graph was already constructed. |
None
|
allow_mocks
|
bool
|
If True, data-source clients may fall back to curated mock data when live APIs fail. Default False. |
False
|
Returns:
| Type | Description |
|---|---|
PipelineResult
|
Complete pipeline output with graph, targets, candidates. |
Source code in src/neorx/core/pipeline/__init__.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
run_rl_pipeline ¶
run_rl_pipeline(disease: str, top_n_targets: int = 5, n_episodes: int = 10, max_steps_per_episode: int = 50, latent_dim: int = 128, *, prebuilt_graph: DiseaseGraph | None = None, allow_mocks: bool = False, seed: int = 42) -> PipelineResult
Run the RL-driven drug-discovery pipeline.
Instead of the linear generate-then-screen flow in
:func:run_pipeline, this mode trains a CausalBioRL agent
inside a :class:DrugDiscoveryEnv. The agent iteratively
selects targets (UCB) and navigates GenMol's latent space
(CEM) to discover high-scoring molecules.
The function reuses the same graph-building and target-identification steps, but replaces Steps 3–5 with an RL optimisation loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
disease
|
str
|
Disease name. |
required |
top_n_targets
|
int
|
Number of causal targets to pursue. |
5
|
n_episodes
|
int
|
Number of RL episodes (each episode is a full campaign). |
10
|
max_steps_per_episode
|
int
|
Generate-screen cycles per episode. |
50
|
latent_dim
|
int
|
GenMol latent-space dimensionality. |
128
|
prebuilt_graph
|
DiseaseGraph
|
Pre-built disease graph (skips Step 1). |
None
|
allow_mocks
|
bool
|
Allow fallback mock data for data sources. |
False
|
seed
|
int
|
Random seed for reproducibility. |
42
|
Returns:
| Type | Description |
|---|---|
PipelineResult
|
Same schema as :func: |
Source code in src/neorx/core/pipeline/__init__.py
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 | |
neorx.core.scoring¶
Candidate ranking. See Ranking candidates.
Composite Drug-Candidate Scorer¶
The scorer ranks drug candidates across six dimensions:
- Causal confidence (0.30) — Is the target genuinely causal?
- Binding affinity (0.25) — How tightly does it bind?
- Drug-likeness (QED) (0.15) — Lipinski / Veber / QED
- Synthetic accessibility (0.10) — Can it be synthesised?
- ADMET (0.10) — Predicted pharmacokinetics
- Novelty (0.10) — Structural novelty vs known drugs
The critical design decision: causal confidence has the highest weight. A moderately-binding molecule aimed at a validated causal target is ranked above a tightly-binding molecule aimed at a correlational bystander. This is what distinguishes NeoRx from conventional virtual screening pipelines.
Normalisation
Raw scores live on different scales: - Binding affinity: −12 to 0 kcal/mol (more negative = better) - QED: 0 to 1 - SA score: 1 to 10 (lower = easier to synthesise) - ADMET: 0 to 1 - Novelty: 0 to 1
We normalise everything to [0, 1] where 1 = best before applying weights.
score_candidate ¶
score_candidate(smiles: str, target_protein_id: str, target_protein_name: str, causal_confidence: float, binding_affinity: float | None = None, qed_score: float | None = None, sa_score: float | None = None, admet_score: float = 0.5, novelty_score: float = 0.5, molecular_weight: float | None = None, logp: float | None = None, drug_likeness_class: str = '', n_filters_passed: int = 0, weights: dict[str, float] | None = None) -> ScoredCandidate
Score a single drug candidate across all dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles
|
str
|
SMILES string of the candidate molecule. |
required |
target_protein_id
|
str
|
Target protein identifier. |
required |
target_protein_name
|
str
|
Target protein name. |
required |
causal_confidence
|
float
|
Causal confidence for the target (0–1). |
required |
binding_affinity
|
float
|
Docking score in kcal/mol (negative = better). |
None
|
qed_score
|
float
|
Quantitative Estimate of Drug-likeness (0–1). |
None
|
sa_score
|
float
|
Synthetic accessibility (1=easy, 10=hard). |
None
|
admet_score
|
float
|
Predicted ADMET score (0–1). |
0.5
|
novelty_score
|
float
|
Structural novelty vs known drugs (0–1). |
0.5
|
molecular_weight
|
float
|
Molecular weight in Da. |
None
|
logp
|
float
|
Predicted logP. |
None
|
drug_likeness_class
|
str
|
Drug-likeness classification. |
''
|
n_filters_passed
|
int
|
Number of drug-likeness filters passed. |
0
|
Returns:
| Type | Description |
|---|---|
ScoredCandidate
|
Fully scored candidate with composite score. |
Source code in src/neorx/core/scoring/scorer.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | |
rank_candidates ¶
Sort candidates by composite score and assign ranks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
candidates
|
list[ScoredCandidate]
|
Unranked scored candidates. |
required |
Returns:
| Type | Description |
|---|---|
list[ScoredCandidate]
|
Ranked (best-first) with |
Source code in src/neorx/core/scoring/scorer.py
normalise_affinity ¶
Normalise binding affinity to [0, 1].
More negative → better → higher score.
Examples: - −12 kcal/mol → 1.0 (excellent binder) - −6 kcal/mol → 0.5 (moderate binder) - 0 kcal/mol → 0.0 (no binding)
Source code in src/neorx/core/scoring/scorer.py
normalise_sa ¶
Normalise synthetic accessibility to [0, 1].
Lower SA → easier to synthesise → higher score.
Examples: - SA = 1 → 1.0 (trivially synthesisable) - SA = 5 → 0.56 (moderate) - SA = 10 → 0.0 (practically unsynthesisable)
Source code in src/neorx/core/scoring/scorer.py
ADMET Property Predictor¶
Multi-rule ADMET (Absorption, Distribution, Metabolism, Excretion, Toxicity) scoring based on established medicinal chemistry rules.
Rules Applied
- Lipinski's Rule of Five (absorption)
- Veber Rules (oral bioavailability)
- Ghose Filter (drug-likeness range)
- Egan Egg Model (intestinal absorption)
- PAINS Filter (pan-assay interference)
- BBB Permeability Estimate
- hERG Liability Estimate
- Reactive-Group Toxicophore Alerts
Each rule contributes to a composite ADMET score in [0, 1].
ADMETProfile
dataclass
¶
Detailed ADMET assessment for a molecule.
Source code in src/neorx/core/scoring/admet.py
predict_admet ¶
Predict ADMET properties for a molecule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles
|
str
|
SMILES string. |
required |
Returns:
| Type | Description |
|---|---|
ADMETProfile
|
Multi-dimensional ADMET assessment with composite score. |
Source code in src/neorx/core/scoring/admet.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | |
neorx.core.bio¶
The biological intelligence layer.
Target Classification System¶
Multi-level target classifier that distinguishes between biologically meaningful target categories. This prevents the critical error observed in malaria runs where host symptom markers (GABRD, SCN2A — brain neurotransmitter / ion channel proteins associated with cerebral malaria seizures) were misclassified as causal drug targets.
Target Hierarchy
- PATHOGEN_DIRECT — Parasite / viral protein (e.g. PfDHFR, HIV protease). Highest-priority drug target.
- HOST_INVASION — Host protein the pathogen directly binds / hijacks (e.g. GYPA for P. falciparum, CCR5 for HIV).
- HOST_IMMUNE — Host immune receptor relevant to disease response (e.g. TLR7, TLR9). Valid target but with caveats.
- HOST_SYMPTOM — Host protein associated with disease symptoms rather than mechanism (e.g. GABRD in cerebral malaria, coagulation factors in sepsis). Should be classified as CORRELATIONAL, not causal.
- CORRELATIONAL — Statistical association without any mechanistic evidence.
Disease Type Awareness
Classification behaviour changes depending on disease type: - Infectious diseases: check for pathogen vs host origin, check host-pathogen interaction evidence. - Cancers: all targets are host, but distinguish driver vs passenger mutations. - Metabolic diseases: distinguish causal pathway genes vs downstream biomarkers.
TargetType ¶
Bases: str, Enum
Biological role of a candidate drug target.
Source code in src/neorx/core/bio/classifier.py
DiseaseType ¶
Bases: str, Enum
Broad disease category affecting target classification.
Source code in src/neorx/core/bio/classifier.py
TargetClassifier ¶
Classify targets into biologically meaningful categories.
This classifier prevents the critical error of treating host symptom markers as genuine causal drug targets. For malaria, this catches GABRD, SCN2A, etc.
The classification pipeline:
- Blocklist check — is the gene in a known symptom marker family (GABA receptors, sodium channels, etc.)?
- Inflammatory cytokine check — TNF, IL6, IL1B, CXCL8, IL10 are HOST_SYMPTOM for infections (must run before the general immune check to avoid being caught as HOST_IMMUNE).
- Immune receptor check — TLR, NOD, HLA, etc. are HOST_IMMUNE for infections.
- Disease-type-aware heuristics — for infectious diseases, check pathogen vs host origin.
Source code in src/neorx/core/bio/classifier.py
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | |
classify ¶
classify(gene_symbol: str, disease_type: DiseaseType, evidence: dict[str, Any] | None = None) -> tuple[TargetType, str]
Classify a single target gene.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gene_symbol
|
str
|
Gene symbol (e.g. "GABRD", "CCR5", "EGFR"). |
required |
disease_type
|
DiseaseType
|
The broad disease category. |
required |
evidence
|
dict
|
Node metadata / evidence from the graph. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[TargetType, str]
|
(target_type, human-readable reason) |
Source code in src/neorx/core/bio/classifier.py
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
classify_batch ¶
classify_batch(targets: list[dict[str, Any]], disease_type: DiseaseType) -> list[tuple[TargetType, str]]
Classify a batch of targets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
list[dict]
|
Each dict must have |
required |
disease_type
|
DiseaseType
|
Broad disease category. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[TargetType, str]]
|
|
Source code in src/neorx/core/bio/classifier.py
classify_disease ¶
Determine the broad disease category from the disease name.
Uses a curated lookup table; falls back to OTHER for
unrecognised diseases.
Source code in src/neorx/core/bio/classifier.py
neorx.core.sources¶
One function per source. Each returns
tuple[list[GraphNode], list[GraphEdge]] and returns empty lists rather
than raising, so the graph builder can aggregate what answered.
Data Sources¶
API clients for biomedical databases used to build disease causal graphs. Each client follows the same pattern:
- Query the database for disease-associated entities
- Parse the response into
GraphNodeandGraphEdgeobjects - Handle rate limits, timeouts, and API errors gracefully
- Return empty lists (never crash) on failure — the graph builder aggregates results from multiple sources
All clients use requests and are synchronous. For
production, consider httpx with async support.
All HTTP traffic in this package is subject to recording. When these
modules run inside neorx.experiments.capture, every request and
response is frozen into the run's cassette so the run can be replayed
exactly. Adding a source that uses a client other than requests will
silently escape that recording -- see neorx/experiments/capture.py.
query_monarch, query_open_targets, query_kegg_pathways,
query_reactome_pathways, query_string_interactions,
query_omnipath, query_uniprot, query_pdb_structures,
query_chembl.
neorx.snapshots¶
The versioned data layer. See Versioned snapshots.
The canonical shape of a derived extract.
Three OpenTargets format eras feed this pipeline: a flat gzipped JSON dump in 2018, an ETL-era Parquet tree in 2021, and the current output layout. Each gets its own reader, and each reader's job is to produce exactly the columns below. Downstream code -- the frame, the resolver, the graph builder -- never learns which era a row came from.
That is the whole value of a derived extract rather than a mirror: format drift is absorbed once, at the edge, instead of leaking into every consumer.
ExtractNotes
dataclass
¶
What a reader had to do to the source that the rows no longer show.
Both facts are recorded rather than defaulted away, because both change
what the extract means and neither is visible in the extract itself.
consensus_direction_synthesised says the 2018 archive had no such
column and is_directed was used in its place -- a weaker criterion
than later eras publish. non_human_rows_dropped says how many rows
the organism filter removed; a count of zero on a real OmniPath archive
means the filter did not fire, not that the dump was human-only.
Source code in src/neorx/snapshots/schema.py
empty_associations ¶
empty_interactions ¶
What a snapshot records about itself.
A release identifier alone does not identify a derived extract. Two extracts of OpenTargets 18.06 produced by different extractor code are different inputs to every number computed downstream, so the extractor version is recorded beside the release id, and the digest is taken over the extract actually written rather than the upstream file.
Keyed by (source, release), so re-running an extraction replaces its entry instead of appending a second one.
SnapshotEntry
dataclass
¶
One derived extract, and everything needed to identify it.
Source code in src/neorx/snapshots/manifest.py
read_manifest ¶
Read every entry, keyed by (source, release). Absent file: no entries.
Source code in src/neorx/snapshots/manifest.py
write_entry ¶
Insert or replace one entry, leaving every other entry untouched.
Source code in src/neorx/snapshots/manifest.py
digest_file ¶
SHA-256 of a file, read in chunks so a large extract does not load.
Source code in src/neorx/snapshots/manifest.py
Reading derived extracts back off disk.
This layer knows the on-disk layout and nothing else. By the time a frame reaches it, which upstream era produced it is invisible -- that is the whole point of extracting to a canonical schema.
A missing snapshot raises rather than returning an empty frame. An empty frame reads downstream as "this release recorded no evidence for that disease", which is a finding; a missing extract is a configuration mistake, and the two must not be confusable.
SnapshotStore ¶
Derived extracts under a root directory.
Layout::
<root>/opentargets/<release>/associations.parquet
<root>/omnipath/<release>/interactions.parquet
<root>/manifest.toml
Source code in src/neorx/snapshots/reader.py
manifest_path
property
¶
The manifest describing the extracts under this root.
Derived from the root rather than configured beside it, so the extracts a run reads and the manifest it cites cannot come from two different places.
__init__ ¶
on_read(source, release, path) runs after every extract read.
It is how a run record learns what a run actually read, so it can cite exactly that -- from this store's own manifest, rather than from a second path that might name a different store.
Required, with no default, deliberately. When it defaulted to
None an experiment could read one extract through
RunRecord.snapshot_store and another through a store it built
itself, and finish complete and citable while citing only the
first: the runner's guard fires when NO read was tracked, not when
some were missed. It cannot see a store it was never told about,
so the construction has to say. on_read=None is still
available -- for the CLI and for unit tests of the reader -- but
it is now written down rather than inherited.
Source code in src/neorx/snapshots/reader.py
has ¶
associations ¶
interactions ¶
Choosing between a live client and a snapshot reader.
With no date, every source resolves to the live client it always used and behaviour is unchanged -- interactive single-disease use is unaffected by this whole sub-project.
With a date, the sources feeding the causal subgraph resolve to snapshot readers, and a source with no snapshot at that date is refused by name. The refusal matters more than it looks: a dated run that quietly mixed in current data would produce exactly the anachronistic graph this sub-project exists to prevent, and would do it invisibly.
Sources that contribute only associational edges stay live even on a dated run. Identification filters those edges out before it runs, so pinning them would buy rigour against a leak that does not exist.
SourceResolver ¶
Maps a source name plus an optional date to a reader.
release_for(source, as_of) maps a date to a release identifier, so
the date-to-release table lives in one place rather than at every call
site.
Source code in src/neorx/snapshots/resolver.py
resolve ¶
Return the reader for this source at this date.
Undated, or unpinned, this is the live client itself. Dated and
pinned, it is a snapshot reader bound to the release, returning
the same tuple[list[GraphNode], list[GraphEdge]] the live
client returns -- so the caller assembles a dated graph through
the same code path as a live one and cannot accidentally hold a
reader it does not know how to call.
Raises UnpinnedSourceError if the date requires a snapshot that
does not exist. It does not fall back to the live client.
Source code in src/neorx/snapshots/resolver.py
Which release a date resolves to, for each pinned source.
SourceResolver takes release_for as an injected callable so the
date-to-release table lives in one place instead of at every call site.
Until now the only implementations were lambdas inside tests, which meant
no production path could run a dated build at all: the machinery existed
and nothing could reach it.
Every entry here was verified against the live archive on 2026-09-06 by listing it, not by reading the spec's table. Two of the three pairings are as close as that table claimed; the third is not, and the discrepancy is recorded rather than smoothed over.
UnknownTimePointError ¶
release_for ¶
The release identifier source is pinned to at as_of.
Raises rather than guessing. A dated run that silently fell back to
some nearby release would produce exactly the anachronistic graph this
sub-project exists to prevent, and would do it invisibly -- the same
reasoning that makes SourceResolver refuse an unbuilt snapshot
instead of using the live client.
Source code in src/neorx/snapshots/releases.py
omnipath_archive_url ¶
The archive URL for the OmniPath dump pinned to as_of.
Every dump is .tsv.xz; the builder detects compression from the
file's magic bytes rather than this extension, because an archive
URL's extension is a claim and this one was wrong in the spec for the
life of the sub-project.
Source code in src/neorx/snapshots/releases.py
neorx.experiments¶
The run-record system. See Experiments and run records.
Run records: the artifact that makes a reported number traceable.
A record is written incrementally. Rows land on disk as each cell of an experiment completes, so a crash costs the current cell rather than the run -- the failure that lost 881 seconds of the original RL benchmark and led to its numbers being retyped by hand.
Nothing here degrades on error. A record that cannot be written is a failed run, not a quiet one.
RunRecord ¶
One execution of one experiment.
Source code in src/neorx/experiments/record.py
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | |
snapshot_reads
property
¶
Every (source, release) this run read, in a stable order.
snapshot_store ¶
A snapshot store whose every read is recorded against this run.
Experiments open stores through this rather than constructing one directly, so what gets cited is what was read -- not the whole manifest, and not a manifest found by a second path that could name a different store.
Source code in src/neorx/experiments/record.py
settle_snapshot_citations ¶
Cite exactly the extracts this run read; return any it could not.
Each citation is the whole manifest entry, not a chosen subset. A
digest pins which bytes an extract was, not what they meant, and
the manifest that says what they meant is replaced in place when an
extract is rebuilt -- so a run record that kept only the digest
would, months later, cite something nothing can interpret.
synthesised_consensus is what makes that bite: it says whether
OmniPath's consensus direction was read or derived, which changes
what every directed edge in a dated graph means. source and
release are dropped only because they are the key.
A read whose extract has no manifest entry is not silently left
out: it is written under snapshots_uncited and returned, so the
caller decides whether that is fatal and the record says so either
way.
Source code in src/neorx/experiments/record.py
note_settlement_failure ¶
Record that citations could not be settled, and why.
Only reached when the run was already failing. Losing the record to a second fault would leave the operator reading the manifest error instead of the one that stopped the run.
Source code in src/neorx/experiments/record.py
append_row ¶
Append one result row, flushed to disk immediately.
Source code in src/neorx/experiments/record.py
ProvenanceError ¶
Bases: RuntimeError
Raised when the code provenance of a run cannot be established.
A run whose git SHA or dirty state cannot be determined has no provenance. It is a failed run, not one that quietly records a fabricated SHA or a false "clean" state.
Source code in src/neorx/experiments/record.py
RecordTooLargeError ¶
Experiment registry.
An experiment is a function taking a RunRecord. It never opens a file and never decides where results go -- the runner does both. That is what makes "a number cannot exist without a record" structural rather than a habit.
ExperimentDef
dataclass
¶
Source code in src/neorx/experiments/registry.py
UnknownExperimentError ¶
experiment ¶
experiment(*, name: str, help: str = '', captures_http: bool = False, volatile_fields: tuple[str, ...] = (), reads_snapshots: bool = False) -> Callable[[ExperimentFn], ExperimentFn]
Register an experiment under name.
captures_http declares that the experiment needs its HTTP traffic
recorded. An experiment never chooses the capture mode -- only the
caller (a live run vs. a replay) knows whether that should be record
or replay -- so it only declares the need; the runner decides the mode.
volatile_fields declares row keys that are expected to differ on
every replay (wall-clock timings and similar) -- see
ExperimentDef.volatile_fields.
reads_snapshots declares that the experiment's numbers come from
pinned extracts, so the runner records which ones. Without it, an
experiment reading snapshots writes an env.json whose
snapshots object is empty -- a run citing no inputs, which is the
provenance failure this project already found in four published
papers.
Source code in src/neorx/experiments/registry.py
run_experiment ¶
Execute an experiment, writing its record whatever the outcome.
env.json cites exactly the extracts the run read, taken from the
manifest of the store it read them from.
Source code in src/neorx/experiments/registry.py
get_experiment ¶
Source code in src/neorx/experiments/registry.py
list_experiments ¶
settle_or_refuse ¶
Cite what the run read, and refuse a run whose inputs cannot be named.
Called after a run completes, by both the runner and replay, so the two
cannot drift apart -- they did once, and a replay cited nothing while
reporting identical: True.
Two refusals. A read with no manifest entry: the extracts were there
and the manifest describing them was not, so the run produced numbers
from inputs it cannot identify -- the failure this project found in
four published papers. And an experiment that declares
reads_snapshots but recorded no reads: it opened a store some way
other than RunRecord.snapshot_store, so nothing it read was tracked.
What it deliberately does NOT accept is "some citation exists". The earlier check did, and a run over the 18.06 release completed while citing only a 25.06 entry that happened to be in the manifest.
Source code in src/neorx/experiments/registry.py
Re-execute a recorded run against its frozen inputs and diff the result.
This is the claim the subsystem rests on: given a run record, anyone can reproduce its numbers without reaching the network. A replay that differs is not a failure of the tool -- it names exactly which values moved, which is the information a reviewer actually needs.
ReplayResult
dataclass
¶
Source code in src/neorx/experiments/replay.py
RowDiff
dataclass
¶
NotReplayableError ¶
replay_experiment ¶
Re-run a recorded experiment against its cassette and diff the rows.
Source code in src/neorx/experiments/replay.py
prune_record ¶
Drop a run's frozen inputs, keeping its results. Returns bytes freed.
Source code in src/neorx/experiments/replay.py
Checks that make "no number without a record" enforceable.
Each gate closes one hole the manuscript audit found:
find_hardcoded_metrics-- _gen_figures.py held the F1 values as literals, so Figure 3 was a transcription of a table rather than a rendering of data.check_records_wellformed-- a record whose summary disagrees with its rows is not evidence.check_cited_runs-- a manuscript citing a run that does not exist, or one nobody can reproduce.check_committed_records_are_citable-- a non-citable run record (dirty tree, incomplete, or failed) committed to git anyway, adding ~MB of weight to the repository while backing no claim.check_record_integrity-- rows.jsonl edited after the fact (e.g. an F1 changed from 0.474 to 0.999, row count left untouched) with no other gate noticing. This detects accidental edits and drift by recomputing the SHA-256 stored at finalise time; it does NOT detect a determined forger who edits rows.jsonl and recomputes/rewrites rows_sha256 to match -- that requires signing the record, which this gate is not.
Known limit of find_hardcoded_metrics: it matches bare ast.Constant
float literals, and ast.Constant string literals that contain a
metric-shaped number (a digit, a decimal point, and >= METRIC_DECIMALS
digits after it -- e.g. "C=0.990"). A metric assembled by computation --
545 / 1000, round(x, 3), an f-string embedding a number, a value
read from a dict -- is invisible to an AST literal check by construction,
not by an oversight fixable here. A clean run of this gate means "no
metric was typed in as a float literal or spelled out in a string
literal"; it does NOT mean "no computed metric literal exists anywhere in
this file". Treat "0 findings" accordingly.
Finding
dataclass
¶
find_hardcoded_metrics ¶
Flag metric-shaped float literals (>= METRIC_DECIMALS decimals) and
metric-shaped numbers spelled inside string literals (e.g. "C=0.990"). A measured value transcribed as a string evades a float-only check just as completely as one assembled by computation -- this closes that hole for the string case specifically.
Source code in src/neorx/experiments/gates.py
check_records_wellformed ¶
Every run directory must have a summary that matches its rows.
Source code in src/neorx/experiments/gates.py
check_record_integrity ¶
Every run record's stored rows_sha256 must match its rows.jsonl.
RunRecord.finalise computes a SHA-256 over rows.jsonl's bytes at
finalise time and stores it in record.json as rows_sha256. A record
edited afterwards -- a metric changed, a row dropped, in either case
with the row count left alone so check_records_wellformed sees
nothing wrong -- will disagree with that stored digest.
This catches accidental edits and drift, not a forger who edits rows.jsonl and also recomputes and rewrites rows_sha256 to match; that is a signing problem, not a hashing problem, and out of scope here.
Source code in src/neorx/experiments/gates.py
check_committed_records_are_citable ¶
check_committed_records_are_citable(runs_dir: Path, tracked: set[str] | None = None) -> list[Finding]
Every run record committed to git must be citable.
runs/ is tracked on the theory that its records are the evidence
behind every reported number. A record with citable: false (built
from a dirty tree, or left incomplete or failed) is not evidence --
the figure command already refuses to render from one -- so committing
it adds weight to the repository without adding anything that backs a
claim. tracked is the set of run-directory names (run IDs) known
to be committed; when omitted, it is read from git ls-files.
Source code in src/neorx/experiments/gates.py
check_cited_runs ¶
Every run cited by a manuscript must exist and be citable.
Source code in src/neorx/experiments/gates.py
check_no_fabricated_statistics ¶
Assert no fabricated statistic has been reintroduced.
Scoped to a directory by argument, never to src/ as a whole:
neorx/genmol/evaluation/distribution.py reports a genuine
Kolmogorov-Smirnov p-value, and a repository-wide search would flag
it. Point this at neorx/core/causal/ only.
Source code in src/neorx/experiments/gates.py
neorx.genmol¶
Molecule generation. See GenMol.
Loading of the GenMol weights shipped with the package.
The loader raises on missing or inconsistent assets. It never returns an untrained model: a randomly initialised VAE emits plausible-looking SMILES, so silent degradation here is undetectable downstream.
GenMolAssetError ¶
load_pretrained ¶
Load the packaged MolVAE and its matching tokenizer.
Returns:
| Type | Description |
|---|---|
tuple[MolVAE, SmilesTokenizer]
|
Model in eval mode, and the tokenizer it was trained against. |
Raises:
| Type | Description |
|---|---|
GenMolAssetError
|
If either asset is absent, or the tokenizer carries no vocabulary. |
Source code in src/neorx/genmol/pretrained.py
Molecule Generation¶
Generates novel molecules from a trained VAE by sampling from the latent space and decoding to SMILES.
Generation modes
-
Random sampling — draw
z ~ N(0, I)and decode. The simplest approach; generates diverse molecules. -
Temperature-controlled — scale logits by
1/Tbefore softmax. Lower T → more conservative (higher probability tokens), higher T → more diverse (and more invalid). -
Beam search — maintain
beam_widthcandidate sequences at each step, expanding the most probable ones. Produces higher validity but lower diversity. -
Latent interpolation — decode a series of points between two latent vectors to observe smooth structural transformations.
-
Conditional generation (CVAE) — specify desired molecular properties and generate molecules matching those targets.
Post-generation filtering
Generated SMILES are validated with RDKit, deduplicated, and optionally filtered through the MolScreen pipeline for drug-likeness.
generate ¶
generate(model: MolVAE, tokenizer: SmilesTokenizer, n: int = 100, temperature: float = 1.0, device: Optional[device] = None, validate: bool = True, deduplicate: bool = True) -> list[str]
Generate molecules by sampling from the prior N(0, I).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
MolVAE
|
Trained VAE model. |
required |
tokenizer
|
SmilesTokenizer
|
Tokenizer for decoding. |
required |
n
|
int
|
Number of molecules to attempt generating. |
100
|
temperature
|
float
|
Sampling temperature (0.5–1.5 recommended). |
1.0
|
device
|
device
|
Computation device. |
None
|
validate
|
bool
|
Only return valid SMILES. |
True
|
deduplicate
|
bool
|
Remove duplicate molecules. |
True
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Generated (and optionally validated) SMILES. |
Source code in src/neorx/genmol/generate.py
generate_conditional ¶
generate_conditional(model: MolCVAE, tokenizer: SmilesTokenizer, conditions: dict[str, float], normalizer: PropertyNormalizer, n: int = 100, temperature: float = 1.0, device: Optional[device] = None, validate: bool = True) -> list[str]
Generate molecules with desired properties (CVAE).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
MolCVAE
|
Trained conditional VAE. |
required |
tokenizer
|
SmilesTokenizer
|
Tokenizer for decoding. |
required |
conditions
|
dict[str, float]
|
Desired properties, e.g. |
required |
normalizer
|
PropertyNormalizer
|
Fitted normalizer for property scaling. |
required |
n
|
int
|
Number of molecules to generate. |
100
|
temperature
|
float
|
Sampling temperature. |
1.0
|
device
|
device
|
Device. |
None
|
validate
|
bool
|
Only return valid SMILES. |
True
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Generated SMILES matching the desired conditions. |
Source code in src/neorx/genmol/generate.py
interpolate ¶
interpolate(model: MolVAE, tokenizer: SmilesTokenizer, smiles_a: str, smiles_b: str, n_steps: int = 10, device: Optional[device] = None) -> list[str]
Interpolate between two molecules in latent space.
Encodes both molecules, then decodes n_steps evenly-spaced
points along the line between them. This reveals how the model
organises chemical space — nearby points should be structurally
similar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
MolVAE
|
Trained VAE. |
required |
tokenizer
|
SmilesTokenizer
|
Tokenizer. |
required |
smiles_a
|
str
|
Starting molecule SMILES. |
required |
smiles_b
|
str
|
Ending molecule SMILES. |
required |
n_steps
|
int
|
Number of interpolation points (including endpoints). |
10
|
device
|
device
|
Device. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
SMILES at each interpolation point (some may be invalid). |
Source code in src/neorx/genmol/generate.py
Molecular VAE (Variational Autoencoder)¶
A β-VAE that learns a continuous latent representation of drug-like molecules from their SMILES strings.
Architecture overview
::
SMILES ──► Encoder (bidirectional GRU) ──► μ, log σ²
│
z ~ N(μ, σ²)
│
Decoder (autoregressive GRU) ◄───────┘
│
SMILES (reconstructed)
Why a VAE for molecules?
- Smooth latent space — nearby points decode to similar molecules, enabling interpolation between drugs and optimisation by gradient descent in latent space.
- Generative — sampling
z ~ N(0, I)produces novel, valid molecules. - Disentangled — β > 1 encourages disentangled representations where individual latent dimensions correspond to molecular properties.
Key design choices
- GRU over LSTM — fewer parameters, trains faster on SMILES (sequence lengths < 120 don't need LSTM's extra gates).
- 3-layer bidirectional encoder — captures both forward and backward context in the SMILES string.
- Teacher forcing — during training, the decoder receives the ground-truth previous token instead of its own prediction. This stabilises early training and speeds convergence.
- KL annealing — the β weight on the KL divergence is linearly increased from 0.01 → 1.0 over the first 10 epochs. Without annealing, the model can fall into "posterior collapse" where the encoder ignores the input and the decoder becomes an unconditional language model.
MolVAE ¶
Bases: Module
Molecular Variational Autoencoder.
Combines MolEncoder and MolDecoder with the
reparameterization trick and β-weighted KL divergence.
The reparameterization trick allows backpropagation through the stochastic sampling step:
.. math::
z = \mu + \sigma \cdot \epsilon, \quad \epsilon \sim N(0, I)
This makes the sampling differentiable — gradients flow through μ and σ, not through the random noise ε.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vocab_size
|
int
|
Vocabulary size. |
required |
embed_dim
|
int
|
Embedding dimension. |
64
|
hidden_dim
|
int
|
GRU hidden dimension. |
256
|
latent_dim
|
int
|
Latent space dimension. |
128
|
num_layers
|
int
|
GRU layers. |
3
|
dropout
|
float
|
Dropout rate. |
0.2
|
max_length
|
int
|
Maximum sequence length. |
120
|
pad_idx
|
int
|
Padding token index. |
0
|
Source code in src/neorx/genmol/models/vae.py
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 | |
reparameterize ¶
Sample z using the reparameterization trick.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mu
|
Tensor[B, D]
|
Mean of the approximate posterior. |
required |
logvar
|
Tensor[B, D]
|
Log-variance of the approximate posterior. |
required |
Returns:
| Type | Description |
|---|---|
Tensor[B, D]
|
Sampled latent vector. |
Source code in src/neorx/genmol/models/vae.py
forward ¶
forward(x: Tensor, target: Optional[Tensor] = None) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]
Forward pass: encode → sample → decode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor[B, L]
|
Input token IDs. |
required |
target
|
Tensor[B, L]
|
Target token IDs for teacher forcing.
If |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
logits |
Tensor[B, L - 1, V]
|
Reconstruction logits. |
mu |
Tensor[B, D]
|
Posterior mean. |
logvar |
Tensor[B, D]
|
Posterior log-variance. |
Source code in src/neorx/genmol/models/vae.py
encode ¶
Encode input to the latent mean (deterministic).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor[B, L]
|
Token IDs. |
required |
Returns:
| Type | Description |
|---|---|
Tensor[B, D]
|
Latent means. |
Source code in src/neorx/genmol/models/vae.py
decode ¶
Decode latent vectors to token sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor[B, D]
|
Latent vectors. |
required |
temperature
|
float
|
Sampling temperature (lower = more conservative). |
1.0
|
greedy
|
bool
|
If True, use argmax instead of sampling. |
False
|
Returns:
| Type | Description |
|---|---|
Tensor[B, L - 1]
|
Generated token ID sequences. |
Source code in src/neorx/genmol/models/vae.py
sample ¶
Sample from the prior N(0, I) and decode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of molecules to generate. |
1
|
temperature
|
float
|
Decoding temperature. |
1.0
|
device
|
device
|
Device for tensors. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor[n, L - 1]
|
Generated token ID sequences. |
Source code in src/neorx/genmol/models/vae.py
vae_loss ¶
vae_loss(logits: Tensor, target: Tensor, mu: Tensor, logvar: Tensor, beta: float = 1.0, pad_idx: int = 0) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]
Compute β-VAE loss = reconstruction + β · KL divergence.
The reconstruction loss is cross-entropy over the vocabulary
at each position, ignoring <PAD> tokens.
The KL divergence measures how far the approximate posterior
q(z|x) deviates from the prior p(z) = N(0, I):
.. math::
D_{KL}(q \| p) = -\frac{1}{2} \sum_{j=1}^{D}
\left(1 + \log \sigma_j^2 - \mu_j^2 - \sigma_j^2\right)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor[B, L - 1, V]
|
Decoder output logits. |
required |
target
|
Tensor[B, L]
|
Ground-truth token IDs (loss is computed against |
required |
mu
|
Tensor[B, D]
|
Posterior mean. |
required |
logvar
|
Tensor[B, D]
|
Posterior log-variance. |
required |
beta
|
float
|
KL weight (β in β-VAE). |
1.0
|
pad_idx
|
int
|
Padding token index to ignore. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
total_loss |
Tensor
|
β-VAE loss. |
recon_loss |
Tensor
|
Reconstruction (cross-entropy) loss. |
kl_loss |
Tensor
|
KL divergence. |
Source code in src/neorx/genmol/models/vae.py
VAE Training Loop¶
Handles the full training pipeline: KL annealing, gradient clipping, learning-rate scheduling, mixed-precision training, and checkpointing.
Training strategy
-
KL annealing — the β weight on the KL divergence is linearly increased from
beta_start(0.01) tobeta_end(1.0) over the firstanneal_epochs(10) epochs. This prevents posterior collapse, where the encoder learns to ignore the input and the KL term drops to zero. By starting with a low β, the model first learns good reconstructions, then gradually learns a structured latent space. -
Gradient clipping — max-norm clipping at 1.0 prevents exploding gradients, which are common in GRU-based models on long sequences.
-
ReduceLROnPlateau — if validation loss doesn't improve for
patienceepochs, the learning rate is reduced by a factor of 0.5. -
Mixed precision —
torch.ampon CUDA/MPS accelerates training by ~2× on modern GPUs with TF32/FP16 compute. -
Checkpoints — model + optimizer state saved every
save_everyepochs and at the best validation loss.
TrainConfig
dataclass
¶
Training hyperparameters.
All defaults are tuned for drug-like molecule generation on a single GPU.
Source code in src/neorx/genmol/train.py
train_vae ¶
train_vae(model: MolVAE, train_loader: DataLoader, val_loader: DataLoader, config: Optional[TrainConfig] = None, tokenizer: Optional[SmilesTokenizer] = None, device: Optional[device] = None) -> dict
Train a MolVAE model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
MolVAE
|
The VAE to train. |
required |
train_loader
|
DataLoader
|
Training data. |
required |
val_loader
|
DataLoader
|
Validation data (for LR scheduling and early stopping). |
required |
config
|
TrainConfig
|
Hyperparameters. Defaults are sensible. |
None
|
tokenizer
|
SmilesTokenizer
|
Saved alongside checkpoints for later generation. |
None
|
device
|
device
|
Training device. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Training history with keys: |
Source code in src/neorx/genmol/train.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | |
load_checkpoint ¶
load_checkpoint(checkpoint_path: str | Path, model: MolVAE, optimizer: Optional[Adam] = None, device: Optional[device] = None) -> dict
Load a training checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint_path
|
str or Path
|
Path to |
required |
model
|
MolVAE
|
Model to load weights into. |
required |
optimizer
|
Adam
|
Optimizer to restore state. |
None
|
device
|
device
|
Map location for loading. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Checkpoint metadata (epoch, val_loss, config). |
Source code in src/neorx/genmol/train.py
neorx.molscreen¶
Drug-likeness screening. See MolScreen.
MolScreen SMILES Parser¶
Parses and validates SMILES (Simplified Molecular-Input Line-Entry System) strings using RDKit, and provides name-to-SMILES lookup via the PubChem PUG REST API.
SMILES is the lingua franca of cheminformatics — a line notation that
encodes molecular structure as a string. For example, CCO is ethanol
and c1ccccc1 is benzene.
This module is the first step in the MolScreen pipeline: every molecule enters as a SMILES string and must be validated before any properties can be calculated.
parse_smiles ¶
Parse a SMILES string and return an RDKit Mol object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles
|
str
|
A SMILES string representing a chemical structure. |
required |
Returns:
| Type | Description |
|---|---|
Mol | None
|
The parsed molecule, or |
Notes
RDKit's MolFromSmiles returns None for un-parseable strings
rather than raising an exception. We log a warning so callers can
trace failures without try/except boilerplate.
Examples:
>>> mol = parse_smiles("CCO") # ethanol
>>> mol is not None
True
>>> parse_smiles("not_a_smiles") is None
True
Source code in src/neorx/molscreen/parser.py
validate_smiles ¶
Return True if smiles can be parsed into a valid molecule.
This is a thin convenience wrapper around :func:parse_smiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles
|
str
|
SMILES string to validate. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in src/neorx/molscreen/parser.py
canonicalise ¶
Return the canonical SMILES for a molecule.
Canonical SMILES is a unique, deterministic representation — two molecules with the same structure will always produce the same canonical SMILES. This is essential for de-duplication and database lookups.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles
|
str
|
Input SMILES (may be non-canonical). |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Canonical SMILES string, or |
Source code in src/neorx/molscreen/parser.py
name_to_smiles ¶
Look up a drug / compound name and return its canonical SMILES.
Uses the PubChem PUG REST API
<https://pubchem.ncbi.nlm.nih.gov/rest/pug>_ to resolve common names
(e.g. "aspirin", "ibuprofen") to SMILES.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Common or IUPAC name of the compound. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Canonical SMILES if found, otherwise |
Notes
This makes an HTTP request to an external service. It will time out
after _PUBCHEM_TIMEOUT seconds and return None on any network
error.
Source code in src/neorx/molscreen/parser.py
smart_parse ¶
Attempt to interpret input_str as a SMILES string or a drug name.
Strategy: 1. Try parsing as SMILES directly. 2. If that fails, treat it as a compound name and query PubChem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_str
|
str
|
A SMILES string or compound name (e.g. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Mol | None, str | None]
|
|
Source code in src/neorx/molscreen/parser.py
MolScreen Property Calculator¶
Calculates physico-chemical molecular properties using RDKit descriptors. These properties are the foundation of drug-likeness assessment — they determine whether a molecule can be absorbed, distributed, metabolised, and excreted (ADME) in the human body.
Every property calculated here maps to a biological reality:
- Molecular Weight — bigger molecules struggle to cross cell membranes.
- LogP — the oil/water balance controls membrane permeation.
- HBD / HBA — hydrogen bonds to water must be broken to enter cells.
- TPSA — polar surface area predicts oral absorption and BBB crossing.
- Rotatable Bonds — flexibility affects binding entropy and bioavailability.
- Rings / Aromatic Rings — shape and planarity affect selectivity.
- Fsp3 — three-dimensionality correlates with clinical success.
- Molar Refractivity — volume and polarisability proxy.
calculate_properties ¶
Calculate a full suite of molecular properties.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol_or_smiles
|
Mol | str
|
An RDKit |
required |
Returns:
| Type | Description |
|---|---|
MolecularProperties | None
|
A populated data model, or |
Notes
All descriptors are computed via RDKit's fast C++ backend. The function is deliberately stateless so it can be safely parallelised for batch processing.
Source code in src/neorx/molscreen/properties.py
MolScreen Synthetic Accessibility & Drug-Likeness Scores¶
Two complementary scores that answer the questions:
-
SA Score (Synthetic Accessibility) — Can a chemist actually make this molecule? A score from 1 (trivially easy) to 10 (practically impossible). Most approved drugs score 2–5. The algorithm was designed by Ertl & Schuffenhauer (2009) and is bundled with RDKit.
-
QED (Quantitative Estimate of Drug-likeness) — How drug-like is this molecule overall? A single number from 0 to 1 that integrates eight desirability functions (MW, LogP, HBA, HBD, TPSA, RotBonds, AromaticRings, Alerts) via a geometric mean. Designed by Bickerton et al. (2012). Higher = more drug-like.
Why both?
SA Score captures synthetic feasibility (can we build it?), while QED captures pharmacological desirability (should we build it?). A molecule needs to score well on both to be a viable drug candidate.
qed_score ¶
Calculate the QED (Quantitative Estimate of Drug-likeness).
QED was designed to replace the pass/fail nature of Lipinski with a continuous score. It uses desirability functions for eight properties:
- Molecular weight
- LogP
- HBA
- HBD
- Polar surface area
- Rotatable bonds
- Aromatic rings
- Number of structural alerts
Each property is scored 0–1 via a fitted asymmetric double-sigmoidal function, and the final QED is the weighted geometric mean.
Interpretation ~~~~~~~~~~~~~~ * > 0.67 — Favourable (in the "drug-like" sweet spot). * 0.49–0.67 — Moderate (some properties are sub-optimal). * < 0.49 — Unfavourable (multiple properties outside drug space).
For reference: aspirin QED ≈ 0.55, atorvastatin (Lipitor) ≈ 0.15.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol_or_smiles
|
Mol | str
|
RDKit Mol or SMILES string. |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
QED score rounded to 3 decimal places, or |
Source code in src/neorx/molscreen/accessibility.py
sa_score ¶
Calculate the Synthetic Accessibility Score (1–10).
The SA Score estimates how easy it would be for a medicinal chemist to synthesise a molecule. It combines two components:
- Fragment score — how common the molecule's substructures are in known compounds (PubChem). Common fragments → easy synthesis.
- Complexity penalty — based on ring complexity, stereocentres, macrocycles, and spiro/bridged systems.
Interpretation ~~~~~~~~~~~~~~ * 1–3 — Easy to synthesise (simple commercial building blocks). * 3–5 — Moderate (most approved drugs live here). * 5–7 — Difficult (requires specialised chemistry). * 7–10 — Very difficult to near-impossible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol_or_smiles
|
Mol | str
|
RDKit Mol or SMILES string. |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
SA score rounded to 2 decimal places, or |
Source code in src/neorx/molscreen/accessibility.py
MolScreen Drug-Likeness Filters¶
Pharmaceutical industry filters that encode decades of empirical knowledge about what makes a small molecule likely to succeed as an oral drug.
Each filter captures a different facet of "drug-likeness":
-
Lipinski's Rule of Five (1997) — The original and most famous filter. Based on an analysis of ~2 200 drugs: oral drugs tend to have MW ≤ 500, LogP ≤ 5, HBD ≤ 5, HBA ≤ 10. One violation is tolerated.
-
Veber Rules (2002) — Adds flexibility and polarity: rotatable bonds ≤ 10 and TPSA ≤ 140 Ų. Predicts rat oral bioavailability.
-
Ghose Filter (1999) — Tighter multi-dimensional box: MW 160–480, LogP −0.4–5.6, MR 40–130, atoms 20–70.
-
Egan Filter (2000) — Simple 2D ellipse in LogP/TPSA space that predicts intestinal absorption.
-
PAINS (2010) — Pan-Assay Interference Compounds. Substructures that give false positives in biological assays (e.g. rhodanines, quinones). These waste enormous amounts of drug-discovery resources.
-
Brenk Filter (2008) — Structural alerts for reactive, toxic, or metabolically unstable functional groups (e.g. Michael acceptors, alkyl halides, epoxides).
lipinski_filter ¶
Apply Lipinski's Rule of Five.
The rule states that poor absorption or permeation is more likely when:
- Molecular weight > 500 Da
- LogP > 5
- Hydrogen-bond donors > 5
- Hydrogen-bond acceptors > 10
A molecule passes if it has ≤ 1 violation (the original paper allows one).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol
|
Mol
|
RDKit Mol object. |
required |
Returns:
| Type | Description |
|---|---|
FilterResult
|
|
Source code in src/neorx/molscreen/filters.py
veber_filter ¶
Apply Veber Rules for oral bioavailability.
Both conditions must be satisfied:
- Rotatable bonds ≤ 10
- TPSA ≤ 140 Ų
Veber et al. (2002) showed these two descriptors are sufficient to predict rat oral bioavailability, independent of molecular weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol
|
Mol
|
RDKit Mol object. |
required |
Returns:
| Type | Description |
|---|---|
FilterResult
|
|
Source code in src/neorx/molscreen/filters.py
ghose_filter ¶
Apply the Ghose Filter.
A four-dimensional box defining drug-like chemical space:
- 160 ≤ MW ≤ 480
- −0.4 ≤ LogP ≤ 5.6
- 40 ≤ Molar Refractivity ≤ 130
- 20 ≤ Total atom count ≤ 70
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol
|
Mol
|
RDKit Mol object. |
required |
Returns:
| Type | Description |
|---|---|
FilterResult
|
|
Source code in src/neorx/molscreen/filters.py
egan_filter ¶
Apply the Egan Filter for intestinal absorption.
Defines an elliptical region in TPSA / LogP space:
- TPSA ≤ 131.6 Ų
- LogP ≤ 5.88
Molecules within this region are predicted to have good human intestinal absorption (HIA).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol
|
Mol
|
RDKit Mol object. |
required |
Returns:
| Type | Description |
|---|---|
FilterResult
|
|
Source code in src/neorx/molscreen/filters.py
pains_filter ¶
Screen for PAINS (Pan-Assay Interference Compounds).
PAINS are substructures known to interfere with many biological assays — they appear as "hits" but are actually artefacts. Common PAINS motifs include:
- Rhodanines
- Catechols
- Quinones
- Hydroxyphenyl hydrazones
Publishing a PAINS compound as a "hit" is considered a serious credibility issue in modern drug discovery.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol
|
Mol
|
RDKit Mol object. |
required |
Returns:
| Type | Description |
|---|---|
FilterResult
|
|
Source code in src/neorx/molscreen/filters.py
brenk_filter ¶
Screen for Brenk structural alerts.
Brenk et al. (2008) compiled a list of 105 substructural features that are undesirable in drug candidates because they are:
- Chemically reactive (e.g. Michael acceptors, epoxides)
- Metabolically unstable (e.g. thiols, aldehydes)
- Toxic or mutagenic (e.g. nitro groups on aromatics)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol
|
Mol
|
RDKit Mol object. |
required |
Returns:
| Type | Description |
|---|---|
FilterResult
|
|
Source code in src/neorx/molscreen/filters.py
run_all_filters ¶
Run all drug-likeness filters on a molecule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol
|
Mol
|
RDKit Mol object. |
required |
Returns:
| Type | Description |
|---|---|
list[FilterResult]
|
Results for every filter, in a fixed order. |
Source code in src/neorx/molscreen/filters.py
classify_drug_likeness ¶
Classify a molecule based on its filter results.
Classification logic
- Drug-like — passes Lipinski and Veber and no PAINS.
- Lead-like — fails one of the above but passes at least 4/6 filters.
- Not drug-like — fails more than 2 filters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filters
|
list[FilterResult]
|
Output of :func: |
required |
Returns:
| Type | Description |
|---|---|
str
|
One of |
Source code in src/neorx/molscreen/filters.py
MolScreen Similarity Search¶
Compares a query molecule against a reference set of approved drugs from the ChEMBL database using molecular fingerprints and the Tanimoto similarity coefficient.
Data source
Approved drugs (max_phase = 4) are fetched from ChEMBL via the
official chembl_webresource_client. Results are cached locally as a
CSV so the API is only hit once (or when you explicitly refresh).
How it works
-
Each molecule is encoded as a Morgan fingerprint (circular fingerprint, radius=2, 2048 bits). This captures the local chemical environment around every atom up to two bonds away — similar to the ECFP4 fingerprints widely used in pharma.
-
Fingerprints are compared using the Tanimoto coefficient (a.k.a. Jaccard index):
.. math::
T(A, B) = \frac{|A \cap B|}{|A \cup B|}
A Tanimoto score of 1.0 means the fingerprints are identical; 0.0 means no overlap.
Why this matters
Finding approved drugs that are structurally similar to a new compound gives clues about its pharmacology, toxicity, and patent landscape. If your molecule is 0.85+ similar to an approved drug, it may share the same target — useful for drug repurposing.
tanimoto_similarity ¶
Calculate Tanimoto similarity between two molecules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles_a
|
str
|
First SMILES string. |
required |
smiles_b
|
str
|
Second SMILES string. |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
Tanimoto coefficient (0–1), or |
Source code in src/neorx/molscreen/similarity.py
find_similar_drugs ¶
Find the most similar FDA-approved drugs to a query molecule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mol_or_smiles
|
Mol | str
|
Query molecule (RDKit Mol or SMILES string). |
required |
top_n
|
int
|
Number of results to return (default 5). |
5
|
Returns:
| Type | Description |
|---|---|
list[SimilarDrug]
|
Top-N most similar approved drugs, sorted by descending Tanimoto similarity. |
Examples:
Source code in src/neorx/molscreen/similarity.py
build_cache ¶
Fetch approved drugs from ChEMBL and save to a local CSV cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit
|
int | None
|
Max drugs to fetch ( |
None
|
force
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the generated cache CSV. |
Source code in src/neorx/molscreen/similarity.py
clear_cache ¶
Clear both the in-memory and on-disk caches.
Call :func:build_cache with force=True afterwards to do a
full refresh from ChEMBL.
Source code in src/neorx/molscreen/similarity.py
MolScreen Data Models¶
Pydantic models for molecular screening data. These models define the schema for molecular properties, filter results, and full screening reports.
All models are serialisable to JSON for seamless integration with the FastAPI layer and downstream pipeline modules (DockBot, GenMol).
MolecularProperties ¶
Bases: BaseModel
Calculated physico-chemical properties of a molecule.
Each property has a direct impact on whether a compound can become a successful drug. The docstrings below explain why each matters.
Source code in src/neorx/molscreen/models.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
FilterResult ¶
Bases: BaseModel
Result of a single drug-likeness filter evaluation.
Each filter encodes decades of pharmaceutical industry knowledge about what makes a molecule likely to succeed as an oral drug.
Source code in src/neorx/molscreen/models.py
ScreeningReport ¶
Bases: BaseModel
Complete screening report for a single molecule.
This is the primary output of MolScreen and the data contract consumed by downstream modules (DockBot for docking, GenMol for generative design).
Source code in src/neorx/molscreen/models.py
DrugLikelihoodCategory ¶
Bases: str, Enum
Classification of a molecule's drug-likeness profile.
- DRUG_LIKE: Passes Lipinski + Veber — looks like an oral drug.
- LEAD_LIKE: Has some violations but is still a viable starting point for medicinal-chemistry optimisation.
- NOT_DRUG_LIKE: Fails too many filters to be a practical oral drug candidate without significant structural modification.
Source code in src/neorx/molscreen/models.py
neorx.dockbot¶
Docking. See DockBot.
DockBot Protein Preparation¶
Fetches protein structures from the RCSB Protein Data Bank and prepares them for molecular docking with AutoDock Vina.
Why preparation matters
Raw PDB files are crystallographic snapshots — they contain artefacts that interfere with docking:
- Water molecules (HOH) — crystallographic waters aren't relevant to most docking experiments and clutter the binding site.
- Co-crystallised ligands — these occupy the binding pocket and must be removed, but their coordinates are valuable for defining the docking box.
- Alternate conformations — some residues have multiple conformations (A/B); we keep only the A conformer.
- Missing hydrogens — X-ray crystallography can't resolve hydrogens; we must add polar hydrogens for proper electrostatic modelling.
The final output is a PDBQT file — PDB format augmented with partial charges (Q) and atom types (T) needed by AutoDock Vina's scoring function.
prepare_protein ¶
Full protein preparation pipeline: fetch → clean → convert to PDBQT.
Results are cached so repeated calls with the same PDB ID are instant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pdb_id
|
str
|
4-character PDB accession code (e.g. |
required |
cache_dir
|
Path | None
|
Directory for caching prepared files. |
None
|
force
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
ProteinInfo
|
Metadata about the prepared protein, including path to PDBQT. |
Source code in src/neorx/dockbot/protein_prep.py
DockBot Ligand Preparation¶
Converts SMILES strings into 3D molecular structures ready for docking.
The pipeline
- Parse SMILES → 2D molecular graph (atoms + bonds).
- Add hydrogens — explicit H atoms needed for force-field calculations.
- Generate 3D conformer — use the ETKDG (Experimental-Torsion Knowledge Distance Geometry) algorithm to produce a realistic 3D geometry.
- Energy minimise — relax the structure using the MMFF94 force field to remove steric clashes and find a local energy minimum.
- Convert to PDBQT — add partial charges and AutoDock atom types using Meeko, the format Vina requires.
Why ETKDG?
ETKDG combines distance geometry (random embedding in 3D space subject to bond-length / angle constraints) with torsion-angle preferences learned from the Cambridge Structural Database. It produces much better starting geometries than older distance geometry methods.
Why MMFF94?
The Merck Molecular Force Field (MMFF94) is parameterised for drug-like organic molecules. It balances accuracy and speed for the geometry optimisation step.
prepare_ligand ¶
prepare_ligand(smiles: str, name: str = '', num_conformers: int = 1, minimize: bool = True, max_iterations: int = 500) -> Optional[Chem.Mol]
Prepare a ligand from SMILES: parse → 3D → minimise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles
|
str
|
SMILES string of the ligand. |
required |
name
|
str
|
Optional molecule name (stored as a property). |
''
|
num_conformers
|
int
|
Number of 3D conformers to generate. The lowest-energy one is kept after minimisation. |
1
|
minimize
|
bool
|
Whether to energy-minimise with MMFF94. |
True
|
max_iterations
|
int
|
Maximum force-field optimisation iterations. |
500
|
Returns:
| Type | Description |
|---|---|
Mol | None
|
RDKit Mol with 3D coordinates, or |
Source code in src/neorx/dockbot/ligand_prep.py
prepare_ligand_pdbqt ¶
prepare_ligand_pdbqt(smiles: str, name: str = '', output_dir: Path | None = None) -> tuple[Chem.Mol | None, str]
Full ligand preparation: SMILES → 3D → minimise → PDBQT string.
Convenience function that combines :func:prepare_ligand and
:func:mol_to_pdbqt_string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles
|
str
|
SMILES string. |
required |
name
|
str
|
Optional molecule name. |
''
|
output_dir
|
Path | None
|
If provided, also write the PDBQT to a file in this directory. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Mol | None, str]
|
|
Source code in src/neorx/dockbot/ligand_prep.py
DockBot Docking Engine¶
Wraps AutoDock Vina to perform molecular docking.
What is molecular docking?
Molecular docking predicts how a small molecule (ligand) fits inside a protein's binding pocket. The algorithm:
- Places the ligand inside the search box using stochastic global optimisation (Vina uses iterated local search with a Monte Carlo component).
- Evaluates each pose with a scoring function that approximates the binding free energy (ΔG, in kcal/mol). More negative = tighter binding.
- Returns the top-ranked poses sorted by predicted affinity.
Vina's scoring function
Vina's empirical scoring function combines:
- Gauss — steric interactions (van der Waals attraction).
- Repulsion — penalises atomic overlap.
- Hydrophobic — favours burying hydrophobic groups.
- Hydrogen bonding — rewards H-bonds between ligand and protein.
- Torsional penalty — penalises ligand flexibility (entropy cost of freezing rotatable bonds).
The weights were fitted to reproduce experimental binding affinities from the PDBbind database.
dock ¶
dock(receptor_pdbqt: str | Path, ligand_pdbqt: str, site: BindingSite, config: VinaConfig | None = None, ligand_name: str = '', ligand_smiles: str = '') -> DockingResult
Run AutoDock Vina and return parsed results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
receptor_pdbqt
|
str | Path
|
Path to the receptor PDBQT file prepared by
:mod: |
required |
ligand_pdbqt
|
str
|
PDBQT string of the ligand (from :mod: |
required |
site
|
BindingSite
|
Binding site that defines the search box. |
required |
config
|
VinaConfig | None
|
Vina run parameters. Defaults are sensible for quick screens. |
None
|
ligand_name
|
str
|
Human-readable name for the ligand. |
''
|
ligand_smiles
|
str
|
Canonical SMILES of the ligand. |
''
|
Returns:
| Type | Description |
|---|---|
DockingResult
|
Contains predicted poses with affinities. |
Source code in src/neorx/dockbot/docker.py
DockBot Data Models¶
Pydantic models for molecular docking data.
All models are JSON-serialisable for seamless integration with the FastAPI layer and downstream pipeline modules (GenMol, NeoRx).
Key biology concepts
-
Binding affinity is reported in kcal/mol. More negative = tighter binding. A compound with -9 kcal/mol binds ~1000x tighter than one at -5 kcal/mol (exponential via Boltzmann: dG = -RT ln Kd).
-
Binding pocket (a.k.a. binding site) is a cavity on the protein surface where a drug molecule fits. Shape complementarity and electrostatic matching determine whether a molecule binds.
-
RMSD (Root-Mean-Square Deviation) measures how far a docked pose deviates from a reference. Lower RMSD = more reproducible pose.
ProteinInfo ¶
Bases: BaseModel
Metadata about a prepared protein target.
Source code in src/neorx/dockbot/models.py
BindingSite ¶
Bases: BaseModel
Defines the docking search space -- a rectangular box centred on the protein binding pocket.
AutoDock Vina searches for low-energy ligand poses within this box. A typical box is 20-30 A on each side.
Source code in src/neorx/dockbot/models.py
BindingSiteMethod ¶
DockingPose ¶
Bases: BaseModel
A single docked pose returned by Vina.
Vina typically returns 1-20 poses ranked by binding affinity. The best pose (rank 1) has the most negative affinity.
Source code in src/neorx/dockbot/models.py
DockingResult ¶
Bases: BaseModel
Full docking output for a single molecule against a target.
Source code in src/neorx/dockbot/models.py
neorx.causalbiorl¶
Reinforcement learning. See CausalBioRL.
Structural Causal Model (SCM) fitting.
Given a causal graph (from discovery or ground truth), this module fits an
SCM where each edge X_i → X_j is parameterised by either:
- a linear function (fast, interpretable), or
- a small neural network (flexible, higher capacity).
The SCM is trained on observed transitions and supports:
predict(state, action)— forward simulation under the current graph.do(variable, value, state)— Pearl's do-operator: set a variable to a fixed value and propagate effects through the graph.
StructuralCausalModel ¶
A differentiable structural causal model fit to transition data.
Supports two modes:
-
Toy-env mode (original): nodes are
s0, s1, a0, a1, …, graph is learned from(state, action, next_state)transitions. -
Disease-graph mode (new): nodes are gene/protein/pathway IDs, edges are typed (
apivslearned), and the graph can be augmented by merging API-derived and data-driven edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
DiGraph
|
The causal graph. Nodes should be named after state/action dims (toy mode) or biological entity IDs (disease-graph mode). |
required |
state_dim
|
int
|
Number of state dimensions. |
required |
action_dim
|
int
|
Number of action dimensions. |
required |
mechanism
|
``"linear"`` | ``"neural"``
|
Function class for edge mechanisms. |
'neural'
|
lr
|
float
|
Learning rate for mechanism fitting. |
0.001
|
epochs
|
int
|
Training epochs. |
200
|
edge_type_weights
|
dict[str, float] | None
|
Mapping |
None
|
Source code in src/neorx/causalbiorl/causal/scm.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 | |
fit ¶
Fit mechanism parameters on transition data.
Returns final training loss.
Source code in src/neorx/causalbiorl/causal/scm.py
predict ¶
Forward-predict next state given current state and action.
Source code in src/neorx/causalbiorl/causal/scm.py
do ¶
do(intervention: dict[str, float], state: NDArray[floating], action: NDArray[floating]) -> NDArray[np.floating]
Apply Pearl's do-operator.
Fixes the intervened variables to their specified values, removes incoming edges (in effect), and propagates the rest through the SCM in topological order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
intervention
|
dict[str, float]
|
Mapping |
required |
state
|
ndarray
|
Current state and action context. |
required |
action
|
ndarray
|
Current state and action context. |
required |
Returns:
| Type | Description |
|---|---|
ndarray — predicted next state under the intervention.
|
|
Source code in src/neorx/causalbiorl/causal/scm.py
get_edge_strengths ¶
Return approximate edge strengths (L2 norm of mechanism weights).
Source code in src/neorx/causalbiorl/causal/scm.py
augment_graph ¶
augment_graph(learned_edges: list[tuple[str, str, dict[str, object]]], rebuild_mechanisms: bool = True) -> int
Augment the SCM graph with data-driven (learned) edges.
Merges learned edges into the existing graph. Each learned
edge is tagged with evidence_type="learned" to distinguish
it from API-derived edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learned_edges
|
list of ``(source, target, attrs)``
|
New edges to add. |
required |
rebuild_mechanisms
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
int
|
Number of new edges actually added (excluding duplicates). |
Source code in src/neorx/causalbiorl/causal/scm.py
get_edge_provenance ¶
Return edges grouped by provenance type.
Returns:
| Type | Description |
|---|---|
dict mapping ``evidence_type → list of (source, target)`` tuples.
|
|
Source code in src/neorx/causalbiorl/causal/scm.py
from_disease_graph
classmethod
¶
from_disease_graph(G: DiGraph, mechanism: Literal['linear', 'neural'] = 'neural', edge_type_weights: dict[str, float] | None = None) -> 'StructuralCausalModel'
Construct an SCM from a NeoRx disease graph.
In disease-graph mode, all nodes are treated as state
dimensions (no explicit action nodes). The SCM can
then be used for counterfactual reasoning via do().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
DiGraph
|
Disease knowledge graph. |
required |
mechanism
|
``"linear"`` | ``"neural"``
|
|
'neural'
|
edge_type_weights
|
dict | None
|
Per-edge-type weight multipliers. |
None
|
Returns:
| Type | Description |
|---|---|
StructuralCausalModel
|
|
Source code in src/neorx/causalbiorl/causal/scm.py
Relational Graph Convolutional Network (R-GCN) encoder.
Encodes a disease knowledge graph (from NeoRx) into a fixed-size embedding vector suitable for RL observation spaces.
Architecture: 1. Each node gets initial features from its biological properties (centrality, degree, evidence count, causal score, tissue relevance, node-type one-hot). 2. R-GCN layers perform message passing with per-relation weight matrices, handling heterogeneous edge types natively (activates, inhibits, binds, participates_in, etc.). 3. Graph-level readout (mean + max pooling) produces a fixed 128-D embedding vector.
The encoder supports two modes: - Frozen: pre-trained or hand-initialised, no gradient updates. Used when the RL agent treats the graph embedding as a fixed observation context. - Trainable: end-to-end with the RL policy. Gradients flow from the policy loss through the GNN.
Implementation note:
Pure PyTorch — no torch_geometric dependency. R-GCN message
passing is implemented via sparse matrix multiplication with
per-relation weight matrices.
Reference: Schlichtkrull et al. (2018) "Modeling Relational Data with Graph Convolutional Networks", ESWC.
DiseaseGraphEncoder ¶
Bases: Module
R-GCN encoder that maps a disease graph to a fixed-size vector.
Architecture: node_features (15D) → Linear projection (15 → hidden_dim) → RGCNLayer × n_layers → Graph readout (mean + max pooling → 2 * hidden_dim) → MLP → embedding_dim
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedding_dim
|
int
|
Output embedding size (default 128). |
128
|
hidden_dim
|
int
|
Hidden dimension in R-GCN layers (default 64). |
64
|
n_layers
|
int
|
Number of R-GCN layers (default 2). |
2
|
n_relations
|
int
|
Number of distinct relation types (default 13). |
len(DEFAULT_EDGE_TYPES)
|
n_bases
|
int | None
|
Basis decomposition rank. |
4
|
node_feature_dim
|
int
|
Input node feature dimension (default 15). |
15
|
dropout
|
float
|
Dropout rate (default 0.1). |
0.1
|
Source code in src/neorx/causalbiorl/causal/graph_encoder.py
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 | |
forward ¶
forward(node_features: Tensor, edge_index: Tensor, edge_type: Tensor) -> tuple[torch.Tensor, torch.Tensor]
Encode the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_features
|
Tensor ``(N, node_feature_dim)``
|
|
required |
edge_index
|
LongTensor ``(2, E)``
|
|
required |
edge_type
|
LongTensor ``(E,)``
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
graph_embedding |
Tensor ``(embedding_dim,)``
|
Graph-level embedding (for RL observation). |
node_embeddings |
Tensor ``(N, embedding_dim)``
|
Per-node embeddings (for target selection). |
Source code in src/neorx/causalbiorl/causal/graph_encoder.py
encode_disease_graph ¶
encode_disease_graph(G: DiGraph, device: device | None = None) -> tuple[torch.Tensor, torch.Tensor, list[str]]
Convenience: encode a networkx DiGraph directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
DiGraph
|
Disease knowledge graph. |
required |
device
|
device | None
|
Target device. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
graph_embedding |
Tensor ``(embedding_dim,)``
|
|
node_embeddings |
Tensor ``(N, embedding_dim)``
|
|
node_order |
list[str]
|
Node IDs in the order they appear in |
Source code in src/neorx/causalbiorl/causal/graph_encoder.py
RGCNLayer ¶
Bases: Module
Single Relational Graph Convolutional layer.
For each relation type r, maintains a weight matrix W_r
of shape (in_dim, out_dim). Message passing:
h_v^{(l+1)} = σ( Σ_r Σ_{u ∈ N_r(v)} 1/c_{v,r} · W_r · h_u^{(l)} + W_0 · h_v^{(l)} )
where c_{v,r} is a normalisation constant (node degree under
relation r), and W_0 is a self-loop weight.
Uses basis decomposition when n_relations is large to
keep parameter count manageable:
W_r = Σ_b a_{rb} · B_b
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_dim
|
int
|
Input feature dimension. |
required |
out_dim
|
int
|
Output feature dimension. |
required |
n_relations
|
int
|
Number of distinct edge/relation types. |
required |
n_bases
|
int | None
|
Number of basis matrices for decomposition. |
None
|
dropout
|
float
|
Dropout probability applied after activation. |
0.1
|
Source code in src/neorx/causalbiorl/causal/graph_encoder.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | |
forward ¶
Forward pass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_features
|
Tensor of shape ``(N, in_dim)``
|
|
required |
edge_index
|
LongTensor of shape ``(2, E)``
|
|
required |
edge_type
|
LongTensor of shape ``(E,)``
|
Relation type index for each edge. |
required |
Returns:
| Type | Description |
|---|---|
Tensor of shape ``(N, out_dim)``
|
|
Source code in src/neorx/causalbiorl/causal/graph_encoder.py
Surrogate docking model — fast approximation of DockBot binding affinity.
Problem: AutoDock Vina takes 5-30 seconds per docking call. An RL training run with 10,000+ docking evaluations would take ~28 hours.
Solution: Train an MLP surrogate that predicts binding affinity from: - Morgan fingerprint of the ligand (2048-bit → float) - Protein-target embedding (from R-GCN node embedding, 128-D)
The surrogate runs in <1ms per call, enabling real-time RL.
Workflow:
1. Seed phase: Run real DockBot on N initial (molecule, target)
pairs to build a training set.
2. Train surrogate: Fit the MLP on (fingerprint, target_emb) → affinity.
3. RL phase: Agent uses surrogate for reward during training.
4. Recalibration: Periodically run real DockBot on agent's best
molecules and retrain the surrogate (prevents distribution shift).
Reference: Gentile et al. (2020) "Deep Docking: A Deep Learning Platform for Augmentation of Structure Based Drug Discovery", ACS Central Science.
SurrogateDockingModel ¶
Fast docking score predictor for RL reward computation.
Predicts binding affinity (kcal/mol) from molecular fingerprints and target protein embeddings. Trained from real DockBot results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fp_dim
|
int
|
Fingerprint dimension (default 2048 for ECFP4). |
2048
|
target_dim
|
int
|
Target embedding dimension (default 128 from R-GCN). |
128
|
hidden_dim
|
int
|
MLP hidden layer size. |
256
|
lr
|
float
|
Learning rate for training. |
0.001
|
device
|
str | None
|
|
None
|
Source code in src/neorx/causalbiorl/causal/surrogate_docker.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 | |
add_observation ¶
add_observation(fingerprint: NDArray[floating], target_embedding: NDArray[floating], real_affinity: float) -> None
Add a real docking observation to the training buffer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fingerprint
|
ndarray ``(fp_dim,)``
|
Morgan fingerprint of the ligand. |
required |
target_embedding
|
ndarray ``(target_dim,)``
|
R-GCN embedding of the target node. |
required |
real_affinity
|
float
|
Actual binding affinity from DockBot (kcal/mol). |
required |
Source code in src/neorx/causalbiorl/causal/surrogate_docker.py
add_smiles_observation ¶
add_smiles_observation(smiles: str, target_embedding: NDArray[floating], real_affinity: float) -> bool
Convenience: add an observation from SMILES string.
Returns True if the SMILES was valid and added.
Source code in src/neorx/causalbiorl/causal/surrogate_docker.py
fit ¶
Train the surrogate on buffered observations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epochs
|
int
|
Training epochs. |
200
|
batch_size
|
int
|
Mini-batch size. |
64
|
verbose
|
bool
|
Print loss every 50 epochs. |
False
|
Returns:
| Type | Description |
|---|---|
float
|
Final training MSE loss. |
Source code in src/neorx/causalbiorl/causal/surrogate_docker.py
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
predict ¶
Predict binding affinity for a single (ligand, target) pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fingerprint
|
ndarray ``(fp_dim,)``
|
|
required |
target_embedding
|
ndarray ``(target_dim,)``
|
|
required |
Returns:
| Type | Description |
|---|---|
float
|
Predicted binding affinity (kcal/mol, negative = better). |
Source code in src/neorx/causalbiorl/causal/surrogate_docker.py
predict_smiles ¶
Convenience: predict affinity from SMILES string.
Returns None if SMILES parsing fails.
Source code in src/neorx/causalbiorl/causal/surrogate_docker.py
predict_batch ¶
predict_batch(fingerprints: NDArray[floating], target_embeddings: NDArray[floating]) -> NDArray[np.floating]
Predict affinities for a batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fingerprints
|
ndarray ``(B, fp_dim)``
|
|
required |
target_embeddings
|
ndarray ``(B, target_dim)``
|
|
required |
Returns:
| Type | Description |
|---|---|
ndarray ``(B,)``
|
|
Source code in src/neorx/causalbiorl/causal/surrogate_docker.py
recalibrate ¶
recalibrate(fingerprints: NDArray[floating], target_embeddings: NDArray[floating], real_affinities: NDArray[floating], epochs: int = 100) -> float
Recalibrate with new real docking data.
Adds the new data to the buffer and retrains. Prevents distribution shift when the RL agent explores regions far from the initial training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fingerprints
|
ndarray ``(N, fp_dim)``
|
|
required |
target_embeddings
|
ndarray ``(N, target_dim)``
|
|
required |
real_affinities
|
ndarray ``(N,)``
|
|
required |
epochs
|
int
|
Recalibration training epochs. |
100
|
Returns:
| Type | Description |
|---|---|
float
|
Final loss after recalibration. |
Source code in src/neorx/causalbiorl/causal/surrogate_docker.py
save ¶
Save model weights and buffer to disk.
Source code in src/neorx/causalbiorl/causal/surrogate_docker.py
load ¶
Load model weights and buffer from disk.
Source code in src/neorx/causalbiorl/causal/surrogate_docker.py
smiles_to_fingerprint ¶
smiles_to_fingerprint(smiles: str, radius: int = 2, n_bits: int = 2048) -> NDArray[np.floating] | None
Convert SMILES to Morgan fingerprint vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
smiles
|
str
|
SMILES string of the molecule. |
required |
radius
|
int
|
Morgan fingerprint radius (default 2 ≈ ECFP4). |
2
|
n_bits
|
int
|
Fingerprint length. |
2048
|
Returns:
| Type | Description |
|---|---|
ndarray of shape ``(n_bits,)`` or ``None`` if parsing fails.
|
|
Source code in src/neorx/causalbiorl/causal/surrogate_docker.py
Adaptive Reward Learner — hindsight reward shaping for multi-objective RL.
In drug discovery, the agent must optimise multiple objectives simultaneously:
1. Binding affinity (DockBot / surrogate)
2. Drug-likeness (QED)
3. Synthetic access. (SA score)
4. Novelty (Tanimoto distance to known drugs)
5. Causal confidence (from SCM do-calculus)
6. Structural stab. (MirrorFold therapeutic score)
A naïve approach uses fixed weights: r = Σ wᵢ rᵢ.
But fixed weights:
- Collapse to the easiest objective (the agent games it)
- Ignore disease-specific difficulty profiles
- Require manual tuning per disease
Hindsight Reward Shaping (Option C): - A critic network estimates objective-specific difficulty - Objectives that are underperforming get up-weighted - Objectives that are easily satisfied get down-weighted - The agent naturally focuses on the bottleneck
This is a form of curriculum learning applied to reward composition — the agent adapts its focus as it improves.
Reference: Adapted from Abels et al. (2019) "Dynamic Weights in Multi-Objective Deep Reinforcement Learning", ICML.
AdaptiveRewardLearner ¶
Learns dynamic reward weights via per-objective difficulty estimation.
Architecture:
- One critic per objective: V_i(state) → expected_score_i
- Difficulty = 1 - V_i(state) (how far from perfect)
- Weight for objective i ∝ difficulty_i^temperature
- Weights are normalised to sum to 1
The temperature parameter controls adaptation strength:
- temperature = 0 → equal weights (fixed)
- temperature = 1 → linear difficulty weighting
- temperature > 1 → aggressive focus on bottleneck
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dim
|
int
|
Dimension of the state vector (graph embedding + mol features). |
128
|
base_weights
|
ndarray | None
|
Initial (prior) weights for each objective. If |
None
|
temperature
|
float
|
Controls how aggressively to up-weight bottleneck objectives. |
1.5
|
lr
|
float
|
Learning rate for critic training. |
0.001
|
gamma
|
float
|
Discount factor for temporal difference learning. |
0.99
|
device
|
str | None
|
|
None
|
Source code in src/neorx/causalbiorl/causal/reward_learner.py
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 | |
score ¶
The adaptively-weighted scalar reward, recording nothing.
compute_reward records each call into the weight and
objective histories, which makes it unusable for scoring
candidate actions -- a planner evaluating a batch would write
hundreds of phantom entries per environment step. This is the
pure half.
Source code in src/neorx/causalbiorl/causal/reward_learner.py
compute_reward ¶
Compute the reward and record it in the learner's history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
ndarray
|
Current state vector (graph embedding + mol features). |
required |
objective_scores
|
dict[str, float]
|
Per-objective scores, keyed by objective name. All values should be in [0, 1] (higher = better). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Scalar reward. |
Source code in src/neorx/causalbiorl/causal/reward_learner.py
update ¶
update(state: NDArray[floating], objective_scores: dict[str, float], next_state: NDArray[floating] | None = None) -> float
Update objective critics with observed scores.
Uses a simple TD(0) update:
V_i(s) ← r_i + γ · V_i(s')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
ndarray
|
Current state. |
required |
objective_scores
|
dict[str, float]
|
Observed objective scores. |
required |
next_state
|
ndarray | None
|
Next state (for TD target). If |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Mean critic loss across objectives. |
Source code in src/neorx/causalbiorl/causal/reward_learner.py
get_current_weights ¶
Return current adaptive weights as a readable dict.
Source code in src/neorx/causalbiorl/causal/reward_learner.py
get_weight_history ¶
Return weight trajectory for analysis/plotting.
Source code in src/neorx/causalbiorl/causal/reward_learner.py
get_objective_history ¶
Return per-objective score trajectory.
Source code in src/neorx/causalbiorl/causal/reward_learner.py
get_difficulty_profile ¶
Return the estimated difficulty for each objective.
Values in [0, 1] — higher = harder to satisfy.
Source code in src/neorx/causalbiorl/causal/reward_learner.py
DrugDiscovery-v0 — Gymnasium environment for RL-driven drug discovery.
This is the integration point where CausalBioRL meets the real NeoRx pipeline. Instead of toy ODE environments, the RL agent interacts with real drug-discovery modules:
- **NeoRx** — disease graph, causal targets, SCM
- **GenMol** — VAE-based molecule generation (latent space navigation)
- **MolScreen** — drug-likeness scoring (QED, SA, filters)
- **DockBot** — binding affinity (via surrogate for speed)
- **MirrorFold** — structural stability assessment
Architecture
State: Graph embedding (128D from R-GCN) + current best molecule features (32D) + per-target summary (n_targets × 8D) → flattened to fixed size.
Action (hierarchical): Level 1: Target selection (discrete: which target to pursue) Level 2: Molecule generation (continuous 128D delta-z in GenMol latent)
Reward: Adaptively-weighted multi-objective (AdaptiveRewardLearner): binding, QED, SA, novelty, causal confidence, stability.
Episode: One disease campaign. Agent has a budget of N generate-screen cycles. It decides which targets to invest in and how to explore the chemical space for each.
Termination: Budget exhausted OR agent outputs "stop" action (early confidence).
Design Decisions
- Disease graph is built once at ``reset()`` and cached.
- DockBot uses a surrogate model during training; real docking only
at episode end for recalibration (see ``screening.py``).
- GenMol generates from ``z_base + delta_z``: the agent learns to
navigate the latent space, not just sample randomly.
DrugDiscoveryEnv ¶
Bases: Env
Gymnasium environment for RL-driven drug discovery campaigns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
disease
|
str
|
Disease name (e.g. "Malaria", "HIV"). |
'Malaria'
|
max_steps
|
int
|
Budget: maximum generate-screen cycles per episode. |
50
|
top_n_targets
|
int
|
Number of causal targets to pursue (from NeoRx pipeline). |
5
|
latent_dim
|
int
|
GenMol VAE latent space dimension. |
LATENT_DIM
|
use_surrogate
|
bool
|
Use surrogate docking model (fast) vs real DockBot (slow). |
True
|
recalibrate_interval
|
int
|
Every N steps, run real docking to recalibrate surrogate. |
10
|
difficulty
|
str
|
|
'medium'
|
prebuilt_graph
|
DiGraph | None
|
Pre-built disease graph. If provided, skips graph building. |
None
|
prebuilt_targets
|
list[dict] | None
|
Pre-identified targets. If provided, skips identification. |
None
|
Source code in src/neorx/causalbiorl/envs/drug_discovery.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 | |
reset ¶
reset(*, seed: int | None = None, options: dict[str, Any] | None = None) -> tuple[NDArray[np.floating], dict[str, Any]]
Reset for a new campaign: build the graph, identify targets, encode with R-GCN, and initialise per-target state.
Source code in src/neorx/causalbiorl/envs/drug_discovery.py
step ¶
Execute one generate-screen cycle.
Action interpretation: action[0] — target selector (continuous → discretised) action[1] — stop signal (> 0.9 = early termination) action[2:] — delta-z for GenMol latent space navigation
Source code in src/neorx/causalbiorl/envs/drug_discovery.py
evaluate_actions ¶
Score candidate actions against real chemistry, mutating nothing.
A planner needs to know what an action is actually worth before
committing to it. step cannot answer that: it advances the
step counter, updates per-target bests, drifts z_base, and
records into the reward learner's history. This decodes and
screens the same molecules step would and returns their
rewards, leaving the environment exactly as it found it.
_screen_molecule draws from self.np_random to add
per-difficulty noise to the objective scores. That draw advances
the environment's shared random stream -- a real mutation, even
though it touches no counter or cache. Left alone, evaluating a
candidate here would desynchronise the noise a later step()
draws for the same action from what it would have drawn
otherwise. The RNG state is saved before screening and restored
after, so this method's random consumption is invisible to the
rest of the environment.
step also bumps the chosen target's n_attempts before
building the observation it scores the reward against, so that
counter is baked into the state the reward learner sees. To
agree with step this replicates the same bump on a copy of
state while scoring each candidate, and never writes it back
to the target.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
NDArray[floating]
|
The observation the rewards are computed against. |
required |
actions
|
NDArray[floating]
|
Array of shape |
required |
Returns:
| Type | Description |
|---|---|
ndarray of shape ``(n,)``
|
|
Source code in src/neorx/causalbiorl/envs/drug_discovery.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
get_causal_graph ¶
Return the disease causal graph (or empty graph if not built).
render ¶
close ¶
Novel causal RL agent — uses structural causal models as world models.
Architecture: 1. Causal Discovery — learns the causal graph from observed transitions (neural or PC algorithm). 2. Causal World Model — fits an SCM to the discovered graph. 3. Causal Planner — selects actions via do-calculus on the SCM. 4. Model-Based RL loop — collect → discover → fit SCM → plan → act.
The agent maintains a replay buffer of transitions and periodically re-discovers the causal structure and re-fits the SCM.
CausalAgent ¶
Causal RL agent with SCM-based world model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Env
|
The environment to act in. |
required |
discovery_method
|
``"pc"`` | ``"neural"``
|
Causal discovery backend. |
'neural'
|
mechanism
|
``"linear"`` | ``"neural"``
|
SCM edge parameterisation. |
'neural'
|
planning_method
|
``"grid"`` | ``"cem"``
|
Action selection strategy. |
'cem'
|
warmup_steps
|
int
|
Collect this many random transitions before first discovery. |
500
|
rediscover_interval
|
int
|
Re-run discovery every N episodes. |
20
|
refit_interval
|
int
|
Re-fit SCM every N episodes. |
5
|
buffer_capacity
|
int
|
Replay buffer size. |
50000
|
planning_samples
|
int
|
Number of candidate actions evaluated per step. |
200
|
planning_horizon
|
int
|
Multi-step look-ahead depth. |
3
|
seed
|
int | None
|
Random seed. |
None
|
Source code in src/neorx/causalbiorl/agents/causal_agent.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 | |
train ¶
train(n_episodes: int = 500, reward_fn: Callable[[NDArray[floating], NDArray[floating]], float] | None = None, verbose: bool = True) -> dict[str, Any]
Run the full causal model-based RL training loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_episodes
|
int
|
Total training episodes. |
500
|
reward_fn
|
callable | None
|
External reward function |
None
|
verbose
|
bool
|
Show progress bar. |
True
|
Returns:
| Type | Description |
|---|---|
dict with training metrics.
|
|
Source code in src/neorx/causalbiorl/agents/causal_agent.py
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 | |
act ¶
Select a single action for the given state.
Source code in src/neorx/causalbiorl/agents/causal_agent.py
get_learned_graph ¶
init_hierarchical_planner ¶
Initialise the hierarchical planner for drug discovery.
Call this before training if the environment is
DrugDiscovery-v0. The planner uses UCB for target
selection and CEM for molecule generation.
Source code in src/neorx/causalbiorl/agents/causal_agent.py
neorx.mirrorfold¶
Mirror-image proteins. See MirrorFold.
Sequence Mirror — L → D Transformation¶
Converts a natural (L-amino acid) protein sequence into its mirror-image (D-amino acid) counterpart, and generates D-amino acid SMILES representations.
Why reverse the sequence?
All modern protein structure predictors (ESMFold, AlphaFold, RoseTTAFold) were trained exclusively on L-protein structures. They cannot directly predict D-protein folds.
However, a beautiful symmetry comes to the rescue:
A D-protein made from sequence ``ABCDE`` folds into the
**mirror image** of the L-protein made from the **reversed**
sequence ``EDCBA``.
This is because:
- D-amino acids have inverted backbone φ/ψ torsion angles compared to L-amino acids.
- Reversing the sequence direction swaps N→C and C→N termini, which combined with the chirality inversion, produces a structure that is the mirror image of the original L-fold.
- After prediction of the reversed sequence, a coordinate reflection (x → −x) yields the D-protein structure.
This "reverse-and-reflect" proxy is an approximation. It works well for globular proteins with defined folds but is less reliable for intrinsically disordered regions or proteins whose folding depends heavily on co-translational effects.
Reference: Milton et al. (1992) "Total Chemical Synthesis of a D-Enzyme: The Enantiomers of HIV-1 Protease Show Demonstration of Reciprocal Chiral Substrate Specificity."
D-amino acid SMILES
Each of the 20 standard amino acids has an L and D form. They differ only in the stereochemistry at the α-carbon:
- L-form:
[C@@H]at the α-carbon (S-configuration, except Cys) - D-form:
[C@H]at the α-carbon (R-configuration, except Cys)
Glycine has no stereocenter (the α-carbon has two hydrogens). Isoleucine and threonine have an additional stereocenter on the side chain, which is also inverted in the D-form (full mirror).
mirror_sequence ¶
Generate the D-protein proxy sequence by reversing.
The reversed sequence, when folded by an L-protein predictor, approximates the mirror-image fold of the D-protein.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sequence
|
str
|
L-protein amino acid sequence (one-letter codes). |
required |
Returns:
| Type | Description |
|---|---|
str
|
Reversed sequence (proxy for D-protein prediction). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the sequence contains non-standard amino acids. |
Examples:
Source code in src/neorx/mirrorfold/mirror.py
is_valid_sequence ¶
Check whether a string is a valid protein sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sequence
|
str
|
Amino acid sequence in one-letter codes. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in src/neorx/mirrorfold/mirror.py
reflect_coordinates ¶
Reflect PDB coordinates across a plane to get the mirror image.
After predicting a structure from the reversed sequence using an L-protein predictor, the resulting coordinates represent an L-protein fold. To obtain the actual D-protein coordinates, we reflect across one axis (e.g., x → −x).
This is mathematically equivalent to multiplying the coordinate matrix by a reflection matrix with determinant −1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pdb_string
|
str
|
PDB-format string. |
required |
axis
|
str
|
Which axis to negate: |
'x'
|
Returns:
| Type | Description |
|---|---|
str
|
PDB string with reflected coordinates. |
Source code in src/neorx/mirrorfold/mirror.py
get_l_smiles ¶
Get the SMILES string for an L-amino acid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
residue
|
str
|
One-letter amino acid code. |
required |
Returns:
| Type | Description |
|---|---|
str or None
|
SMILES with correct L-stereochemistry, or |
Source code in src/neorx/mirrorfold/mirror.py
get_d_smiles ¶
Get the SMILES string for a D-amino acid.
The D-form is the mirror image — all stereocentres are inverted compared to the L-form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
residue
|
str
|
One-letter amino acid code. |
required |
Returns:
| Type | Description |
|---|---|
str or None
|
SMILES with correct D-stereochemistry, or |
Source code in src/neorx/mirrorfold/mirror.py
verify_mirror_smiles ¶
Verify that L and D SMILES for a residue are valid mirror images.
Uses RDKit to confirm both SMILES parse correctly and that their InChI representations differ only in stereochemistry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
residue
|
str
|
One-letter amino acid code. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Verification result with |
Source code in src/neorx/mirrorfold/mirror.py
Structure Prediction with ESMFold¶
Predicts 3D protein structures from amino-acid sequences using Meta AI's ESMFold model, with automatic fallback to the ESMFold REST API.
What is ESMFold?
ESMFold is a protein structure prediction model from Meta (FAIR) that predicts 3D coordinates directly from a single sequence — no multiple sequence alignment (MSA) needed. This makes it much faster than AlphaFold2 (seconds vs hours) while achieving comparable accuracy for well-folded proteins.
The model is built on the ESM-2 protein language model (650M parameters) and a structure module inspired by AlphaFold2. It outputs:
- Atom coordinates in PDB format
- pLDDT scores — per-residue confidence (0–100) stored in the B-factor column of the PDB file
pLDDT interpretation
- > 90 — Very high confidence. Backbone and side-chain positions are reliable.
- 70–90 — Confident. Backbone is reliable; side chains may have some error.
- 50–70 — Low confidence. Possible loop region or partial disorder.
- < 50 — Very low confidence. Likely intrinsically disordered or prediction is unreliable.
Limitations for D-proteins
ESMFold was trained exclusively on L-protein structures from the
PDB. It has never seen a D-protein. We approximate the
D-protein structure using the reversed-sequence proxy (see
mirror.py). This works because:
fold(D-protein seq ABCDE) ≈ mirror(fold(L-protein seq EDCBA))
This approximation is well-validated for globular proteins (Kent et al., HIV protease) but less reliable for: * Intrinsically disordered regions * Proteins whose folding depends on chaperones * Very long sequences (> 400 residues)
predict_structure ¶
predict_structure(sequence: str, chirality: str = 'L', use_cache: bool = True, allow_api_fallback: bool = True, allow_mock: bool = False) -> StructurePrediction
Predict the 3D structure of a protein sequence.
Attempts prediction in order:
1. Check file cache
2. Local ESMFold model (requires fair-esm[esmfold])
3. ESMFold REST API (requires internet)
4. Mock prediction (if allow_mock=True, for testing)
For D-proteins, the sequence is reversed before prediction (the "reverse-and-reflect" proxy), and the resulting coordinates are reflected to produce D-protein geometry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sequence
|
str
|
Amino acid sequence in one-letter codes. |
required |
chirality
|
str
|
|
'L'
|
use_cache
|
bool
|
Check/write the prediction cache. |
True
|
allow_api_fallback
|
bool
|
Allow the ESMFold API as a fallback. |
True
|
allow_mock
|
bool
|
Generate a mock structure if all else fails. |
False
|
Returns:
| Type | Description |
|---|---|
StructurePrediction
|
Predicted structure with pLDDT scores. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no prediction method is available. |
Source code in src/neorx/mirrorfold/predictor.py
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 | |
predict_pair ¶
predict_pair(sequence: str, use_cache: bool = True, allow_api_fallback: bool = True, allow_mock: bool = False) -> tuple[StructurePrediction, StructurePrediction]
Predict both L- and D-protein structures.
Convenience function that predicts the natural L-form and the mirror-image D-form for the same sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sequence
|
str
|
Amino acid sequence. |
required |
use_cache
|
bool
|
Use prediction cache. |
True
|
allow_api_fallback
|
bool
|
Allow ESMFold API fallback. |
True
|
allow_mock
|
bool
|
Allow mock predictions for testing. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[StructurePrediction, StructurePrediction]
|
(L-structure, D-structure) |
Source code in src/neorx/mirrorfold/predictor.py
Structure Comparison — L vs D Proteins¶
Aligns and compares the predicted structures of L- and D-protein forms using RMSD, TM-score, and secondary structure analysis.
RMSD vs TM-score
-
RMSD (Root Mean Square Deviation) is the most intuitive metric: the average Cα displacement in Ångströms after optimal superposition. But RMSD has a flaw — a single badly-aligned loop can inflate the score even if the rest of the structure matches perfectly.
-
TM-score (Template Modelling score) solves this by down-weighting large distances. It ranges from 0 to 1:
-
TM > 0.5 → same fold (statistically significant)
- TM > 0.7 → very similar structures
- TM > 0.9 → essentially identical
Formula: TM = (1/L) Σ 1/(1 + (dᵢ/d₀)²)
where L is target length, dᵢ is per-residue distance, and d₀ = 1.24 ∛(L − 15) − 1.8 is a length-dependent normaliser.
Reference: Zhang & Skolnick (2004) Proteins 57:702-710.
Secondary structure comparison
We assign each residue to one of three states based on backbone torsion angles (φ, ψ) from the Ramachandran plot:
- H (helix): −160° < φ < −20° and −80° < ψ < 0°
- E (sheet): −180° < φ < −40° and 50° < ψ < 180°
- C (coil): everything else
For D-proteins, the Ramachandran plot is mirrored: the allowed regions have positive φ values (the exact reflection of the L-protein regions). When comparing secondary structure between L and D forms, we compare the topology (helix vs sheet vs coil) regardless of the sign of the torsion angles.
compare_structures ¶
compare_structures(l_prediction: StructurePrediction, d_prediction: StructurePrediction, distance_threshold: float = 2.0) -> ComparisonReport
Compare L- and D-protein predicted structures.
Performs: 1. Extract Cα coordinates from both PDB strings 2. Superimpose using the Kabsch algorithm 3. Calculate RMSD and TM-score 4. Compute per-residue distances 5. Assign and compare secondary structure 6. Identify conserved and divergent regions
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
l_prediction
|
StructurePrediction
|
Predicted L-protein structure. |
required |
d_prediction
|
StructurePrediction
|
Predicted D-protein structure. |
required |
distance_threshold
|
float
|
Cα distance threshold (Å) for classifying conserved vs divergent regions. Default 2.0 Å. |
2.0
|
Returns:
| Type | Description |
|---|---|
ComparisonReport
|
Full structural comparison report. |
Source code in src/neorx/mirrorfold/compare.py
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 | |
superimpose ¶
Optimal superposition using the Kabsch algorithm.
Finds the rotation and translation that minimises RMSD between two sets of corresponding points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coords_fixed
|
ndarray[N, 3]
|
Reference coordinates (will not move). |
required |
coords_moving
|
ndarray[N, 3]
|
Mobile coordinates (will be rotated/translated). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
coords_aligned |
ndarray[N, 3]
|
The moving coordinates after optimal superposition. |
rmsd |
float
|
RMSD in Ångströms. |
Source code in src/neorx/mirrorfold/compare.py
calculate_tm_score ¶
calculate_tm_score(coords_ref: ndarray, coords_aligned: ndarray, target_length: Optional[int] = None) -> float
Calculate the TM-score between two aligned structures.
TM-score is more robust than RMSD because it uses a
length-dependent distance cutoff d₀ that down-weights
large per-residue deviations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coords_ref
|
ndarray[N, 3]
|
Reference Cα coordinates. |
required |
coords_aligned
|
ndarray[N, 3]
|
Aligned Cα coordinates (after superposition). |
required |
target_length
|
int
|
Normalisation length. Defaults to the number of residues. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
TM-score in [0, 1]. |
Source code in src/neorx/mirrorfold/compare.py
D-Protein Therapeutic Assessment¶
Evaluates the potential of D-protein (mirror-image) variants as therapeutics. This is one of the most exciting areas of mirror biology — D-proteins have several inherent advantages:
Why D-protein therapeutics?
-
Protease resistance — Natural proteases (trypsin, chymotrypsin, pepsin, etc.) evolved to recognise L-amino acid peptide bonds. They literally cannot grip D-peptide bonds because the active site geometry is wrong. D-proteins are essentially invisible to the body's proteolytic machinery.
-
Immune evasion — MHC class I and II molecules present peptide fragments to T cells. These molecules bind peptides in a specific L-amino acid configuration. D-peptides cannot be presented, making D-proteins practically non-immunogenic.
-
Extended half-life — Because D-proteins resist proteases and evade the immune system, they have dramatically longer serum half-lives than L-protein drugs. An L-peptide that survives minutes in blood can last days as a D-peptide.
-
Oral bioavailability — Resistance to digestive proteases opens the possibility of oral administration, which is the holy grail for protein therapeutics.
The catch
The D-protein must fold into the correct 3D structure — specifically, the mirror image of the L-protein's fold. If it folds correctly, it will bind the same target (because the mirror-image binding surface is complementary to the same binding pocket).
This module quantifies how likely a D-protein is to maintain its fold and function, based on structural comparison.
assess_therapeutic_potential ¶
assess_therapeutic_potential(protein_name: str, comparison: ComparisonReport, l_properties: PropertyProfile, d_properties: PropertyProfile, pdb_id: Optional[str] = None, pocket_residues: Optional[list[int]] = None) -> TherapeuticAssessment
Run a full D-protein therapeutic assessment.
Integrates structural comparison and property analysis to produce a comprehensive evaluation of whether a D-protein variant is a viable therapeutic candidate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
protein_name
|
str
|
Human-readable name (e.g. "Insulin B chain"). |
required |
comparison
|
ComparisonReport
|
Structural comparison between L and D forms. |
required |
l_properties
|
PropertyProfile
|
L-protein biophysical properties. |
required |
d_properties
|
PropertyProfile
|
D-protein biophysical properties. |
required |
pdb_id
|
str
|
PDB identifier if available. |
None
|
pocket_residues
|
list[int]
|
Residue indices forming the binding pocket. |
None
|
Returns:
| Type | Description |
|---|---|
TherapeuticAssessment
|
Complete therapeutic assessment. |
Source code in src/neorx/mirrorfold/therapeutic.py
assess_protease_resistance ¶
Estimate protease resistance based on chirality.
This is straightforward: L-proteins are susceptible to all natural proteases. D-proteins are resistant to essentially all of them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chirality
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
str
|
Qualitative resistance level. |
Source code in src/neorx/mirrorfold/therapeutic.py
assess_immunogenicity ¶
Estimate immunogenicity based on chirality.
MHC class I molecules bind peptide fragments of 8–10 residues in a groove that is stereospecific for L-amino acids. MHC class II binds 13–25-mers, also stereospecifically. Since D-peptides cannot fit these grooves, D-proteins evade adaptive immunity almost completely.
Innate immunity (e.g. toll-like receptors) is less chirality- dependent, so some innate immune response is possible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chirality
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
str
|
Qualitative immunogenicity level. |