File size: 9,554 Bytes
0252cb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""IDFF surrogate model for polyALA molecular dynamics (paper, Sec. "Surrogate Models for Molecular Dynamics").

The data are the 46 backbone dihedral angles (23 phi/psi pairs) of a 200-frame polyALA trajectory.
A single joint-head network with dual-time indexing (flow time t, sequence position n) is trained
with the IDFF objective (Algorithm 3) and sampled autoregressively (Algorithm 4): position 0 starts
from N(0, I), every later position from x0^n ~ N(x1^{n-1}, sigma0^2 I).

Generated trajectories are compared with the true one by MAE / RMSE (wrapped angular error, degrees)
and the correlation coefficient, for the deterministic CFM sampler and IDFF with K = 1 and K = 2,
all sharing the same trained network.

Scale of the Langevin amplitude: the paper's gamma_bar in [0.1, 0.3] refers to a unit-variance base
N(0, I). Here the base is the previous frame plus N(0, sigma0^2 I) noise, so p_t has width ~sigma0
and its score a Lipschitz constant ~1/sigma0^2; Euler-Maruyama on the Langevin term is only stable
when gamma_t dt / sigma0^2 is small. We therefore set gamma_bar = gamma_rel * sigma0^2 (gamma_rel = 1
by default, chosen a priori, not tuned on the evaluation trajectory). ``--sweep`` reports the
sensitivity to gamma_rel and alpha_2. Example:

    python timeseris_example/MD_simulation.py --nfes 3 5 10
"""
import argparse
import csv
import json
import sys
import time
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
import numpy as np  # noqa: E402
import torch  # noqa: E402

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent))

from idff import JointHeadMLP, idff_loss, sample_sequence, sequence_training_pairs  # noqa: E402
from idff.datasets import load_polyala_angles  # noqa: E402
from idff.metrics import trajectory_metrics, wrap_degrees  # noqa: E402


def repo_relative(args):
    """Command-line arguments with paths made relative to the repository (for config.json)."""
    out = dict(vars(args))
    for key in ("out", "data"):
        if key in out:
            try:
                out[key] = str(Path(out[key]).resolve().relative_to(HERE.parent))
            except ValueError:
                pass
    return out


def parse_args():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--data", default=str(HERE / "data" / "polyALA_angles.npz"),
                   help="polyALA_angles.npz (shipped) or the original polyALA_dataset.p")
    p.add_argument("--iters", type=int, default=20000)
    p.add_argument("--batch", type=int, default=256)
    p.add_argument("--lr", type=float, default=1e-3)
    p.add_argument("--sigma0", type=float, default=0.1, help="path bandwidth and Markov-init noise (standardised units)")
    p.add_argument("--nfes", type=int, nargs="+", default=[3, 5, 10])
    p.add_argument("--gamma-rel", type=float, default=1.0,
                   help="Langevin amplitude relative to the base variance: gamma_bar = gamma_rel * sigma0^2")
    p.add_argument("--alpha2", type=float, default=0.05, help="second-order scale (paper: ~0.05)")
    p.add_argument("--num-traj", type=int, default=5)
    p.add_argument("--seeds", type=int, default=3)
    p.add_argument("--sweep", action="store_true", help="also report a gamma_bar / alpha_2 sensitivity sweep")
    p.add_argument("--retrain", action="store_true")
    p.add_argument("--out", default=str(HERE / "outputs" / "polyALA"))
    return p.parse_args()


def prepare(path):
    """Unwrap each angle in time (period 360) so consecutive frames are close, then standardise."""
    raw = load_polyala_angles(path)
    unwrapped = np.unwrap(raw, period=360.0, axis=0)
    mean, std = unwrapped.mean(0), unwrapped.std(0) + 1e-6
    data = torch.tensor((unwrapped - mean) / std, dtype=torch.float32)[None]  # (1, frames, 46)
    return raw, unwrapped, data, mean, std


def train(args, data, out_dir):
    length, dim = data.shape[1], data.shape[2]
    model = JointHeadMLP(dim, hidden=256, depth=3, sigma0=args.sigma0, base_std=args.sigma0,
                         num_positions=length, residual=True)
    ckpt = out_dir / "idff_md.pt"
    if ckpt.exists() and not args.retrain:
        model.load_state_dict(torch.load(ckpt, map_location="cpu", weights_only=True))
        print(f"loaded {ckpt}")
        return model.eval()
    torch.manual_seed(0)
    opt = torch.optim.Adam(model.parameters(), lr=args.lr)
    sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, args.iters)
    start = time.time()
    for it in range(1, args.iters + 1):
        x0, x1, n = sequence_training_pairs(data, args.batch, args.sigma0)
        loss, stats = idff_loss(model, x1, x0=x0, sigma0=args.sigma0, model_kwargs={"n": n})
        opt.zero_grad()
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        sched.step()
        if it % 2000 == 0:
            print(f"iter {it:6d}  loss {loss.item():.4f}  denoiser {stats['denoiser']:.4f}  "
                  f"score {stats['score']:.4f}  ({time.time() - start:.0f}s)")
    torch.save(model.state_dict(), ckpt)
    return model.eval()


def generate(model, data, args, nfe, seed, **cfg):
    gen = torch.Generator().manual_seed(seed)
    traj = sample_sequence(model, data.shape[1], args.num_traj, data.shape[2], nfe, args.sigma0,
                           generator=gen, **cfg)
    return traj.numpy()  # (frames, num_traj, 46), standardised


def evaluate(model, data, unwrapped, mean, std, args, nfe, cfg):
    """Mean of each metric over sampling seeds; each seed rolls out ``num_traj`` trajectories."""
    per_seed = []
    for seed in range(args.seeds):
        gen = generate(model, data, args, nfe, seed, **cfg) * std + mean  # degrees (unwrapped)
        per_seed.append(trajectory_metrics(gen, unwrapped, angles=True))
    keys = ["MAE", "RMSE", "CC"]
    return {k: float(np.mean([m[k] for m in per_seed])) for k in keys} | \
           {k + "_seed_std": float(np.std([m[k] for m in per_seed])) for k in keys}


def main():
    args = parse_args()
    out_dir = Path(args.out)
    out_dir.mkdir(parents=True, exist_ok=True)
    raw, unwrapped, data, mean, std = prepare(args.data)
    print(f"polyALA: {data.shape[1]} frames x {data.shape[2]} dihedral angles")
    model = train(args, data, out_dir)

    gamma_bar = args.gamma_rel * args.sigma0 ** 2
    methods = {
        "CFM (det.)": dict(K=0),
        "IDFF K=1": dict(K=1, gamma_bar=gamma_bar),
        "IDFF K=2": dict(K=2, gamma_bar=gamma_bar, alphas={2: args.alpha2}),
    }
    rows = []
    for nfe in args.nfes:
        for name, cfg in methods.items():
            m = evaluate(model, data, unwrapped, mean, std, args, nfe, cfg)
            rows.append({"method": name, "nfe": nfe, "gamma_rel": args.gamma_rel if "gamma_bar" in cfg else 0.0,
                         "alpha2": cfg.get("alphas", {}).get(2, ""), **m})
            print(f"NFE={nfe:3d}  {name:12s}  MAE {m['MAE']:6.2f}  RMSE {m['RMSE']:6.2f}  CC {100 * m['CC']:5.1f}%")

    if args.sweep:
        print("\nsensitivity (NFE = max of --nfes):")
        nfe = max(args.nfes)
        for rel in [0.1, 0.3, 1.0, 3.0, 10.0]:
            g = rel * args.sigma0 ** 2
            for name, cfg in [("IDFF K=1", dict(K=1, gamma_bar=g))] + \
                             [("IDFF K=2", dict(K=2, gamma_bar=g, alphas={2: a})) for a in [-5.0, -1.0, 0.05, 1.0, 5.0]]:
                m = evaluate(model, data, unwrapped, mean, std, args, nfe, cfg)
                rows.append({"method": name + " (sweep)", "nfe": nfe, "gamma_rel": rel,
                             "alpha2": cfg.get("alphas", {}).get(2, ""), **m})
                print(f"  gamma_rel={rel:<5} {name} alpha2={cfg.get('alphas', {}).get(2, '-')!s:<5} "
                      f"MAE {m['MAE']:6.2f}  RMSE {m['RMSE']:6.2f}  CC {100 * m['CC']:5.1f}%")

    with open(out_dir / "evaluation_results.csv", "w", newline="") as fh:
        writer = csv.DictWriter(fh, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    with open(out_dir / "config.json", "w") as fh:
        json.dump(repo_relative(args), fh, indent=2)
    plot(model, data, raw, mean, std, args, out_dir)
    print(f"\nwrote results to {out_dir}")


def plot(model, data, raw, mean, std, args, out_dir, angle=10):
    """Figure in the style of the paper's MD figure: true vs generated (phi, psi) and one angle over time."""
    nfe = max(args.nfes)
    gen = generate(model, data, args, nfe, 0, K=1, gamma_bar=args.gamma_rel * args.sigma0 ** 2) * std + mean
    gen_w = wrap_degrees(gen)
    fig, axs = plt.subplots(1, 3, figsize=(13, 3.8))
    axs[0].scatter(raw[:, 0::2].ravel(), raw[:, 1::2].ravel(), s=2, c="k", alpha=0.3)
    axs[0].set_title("(A) true (phi, psi)")
    axs[1].scatter(gen_w[:, :, 0::2].ravel(), gen_w[:, :, 1::2].ravel(), s=2, c="tab:red", alpha=0.3)
    axs[1].set_title(f"(B) IDFF K=1, NFE={nfe}")
    for ax in axs[:2]:
        ax.set_xlim(-180, 180)
        ax.set_ylim(-180, 180)
        ax.set_xlabel("phi")
        ax.set_ylabel("psi")
    for k in range(gen_w.shape[1]):
        axs[2].plot(gen_w[:, k, angle], c="tab:red", alpha=0.5, lw=1)
    axs[2].plot(raw[:, angle], c="k", lw=1.5, label="true")
    axs[2].set_title(f"(C) angle {angle}: true (black) vs generated (red)")
    axs[2].set_xlabel("frame")
    axs[2].set_ylabel("degrees")
    fig.tight_layout()
    fig.savefig(out_dir / "md_samples.png", dpi=130)
    plt.close(fig)


if __name__ == "__main__":
    main()