IDFF-code / idff /datasets.py
rezapop's picture
IDFF code release v1.0.0 (mirror of GitHub)
0252cb7 verified
Raw History Blame Contribute Delete
4.63 kB
"""Datasets used by the examples: 2-D toy distributions, 3-D chaotic attractors and the polyALA MD data."""
import math
import pickle
from pathlib import Path
import numpy as np
import torch
# ----------------------------------------------------------------------------------------------
# 2-D toy distributions
# ----------------------------------------------------------------------------------------------
def eight_gaussians(n, scale=5.0, std=0.1 ** 0.25, generator=None):
"""Mixture of 8 Gaussians on a circle of radius ``scale`` (same law as the original torchcfm helper)."""
angles = torch.arange(8) * (2 * math.pi / 8)
centers = scale * torch.stack([torch.cos(angles), torch.sin(angles)], dim=1)
idx = torch.randint(8, (n,), generator=generator)
return centers[idx] + std * torch.randn(n, 2, generator=generator)
def checkerboard(n, generator=None):
"""Checkerboard on [-4, 4]^2 (same law as the original torchcfm helper)."""
x1 = torch.rand(n, generator=generator) * 4 - 2
x2_ = torch.rand(n, generator=generator) - torch.randint(0, 2, (n,), generator=generator) * 2
x2 = x2_ + torch.floor(x1) % 2
return torch.stack([x1, x2], dim=1) * 2
def moons(n, noise=0.2, generator=None):
"""Two interleaving half circles, scaled as x * 3 - 1 like the original torchcfm helper."""
n_out = n // 2
n_in = n - n_out
a = torch.rand(n_out, generator=generator) * math.pi
b = torch.rand(n_in, generator=generator) * math.pi
outer = torch.stack([torch.cos(a), torch.sin(a)], dim=1)
inner = torch.stack([1 - torch.cos(b), 0.5 - torch.sin(b)], dim=1)
x = torch.cat([outer, inner], dim=0)
x = x + noise * torch.randn(x.shape, generator=generator)
return x[torch.randperm(n, generator=generator)] * 3 - 1
TOY_DATASETS = {"8gaussians": eight_gaussians, "checkerboard": checkerboard, "moons": moons}
# ----------------------------------------------------------------------------------------------
# 3-D chaotic attractors (Appendix "3D Attractors")
# ----------------------------------------------------------------------------------------------
def _lorenz(state, sigma=10.0, rho=28.0, beta=8.0 / 3.0):
x, y, z = state[..., 0], state[..., 1], state[..., 2]
return np.stack([sigma * (y - x), x * (rho - z) - y, x * y - beta * z], axis=-1)
def _rossler(state, a=0.2, b=0.2, c=5.7):
x, y, z = state[..., 0], state[..., 1], state[..., 2]
return np.stack([-y - z, x + a * y, b + z * (x - c)], axis=-1)
def attractor_trajectories(system, num_traj, length, dt=None, stride=None, burn_in=2000, seed=0):
"""Simulate ``num_traj`` trajectories of ``length`` frames with RK4.
``system`` is ``"lorenz"`` (sigma=10, rho=28, beta=8/3) or ``"rossler"`` (a=b=0.2, c=5.7), the
parameters used in the paper. Returns an array of shape (num_traj, length, 3).
"""
f = {"lorenz": _lorenz, "rossler": _rossler}[system]
dt = dt if dt is not None else {"lorenz": 0.01, "rossler": 0.05}[system]
stride = stride if stride is not None else {"lorenz": 2, "rossler": 2}[system]
rng = np.random.default_rng(seed)
state = rng.normal(size=(num_traj, 3)) + (np.array([0.0, 0.0, 25.0]) if system == "lorenz" else 0.0)
def step(s):
k1 = f(s)
k2 = f(s + 0.5 * dt * k1)
k3 = f(s + 0.5 * dt * k2)
k4 = f(s + dt * k3)
return s + dt / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4)
for _ in range(burn_in):
state = step(state)
out = np.empty((num_traj, length, 3))
for i in range(length):
out[:, i] = state
for _ in range(stride):
state = step(state)
return out
# ----------------------------------------------------------------------------------------------
# polyALA molecular dynamics (Sec. "Surrogate Models for Molecular Dynamics")
# ----------------------------------------------------------------------------------------------
def load_polyala_angles(path):
"""Load the polyALA dihedral-angle trajectory, shape (frames, 46), in degrees.
Accepts the compact ``.npz`` shipped with the repository (key ``angles``) or the original
simulation pickle (``data['angles'][1]`` reshaped to (sim_length, -1), as in the original script).
"""
path = Path(path)
if not path.exists():
raise FileNotFoundError(f"MD dataset not found: {path}")
if path.suffix == ".npz":
return np.load(path)["angles"].astype(np.float64)
with open(path, "rb") as fh:
data = pickle.load(fh) # trusted local simulation output
return np.asarray(data["angles"][1]).reshape(data["sim_length"], -1).astype(np.float64)