File size: 6,240 Bytes
84a242a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
126
127
128
129
import random
import pandas as pd

import pytorch_lightning as pl
from torch_geometric.data import Data, Dataset
from torch_geometric.loader import DataLoader, DataListLoader
from .dataset import CombinedDataset, prepare_data_composite, prepare_data_score, protein_graph_path
from sklearn.model_selection import train_test_split, KFold
from torch_geometric.utils import degree
import torch
from tqdm import tqdm

class DInterface(pl.LightningDataModule):
    def __init__(self, num_workers=8, dataset='', **kwargs):
        super().__init__()
        pl.seed_everything(kwargs.get('seed'), workers=True)
        self.num_workers = num_workers
        self.kwargs = kwargs
        self.batch_size = kwargs.get('batch_size', 8)
        self.incl_columns = kwargs.get('incl_columns', [])
        self.test_size = kwargs.get('test_size', 0.5)
        self.seed = kwargs.get('seed')
        self.k_folds = kwargs.get('k_folds', None)  # None means no K-Fold, just train/val/test split
        self.current_fold = kwargs.get('fold_num', 0)  # Default to first fold
        self.benchmark = kwargs.get('benchmark', 'posex_self_docking')
        self.label_source = kwargs.get('label_source', 'score')
        self.score_matrix_path = kwargs.get('score_matrix_path', None)

        if self.label_source in ['score', 'al']:
            prepare_data_fn = prepare_data_score
        elif self.label_source == 'composite':
            prepare_data_fn = prepare_data_composite
        else:
            raise ValueError("label_source must be one of ['score', 'composite', 'al']")

        if self.score_matrix_path is not None and isinstance(self.benchmark, list) and len(self.benchmark) > 1:
            raise ValueError("score_matrix_path only supports a single benchmark at a time.")

        # Prepare dataset differently based on AS criteria
        if isinstance(self.benchmark, list):
            
            for b in self.benchmark:
                matrix_path = self.score_matrix_path if self.score_matrix_path is not None else None
                if prepare_data_fn is prepare_data_score:
                    ds, num_classes = prepare_data_fn(self.incl_columns, b, matrix_path)
                else:
                    ds, num_classes = prepare_data_fn(self.incl_columns, b)
                
                if hasattr(self, 'dataset'):
                    self.dataset = pd.concat([self.dataset, ds], ignore_index=True)
                else:
                    self.dataset = ds
                    self.num_classes = num_classes
                
        elif isinstance(self.benchmark, str):
            if prepare_data_fn is prepare_data_score:
                self.dataset, self.num_classes = prepare_data_fn(self.incl_columns, self.benchmark, self.score_matrix_path)
            else:
                self.dataset, self.num_classes = prepare_data_fn(self.incl_columns, self.benchmark)

        else:
            raise ValueError("benchmark must be a string or a list of strings")

        expected_num_classes = kwargs.get('num_classes', None)
        if expected_num_classes is not None and int(expected_num_classes) != int(self.num_classes):
            raise ValueError(
                f"num_classes mismatch: args.num_classes={expected_num_classes}, "
                f"loaded label columns={self.num_classes}. "
                "Ensure incl_columns/label matrix matches the checkpoint output dimension."
            )
            
        self.load_data_module()

    def setup(self, stage=None):
        if self.k_folds is not None:
            print("K-Fold enabled")            
            self.kf = KFold(n_splits=self.k_folds, shuffle=True, random_state=self.seed)
            self.folds = list(self.kf.split(self.dataset))
            train_idx, test_idx = self.folds[self.current_fold]
            
            self.trainset, self.valset = train_test_split(self.dataset.iloc[train_idx], test_size=0.1, random_state=self.seed)
            self.testset = self.dataset.iloc[test_idx]

        else:
            print("K-Fold disabled")
            if self.test_size == 1 or self.test_size == 0:
                self.trainset, self.valset = train_test_split(self.dataset, test_size=0.1, random_state=self.seed)
                self.testset = self.dataset
            else:
                train_val, self.testset = train_test_split(self.dataset, test_size=self.test_size, random_state=self.seed)
                self.trainset, self.valset = train_test_split(train_val, test_size=self.test_size, random_state=self.seed)

    def train_dataloader(self):
        # Combining the protein and ligand graphs into the dataset
        trainset_combined = CombinedDataset(self.trainset)
        return DataLoader(trainset_combined, batch_size=self.batch_size, shuffle=True, num_workers=self.num_workers, persistent_workers=False, drop_last=False)

    def val_dataloader(self):
        valset_combined = CombinedDataset(self.valset)
        return DataLoader(valset_combined, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers, persistent_workers=False, drop_last=False)

    def test_dataloader(self):
        testset_combined = CombinedDataset(self.testset)
        return DataLoader(testset_combined, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers, persistent_workers=False)
    
    def get_train_deg(self):

        deg_hist = torch.zeros(256, dtype=torch.long)
        return deg_hist 
        graph_ds = self.trainset  # or self.graph_dataset if that’s what you saved

        for idx in range(len(graph_ds)):
            # Load just the graph part directly

            protein_name = graph_ds.iloc[idx]['protein']
            ligand_name = graph_ds.iloc[idx]['ligand']
            graph_path = f'{protein_graph_path}/pyg_graph_{protein_name}_{ligand_name}_protein.pt'
            graph = torch.load(graph_path, weights_only=False)
            d = degree(graph.edge_index[1], num_nodes=graph.x.size(0), dtype=torch.long)
            deg_hist.index_add_(0, d, torch.ones_like(d))

        return deg_hist

    # These are from the template, but not used in our implementation.
    def load_data_module(self):
        pass

    def instancialize(self, **other_args):
        pass