API Reference¶
This page is auto-generated from the source-code docstrings by
mkdocstrings. For narrative examples and
recipes see the hand-written Python API guide.
The reference is grouped by sub-package. Every public symbol exported from a
sub-package is included; private helpers (those starting with _) are not.
Top-level¶
dta_gnn
¶
End-to-End Pipeline (dta_gnn.training)¶
run_gnn_end_to_end
¶
Run the complete GNN training pipeline end-to-end.
Steps¶
- Parse UniProt accessions and map them to ChEMBL target IDs.
- Build a DTA dataset from ChEMBL using a scaffold split; save all
required files (
dataset.csv,compounds.csv,metadata.json) to a new timestamped run directory. - Run a W&B Bayes hyperparameter sweep (validation set used for scoring).
- Train the final model with the best hyperparameters and log the run to the same W&B project.
- Return an :class:
EndToEndResultwith test metrics and per-step timings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
EndToEndConfig
|
Pipeline configuration. |
required |
Returns:
| Type | Description |
|---|---|
EndToEndResult
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no ChEMBL targets can be resolved or the dataset is empty. |
Source code in src/dta_gnn/training/end_to_end.py
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 | |
EndToEndConfig
dataclass
¶
EndToEndConfig(uniprot_ids: str, architecture: Literal['gin', 'gcn', 'gat', 'sage', 'pna', 'transformer', 'tag', 'arma', 'cheb', 'supergat'] = 'gin', sqlite_path: str | None = None, standard_types: list[str] | None = None, test_size: float = 0.2, val_size: float = 0.1, wandb_project: str = 'dta_gnn', wandb_entity: str | None = None, wandb_api_key: str | None = None, n_trials: int = 20, lr_min: float = 1e-05, lr_max: float = 0.01, embedding_dim_min: int = 32, embedding_dim_max: int = 256, hidden_dim_min: int = 32, hidden_dim_max: int = 256, num_layers_min: int = 1, num_layers_max: int = 5, dropout_min: float = 0.0, dropout_max: float = 0.5, epochs: int = 30, batch_size: int = 64, runs_root: str = 'runs', device: str | None = None)
Configuration for the end-to-end GNN training pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uniprot_ids
|
str
|
One or more UniProt accessions (comma/space/semicolon-separated).
Example: |
required |
architecture
|
Literal['gin', 'gcn', 'gat', 'sage', 'pna', 'transformer', 'tag', 'arma', 'cheb', 'supergat']
|
GNN architecture to train and tune. |
'gin'
|
sqlite_path
|
str | None
|
Path to a local ChEMBL SQLite database. When provided,
all ChEMBL data is fetched from this file. When |
None
|
standard_types
|
list[str] | None
|
Activity standard types to include (e.g.
|
None
|
test_size
|
float
|
Fraction of data reserved for the test split. |
0.2
|
val_size
|
float
|
Fraction of data reserved for the validation split. |
0.1
|
wandb_project
|
str
|
W&B project name used for both the HPO sweep and the final training run. |
'dta_gnn'
|
wandb_entity
|
str | None
|
W&B entity (username or team). |
None
|
wandb_api_key
|
str | None
|
W&B API key. |
None
|
n_trials
|
int
|
Number of W&B Bayes sweep trials for hyperparameter search. |
20
|
lr_min
|
float
|
Lower bound for learning-rate search (log-uniform). |
1e-05
|
lr_max
|
float
|
Upper bound for learning-rate search (log-uniform). |
0.01
|
embedding_dim_min
|
int
|
Lower bound for embedding dimension search. |
32
|
embedding_dim_max
|
int
|
Upper bound for embedding dimension search. |
256
|
hidden_dim_min
|
int
|
Lower bound for hidden dimension search. |
32
|
hidden_dim_max
|
int
|
Upper bound for hidden dimension search. |
256
|
num_layers_min
|
int
|
Lower bound for number of GNN layers search. |
1
|
num_layers_max
|
int
|
Upper bound for number of GNN layers search. |
5
|
dropout_min
|
float
|
Lower bound for dropout rate search. |
0.0
|
dropout_max
|
float
|
Upper bound for dropout rate search. |
0.5
|
epochs
|
int
|
Number of training epochs for the final model (HPO trials use fewer epochs internally). |
30
|
batch_size
|
int
|
Mini-batch size for both HPO and final training. |
64
|
runs_root
|
str
|
Root directory under which timestamped run directories are
created (default: |
'runs'
|
device
|
str | None
|
PyTorch device string. |
None
|
EndToEndResult
dataclass
¶
EndToEndResult(run_dir: Path, uniprot_ids: list[str], target_chembl_ids: list[str], architecture: str, dataset_size: int, train_size: int, val_size_actual: int, test_size_actual: int, hyperopt_result: HyperoptResult, train_result: GnnTrainResult, test_metrics: dict, timings: dict)
Result of a complete end-to-end GNN training run.
Attributes:
| Name | Type | Description |
|---|---|---|
run_dir |
Path
|
Path to the timestamped run directory holding all artifacts. |
uniprot_ids |
list[str]
|
Validated UniProt accessions used as input. |
target_chembl_ids |
list[str]
|
Resolved ChEMBL target IDs. |
architecture |
str
|
GNN architecture that was trained. |
dataset_size |
int
|
Total number of rows in the built dataset. |
train_size |
int
|
Number of training rows. |
val_size_actual |
int
|
Number of validation rows. |
test_size_actual |
int
|
Number of test rows. |
hyperopt_result |
HyperoptResult
|
Full result from |
train_result |
GnnTrainResult
|
Full result from |
test_metrics |
dict
|
Test-split metrics dict ( |
timings |
dict
|
Wall-clock time in seconds for each pipeline step. |
Dataset Pipeline (dta_gnn.pipeline)¶
Pipeline
¶
Source code in src/dta_gnn/pipeline.py
build_dta
¶
build_dta(*, target_ids: Optional[List[str]] = None, molecule_ids: Optional[List[str]] = None, standard_types: Optional[List[str]] = None, split_method: str = 'random', output_path: Optional[str] = None, test_size: float = 0.2, val_size: float = 0.1, split_year: int = 2022, featurize: bool = False, progress_callback: Optional[callable] = None) -> pd.DataFrame
Build a DTA-style regression dataset.
The regression label is always pchembl_value (after optional cleaning).
Target sequences/metadata are stored separately in self.last_targets_csv.
Source code in src/dta_gnn/pipeline.py
32 33 34 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 | |
Data Sources (dta_gnn.io)¶
ChEMBL sources¶
ChemblSource
¶
Bases: ABC
Abstract base class for ChEMBL data sources.
fetch_activities
abstractmethod
¶
fetch_activities(target_ids: Optional[List[str]] = None, molecule_ids: Optional[List[str]] = None, standard_types: Optional[List[str]] = None, progress_callback: Optional[callable] = None) -> pd.DataFrame
Fetch activity data.
Returns a DataFrame with columns: - molecule_chembl_id - target_chembl_id - standard_type - standard_value - standard_units - standard_relation - pchembl_value (optional) - canonical_smiles (optional, avoids a separate fetch_molecules call)
Source code in src/dta_gnn/io/chembl_source.py
fetch_molecules
abstractmethod
¶
Fetch molecule structures.
Returns a DataFrame with columns: - molecule_chembl_id - smiles
fetch_targets
abstractmethod
¶
Fetch target sequences.
Returns a DataFrame with columns: - target_chembl_id - sequence - organism
ChemblSQLiteSource
¶
Bases: ChemblSource
ChEMBL data source using a local SQLite database dump.
Source code in src/dta_gnn/io/sqlite_source.py
ChemblWebSource
¶
Bases: ChemblSource
ChEMBL data source using the official Web Resource Client.
get_targets
¶
Get targets by UniProt accession.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accession
|
Optional[str]
|
UniProt accession (e.g., 'P00533' for EGFR) |
None
|
Returns:
| Type | Description |
|---|---|
List[dict]
|
List of target dictionaries with target_chembl_id |
Source code in src/dta_gnn/io/web_source.py
UniProt → ChEMBL target mapping¶
UniProtToChEMBLResult
dataclass
¶
UniProtToChEMBLResult(resolved_target_chembl_ids: list[str], per_input: Mapping[str, list[str]], unmapped: list[str])
parse_uniprot_accessions
¶
Source code in src/dta_gnn/io/target_mapping.py
parse_chembl_target_ids
¶
Source code in src/dta_gnn/io/target_mapping.py
map_uniprot_to_chembl_targets_sqlite
¶
map_uniprot_to_chembl_targets_sqlite(sqlite_path: str | Path, accessions: Iterable[str]) -> UniProtToChEMBLResult
Source code in src/dta_gnn/io/target_mapping.py
map_uniprot_to_chembl_targets_web
¶
Web-based UniProt→ChEMBL mapping.
This is implemented as a thin fallback to the existing ChEMBL web client logic in the app. It keeps the API stable for the UI.
Source code in src/dta_gnn/io/target_mapping.py
Run directories¶
create_run_dir
¶
Create a new timestamped run directory and update runs/current.
Returns the created run directory path.
Source code in src/dta_gnn/io/runs.py
resolve_run_dir
¶
Resolve and normalize a run directory path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
run_dir
|
str | Path | None
|
Path to run directory (string or Path object) |
required |
Returns:
| Type | Description |
|---|---|
Path | None
|
Resolved Path object, or None if input is None or resolution fails |
Source code in src/dta_gnn/io/runs.py
resolve_current_run_dir
¶
Resolve the current run folder.
Prefers runs/current if it exists (dir or symlink). If missing, raises
FileNotFoundError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hint
|
str
|
Optional hint message to include in error |
'Build a dataset first.'
|
Returns:
| Type | Description |
|---|---|
Path
|
Resolved Path to current run directory |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If runs/current does not exist |
Source code in src/dta_gnn/io/runs.py
Database downloader¶
download_chembl_db
¶
Download and extract ChEMBL SQLite database. Returns path to the extracted .db file.
Source code in src/dta_gnn/io/downloader.py
File / CSV utilities¶
CsvPreview
dataclass
¶
Result of CSV preview operation.
normalize_csv_path
¶
Normalize a CSV file path string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | None
|
Path string to normalize |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Normalized path string, or None if input is empty/None |
Source code in src/dta_gnn/io/utils.py
preview_csv
¶
Preview a CSV file (wrapper that returns only DataFrame).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | None
|
Path to CSV file |
required |
n
|
int
|
Number of rows to read (default: 50) |
50
|
Returns:
| Type | Description |
|---|---|
DataFrame | None
|
DataFrame with first n rows, or None if error |
Source code in src/dta_gnn/io/utils.py
preview_csv_with_error
¶
Preview a CSV file with error handling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | None
|
Path to CSV file |
required |
n
|
int
|
Number of rows to read (default: 50) |
50
|
Returns:
| Type | Description |
|---|---|
CsvPreview
|
CsvPreview object with DataFrame and optional error message |
Source code in src/dta_gnn/io/utils.py
iter_existing_files
¶
Filter a list of paths to only those that exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
Iterable[str | None]
|
Iterable of file paths (may include None) |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of existing file paths |
Source code in src/dta_gnn/io/utils.py
find_chembl_sqlite_dbs
¶
Find available ChEMBL SQLite DB files under a chembl_dbs/ folder.
Searches both the current working directory and the repo root (when running from source). Returns absolute paths.
Returns:
| Type | Description |
|---|---|
list[str]
|
Sorted list of absolute paths to SQLite database files |
Source code in src/dta_gnn/io/utils.py
Cleaning (dta_gnn.cleaning)¶
standardize_activities
¶
standardize_activities(df: DataFrame, convert_to_pchembl: bool = True, drop_censored: bool = False) -> pd.DataFrame
Standardize activity values. - Filters rows with missing standard_value. - Converts nanomolar units to molar if needed (though ChEMBL standard_value is usually nM). - Calculates pChEMBL if missing and requested.
Source code in src/dta_gnn/cleaning/functions.py
aggregate_duplicates
¶
aggregate_duplicates(df: DataFrame, group_cols: list = ['molecule_chembl_id', 'target_chembl_id'], agg_method: Literal['median', 'mean', 'max', 'min'] = 'median') -> pd.DataFrame
Deduplicate measurements for the same drug-target pair.
Source code in src/dta_gnn/cleaning/functions.py
canonicalize_smiles
¶
Canonicalize a single SMILES string using RDKit.
Source code in src/dta_gnn/cleaning/functions.py
validate_split_sizes
¶
Validate test and validation split sizes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
test_size
|
float
|
Test set size (fraction) |
required |
val_size
|
float
|
Validation set size (fraction) |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If sizes are invalid (not numbers, negative, or sum >= 1.0) |
Source code in src/dta_gnn/cleaning/validation.py
validate_sqlite_path
¶
Validate SQLite database path if source is 'sqlite'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Data source type ('sqlite' or 'web') |
required |
sqlite_path
|
str | None
|
Path to SQLite database file |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If source is 'sqlite' and path is missing or invalid |
Source code in src/dta_gnn/cleaning/validation.py
Splitting (dta_gnn.splits)¶
split_random
¶
split_random(df: DataFrame, test_size: float = 0.2, val_size: float = 0.1, seed: int = 42) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]
Random split into Train/Val/Test.
Source code in src/dta_gnn/splits/strategies.py
split_cold_drug_scaffold
¶
split_cold_drug_scaffold(df: DataFrame, smiles_col: str = 'smiles', test_size: float = 0.2, val_size: float = 0.1, seed: int = 42) -> pd.DataFrame
Scaffold split (Cold Drug).
Source code in src/dta_gnn/splits/strategies.py
split_temporal
¶
split_temporal(df: DataFrame, year_col: str = 'year', split_year: int = 2022, val_size: float = 0.1) -> pd.DataFrame
Temporal split based on year. Train: year < split_year Test: year >= split_year Val: random subset of Train (or could be time-based if requested, but simple random of past is standard)
Source code in src/dta_gnn/splits/strategies.py
Featurisation (dta_gnn.features)¶
Morgan fingerprints¶
calculate_morgan_fingerprints
¶
calculate_morgan_fingerprints(df: DataFrame, smiles_col: str = 'smiles', radius: int = 2, n_bits: int = 2048, *, out_col: str = 'morgan_fingerprint', drop_failures: bool = True) -> pd.DataFrame
Calculate Morgan fingerprints for molecules in the DataFrame.
Returns a copy of df with an added fingerprint column containing bitstrings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input dataframe |
required |
smiles_col
|
str
|
Column containing SMILES strings |
'smiles'
|
radius
|
int
|
Morgan radius (2 => ECFP4) |
2
|
n_bits
|
int
|
Fingerprint bit length |
2048
|
out_col
|
str
|
Output column name |
'morgan_fingerprint'
|
drop_failures
|
bool
|
Whether to drop rows that fail featurization |
True
|
Source code in src/dta_gnn/features/__init__.py
2-D molecular graphs¶
MoleculeGraph2D
dataclass
¶
MoleculeGraph2D(molecule_chembl_id: str, atom_type: ndarray, atom_feat: ndarray, edge_index: ndarray, edge_attr: ndarray)
smiles_to_graph_2d
¶
Convert a SMILES string into a simple 2D molecular graph.
Node features are fixed-size (6) numeric features. Edge features are fixed-size (6) numeric features.
Source code in src/dta_gnn/features/molecule_graphs.py
build_graphs_2d
¶
build_graphs_2d(*, molecules: Iterable[tuple[str, str]], drop_failures: bool = True) -> list[MoleculeGraph2D]
Source code in src/dta_gnn/features/molecule_graphs.py
Models (dta_gnn.models)¶
Random Forest baseline¶
train_random_forest_on_run
¶
train_random_forest_on_run(run_dir: str | Path, *, n_estimators: int = 100, max_depth: int | None = 5, random_seed: int = 42) -> RandomForestTrainResult
Train a RandomForest baseline on runs/<run>/dataset.csv + compounds.csv.
Writes: - model_rf.pkl - model_metrics.json - model_predictions.csv
Source code in src/dta_gnn/models/random_forest.py
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 | |
SVR baseline¶
train_svr_on_run
¶
train_svr_on_run(run_dir: str | Path, *, C: float = 1.0, epsilon: float = 0.5, kernel: str = 'rbf', random_seed: int = 42) -> SvrTrainResult
Train an SVR baseline on Morgan fingerprints.
Writes: - model_svr.pkl - model_metrics_svr.json - model_predictions_svr.csv
Source code in src/dta_gnn/models/svr.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 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | |
Graph Neural Networks¶
GnnTrainConfig
dataclass
¶
GnnTrainConfig(architecture: Literal['gin', 'gcn', 'gat', 'sage', 'pna', 'transformer', 'tag', 'arma', 'cheb', 'supergat'] = 'gin', embedding_dim: int = 128, hidden_dim: int = 128, num_layers: int = 5, dropout: float = 0.1, pooling: Literal['add', 'mean', 'max', 'attention'] = 'add', residual: bool = False, head_mlp_layers: int = 2, gin_conv_mlp_layers: int = 2, gin_train_eps: bool = False, gin_eps: float = 0.0, gat_heads: int = 4, sage_aggr: str = 'mean', transformer_heads: int = 4, transformer_edge_dim: int | None = None, tag_k: int = 2, arma_num_stacks: int = 1, arma_num_layers: int = 1, cheb_k: int = 2, supergat_heads: int = 4, supergat_attention_type: str = 'MX', lr: float = 0.001, weight_decay: float = 0.0, batch_size: int = 64, epochs: int = 10, random_seed: int = 42, device: str | None = None)
GnnTrainResult
dataclass
¶
GnnTrainResult(run_dir: Path, task_type: Literal['regression'], model_path: Path, encoder_path: Path, encoder_config_path: Path, metrics_path: Path, predictions_path: Path, metrics: dict[str, Any], best_epoch: int | None = None)
train_gnn_on_run
¶
train_gnn_on_run(run_dir: str | Path, *, config: GnnTrainConfig | None = None, wandb_run=None) -> GnnTrainResult
Train a 2D GNN model on the run's dataset.csv, using molecule graphs from compounds.csv.
Writes
- model_gnn_
.pt - encoder_
.pt - encoder_
_config.json - model_metrics_gnn_
.json - model_predictions_gnn_
.csv
Source code in src/dta_gnn/models/gnn.py
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 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 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 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 | |
GnnEmbeddingExtractResult
dataclass
¶
GnnEmbeddingExtractResult(run_dir: Path, embeddings_path: Path, n_molecules: int, embedding_dim: int)
extract_gnn_embeddings_on_run
¶
extract_gnn_embeddings_on_run(run_dir: str | Path, *, batch_size: int = 256, device: str | None = None) -> GnnEmbeddingExtractResult
Use a saved GNN encoder to generate embeddings for molecules in compounds.csv.
Requires
- compounds.csv
- encoder_
.pt - encoder_
_config.json
Writes
- molecule_embeddings.npz (molecule_chembl_id, embeddings)
Source code in src/dta_gnn/models/gnn.py
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 | |
Prediction on new molecules¶
PredictionResult
dataclass
¶
PredictionResult(predictions: DataFrame, model_type: Literal['RandomForest', 'SVR', 'GNN'], model_path: str, run_dir: Path)
Result from model prediction.
predict_with_random_forest
¶
predict_with_random_forest(run_dir: Path, smiles_list: list[str], molecule_ids: list[str] | None = None) -> PredictionResult
Predict using a trained RandomForest model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
run_dir
|
Path
|
Directory containing the trained model (model_rf.pkl) |
required |
smiles_list
|
list[str]
|
List of SMILES strings to predict |
required |
molecule_ids
|
list[str] | None
|
Optional list of molecule IDs (defaults to mol_0, mol_1, ...) |
None
|
Returns:
| Type | Description |
|---|---|
PredictionResult
|
PredictionResult with predictions DataFrame |
Source code in src/dta_gnn/models/predict.py
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 | |
predict_with_svr
¶
predict_with_svr(run_dir: Path, smiles_list: list[str], molecule_ids: list[str] | None = None) -> PredictionResult
Predict using a trained SVR model.
Expects model_svr.pkl in the run directory.
Uses Morgan (ECFP4) fingerprints with radius=2, nBits=2048.
Source code in src/dta_gnn/models/predict.py
predict_with_gnn
¶
predict_with_gnn(run_dir: Path, smiles_list: list[str], molecule_ids: list[str] | None = None, batch_size: int = 64, device: str | None = None, architecture: str | None = None) -> PredictionResult
Predict using a trained GNN model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
run_dir
|
Path
|
Directory containing the trained model (model_gnn_ |
required |
smiles_list
|
list[str]
|
List of SMILES strings to predict |
required |
molecule_ids
|
list[str] | None
|
Optional list of molecule IDs (defaults to mol_0, mol_1, ...) |
None
|
batch_size
|
int
|
Batch size for inference |
64
|
Returns:
| Type | Description |
|---|---|
PredictionResult
|
PredictionResult with predictions DataFrame |
Source code in src/dta_gnn/models/predict.py
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 | |
Hyperparameter optimisation¶
HyperoptConfig
dataclass
¶
HyperoptConfig(model_type: Literal['RandomForest', 'SVR', 'GNN'], n_trials: int = 20, n_jobs: int = 1, sampler_seed: int = 42, rf_optimize_n_estimators: bool = False, rf_n_estimators_min: int = 50, rf_n_estimators_max: int = 500, rf_optimize_max_depth: bool = False, rf_max_depth_min: int = 5, rf_max_depth_max: int = 50, rf_optimize_min_samples_split: bool = False, rf_min_samples_split_min: int = 2, rf_min_samples_split_max: int = 20, svr_optimize_C: bool = False, svr_C_min: float = 0.1, svr_C_max: float = 100.0, svr_C_default: float = 10.0, svr_optimize_epsilon: bool = False, svr_epsilon_min: float = 0.01, svr_epsilon_max: float = 0.2, svr_epsilon_default: float = 0.1, svr_optimize_kernel: bool = False, svr_kernel_choices: list[str] = None, svr_kernel_default: str = 'rbf', architecture: Literal['gin', 'gcn', 'gat', 'sage', 'pna', 'transformer', 'tag', 'arma', 'cheb', 'supergat'] = 'gin', optimize_epochs: bool = False, epochs_min: int = 5, epochs_max: int = 50, epochs_default: int = 20, optimize_lr: bool = False, lr_min: float = 1e-05, lr_max: float = 0.01, optimize_batch_size: bool = False, batch_size_min: int = 16, batch_size_max: int = 256, batch_size_default: int = 64, optimize_embedding_dim: bool = False, embedding_dim_min: int = 32, embedding_dim_max: int = 512, embedding_dim_default: int = 128, optimize_hidden_dim: bool = False, hidden_dim_min: int = 32, hidden_dim_max: int = 512, hidden_dim_default: int = 128, optimize_num_layers: bool = False, num_layers_min: int = 1, num_layers_max: int = 5, num_layers_default: int = 3, optimize_dropout: bool = False, dropout_min: float = 0.0, dropout_max: float = 0.6, dropout_default: float = 0.1, optimize_pooling: bool = False, pooling_choices: list[str] = None, pooling_default: str = 'add', optimize_residual: bool = False, residual_default: bool = False, optimize_head_mlp_layers: bool = False, head_mlp_layers_min: int = 1, head_mlp_layers_max: int = 4, head_mlp_layers_default: int = 2, optimize_gin_conv_mlp_layers: bool = False, gin_conv_mlp_layers_min: int = 1, gin_conv_mlp_layers_max: int = 4, gin_conv_mlp_layers_default: int = 2, optimize_gin_train_eps: bool = False, gin_train_eps_default: bool = False, optimize_gin_eps: bool = False, gin_eps_min: float = 0.0, gin_eps_max: float = 1.0, gin_eps_default: float = 0.0, optimize_gat_heads: bool = False, gat_heads_min: int = 1, gat_heads_max: int = 8, gat_heads_default: int = 4, optimize_sage_aggr: bool = False, sage_aggr_choices: list[str] = None, sage_aggr_default: str = 'mean', optimize_transformer_heads: bool = False, transformer_heads_min: int = 1, transformer_heads_max: int = 8, transformer_heads_default: int = 4, optimize_tag_k: bool = False, tag_k_min: int = 1, tag_k_max: int = 5, tag_k_default: int = 2, optimize_arma_stacks: bool = False, arma_num_stacks_min: int = 1, arma_num_stacks_max: int = 3, arma_num_stacks_default: int = 1, optimize_arma_layers: bool = False, arma_num_layers_min: int = 1, arma_num_layers_max: int = 3, arma_num_layers_default: int = 1, optimize_cheb_k: bool = False, cheb_k_min: int = 1, cheb_k_max: int = 5, cheb_k_default: int = 2, optimize_supergat_heads: bool = False, supergat_heads_min: int = 1, supergat_heads_max: int = 8, supergat_heads_default: int = 4, optimize_supergat_attention_type: bool = False, supergat_attention_type_choices: list[str] = None, supergat_attention_type_default: str = 'MX', optimize_weight_decay: bool = False, weight_decay_min: float = 1e-06, weight_decay_max: float = 0.001, weight_decay_default: float = 0.0, device: str | None = None)
Configuration for hyperparameter optimization.
HyperoptResult
dataclass
¶
HyperoptResult(run_dir: Path, best_params: dict, best_value: float, best_trial_number: int, n_trials: int, study_path: str, best_params_path: str, strategy: Literal['holdout-val', 'cv'], cv_folds_used: Optional[int])
Result from hyperparameter optimization.
optimize_random_forest_wandb
¶
optimize_random_forest_wandb(run_dir: Path, *, config: HyperoptConfig, project: str, entity: str | None = None, api_key: str | None = None, sweep_name: str | None = None, radius: int = 2, n_bits: int = 2048) -> HyperoptResult
Optimize RandomForest hyperparameters using a W&B Bayes sweep.
Uses: - Holdout validation if a val split exists. - Otherwise CV (KFold for regression).
Source code in src/dta_gnn/models/hyperopt.py
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 | |
optimize_svr_wandb
¶
optimize_svr_wandb(run_dir: Path, *, config: HyperoptConfig, project: str, entity: str | None = None, api_key: str | None = None, sweep_name: str | None = None, radius: int = 2, n_bits: int = 2048) -> HyperoptResult
Optimize SVR hyperparameters using a W&B Bayes sweep.
Notes:
- SVR sweep is intended for regression runs (DTA).
- Uses holdout validation if a val split exists; otherwise uses KFold CV.
- Logs a single scalar metric val_score (maximize).
Source code in src/dta_gnn/models/hyperopt.py
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 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 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 | |
optimize_gnn_wandb
¶
optimize_gnn_wandb(run_dir: Path, *, config: HyperoptConfig, project: str, entity: str | None = None, api_key: str | None = None, sweep_name: str | None = None) -> HyperoptResult
Optimize GNN hyperparameters using a W&B Bayes sweep.
Notes:
- Uses the existing train/val split (requires a non-empty val split).
- Runs each trial in an isolated subdirectory so artifacts don't overwrite.
- Logs a single scalar metric val_score (maximize).
Source code in src/dta_gnn/models/hyperopt.py
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 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 | |
optimize_random_forestandoptimize_gnnare aliases that resolve tooptimize_random_forest_wandbandoptimize_gnn_wandbrespectively.
Model utilities¶
list_available_models
¶
List all available trained models in the run directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
run_dir
|
Path | None
|
Path to run directory. If None, attempts to resolve current run directory. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, list[str]]
|
Dictionary with keys: 'rf', 'svr', 'gnn' |
dict[str, list[str]]
|
Each value is a list of model identifiers (for GNN: architecture names) |
Source code in src/dta_gnn/models/utils.py
Audits (dta_gnn.audits)¶
audit_scaffold_leakage
¶
audit_scaffold_leakage(train_df: DataFrame, test_df: DataFrame, smiles_col: str = 'smiles') -> Dict[str, Any]
Check if scaffolds from test set appear in train set.
Source code in src/dta_gnn/audits/leakage.py
audit_target_leakage
¶
audit_target_leakage(train_df: DataFrame, test_df: DataFrame, target_col: str = 'target_chembl_id') -> Dict[str, Any]
Check exact target ID overlap.
Source code in src/dta_gnn/audits/leakage.py
Exporters (dta_gnn.exporters)¶
collect_artifacts
¶
collect_artifacts(*, run_dir: str | None, dataset_path: str | None = None, targets_path: str | None = None, compounds_path: str | None = None) -> dict[str, str | None]
Collect artifact file paths from a run directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
run_dir
|
str | None
|
Path to the run directory |
required |
dataset_path
|
str | None
|
Optional explicit path to dataset.csv |
None
|
targets_path
|
str | None
|
Optional explicit path to targets.csv |
None
|
compounds_path
|
str | None
|
Optional explicit path to compounds.csv |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, str | None]
|
Dictionary mapping artifact keys to file paths (or None if not found) |
Source code in src/dta_gnn/exporters/artifacts.py
write_artifacts_zip
¶
Create a zip file from a list of artifact paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zip_path
|
str | None
|
Path where the zip file should be created |
required |
paths
|
list[str | None]
|
List of file paths to include in the zip |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Path to the created zip file, or None if creation failed |
Source code in src/dta_gnn/exporters/artifacts.py
write_artifacts_zip_from_manifest
¶
Create a zip file from an artifacts manifest dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
artifacts
|
dict[str, str | None]
|
Dictionary mapping artifact keys to file paths |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Path to the created zip file, or None if creation failed |
Source code in src/dta_gnn/exporters/artifacts.py
artifacts_table
¶
Create a DataFrame table of artifacts for UI display.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
artifacts
|
dict[str, str | None]
|
Dictionary mapping artifact keys to file paths |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns 'artifact' and 'path' |
Source code in src/dta_gnn/exporters/artifacts.py
artifact_keys_in_zip
¶
Stable list of artifact keys included in artifacts.zip.
Keep this centralized so handlers don't duplicate long lists.
Source code in src/dta_gnn/exporters/artifacts.py
generate_dataset_card
¶
Generate a markdown dataset card.
Source code in src/dta_gnn/exporters/card.py
Visualisation (dta_gnn.visualization)¶
plot_activity_distribution
¶
Plot histogram of pChEMBL values.
Source code in src/dta_gnn/visualization.py
plot_split_sizes
¶
Plot bar chart of split sizes.
Source code in src/dta_gnn/visualization.py
plot_chemical_space
¶
plot_chemical_space(smiles_data: Union[dict, list], method: str = 't-SNE', radius: int = 2, n_bits: int = 1024, n_components: int = 2, perplexity: int = 30, learning_rate: float = 200.0, random_state: int = 42) -> plt.Figure
Visualize chemical space using Morgan fingerprints and dimensionality reduction. Acceps a dictionary {group_name: [smiles]} or a flat list of SMILES.
Source code in src/dta_gnn/visualization.py
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 | |