File size: 12,280 Bytes
5b2e6c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
import argparse
import os
import pickle
import pandas as pd
import numpy as np
import functools
from multiprocessing import Pool
from tqdm import tqdm
from scipy.stats import bootstrap
from typing import List, Tuple, Dict, Union, Optional

from bbflow.analysis.analyse_bbflow import (
    _load_ref_traj_full,
    _load_ref_traj_subset,
    _load_model_traj,
    _calc_metrics_bootstrap,
    _analyze_data,
)

default_metrics = [
    "RMSD",
    "RMSF",
    "DCCM",
    "RMWD",
    "PCA-W2",
    "Cosine Sim",
    "Weak Transient Contacts",
]

COMPACT_BASELINE_ROWS = [
    ("AlphaFlow", "0.86", "0.59 (0.01)", "1.51", "1.34 (0.01)", "2.89", "1.47 (0.03)", "32.0"),
    ("ConfDiff", "0.88", "0.62 (0.01)", "2.00", "1.45 (0.01)", "3.43", "1.41 (0.03)", "20.2"),
    ("AlphaFlow-T", "0.92", "0.41 (0.01)", "1.17", "0.91 (0.01)", "2.18", "1.28 (0.03)", "32.6"),
    ("ESMFlow-T", "0.92", "0.52 (0.01)", "0.94", "1.22 (0.01)", "2.00", "1.48 (0.03)", "11.2"),
    ("AlphaFlow-T dist", "0.92", "0.68 (0.01)", "0.90", "1.41 (0.01)", "1.73", "1.44 (0.03)", "3.3"),
    ("AlphaFlow-T 12L,dist", "0.90", "0.85 (0.01)", "0.68", "1.80 (0.01)", "1.40", "1.60 (0.03)", "1.2"),
    ("BBFlow (Ours)", "0.89", "0.47 (0.01)", "1.48", "0.78 (0.01)", "2.76", "1.34 (0.03)", "0.9"),
]


def _fmt_metric(metrics_dict, key, digits=2):
    value = metrics_dict.get(key)
    if value is None or pd.isna(value):
        return "-"
    return f"{float(value):.{digits}f}"


def _compact_metrics_df(metrics_dict, method_name, time_seconds=None):
    md_rmsf = _fmt_metric(metrics_dict, "MD RMSF", digits=2)
    md_pairwise = _fmt_metric(metrics_dict, "MD pairwise RMSD", digits=2)
    time_value = "-" if time_seconds is None else f"{time_seconds:.1f}"
    columns = [
        "Method",
        "RMSF r (↑)",
        "RMSF MAE (↓)",
        f"RMSF Median ({md_rmsf})",
        "Pairwise RMSD MAE (↓)",
        f"Pairwise RMSD Median ({md_pairwise})",
        "PCA W2 (↓)",
        "Time [s]",
    ]
    rows = [dict(zip(columns, row)) for row in COMPACT_BASELINE_ROWS]
    rows.append({
        "Method": method_name,
        "RMSF r (↑)": _fmt_metric(metrics_dict, "Per target RMSF r", digits=2),
        "RMSF MAE (↓)": _fmt_metric(metrics_dict, "Per target RMSF MAE", digits=2),
        f"RMSF Median ({md_rmsf})": _fmt_metric(metrics_dict, "RMSF", digits=2),
        "Pairwise RMSD MAE (↓)": _fmt_metric(metrics_dict, "Pairwise RMSD MAE", digits=2),
        f"Pairwise RMSD Median ({md_pairwise})": _fmt_metric(metrics_dict, "Pairwise RMSD", digits=2),
        "PCA W2 (↓)": _fmt_metric(metrics_dict, "MD PCA W2", digits=2),
        "Time [s]": time_value,
    })
    return pd.DataFrame(rows, columns=columns)


def calc_metrics(
    names: Union[List[str]]=None,
    md_dirs: Optional[List[str]]=None,
    ensemble_dirs: Optional[List[str]]=None,
    paths: Optional[List[Tuple]]=None,
    num_workers: int=8,
    metrics_subset: Optional[List[str]]=None,
    use_tqdm: bool=True,
    analysis_data_path: str="",
    analysis_metrics_path: str="",
    compact_metrics_path: str="",
    compact_method_name: str="BBFlow-base-prior-z",
    compact_time_seconds: Optional[float]=None,
    print_metrics: bool=True,
):
    """
    Calculate metrics for protein ensembles against reference MD trajectories.

    Either provide:
        1. names, md_dirs and ensemble_dirs
        or
        2. paths: list of tuples, each containing 
                (model_ensemble_pdb, reference_pdb, reference_traj1, ..., reference_trajN)

    Args:
        names:
            List of names of the ensembles to analyze. For each name, there must
            be a corresponding pdb file or directory in each of the ensemble_dirs,
            i.e. `ensemble_dirs[i]/name.pdb` or `ensemble_dirs[i]/name/sampled_conformations.pdb`,
            as well as a corresponding reference pdb and trajs in each of the md_dirs,
            i.e. `md_dirs[i]/name.pdb` and `md_dirs[i]/name/name_traj_R{j}.xtc` for j=1,2,3.
        md_dirs:
            List of directories containing reference MD data. Each directory must contain
            reference pdbs and 3 trajectories.
        ensemble_dirs:
            List of directories containing model ensembles. Each directory must contain
            pdb files or directories for each ensemble.
        paths:
            List of tuples, each containing 
            (model_ensemble.pdb, reference.pdb, reference_traj1.xtc, ..., reference_trajN.xtc)
        num_workers:
            Number of parallel workers to use.
        metrics_subset:
            Subset of metrics to calculate. If None, all metrics are calculated.
        use_tqdm:
            Whether to use tqdm progress bar.
        analysis_data_path:
            Path to save raw analysis data (pickle file). If empty, no file is saved.
        analysis_metrics_path:
            Path to save metrics summary (CSV file). If empty, no file is saved.
        print_metrics:
            Whether to print metrics to console.
    """
    if paths is not None:
        if names is not None or md_dirs is not None or ensemble_dirs is not None:
            raise ValueError("Either provide paths OR names, md_dirs and ensemble_dirs.")
        names = paths

    if metrics_subset is None:
        metrics_subset = default_metrics
    
    if num_workers > 1:
        p = Pool(num_workers)
        p.__enter__()
        __map__ = p.imap
    else:
        __map__ = map

    _calc_metrics_partial = functools.partial(
        _calc_metrics_bootstrap, 
        reference_dirs=md_dirs, 
        pdbdirs=ensemble_dirs,
        metrics_subset=metrics_subset
    )
    if use_tqdm:
        out = dict(tqdm(__map__(_calc_metrics_partial, names), total=len(names), leave=False))
    else:
        out = dict(__map__(_calc_metrics_partial, names))
    if num_workers > 1:
        p.__exit__(None, None, None)

    out = {k: v for k, v in out.items() if v is not None}
    if len(out) == 0:
        raise ValueError("No valid trajectories were loaded.")

    metrics_dict = _analyze_data(out, metrics_subset)

    if analysis_data_path != "":
        if paths is not None:
            # replace keys with range(len(paths)), otherwise keys are unreadable tuples
            out = {f"path_{i}": out[k] for i, k in enumerate(out.keys())}
        with open(analysis_data_path, 'wb') as f:
            pickle.dump(out, f)

    if analysis_metrics_path != "":
        df = pd.DataFrame({"": metrics_dict}).round(4)
        df = df.reindex([k for k in metrics_dict.keys()])
        df.to_csv(analysis_metrics_path)

    compact_df = _compact_metrics_df(
        metrics_dict,
        method_name=compact_method_name,
        time_seconds=compact_time_seconds,
    )
    if compact_metrics_path != "":
        compact_df.to_csv(compact_metrics_path, index=False)

    if print_metrics:
        print(compact_df.to_string(index=False))


def main():
    """
    Command line interface for calculating metrics.

    Usage:
        1. Provide md_dirs, ensemble_dirs and names:

        `
        python analysis_script.py --md_dirs md_dir1 md_dir2 ... \
            --ensemble_dirs ensemble_dir1 ensemble_dir2 ... \
            --names name1 name2 ...
        `

        2. Provide md_dirs, ensemble_dirs and auto-detect names from ensemble_dirs:

        `
        python analysis_script.py --md_dirs md_dir1 md_dir2 ... \
            --ensemble_dirs ensemble_dir1 ensemble_dir2 ... 
        `

        3. Provide paths directly of the form:    

        `
        python analysis_script.py --paths \
            model1.pdb ref1.pdb ref_traj1.xtc ... ref_trajN1.xtc \
            model2.pdb ref2.pdb ref_traj1.xtc ... ref_trajN2.xtc ...
        `

        
        Additional arguments:

        ```
        --num_workers N : Number of parallel workers (default: 8)
        --metrics metric1 metric2 ... : Subset of metrics to calculate (default: all)
        --use_tqdm : Show progress bar
        --analysis_data_path path : Path to save raw analysis data (pickle file)
        --analysis_metrics_path path : Path to save metrics summary (CSV file)
        --print_metrics : Print metrics to console
        ```
                                    
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('--md_dirs', nargs='*', default=[])
    parser.add_argument('--ensemble_dirs', nargs='*', default=[])
    parser.add_argument('--names', nargs='*', default=[])
    parser.add_argument('--paths', nargs='*', default=[])
    parser.add_argument('--num_workers', type=int, default=1)
    parser.add_argument('--metrics', nargs='*', default=default_metrics)
    parser.add_argument('--no_tqdm', action='store_true')
    parser.add_argument('--analysis_data_path', type=str, default='')
    parser.add_argument('--analysis_metrics_path', type=str, default='')
    parser.add_argument('--compact_metrics_path', type=str, default='')
    parser.add_argument('--compact_method_name', type=str, default='BBFlow-base-prior-z')
    parser.add_argument('--compact_time_seconds', type=float, default=None)
    parser.add_argument('--print_metrics', action='store_true')
    args = parser.parse_args()

    # Either provide md_dirs, ensemble_dirs and names,
    # or provide paths where each path contains both md and ensemble pdbs.
    if len(args.paths) > 0:
        if len(args.md_dirs) > 0 or len(args.ensemble_dirs) > 0 or len(args.names) > 0:
            raise ValueError("Either provide --paths OR --md_dirs, --ensemble_dirs and --names.")
        args.md_dirs = None
        args.ensemble_dirs = None
        args.names = None
        paths = []
        # args.paths must be in the format:
        # model1.pdb, ref1.pdb, ref_traj1.xtc, ..., ref_trajN1.xtc,
        # model2.pdb, ref2.pdb, ref_traj1.xtc, ..., ref_trajN2.xtc,
        # ...
        paths.append([])
        for p in args.paths:
            if p.endswith('.pdb') and len(paths[-1]) < 2:
                # model ensemble pdb or reference pdb
                paths[-1].append(p)
            elif p.endswith('.pdb') and len(paths[-1]) >= 3:
                # start a new entry
                paths.append([p])
            elif p.endswith('.xtc'):
                # reference traj
                if len(paths[-1]) < 2:
                    raise ValueError("Reference traj provided before model ensemble pdb or reference pdb.")
                paths[-1].append(p)
            elif p.endswith('.pdb') and len(paths[-1]) == 2:
                raise ValueError("More than two pdbs provided before reference trajs.")
            
        if len(paths[-1]) == 0:
            paths = paths[:-1]

        if len(paths) == 0:
            raise ValueError("No valid paths provided.")
        
        if not paths[-1][-1].endswith('.xtc'):
            raise ValueError("Last entry in paths missing reference trajs.")
        
        for i in range(len(paths)):
            paths[i] = tuple(paths[i])

        names = None
        
    else:
        paths = None
        if len(args.names) == 0:
            # auto-detect names from ensemble_dirs. 
            # Include all pdbs and dirs in ensemble_dirs
            names = []
            for ensemble_dir in args.ensemble_dirs:
                names_ = [
                    f for f in os.listdir(ensemble_dir)
                    if f.endswith('.pdb') or os.path.isdir(os.path.join(ensemble_dir, f))
                ]
                names.extend(names_)
            names = list(set(names))
            print(f"Found {len(names)} generated ensembles to analyze:")
            print(names)
        else:
            names = args.names

        assert len(names) > 0, "No names provided for analysis."
    

    calc_metrics(
        names=names,
        md_dirs=args.md_dirs,
        ensemble_dirs=args.ensemble_dirs,
        paths=paths,
        num_workers=args.num_workers,
        metrics_subset=args.metrics,
        use_tqdm=not args.no_tqdm,
        analysis_data_path=args.analysis_data_path,
        analysis_metrics_path=args.analysis_metrics_path,
        compact_metrics_path=args.compact_metrics_path,
        compact_method_name=args.compact_method_name,
        compact_time_seconds=args.compact_time_seconds,
        print_metrics=args.print_metrics,
    )



if __name__ == "__main__":
    main()