File size: 8,015 Bytes
6e7d4ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
import os
import sys
import re

from pathlib import Path
from typing import Collection, List, Dict, Type

import numpy as np
import pandas as pd
from tqdm import tqdm

from .metrics import FullEvaluator, FullCollectionEvaluator

AUXILIARY_COLUMNS = ['sample', 'sdf_file', 'pdb_file', 'subdir']
VALIDITY_METRIC_NAME = 'medchem.valid'


def get_data_type(key: str, data_types: Dict[str, Type], default=float) -> Type:
    found_data_type_key = None
    found_data_type_value = None
    for data_type_key, data_type_value in data_types.items():
        if re.match(data_type_key, key) is not None:
            if found_data_type_key is not None:
                raise ValueError(f'Multiple data type keys match [{key}]: {found_data_type_key}, {data_type_key}')

            found_data_type_value = data_type_value
            found_data_type_key = data_type_key

    if found_data_type_key is None:
        if default is None:
            raise KeyError(key)
        else:
            found_data_type_value = default

    return found_data_type_value


def convert_data_to_table(data: List[Dict], data_types: Dict[str, Type]) -> pd.DataFrame:
    """
    Converts data from `evaluate_drugflow` to a detailed table
    """
    table = []
    for entry in data:
        table_entry = {}
        for key, value in entry.items():
            if key in AUXILIARY_COLUMNS:
                table_entry[key] = value
                continue
            if get_data_type(key, data_types) != list:
                table_entry[key] = value
        table.append(table_entry)

    return pd.DataFrame(table)

def aggregated_metrics(table: pd.DataFrame, data_types: Dict[str, Type], validity_metric_name: str = None):
    """
    Args:
        table (pd.DataFrame): table with metrics computed for each sample
        data_types (Dict[str, Type]): dictionary with data types for each column
        validity_metric_name (str): name of the column that has validity metric

    Returns:
        agg_table (pd.DataFrame): table with columns ['metric', 'value', 'std']
    """
    aggregated_results = []

    # If validity column name is provided:
    #    1. compute validity on the entire data
    #    2. drop all invalid molecules to compute the rest
    if validity_metric_name is not None:
        aggregated_results.append({
            'metric': validity_metric_name,
            'value': table[validity_metric_name].fillna(False).astype(float).mean(),
            'std': None,
        })
        table = table[table[validity_metric_name]]

    # Compute aggregated metrics + standard deviations where applicable
    for column in table.columns:
        if column in AUXILIARY_COLUMNS + [validity_metric_name] or get_data_type(column, data_types) == str:
            continue
        with pd.option_context("future.no_silent_downcasting", True):
            if get_data_type(column, data_types) == bool:
                values = table[column].fillna(0).values.astype(float).mean()
                std = None
            else:
                values = table[column].dropna().values.astype(float).mean()
                std = table[column].dropna().values.astype(float).std()

        aggregated_results.append({
            'metric': column,
            'value': values,
            'std': std,
        })

    agg_table = pd.DataFrame(aggregated_results)
    return agg_table


def collection_metrics(
        table: pd.DataFrame,
        reference_smiles: Collection[str],
        validity_metric_name: str = None,
        exclude_evaluators: Collection[str] = [],
):
    """
    Args:
        table (pd.DataFrame): table with metrics computed for each sample
        reference_smiles (Collection[str]): list of reference SMILES (e.g. training set)
        validity_metric_name (str): name of the column that has validity metric
        exclude_evaluators (Collection[str]): Evaluator IDs to exclude

    Returns:
        col_table (pd.DataFrame): table with columns ['metric', 'value']
    """

    # If validity column name is provided drop all invalid molecules
    if validity_metric_name is not None:
        table = table[table[validity_metric_name]]

    evaluator = FullCollectionEvaluator(reference_smiles, exclude_evaluators=exclude_evaluators)
    smiles = table['representation.smiles'].values
    if len(smiles) == 0:
        print('No valid input molecules')
        return pd.DataFrame(columns=['metric', 'value'])

    collection_metrics = evaluator(smiles)
    results = [
        {'metric': key, 'value': value}
        for key, value in collection_metrics.items()
    ]

    col_table = pd.DataFrame(results)
    return col_table


def evaluate_drugflow_subdir(
        in_dir: Path,
        evaluator: FullEvaluator,
        desc: str = None,
        n_samples: int = None,
) -> List[Dict]:
    """
    Computes per-molecule metrics for a single directory of samples for one target
    """
    results = []
    valid_files = [
        int(fname.split('_')[0])
        for fname in os.listdir(in_dir)
        if fname.endswith('_ligand.sdf') and not fname.startswith('.')
    ]
    if len(valid_files) == 0:
        return pd.DataFrame()

    upper_bound = max(valid_files) + 1
    if n_samples is not None:
        upper_bound = min(upper_bound, n_samples)

    for i in tqdm(range(upper_bound), desc=desc, file=sys.stdout):
        in_mol = Path(in_dir, f'{i}_ligand.sdf')
        in_prot = Path(in_dir, f'{i}_pocket.pdb')
        res = evaluator(in_mol, in_prot)

        res['sample'] = i
        res['sdf_file'] = str(in_mol)
        res['pdb_file'] = str(in_prot)
        results.append(res)

    return results


def evaluate_drugflow(
        in_dir: Path,
        evaluator: FullEvaluator,
        n_samples: int = None,
        job_id: int = 0,
        n_jobs: int = 1,
) -> List[Dict]:
    """
    1. Computes per-molecule metrics for all single directories of samples
    2. Aggregates these metrics
    3. Computes additional collection metrics (if `reference_smiles_path` is provided)
    """
    data = []
    total_number_of_subdirs = len([path for path in in_dir.glob("[!.]*") if os.path.isdir(path)])
    i = 0
    for subdir in in_dir.glob("[!.]*"):
        if not os.path.isdir(subdir):
            continue

        i += 1
        if (i - 1) % n_jobs != job_id:
            continue

        curr_data = evaluate_drugflow_subdir(
            in_dir=subdir,
            evaluator=evaluator,
            desc=f'[{i}/{total_number_of_subdirs}] {str(subdir.name)}',
            n_samples=n_samples,
        )
        for entry in curr_data:
            entry['subdir'] = str(subdir)
            data.append(entry)

    return data


def compute_all_metrics_drugflow(
        in_dir: Path,
        gnina_path: Path,
        reduce_path: Path = None,
        reference_smiles_path: Path = None,
        n_samples: int = None,
        validity_metric_name: str = VALIDITY_METRIC_NAME,
        exclude_evaluators: Collection[str] = [],
        job_id: int = 0,
        n_jobs: int = 1,
):
    evaluator = FullEvaluator(gnina=gnina_path, reduce=reduce_path, exclude_evaluators=exclude_evaluators)
    data = evaluate_drugflow(in_dir=in_dir, evaluator=evaluator, n_samples=n_samples, job_id=job_id, n_jobs=n_jobs)
    table_detailed = convert_data_to_table(data, evaluator.dtypes)
    table_aggregated = aggregated_metrics(
        table_detailed,
        data_types=evaluator.dtypes,
        validity_metric_name=validity_metric_name
    )

    # Add collection metrics (uniqueness, novelty, FCD, etc.) if reference smiles are provided
    if reference_smiles_path is not None:
        reference_smiles = np.load(reference_smiles_path)
        col_metrics = collection_metrics(
            table=table_detailed,
            reference_smiles=reference_smiles,
            validity_metric_name=validity_metric_name,
            exclude_evaluators=exclude_evaluators
        )
        table_aggregated = pd.concat([table_aggregated, col_metrics])

    return data, table_detailed, table_aggregated