pymonge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pymonge/__init__.py ADDED
@@ -0,0 +1,38 @@
1
+ """pymonge -- minimum-work transport protocols for trapped (active) colloids.
2
+
3
+ Named after Gaspard Monge, who posed the problem of moving matter at least cost.
4
+
5
+ Ritz method: the trap protocol is expanded in Chebyshev polynomials and
6
+ optimised with Adam (pathwise gradients through the stochastic integrator) or a
7
+ genetic algorithm, using only stochastic simulations of the Langevin dynamics.
8
+ The built-in model is an active particle (stresslet) near a plane no-slip wall.
9
+
10
+ Quick start::
11
+
12
+ import pymonge as pm
13
+ model = pm.NearWallModel.paper(alpha=25) # puller near a wall
14
+ problem = pm.TransportProblem(model, H0=2.0, dH=5.0) # trap moves 2 -> 7
15
+ res = pm.optimize_adam(problem, n_trials=4, epochs=100)
16
+ print(problem.evaluate(res.coeffs.mean(0)).mean / problem.W_star)
17
+ """
18
+ from .model import (BrennerMobility, BulkMobility, NearWallModel, NoDrift,
19
+ StressletDrift)
20
+ from .protocol import (ChebyshevProtocol, PiecewiseLinearProtocol, TimeGrid,
21
+ schmiedl_seifert, schmiedl_seifert_work)
22
+ from .simulate import WorkEstimate, WorkEvaluator, sample_initial, simulate
23
+ from .gradient import work_and_grad
24
+ from .problem import TransportProblem
25
+ from .optimize import (AdamConfig, AdamResult, GAConfig, GAResult,
26
+ evaluate_history, optimize_adam, optimize_ga)
27
+
28
+ __version__ = "0.1.0"
29
+
30
+ __all__ = [
31
+ "BrennerMobility", "BulkMobility", "NearWallModel", "NoDrift", "StressletDrift",
32
+ "ChebyshevProtocol", "PiecewiseLinearProtocol", "TimeGrid",
33
+ "schmiedl_seifert", "schmiedl_seifert_work",
34
+ "WorkEstimate", "WorkEvaluator", "sample_initial", "simulate", "work_and_grad",
35
+ "TransportProblem",
36
+ "AdamConfig", "AdamResult", "GAConfig", "GAResult",
37
+ "evaluate_history", "optimize_adam", "optimize_ga",
38
+ ]
pymonge/gradient.py ADDED
@@ -0,0 +1,97 @@
1
+ """Pathwise (reparameterisation) gradient of the mean work by reverse-mode
2
+ differentiation through the Ito integrator -- a hand-written adjoint, so no
3
+ autodiff framework is required.
4
+
5
+ For fixed noise {z_n} and initial positions, the discrete dynamics are
6
+
7
+ W = sum_n k/2 [(h_n - p_{n+1})^2 - (h_n - p_n)^2] + final jump
8
+ h_{n+1} = R( h_n + dt F(h_n, p_{n+1}) + sigma(h_n) z_n )
9
+
10
+ with F = -mu k (h - p) + v_A + kT mu', sigma = sqrt(2 kT mu dt) and R the
11
+ reflection. Back-propagating g_n = dW/dh_n gives dW/dp_n exactly for the
12
+ discretised problem. With multiplicative noise the sigma'(h) z_n term makes
13
+ the estimator heavy-tailed, which is why the optimiser clips gradients.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import numpy as np
18
+
19
+ from .model import NearWallModel
20
+ from .simulate import sample_initial
21
+
22
+ __all__ = ["work_and_grad"]
23
+
24
+
25
+ def work_and_grad(model: NearWallModel, dt: float, p: np.ndarray, n_traj: int,
26
+ rng, initial: str = "boltzmann", shared_noise: bool = False):
27
+ """Mean work and its gradient w.r.t. every protocol value.
28
+
29
+ Parameters
30
+ ----------
31
+ p : (T, n_steps + 2)
32
+ A batch of T protocols (e.g. independent optimisation trials).
33
+ n_traj
34
+ Trajectories per protocol.
35
+ rng
36
+ ``numpy.random.Generator``.
37
+ shared_noise
38
+ Use the same noise for all T protocols (CRN) instead of independent.
39
+
40
+ Returns
41
+ -------
42
+ W_mean : (T,)
43
+ grad_p : (T, n_steps + 2) dW_mean / dp
44
+ """
45
+ p = np.atleast_2d(np.asarray(p, float))
46
+ T, L = p.shape
47
+ N = L - 2
48
+ M = n_traj
49
+ k, kT = model.k, model.kT
50
+ mob, drv = model.mobility, model.drift
51
+
52
+ lam_i = p[0, 0]
53
+ if shared_noise:
54
+ h = np.broadcast_to(sample_initial(model, lam_i, M, rng, initial, dt=dt), (T, M)).copy()
55
+ else:
56
+ h = sample_initial(model, lam_i, T * M, rng, initial, dt=dt).reshape(T, M)
57
+
58
+ # ---- forward pass, storing what the backward pass needs ----------
59
+ H = np.empty((N + 1, T, M))
60
+ Z = np.empty((N, T, M), dtype=np.float32)
61
+ signs = {}
62
+ W = np.zeros((T, M))
63
+ for n in range(N):
64
+ H[n] = h
65
+ pn, pn1 = p[:, n, None], p[:, n + 1, None]
66
+ W += 0.5 * k * (pn - pn1) * (2.0 * h - pn - pn1)
67
+ z = rng.standard_normal(M if shared_noise else (T, M)).astype(np.float32)
68
+ Z[n] = z
69
+ h = model.step(h, pn1, dt, z)
70
+ h, s = model.reflect(h)
71
+ if s is not None:
72
+ signs[n] = s
73
+ H[N] = h
74
+ pN, pf = p[:, N, None], p[:, N + 1, None]
75
+ W += 0.5 * k * (pN - pf) * (2.0 * h - pN - pf)
76
+
77
+ # ---- backward pass ------------------------------------------------
78
+ gp = np.zeros((T, L))
79
+ # final jump: k/2[(h_N - p_f)^2 - (h_N - p_N)^2]
80
+ g = k * (pN - pf) * np.ones_like(h) # dW/dh_N
81
+ gp[:, N] += (k * (h - pN)).sum(axis=1)
82
+ sq2dt = np.sqrt(2.0 * dt * kT)
83
+ for n in range(N - 1, -1, -1):
84
+ hn = H[n]
85
+ pn, pn1 = p[:, n, None], p[:, n + 1, None]
86
+ if n in signs:
87
+ g = g * signs[n] # through reflection
88
+ mu, dmu, d2mu = mob.mu(hn), mob.dmu(hn), mob.d2mu(hn)
89
+ dF_dh = -dmu * k * (hn - pn1) - mu * k + drv.dv(hn) + kT * d2mu
90
+ dsig = sq2dt * 0.5 * dmu / np.sqrt(mu) # d sigma / dh
91
+ # protocol gradients from this step
92
+ gp[:, n + 1] += (g * (dt * mu * k) - k * (hn - pn1)).sum(axis=1)
93
+ gp[:, n] += (k * (hn - pn)).sum(axis=1)
94
+ # propagate to h_n (dynamics + explicit work dependence)
95
+ g = g * (1.0 + dt * dF_dh + dsig * Z[n]) + k * (pn - pn1)
96
+
97
+ return W.mean(axis=1), gp / M
pymonge/model.py ADDED
@@ -0,0 +1,193 @@
1
+ """Physical model: an active particle in a harmonic trap near a no-slip wall.
2
+
3
+ All quantities are dimensionless (b = mu0 = k = kBT = 1 by default), matching
4
+ Section II of Maurya, Swaminathan, Ashraf & Singh. The model is written so that
5
+ every function needed by the integrator *and* by the adjoint gradient is
6
+ available in closed form:
7
+
8
+ dh = A(h, lam) dt + kT * mu'(h) dt + sqrt(2 kT mu(h)) dB (Ito)
9
+ A(h, lam) = -mu(h) k (h - lam) + v_A(h)
10
+
11
+ Mobility and active drift are pluggable: any object with ``mu``, ``dmu``,
12
+ ``d2mu`` (mobility) or ``v``, ``dv`` (drift) methods can be passed in.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass, field
17
+
18
+ import numpy as np
19
+
20
+ __all__ = [
21
+ "BrennerMobility",
22
+ "BulkMobility",
23
+ "StressletDrift",
24
+ "NoDrift",
25
+ "NearWallModel",
26
+ ]
27
+
28
+
29
+ # --------------------------------------------------------------------------
30
+ # Mobilities
31
+ # --------------------------------------------------------------------------
32
+ @dataclass(frozen=True)
33
+ class BrennerMobility:
34
+ r"""Far-field Brenner wall-normal mobility, Eq. (3):
35
+
36
+ .. math:: \mu(h) = \mu_0\,[1 - \tfrac98 (b/h) + \tfrac12 (b/h)^3]
37
+ """
38
+
39
+ mu0: float = 1.0
40
+ b: float = 1.0
41
+
42
+ def mu(self, h):
43
+ x = self.b / h
44
+ return self.mu0 * (1.0 - 1.125 * x + 0.5 * x**3)
45
+
46
+ def dmu(self, h):
47
+ x = self.b / h
48
+ return self.mu0 * (1.125 * x**2 - 1.5 * x**4) / self.b
49
+
50
+ def d2mu(self, h):
51
+ x = self.b / h
52
+ return self.mu0 * (-2.25 * x**3 + 6.0 * x**5) / self.b**2
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class BulkMobility:
57
+ """Constant Stokes mobility (no wall)."""
58
+
59
+ mu0: float = 1.0
60
+
61
+ def mu(self, h):
62
+ return np.full_like(h, self.mu0, dtype=float)
63
+
64
+ def dmu(self, h):
65
+ return np.zeros_like(h, dtype=float)
66
+
67
+ def d2mu(self, h):
68
+ return np.zeros_like(h, dtype=float)
69
+
70
+
71
+ # --------------------------------------------------------------------------
72
+ # Active drifts
73
+ # --------------------------------------------------------------------------
74
+ @dataclass(frozen=True)
75
+ class StressletDrift:
76
+ r"""Wall-induced drift of a force dipole, Eq. (4):
77
+
78
+ .. math:: v_A(h) = -\tfrac{s_0}{8}\,[(b/h)^2 - (b/h)^4]
79
+
80
+ ``s0 > 0`` is a puller (drift towards the wall), ``s0 < 0`` a pusher.
81
+ """
82
+
83
+ s0: float = 0.0
84
+ b: float = 1.0
85
+
86
+ def v(self, h):
87
+ x = self.b / h
88
+ return -0.125 * self.s0 * (x**2 - x**4)
89
+
90
+ def dv(self, h):
91
+ x = self.b / h
92
+ return -0.125 * self.s0 * (-2.0 * x**3 + 4.0 * x**5) / self.b
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class NoDrift:
97
+ """Passive particle."""
98
+
99
+ def v(self, h):
100
+ return np.zeros_like(h, dtype=float)
101
+
102
+ def dv(self, h):
103
+ return np.zeros_like(h, dtype=float)
104
+
105
+
106
+ # --------------------------------------------------------------------------
107
+ # Full model
108
+ # --------------------------------------------------------------------------
109
+ @dataclass(frozen=True)
110
+ class NearWallModel:
111
+ """Overdamped particle in a translating harmonic trap near a wall.
112
+
113
+ Parameters
114
+ ----------
115
+ mobility, drift
116
+ Pluggable physics (see module docstring).
117
+ k, kT
118
+ Trap stiffness and thermal energy.
119
+ h_min
120
+ Position of a reflecting boundary. Default ``1.0`` = particle radius,
121
+ i.e. the particle touching the wall. The far-field Brenner formula is
122
+ unphysical below this, so trajectories are reflected there. Set to
123
+ ``None`` (or ``-inf``) to disable.
124
+ """
125
+
126
+ mobility: object = field(default_factory=BrennerMobility)
127
+ drift: object = field(default_factory=NoDrift)
128
+ k: float = 1.0
129
+ kT: float = 1.0
130
+ h_min: float | None = 1.0
131
+
132
+ # -- convenient constructor matching the paper's parameters ----------
133
+ @classmethod
134
+ def paper(cls, alpha: float = 0.0, *, b: float = 1.0, mu0: float = 1.0,
135
+ k: float = 1.0, kT: float = 1.0, h_min: float | None = 1.0,
136
+ wall: bool = True) -> "NearWallModel":
137
+ """Model of the paper with dimensionless activity ``alpha``, Eq. (7).
138
+
139
+ ``alpha = s0 / (mu0 k b)``; ``alpha > 0`` puller, ``alpha < 0`` pusher.
140
+ ``wall=False`` gives the bulk limit (constant mobility, no drift).
141
+ """
142
+ if not wall:
143
+ return cls(BulkMobility(mu0), NoDrift(), k, kT, None)
144
+ s0 = alpha * mu0 * k * b
145
+ drift = StressletDrift(s0, b) if alpha != 0 else NoDrift()
146
+ return cls(BrennerMobility(mu0, b), drift, k, kT, h_min * b if h_min else None)
147
+
148
+ # -- quantities used by the integrator ------------------------------
149
+ @property
150
+ def tau(self) -> float:
151
+ """Trap relaxation time 1/(mu0 k)."""
152
+ mu0 = getattr(self.mobility, "mu0", 1.0)
153
+ return 1.0 / (mu0 * self.k)
154
+
155
+ def potential(self, h, lam):
156
+ return 0.5 * self.k * (h - lam) ** 2
157
+
158
+ def drift_total(self, h, lam):
159
+ """A(h, lam) + kT mu'(h): the full Ito drift."""
160
+ mu = self.mobility.mu(h)
161
+ return -mu * self.k * (h - lam) + self.drift.v(h) + self.kT * self.mobility.dmu(h)
162
+
163
+ def diffusion(self, h):
164
+ return self.kT * self.mobility.mu(h)
165
+
166
+ def step(self, h, lam, dt, z):
167
+ """One Euler-Maruyama step (before reflection).
168
+
169
+ A fused fast path is used for the paper's Brenner + stresslet model
170
+ (powers of b/h are computed once); other physics use the generic path.
171
+ """
172
+ mob, drv = self.mobility, self.drift
173
+ if type(mob) is BrennerMobility and type(drv) in (StressletDrift, NoDrift) \
174
+ and (type(drv) is NoDrift or drv.b == mob.b):
175
+ x = mob.b / h
176
+ x2 = x * x
177
+ x3 = x2 * x
178
+ mu = mob.mu0 * (1.0 - 1.125 * x + 0.5 * x3)
179
+ f = -mu * self.k * (h - lam) + (self.kT * mob.mu0 / mob.b) * (1.125 * x2 - 1.5 * x2 * x2)
180
+ if type(drv) is StressletDrift:
181
+ f += -0.125 * drv.s0 * (x2 - x2 * x2)
182
+ return h + dt * f + np.sqrt((2.0 * dt * self.kT) * mu) * z
183
+ return h + dt * self.drift_total(h, lam) + np.sqrt(2.0 * dt * self.diffusion(h)) * z
184
+
185
+ def reflect(self, h):
186
+ """Reflect at ``h_min``. Returns (h_new, sign) with sign = dh_new/dh."""
187
+ if self.h_min is None or not np.isfinite(self.h_min):
188
+ return h, None
189
+ below = h < self.h_min
190
+ if not below.any():
191
+ return h, None
192
+ h = np.where(below, 2.0 * self.h_min - h, h)
193
+ return h, np.where(below, -1.0, 1.0)
pymonge/optimize.py ADDED
@@ -0,0 +1,277 @@
1
+ """Optimisers for the Ritz coefficients: Adam (gradient) and a genetic algorithm.
2
+
3
+ Both follow Sec. II D / Fig. 2 of the paper. Many independent trials are run
4
+ at once: Adam trials are vectorised in a single simulation batch, GA trials
5
+ are distributed over processes.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import multiprocessing as mp
10
+ import os
11
+ import time
12
+ from concurrent.futures import ProcessPoolExecutor
13
+ from dataclasses import dataclass, field, asdict
14
+
15
+ import numpy as np
16
+
17
+ from .gradient import work_and_grad
18
+ from .problem import TransportProblem
19
+
20
+ __all__ = ["AdamConfig", "AdamResult", "optimize_adam", "evaluate_history",
21
+ "GAConfig", "GAResult", "optimize_ga"]
22
+
23
+
24
+ # ==========================================================================
25
+ # Adam
26
+ # ==========================================================================
27
+ @dataclass
28
+ class AdamConfig:
29
+ """Adam hyper-parameters (defaults: paper values where stated)."""
30
+
31
+ epochs: int = 150 # E
32
+ n_traj: int = 1000 # trajectories per gradient estimate
33
+ lr: float = 0.05 # initial learning rate
34
+ lr_min: float = 1e-3 # end of cosine decay
35
+ beta1: float = 0.9
36
+ beta2: float = 0.999
37
+ eps: float = 1e-8
38
+ clip: float = 5.0 # max gradient norm per trial
39
+ init: str = "ramp" # "ramp" (SS protocol), "gaussian", "linear"
40
+ init_scale: float = 0.05 # Gaussian jitter added to the initial coeffs
41
+ seed: int = 0
42
+ verbose: bool = True
43
+
44
+ def lr_at(self, epoch: int) -> float:
45
+ c = 0.5 * (1.0 + np.cos(np.pi * epoch / max(self.epochs - 1, 1)))
46
+ return self.lr_min + (self.lr - self.lr_min) * c
47
+
48
+
49
+ @dataclass
50
+ class AdamResult:
51
+ coeffs: np.ndarray # (T, Nc) final coefficients per trial
52
+ history: np.ndarray # (T, E+1, Nc) coefficients after each epoch (0 = init)
53
+ train_work: np.ndarray # (T, E) mini-batch <W> during training
54
+ config: dict = field(default_factory=dict)
55
+ seconds: float = 0.0
56
+
57
+ @property
58
+ def best_coeffs(self) -> np.ndarray:
59
+ """Mean over trials of the final coefficients."""
60
+ return self.coeffs.mean(axis=0)
61
+
62
+ def save(self, path):
63
+ np.savez(path, coeffs=self.coeffs, history=self.history,
64
+ train_work=self.train_work, seconds=self.seconds,
65
+ config=np.array(repr(self.config)))
66
+
67
+ @classmethod
68
+ def load(cls, path) -> "AdamResult":
69
+ d = np.load(path, allow_pickle=False)
70
+ return cls(d["coeffs"], d["history"], d["train_work"],
71
+ {"repr": str(d["config"])}, float(d["seconds"]))
72
+
73
+
74
+ def _initial_coeffs(problem: TransportProblem, n: int, kind: str, scale: float, rng):
75
+ ans = problem.ansatz
76
+ if kind == "ramp":
77
+ base = ans.ramp_coeffs()
78
+ elif kind == "linear":
79
+ base = ans.linear_coeffs()
80
+ elif kind == "gaussian":
81
+ return ans.random_coeffs(rng, n, scale=max(scale, 0.5), center="midpoint")
82
+ else:
83
+ raise ValueError(kind)
84
+ return base + scale * rng.standard_normal((n, ans.n_basis))
85
+
86
+
87
+ def optimize_adam(problem: TransportProblem, n_trials: int = 30,
88
+ config: AdamConfig | None = None, **kw) -> AdamResult:
89
+ """Optimise the Chebyshev coefficients with Adam, ``n_trials`` at once.
90
+
91
+ Keyword arguments override fields of :class:`AdamConfig`.
92
+ """
93
+ cfg = config or AdamConfig()
94
+ for key, val in kw.items():
95
+ setattr(cfg, key, val)
96
+ rng = np.random.default_rng(cfg.seed)
97
+ ans = problem.ansatz
98
+ a = _initial_coeffs(problem, n_trials, cfg.init, cfg.init_scale, rng)
99
+ m = np.zeros_like(a)
100
+ v = np.zeros_like(a)
101
+ hist = np.empty((n_trials, cfg.epochs + 1, ans.n_basis))
102
+ hist[:, 0] = a
103
+ train = np.empty((n_trials, cfg.epochs))
104
+ t0 = time.time()
105
+ for e in range(cfg.epochs):
106
+ W, gp = work_and_grad(problem.model, problem.grid.dt, ans(a), cfg.n_traj,
107
+ rng, initial=problem.initial)
108
+ g = ans.grad_to_coeffs(gp)
109
+ norm = np.linalg.norm(g, axis=1, keepdims=True)
110
+ g = g * np.minimum(1.0, cfg.clip / np.maximum(norm, 1e-300))
111
+ m = cfg.beta1 * m + (1 - cfg.beta1) * g
112
+ v = cfg.beta2 * v + (1 - cfg.beta2) * g * g
113
+ mh = m / (1 - cfg.beta1 ** (e + 1))
114
+ vh = v / (1 - cfg.beta2 ** (e + 1))
115
+ a = a - cfg.lr_at(e) * mh / (np.sqrt(vh) + cfg.eps)
116
+ hist[:, e + 1] = a
117
+ train[:, e] = W
118
+ if cfg.verbose and (e % 10 == 0 or e == cfg.epochs - 1):
119
+ print(f" epoch {e:4d} <W>/W* = {W.mean() / problem.W_star:.4f}"
120
+ f" lr = {cfg.lr_at(e):.4f} [{time.time() - t0:6.1f}s]", flush=True)
121
+ return AdamResult(a, hist, train, asdict(cfg), time.time() - t0)
122
+
123
+
124
+ def evaluate_history(problem: TransportProblem, result: AdamResult, epochs,
125
+ n_traj: int = 100_000, seed: int = 12345, n_jobs: int = 1,
126
+ verbose: bool = True) -> np.ndarray:
127
+ """Retrospective CRN evaluation of every trial at the given epochs.
128
+
129
+ Returns an array (len(epochs), T) of <W> (same noise for every entry, so
130
+ entries are directly comparable -- the Common Random Numbers technique).
131
+ """
132
+ ev = problem.evaluator(n_traj, seed, n_jobs=n_jobs)
133
+ out = np.empty((len(epochs), result.history.shape[0]))
134
+ t0 = time.time()
135
+ for i, e in enumerate(epochs):
136
+ out[i] = ev.evaluate(problem.protocol(result.history[:, e])).mean
137
+ if verbose:
138
+ print(f" eval epoch {e:4d}: <W>/W* = {out[i].mean() / problem.W_star:.5f}"
139
+ f" +- {out[i].std() / problem.W_star:.5f} [{time.time() - t0:6.1f}s]",
140
+ flush=True)
141
+ return out
142
+
143
+
144
+ # ==========================================================================
145
+ # Genetic algorithm
146
+ # ==========================================================================
147
+ @dataclass
148
+ class GAConfig:
149
+ """Two-stage progressive-fidelity GA (defaults: paper values)."""
150
+
151
+ population: int = 150
152
+ elite_frac: float = 0.10
153
+ tournament: int = 10
154
+ gens_stage1: int = 30
155
+ gens_stage2: int = 70
156
+ traj_stage1: int = 500
157
+ traj_stage2: int = 2000
158
+ elite_traj: int = 100_000 # hi-fi re-evaluation of stage-2 elites
159
+ elite_seed: int = 777 # CRN seed for hi-fi evaluations
160
+ hifi_top: int | None = None # new candidates re-evaluated per generation
161
+ # (None = all elite-sized top set, as in the paper)
162
+ sigma_max: float = 0.2 # annealed mutation scale
163
+ sigma_min: float = 0.005
164
+ init_scale: float = 1.0
165
+ seed: int = 0
166
+ verbose: bool = False
167
+
168
+ def sigma(self, g: int, G: int) -> float:
169
+ return self.sigma_max - (self.sigma_max - self.sigma_min) * g / max(G - 1, 1)
170
+
171
+
172
+ @dataclass
173
+ class GAResult:
174
+ best_coeffs: np.ndarray # (Nc,)
175
+ best_work: float # hi-fi <W> of the best individual
176
+ history: np.ndarray # (G,) best fitness per generation
177
+ config: dict = field(default_factory=dict)
178
+ seconds: float = 0.0
179
+
180
+
181
+ def _ga_trial(problem: TransportProblem, cfg: GAConfig) -> GAResult:
182
+ rng = np.random.default_rng(cfg.seed)
183
+ ans = problem.ansatz
184
+ P = cfg.population
185
+ n_elite = max(1, int(round(cfg.elite_frac * P)))
186
+ hifi = problem.evaluator(cfg.elite_traj, cfg.elite_seed)
187
+ cache: dict[bytes, float] = {}
188
+ t0 = time.time()
189
+
190
+ def lofi(pop, n_traj, gen):
191
+ ev = problem.evaluator(n_traj, seed=int(rng.integers(2**31)))
192
+ return ev.evaluate(ans(pop)).mean
193
+
194
+ def tournament(pop, fit, n):
195
+ idx = rng.integers(0, len(pop), size=(n, cfg.tournament))
196
+ win = idx[np.arange(n), np.argmin(fit[idx], axis=1)]
197
+ return pop[win]
198
+
199
+ history = []
200
+
201
+ def run_stage(pop, G, n_traj, use_hifi):
202
+ elite_pop, elite_fit = None, None
203
+ for g in range(G):
204
+ fit = lofi(pop, n_traj, g)
205
+ order = np.argsort(fit)
206
+ cand = pop[order[:n_elite]]
207
+ if use_hifi:
208
+ if cfg.hifi_top is not None:
209
+ cand = cand[:cfg.hifi_top]
210
+ if elite_pop is not None:
211
+ cand = np.concatenate([elite_pop, cand])
212
+ cf = np.empty(len(cand))
213
+ for i, c in enumerate(cand):
214
+ key = np.round(c, 12).tobytes()
215
+ if key not in cache:
216
+ cache[key] = float(hifi.evaluate(ans(c)).mean[0])
217
+ cf[i] = cache[key]
218
+ keep = np.argsort(cf)[:n_elite]
219
+ elite_pop, elite_fit = cand[keep], cf[keep]
220
+ else:
221
+ elite_pop, elite_fit = cand, fit[order[:n_elite]]
222
+ history.append(elite_fit[0])
223
+ if cfg.verbose:
224
+ print(f" gen {len(history):3d} best <W>/W* = "
225
+ f"{elite_fit[0] / problem.W_star:.4f} [{time.time() - t0:.0f}s]",
226
+ flush=True)
227
+ if g == G - 1:
228
+ break
229
+ # selection pool: population with elites' fitness substituted
230
+ pool = np.concatenate([elite_pop, pop])
231
+ pool_fit = np.concatenate([elite_fit, fit])
232
+ kids = tournament(pool, pool_fit, P - n_elite)
233
+ kids = kids + cfg.sigma(g, G) * rng.standard_normal(kids.shape)
234
+ pop = np.concatenate([elite_pop, kids])
235
+ return elite_pop[0], elite_fit[0]
236
+
237
+ # Stage 1: broad exploration, low fidelity
238
+ pop = ans.random_coeffs(rng, P, scale=cfg.init_scale, center="midpoint")
239
+ best, _ = run_stage(pop, cfg.gens_stage1, cfg.traj_stage1, use_hifi=False)
240
+ # Stage 2: re-initialise around the stage-1 champion
241
+ pop = best + cfg.sigma_max * rng.standard_normal((P, ans.n_basis))
242
+ pop[0] = best
243
+ best, best_w = run_stage(pop, cfg.gens_stage2, cfg.traj_stage2,
244
+ use_hifi=cfg.elite_traj > 0)
245
+ if cfg.elite_traj <= 0:
246
+ best_w = float(hifi.evaluate(ans(best)).mean[0])
247
+ return GAResult(best, best_w, np.array(history), asdict(cfg), time.time() - t0)
248
+
249
+
250
+ def _ga_worker(args):
251
+ problem, cfg = args
252
+ return _ga_trial(problem, cfg)
253
+
254
+
255
+ def optimize_ga(problem: TransportProblem, n_trials: int = 5,
256
+ config: GAConfig | None = None, n_jobs: int = 1, **kw) -> list[GAResult]:
257
+ """Run ``n_trials`` independent GA optimisations (seeds cfg.seed + i)."""
258
+ base = config or GAConfig()
259
+ for key, val in kw.items():
260
+ setattr(base, key, val)
261
+ cfgs = []
262
+ for i in range(n_trials):
263
+ c = GAConfig(**asdict(base))
264
+ c.seed = base.seed + i
265
+ c.verbose = base.verbose and (n_jobs == 1)
266
+ cfgs.append(c)
267
+ n_jobs = os.cpu_count() if n_jobs == -1 else n_jobs
268
+ if n_jobs > 1:
269
+ with ProcessPoolExecutor(n_jobs, mp_context=mp.get_context("fork")) as ex:
270
+ out = list(ex.map(_ga_worker, [(problem, c) for c in cfgs]))
271
+ else:
272
+ out = [_ga_trial(problem, c) for c in cfgs]
273
+ if base.verbose:
274
+ for i, r in enumerate(out):
275
+ print(f" GA trial {i}: <W>/W* = {r.best_work / problem.W_star:.4f}"
276
+ f" ({r.seconds:.0f}s)")
277
+ return out
pymonge/plotting.py ADDED
@@ -0,0 +1,117 @@
1
+ """Matplotlib helpers: protocol plots and the Figure-8 style convergence panel."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+
6
+ __all__ = ["paper_style", "plot_protocol", "plot_convergence", "plot_fig8"]
7
+
8
+ BLUE = "#1f5fa8"
9
+ ORANGE = "#d9641e"
10
+ GREY = "#555555"
11
+
12
+
13
+ def paper_style():
14
+ import matplotlib as mpl
15
+ mpl.rcParams.update({
16
+ "font.family": "serif", "mathtext.fontset": "cm", "font.size": 11,
17
+ "axes.linewidth": 0.8, "xtick.direction": "in", "ytick.direction": "in",
18
+ "xtick.top": True, "ytick.right": True, "legend.frameon": True,
19
+ "legend.framealpha": 0.9, "legend.edgecolor": "0.8",
20
+ "savefig.dpi": 200, "savefig.bbox": "tight",
21
+ })
22
+
23
+
24
+ def _xy(problem, p, shift=0.0, normalise=True):
25
+ t = problem.grid.t_plot()
26
+ if normalise:
27
+ t = t / problem.grid.t_f
28
+ return t, np.asarray(p) - shift
29
+
30
+
31
+ def plot_protocol(ax, problem, protocol, *, shift=0.0, normalise=True, **kw):
32
+ """Draw a full protocol array (with endpoint jumps)."""
33
+ t, y = _xy(problem, protocol, shift, normalise)
34
+ return ax.plot(t, y, **kw)
35
+
36
+
37
+ def plot_convergence(ax, epochs, works, W_star, *, color=BLUE, label="Mean best individual"):
38
+ """Mean +- 1 sigma (across trials) of <W>/W* vs epoch.
39
+
40
+ works : (len(epochs), T)
41
+ """
42
+ w = np.asarray(works) / W_star
43
+ m, s = w.mean(axis=1), w.std(axis=1)
44
+ ax.fill_between(epochs, m - s, m + s, color=color, alpha=0.25, lw=0,
45
+ label=r"$\pm1\sigma$ Ensemble Variance")
46
+ ax.plot(epochs, m, color=color, lw=1.6, label=label)
47
+ ax.set_xlabel("Epoch")
48
+ ax.set_ylabel(r"$\langle W\rangle / W^*$")
49
+
50
+
51
+ def plot_fig8(problem, adam_result, eval_epochs, eval_works, ga_protocols,
52
+ ga_works, adam_works_final, inset_epochs=(1, 10, 30, 150),
53
+ path=None, title=None):
54
+ """Reproduce Fig. 8 of the paper.
55
+
56
+ (a) CRN-evaluated convergence of Adam with an inset of protocol snapshots.
57
+ (b) Mean optimal protocol from GA vs Adam with <W> mean +- std.
58
+ """
59
+ import matplotlib.pyplot as plt
60
+ from mpl_toolkits.axes_grid1.inset_locator import inset_axes
61
+
62
+ paper_style()
63
+ panel_a_only = ga_protocols is None
64
+ if panel_a_only:
65
+ fig, axa = plt.subplots(figsize=(6.2, 4.1))
66
+ else:
67
+ fig, (axa, axb) = plt.subplots(1, 2, figsize=(11, 4.1),
68
+ gridspec_kw={"width_ratios": [1.25, 1]})
69
+ # ---- (a) convergence ------------------------------------------------
70
+ plot_convergence(axa, eval_epochs, eval_works, problem.W_star)
71
+ axa.legend(loc="upper center", bbox_to_anchor=(0.5, 1.17), ncol=2, frameon=False)
72
+ axa.text(0.03, 0.05, "(a)", transform=axa.transAxes, va="bottom")
73
+ m = np.asarray(eval_works).mean(axis=1) / problem.W_star
74
+ span = max(m.max() - m.min(), 2e-3)
75
+ lo = m.min() - 0.15 * span
76
+ hi = m.max() + 1.6 * span # head-room for the inset
77
+ axa.set_ylim(lo, hi)
78
+ ins = inset_axes(axa, width="52%", height="58%", loc="upper right",
79
+ bbox_to_anchor=(0, -0.03, 0.97, 1), bbox_transform=axa.transAxes)
80
+ cmap = plt.get_cmap("Blues")
81
+ for i, e in enumerate(inset_epochs):
82
+ c = problem.protocol(adam_result.history[:, e].mean(axis=0))
83
+ plot_protocol(ins, problem, c, shift=problem.H0, color=cmap(0.4 + 0.6 * i / max(len(inset_epochs) - 1, 1)),
84
+ lw=1.3, label=f"Epoch {e}")
85
+ ins.set_xlabel(r"$t/t_f$", fontsize=9, labelpad=1)
86
+ ins.set_ylabel(r"$\Lambda(t)-H_0$", fontsize=9, labelpad=1)
87
+ ins.tick_params(labelsize=7)
88
+ ins.legend(fontsize=7, loc="lower right")
89
+
90
+ if panel_a_only:
91
+ if title:
92
+ axa.set_title(title, fontsize=11, pad=34)
93
+ if path:
94
+ fig.savefig(path)
95
+ return fig
96
+
97
+ # ---- (b) GA vs Adam ---------------------------------------------------
98
+ t = problem.grid.t_plot()
99
+ ga_mean = np.mean(ga_protocols, axis=0)
100
+ ad_mean = problem.protocol(adam_result.coeffs.mean(axis=0))
101
+ axb.plot(t, ga_mean, color="blue", lw=1.6, label="GA (mean)")
102
+ axb.plot(t, ad_mean, color="red", lw=1.4, ls="--", label="Adam (mean)")
103
+ axb.set_xlabel(r"Time $t$")
104
+ axb.set_ylabel(r"Trap center $\lambda(t)$")
105
+ axb.legend(loc="upper left")
106
+ axb.text(0.10, 0.05, "(b)", transform=axb.transAxes, va="bottom", ha="left")
107
+ txt = (r"$\langle W\rangle$ (mean $\pm$ std)" + "\n"
108
+ + f"GA: {np.mean(ga_works):.5f} $\\pm$ {np.std(ga_works):.5f}\n"
109
+ + f"Adam: {np.mean(adam_works_final):.5f} $\\pm$ {np.std(adam_works_final):.5f}")
110
+ axb.text(0.96, 0.05, txt, transform=axb.transAxes, ha="right", va="bottom",
111
+ fontsize=9, bbox=dict(boxstyle="round", fc="white", ec="0.7"))
112
+ if title:
113
+ fig.suptitle(title, y=1.04, fontsize=11)
114
+ fig.subplots_adjust(wspace=0.28)
115
+ if path:
116
+ fig.savefig(path)
117
+ return fig
pymonge/problem.py ADDED
@@ -0,0 +1,56 @@
1
+ """A transport problem bundles physics, endpoints, time grid and ansatz."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+
6
+ import numpy as np
7
+
8
+ from .model import NearWallModel
9
+ from .protocol import ChebyshevProtocol, TimeGrid, schmiedl_seifert_work
10
+ from .simulate import WorkEvaluator
11
+
12
+ __all__ = ["TransportProblem"]
13
+
14
+
15
+ @dataclass
16
+ class TransportProblem:
17
+ """Move the trap from ``H0`` to ``H0 + dH`` (units of b) in time ``t_f``.
18
+
19
+ ``dH < 0`` gives transport towards the wall. Defaults reproduce the paper:
20
+ dH = 5, t_f = 2 tau, dt = 0.002, N = 5 Chebyshev coefficients.
21
+ """
22
+
23
+ model: NearWallModel = field(default_factory=NearWallModel.paper)
24
+ H0: float = 2.0
25
+ dH: float = 5.0
26
+ grid: TimeGrid = field(default_factory=TimeGrid)
27
+ n_basis: int = 5
28
+ initial: str = "boltzmann"
29
+
30
+ def __post_init__(self):
31
+ b = getattr(self.model.mobility, "b", 1.0)
32
+ self.lam_i = self.H0 * b
33
+ self.lam_f = (self.H0 + self.dH) * b
34
+ self.ansatz = ChebyshevProtocol(self.lam_i, self.lam_f, self.grid, self.n_basis)
35
+
36
+ @property
37
+ def W_star(self) -> float:
38
+ """Bulk minimum work, Eq. (B2) -- the normalisation used in the paper."""
39
+ mu0 = getattr(self.model.mobility, "mu0", 1.0)
40
+ return schmiedl_seifert_work(self.lam_i, self.lam_f, self.grid.t_f,
41
+ self.model.k, mu0)
42
+
43
+ def protocol(self, coeffs) -> np.ndarray:
44
+ return self.ansatz(coeffs)
45
+
46
+ def ss_protocol(self) -> np.ndarray:
47
+ """Schmiedl-Seifert bulk protocol on this grid."""
48
+ return self.ansatz(self.ansatz.ramp_coeffs())
49
+
50
+ def evaluator(self, n_traj: int = 100_000, seed: int = 12345, **kw) -> WorkEvaluator:
51
+ return WorkEvaluator(self.model, self.grid, n_traj, seed,
52
+ initial=self.initial, **kw)
53
+
54
+ def evaluate(self, coeffs, n_traj: int = 100_000, seed: int = 12345, **kw):
55
+ """<W> for coefficient vector(s), CRN with ``seed``."""
56
+ return self.evaluator(n_traj, seed, **kw).evaluate(self.protocol(coeffs))
pymonge/protocol.py ADDED
@@ -0,0 +1,152 @@
1
+ """Protocol representations (Ritz method) and the Schmiedl-Seifert benchmark.
2
+
3
+ Discretisation convention (used consistently by the simulator and gradient)
4
+ --------------------------------------------------------------------------
5
+ A protocol on ``n_steps`` time steps of size ``dt`` is an array ``p`` of length
6
+ ``n_steps + 2``::
7
+
8
+ p[0] = lam_i (trap before t = 0)
9
+ p[1..n_steps] = interior values at t_n = n dt, n = 1..n_steps
10
+ p[n_steps+1] = lam_f (trap after t = t_f)
11
+
12
+ At step ``n`` the trap first moves ``p[n] -> p[n+1]`` (work is done with the
13
+ particle frozen) and then the particle evolves for ``dt`` in the new trap. The
14
+ final move ``p[n_steps] -> lam_f`` happens at ``t_f``. Endpoint jumps therefore
15
+ emerge freely: only the interior is parametrised, exactly as in Sec. II B.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass
20
+
21
+ import numpy as np
22
+ from numpy.polynomial import chebyshev as C
23
+
24
+ __all__ = [
25
+ "TimeGrid",
26
+ "ChebyshevProtocol",
27
+ "schmiedl_seifert",
28
+ "schmiedl_seifert_work", "PiecewiseLinearProtocol"]
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class TimeGrid:
33
+ """Uniform time grid on [0, t_f]."""
34
+
35
+ t_f: float = 2.0
36
+ n_steps: int = 1000
37
+
38
+ @property
39
+ def dt(self) -> float:
40
+ return self.t_f / self.n_steps
41
+
42
+ @property
43
+ def t_interior(self) -> np.ndarray:
44
+ """Times t_n = n dt, n = 1..n_steps, at which interior values live."""
45
+ return self.dt * np.arange(1, self.n_steps + 1)
46
+
47
+ def t_plot(self) -> np.ndarray:
48
+ """Time axis of length n_steps+2 for plotting a full protocol array
49
+ (endpoints duplicated at t = 0 and t = t_f to draw the jumps)."""
50
+ return np.concatenate([[0.0], [0.0], self.t_interior[:-1], [self.t_f]])
51
+
52
+
53
+ class ChebyshevProtocol:
54
+ """Ritz ansatz lam(t) = sum_n a_n T_n(2t/t_f - 1) on the interior, Eq. (6).
55
+
56
+ Parameters
57
+ ----------
58
+ lam_i, lam_f
59
+ Fixed endpoint trap positions.
60
+ grid
61
+ :class:`TimeGrid`.
62
+ n_basis
63
+ Number of Chebyshev coefficients ``N`` (paper: 5).
64
+ """
65
+
66
+ def __init__(self, lam_i: float, lam_f: float, grid: TimeGrid = TimeGrid(),
67
+ n_basis: int = 5):
68
+ self.lam_i = float(lam_i)
69
+ self.lam_f = float(lam_f)
70
+ self.grid = grid
71
+ self.n_basis = int(n_basis)
72
+ x = 2.0 * grid.t_interior / grid.t_f - 1.0
73
+ # basis matrix B[n, j] = T_j(x_n); interior = B @ a
74
+ self.basis = C.chebvander(x, self.n_basis - 1)
75
+
76
+ # -- evaluation -----------------------------------------------------
77
+ def interior(self, coeffs):
78
+ """Interior values, shape (..., n_steps)."""
79
+ return np.asarray(coeffs) @ self.basis.T
80
+
81
+ def __call__(self, coeffs) -> np.ndarray:
82
+ """Full protocol array(s) with endpoints, shape (..., n_steps + 2)."""
83
+ inner = self.interior(coeffs)
84
+ shape = inner.shape[:-1] + (1,)
85
+ return np.concatenate([np.full(shape, self.lam_i), inner,
86
+ np.full(shape, self.lam_f)], axis=-1)
87
+
88
+ def grad_to_coeffs(self, grad_p):
89
+ """Chain rule: dL/da from dL/dp (full protocol array gradient)."""
90
+ return np.asarray(grad_p)[..., 1:-1] @ self.basis
91
+
92
+ # -- initial guesses ------------------------------------------------
93
+ def fit(self, values) -> np.ndarray:
94
+ """Least-squares coefficients reproducing given interior values."""
95
+ a, *_ = np.linalg.lstsq(self.basis, np.asarray(values, float), rcond=None)
96
+ return a
97
+
98
+ def ramp_coeffs(self) -> np.ndarray:
99
+ """Coefficients of the Schmiedl-Seifert bulk protocol (exact for N>=2)."""
100
+ return self.fit(schmiedl_seifert(self.grid.t_interior, self.lam_i,
101
+ self.lam_f, self.grid.t_f))
102
+
103
+ def linear_coeffs(self) -> np.ndarray:
104
+ """Coefficients of the naive straight line lam_i -> lam_f."""
105
+ t = self.grid.t_interior
106
+ return self.fit(self.lam_i + (self.lam_f - self.lam_i) * t / self.grid.t_f)
107
+
108
+ def random_coeffs(self, rng, n: int, scale: float = 0.5,
109
+ center: str = "midpoint") -> np.ndarray:
110
+ """Gaussian random coefficients, a_0 biased to the midpoint (Sec. II D)."""
111
+ a = scale * rng.standard_normal((n, self.n_basis))
112
+ if center == "midpoint":
113
+ a[:, 0] += 0.5 * (self.lam_i + self.lam_f)
114
+ elif center == "ramp":
115
+ a += self.ramp_coeffs()
116
+ return a
117
+
118
+
119
+ # --------------------------------------------------------------------------
120
+ # Bulk analytical benchmark (Appendix B 1)
121
+ # --------------------------------------------------------------------------
122
+ def schmiedl_seifert(t, lam_i, lam_f, t_f, mu_k: float = 1.0):
123
+ """Optimal bulk protocol for 0 < t < t_f, Eq. (B1) (general mu*k)."""
124
+ tau = 1.0 / mu_k
125
+ return lam_i + (lam_f - lam_i) * (t + tau) / (t_f + 2.0 * tau)
126
+
127
+
128
+ def schmiedl_seifert_work(lam_i, lam_f, t_f, k: float = 1.0, mu: float = 1.0):
129
+ """Minimum bulk work W* = k (dlam)^2 / (mu k t_f + 2), Eq. (B2)."""
130
+ return k * (lam_f - lam_i) ** 2 / (mu * k * t_f + 2.0)
131
+
132
+
133
+ class PiecewiseLinearProtocol(ChebyshevProtocol):
134
+ """Protocol whose interior is a linear interpolation between ``n_basis`` free nodes.
135
+
136
+ Same interface as :class:`ChebyshevProtocol` (only the basis matrix differs),
137
+ so it can replace ``problem.ansatz``::
138
+
139
+ problem.ansatz = PiecewiseLinearProtocol(problem.lam_i, problem.lam_f, problem.grid, 500)
140
+ """
141
+
142
+ def __init__(self, lam_i, lam_f, grid, n_basis=500):
143
+ super().__init__(lam_i, lam_f, grid, 2)
144
+ self.n_basis = int(n_basis)
145
+ t = grid.t_interior
146
+ nodes = np.linspace(t[0], t[-1], self.n_basis)
147
+ B = np.zeros((len(t), self.n_basis))
148
+ for j in range(self.n_basis): # hat functions
149
+ e = np.zeros(self.n_basis)
150
+ e[j] = 1.0
151
+ B[:, j] = np.interp(t, nodes, e)
152
+ self.basis = B
pymonge/simulate.py ADDED
@@ -0,0 +1,191 @@
1
+ """Stochastic simulation and Monte-Carlo estimation of the mean work.
2
+
3
+ The integrator is the Ito-Euler-Maruyama scheme of Eq. (9) with the spurious
4
+ drift kT mu'(h), plus an optional reflecting wall (see ``NearWallModel``).
5
+ Work is accumulated exactly for the piecewise-constant protocol::
6
+
7
+ W += V(h_n, p[n+1]) - V(h_n, p[n])
8
+
9
+ which includes the endpoint jumps without special treatment.
10
+
11
+ :class:`WorkEvaluator` uses Common Random Numbers (CRN): every call with the
12
+ same seed sees identical initial conditions and noise, so work differences
13
+ between protocols are estimated with very small variance.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ from concurrent.futures import ProcessPoolExecutor
19
+ from dataclasses import dataclass
20
+ import multiprocessing as mp
21
+
22
+ import numpy as np
23
+
24
+ from .model import NearWallModel
25
+ from .protocol import TimeGrid
26
+
27
+ __all__ = ["sample_initial", "simulate", "WorkEvaluator", "WorkEstimate"]
28
+
29
+
30
+ # --------------------------------------------------------------------------
31
+ # Initial conditions
32
+ # --------------------------------------------------------------------------
33
+ def sample_initial(model: NearWallModel, lam_i: float, n: int, rng,
34
+ kind: str = "boltzmann", t_relax: float = 5.0,
35
+ dt: float = 0.002) -> np.ndarray:
36
+ """Initial particle positions for a trap sitting at ``lam_i``.
37
+
38
+ kind = "boltzmann"
39
+ Equilibrium of V: Gaussian N(lam_i, kT/k), truncated at ``h_min``.
40
+ kind = "relaxed"
41
+ Boltzmann sample relaxed for ``t_relax`` with the full dynamics
42
+ (activity included) at fixed trap: approximates the active
43
+ non-equilibrium steady state.
44
+ kind = "trap"
45
+ Every particle starts exactly at the trap centre.
46
+ """
47
+ if kind == "trap":
48
+ return np.full(n, float(lam_i))
49
+ s = np.sqrt(model.kT / model.k)
50
+ h = lam_i + s * rng.standard_normal(n)
51
+ if model.h_min is not None:
52
+ bad = h < model.h_min
53
+ while bad.any():
54
+ h[bad] = lam_i + s * rng.standard_normal(bad.sum())
55
+ bad = h < model.h_min
56
+ if kind == "boltzmann":
57
+ return h
58
+ if kind != "relaxed":
59
+ raise ValueError(f"unknown initial condition {kind!r}")
60
+ for _ in range(int(round(t_relax / dt))):
61
+ drift = model.drift_total(h, lam_i)
62
+ h = h + dt * drift + np.sqrt(2 * dt * model.diffusion(h)) * rng.standard_normal(n)
63
+ h, _ = model.reflect(h)
64
+ return h
65
+
66
+
67
+ # --------------------------------------------------------------------------
68
+ # Core forward integrator
69
+ # --------------------------------------------------------------------------
70
+ def _forward(model: NearWallModel, dt: float, p: np.ndarray, h0: np.ndarray,
71
+ rng, shared_noise: bool, record: bool = False):
72
+ """Integrate a batch of protocols.
73
+
74
+ p : (P, n_steps + 2) protocol arrays.
75
+ h0: (M,) or (P, M) initial positions.
76
+ shared_noise: if True one noise realisation (M,) is broadcast to all P
77
+ protocols (CRN); otherwise independent (P, M) noise.
78
+ Returns W (P, M) and, if ``record``, the path h (n_steps+1, P, M).
79
+ """
80
+ P, L = p.shape
81
+ n_steps = L - 2
82
+ h = np.broadcast_to(h0, (P, h0.shape[-1])).astype(float, copy=True)
83
+ M = h.shape[1]
84
+ W = np.zeros_like(h)
85
+ path = np.empty((n_steps + 1, P, M)) if record else None
86
+ half_k = 0.5 * model.k
87
+ for n in range(n_steps):
88
+ if record:
89
+ path[n] = h
90
+ pn = p[:, n, None]
91
+ pn1 = p[:, n + 1, None]
92
+ W += half_k * (pn - pn1) * (2.0 * h - pn - pn1)
93
+ z = rng.standard_normal(M if shared_noise else (P, M))
94
+ h = model.step(h, pn1, dt, z)
95
+ h, _ = model.reflect(h)
96
+ if record:
97
+ path[n_steps] = h
98
+ pn, pn1 = p[:, n_steps, None], p[:, n_steps + 1, None]
99
+ W += half_k * (pn - pn1) * (2.0 * h - pn - pn1)
100
+ return W, path
101
+
102
+
103
+ def simulate(model: NearWallModel, grid: TimeGrid, protocol: np.ndarray,
104
+ n_traj: int = 1000, seed: int = 0, initial: str = "boltzmann"):
105
+ """Simulate trajectories for one protocol and return (W, h_path).
106
+
107
+ W : (n_traj,) work per trajectory.
108
+ h_path : (n_steps + 1, n_traj) particle positions at t_n = n dt.
109
+ """
110
+ p = np.atleast_2d(protocol)
111
+ rng = np.random.default_rng(seed)
112
+ h0 = sample_initial(model, p[0, 0], n_traj, rng, kind=initial, dt=grid.dt)
113
+ W, path = _forward(model, grid.dt, p, h0, rng, shared_noise=True, record=True)
114
+ return W[0], path[:, 0, :]
115
+
116
+
117
+ # --------------------------------------------------------------------------
118
+ # CRN Monte-Carlo evaluator
119
+ # --------------------------------------------------------------------------
120
+ @dataclass
121
+ class WorkEstimate:
122
+ mean: np.ndarray # (P,)
123
+ sem: np.ndarray # (P,) standard error of the mean
124
+ std: np.ndarray # (P,) trajectory-to-trajectory std of W
125
+
126
+
127
+ def _eval_chunk(args):
128
+ model, dt, p, lam_i, n, seed, chunk_id, initial = args
129
+ rng = np.random.default_rng([seed, chunk_id])
130
+ h0 = sample_initial(model, lam_i, n, rng, kind=initial, dt=dt)
131
+ W, _ = _forward(model, dt, p, h0, rng, shared_noise=True)
132
+ return W.sum(axis=1), (W * W).sum(axis=1), n
133
+
134
+
135
+ class WorkEvaluator:
136
+ """Estimate <W> for a batch of protocols with Common Random Numbers.
137
+
138
+ Parameters
139
+ ----------
140
+ model, grid
141
+ Physics and time grid.
142
+ n_traj
143
+ Number of trajectories per protocol.
144
+ seed
145
+ CRN seed: identical seeds give identical noise for every protocol.
146
+ chunk
147
+ Trajectories per chunk (keeps arrays cache-friendly).
148
+ initial
149
+ Initial condition, see :func:`sample_initial`.
150
+ n_jobs
151
+ Worker processes (chunks are distributed; results do not depend on
152
+ ``n_jobs``). ``-1`` uses all cores.
153
+ """
154
+
155
+ def __init__(self, model: NearWallModel, grid: TimeGrid, n_traj: int = 100_000,
156
+ seed: int = 12345, chunk: int = 2000, initial: str = "boltzmann",
157
+ n_jobs: int = 1):
158
+ self.model, self.grid = model, grid
159
+ self.n_traj, self.seed, self.chunk = int(n_traj), seed, int(chunk)
160
+ self.initial = initial
161
+ self.n_jobs = os.cpu_count() if n_jobs == -1 else max(1, int(n_jobs))
162
+
163
+ def _tasks(self, p, seed):
164
+ lam_i = float(p[0, 0])
165
+ sizes = [self.chunk] * (self.n_traj // self.chunk)
166
+ if self.n_traj % self.chunk:
167
+ sizes.append(self.n_traj % self.chunk)
168
+ return [(self.model, self.grid.dt, p, lam_i, n, seed, c, self.initial)
169
+ for c, n in enumerate(sizes)]
170
+
171
+ def evaluate(self, protocols, seed: int | None = None) -> WorkEstimate:
172
+ """Evaluate protocols of shape (n_steps+2,) or (P, n_steps+2)."""
173
+ p = np.atleast_2d(np.asarray(protocols, float))
174
+ if not np.allclose(p[:, 0], p[0, 0]):
175
+ raise ValueError("all protocols in a batch must share lam_i")
176
+ tasks = self._tasks(p, self.seed if seed is None else seed)
177
+ if self.n_jobs > 1 and len(tasks) > 1:
178
+ ctx = mp.get_context("fork")
179
+ with ProcessPoolExecutor(self.n_jobs, mp_context=ctx) as ex:
180
+ results = list(ex.map(_eval_chunk, tasks))
181
+ else:
182
+ results = [_eval_chunk(t) for t in tasks]
183
+ s = sum(r[0] for r in results)
184
+ s2 = sum(r[1] for r in results)
185
+ n = sum(r[2] for r in results)
186
+ mean = s / n
187
+ var = np.maximum(s2 / n - mean**2, 0.0)
188
+ std = np.sqrt(var * n / max(n - 1, 1))
189
+ return WorkEstimate(mean, std / np.sqrt(n), std)
190
+
191
+ __call__ = evaluate
@@ -0,0 +1,135 @@
1
+ Metadata-Version: 2.4
2
+ Name: pymonge
3
+ Version: 0.1.0
4
+ Summary: Minimum-work transport protocols for trapped active colloids near a wall (Ritz method with Adam and a genetic algorithm)
5
+ Author: Utkarsh Maurya, Kavya Swaminathan, Ejaz Ashraf, Rajesh Singh
6
+ Keywords: stochastic thermodynamics,optimal control,active matter,optical tweezers
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: numpy>=1.22
11
+ Requires-Dist: matplotlib>=3.5
12
+ Provides-Extra: test
13
+ Requires-Dist: pytest; extra == "test"
14
+ Dynamic: license-file
15
+
16
+ # pymonge
17
+
18
+ Minimum-work transport protocols for trapped colloidal particles, found with the
19
+ **Ritz method**: the trap protocol λ(t) is expanded in Chebyshev polynomials and
20
+ its coefficients are optimised with **Adam** (exact pathwise gradients through
21
+ the stochastic integrator) or a **genetic algorithm**. Only the ability to
22
+ simulate stochastic trajectories is needed. The built-in model is an active
23
+ particle (stresslet) near a plane no-slip wall.
24
+
25
+ ## Why Monge
26
+
27
+ Gaspard Monge (1746–1818) was a French mathematician, the founder of descriptive
28
+ geometry. In his 1781 memoir *Mémoire sur la théorie des déblais et des
29
+ remblais* he asked how to move a pile of earth into an excavation of the same
30
+ volume while doing the least total work of transport. This is the first
31
+ optimal-transport problem, and the question this package answers is of the same
32
+ kind: how to move a colloidal particle from one place to another, in a fixed
33
+ time, with the least work. The link is more than an analogy: for overdamped
34
+ dynamics, the minimum dissipation of a finite-time process is set by an
35
+ optimal-transport distance between the initial and final distributions.
36
+
37
+ Companion code for *Optimal protocols for the transport of an active particle
38
+ near a plane wall* (Maurya, Swaminathan, Ashraf & Singh).
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install -e . # from this folder; needs numpy and matplotlib
44
+ pip install -e .[test] # with pytest
45
+ pytest # 12 tests, a few seconds
46
+ ```
47
+
48
+ ## Quick start
49
+
50
+ ```python
51
+ import pymonge as pm
52
+
53
+ model = pm.NearWallModel.paper(alpha=25) # puller near a wall
54
+ problem = pm.TransportProblem(model, H0=2.0, dH=5.0) # trap moves from 2 to 7
55
+
56
+ res = pm.optimize_adam(problem, n_trials=6, epochs=100)
57
+ lam = problem.protocol(res.coeffs.mean(0)) # full protocol, jumps included
58
+
59
+ opt = problem.evaluate(res.coeffs.mean(0), n_traj=100_000)
60
+ ss = problem.evaluate(problem.ansatz.ramp_coeffs(), n_traj=100_000) # bulk protocol
61
+ print(opt.mean / problem.W_star, ss.mean / problem.W_star)
62
+ ```
63
+
64
+ ## What is in the package
65
+
66
+ | module | contents |
67
+ |---|---|
68
+ | `model` | `NearWallModel` with pluggable `BrennerMobility` / `BulkMobility` and `StressletDrift` / `NoDrift`; `NearWallModel.paper(alpha)` builds the model of the paper |
69
+ | `protocol` | `TimeGrid`, `ChebyshevProtocol`, `PiecewiseLinearProtocol`, `schmiedl_seifert`, `schmiedl_seifert_work` |
70
+ | `simulate` | Itô–Euler–Maruyama integrator, `simulate` for trajectories, `WorkEvaluator` (Monte-Carlo ⟨W⟩ with common random numbers, multi-process) |
71
+ | `gradient` | `work_and_grad`: hand-written adjoint of the integrator; exact gradient of the discretised ⟨W⟩ with respect to every protocol value |
72
+ | `problem` | `TransportProblem`: physics, end points, time grid and ansatz in one object |
73
+ | `optimize` | `optimize_adam` (trials vectorised), `evaluate_history`, `optimize_ga` (two-stage genetic algorithm) |
74
+ | `plotting` | small matplotlib helpers used by the examples |
75
+
76
+ ## Folders
77
+
78
+ | folder | contents |
79
+ |---|---|
80
+ | `src/pymonge/` | the package |
81
+ | `tests/` | unit tests (derivatives, adjoint against finite differences, bulk limit, reproducibility) |
82
+ | `examples/` | four short tutorials; each takes `--quick` |
83
+ | `paper/` | scripts, data and figures of the paper; see `paper/README.md` |
84
+
85
+ Examples:
86
+
87
+ | file | what it shows |
88
+ |---|---|
89
+ | `01_bulk_validation.py` | Adam started from a straight line recovers the Schmiedl–Seifert ramp and W* = 6.25 |
90
+ | `02_activity_near_wall.py` | pushers, passive particles and pullers close to the wall |
91
+ | `03_symmetry_breaking.py` | away against towards transport |
92
+ | `04_custom_physics.py` | adding your own drift (gravity) to the model |
93
+
94
+ ## Conventions
95
+
96
+ **Notation.** Lengths are in units of the particle radius. In the paper the
97
+ initial trap position is Λ₀ and the displacement ΔΛ; in the code these are the
98
+ arguments `H0` and `dH` of `TransportProblem` (the name is historical: `H0`
99
+ is a trap position, not a particle height).
100
+
101
+ **Activity.** `alpha > 0` is a puller, whose wall-induced drift is towards the
102
+ wall; `alpha < 0` is a pusher, drifting away from the wall.
103
+
104
+ **Dynamics.** `dh = [−μ(h) k (h − λ) + v_A(h) + k_BT μ'(h)] dt + √(2 k_BT μ(h)) dB`
105
+ (Itô; the term k_BT μ' makes a passive particle relax to the Boltzmann distribution).
106
+
107
+ **Discretisation.** A protocol on `n_steps` steps is an array of length
108
+ `n_steps + 2`: `[λ_i, λ(t_1), …, λ(t_N), λ_f]`. At each step the trap moves
109
+ first, with the particle fixed, and then the particle moves for `dt`. The end
110
+ points are not part of the Chebyshev expansion, so the jumps at t = 0 and
111
+ t = t_f come out of the optimisation.
112
+
113
+ **Wall.** Trajectories are reflected at contact, `h_min = 1`. Change it with
114
+ `NearWallModel(..., h_min=...)`.
115
+
116
+ **Initial condition.** `TransportProblem(initial=...)`: `"boltzmann"` (default;
117
+ equilibrium in the initial trap, cut off at the wall), `"relaxed"` (relaxed with
118
+ the active dynamics) or `"trap"` (all particles at the trap centre). Near the
119
+ wall the work depends noticeably on this choice.
120
+
121
+ **Common random numbers.** `WorkEvaluator` with the same `seed` uses the same
122
+ initial positions and noise for every protocol, so differences between
123
+ protocols are resolved far better than each absolute value (whose standard
124
+ error is about 0.002 W* at 100,000 trajectories).
125
+
126
+ ## Optimiser settings
127
+
128
+ Adam defaults (`AdamConfig`): 1000 trajectories per step, learning rate 0.05
129
+ with cosine decay to 10⁻³, gradient-norm clipping at 5, β₁ = 0.9, β₂ = 0.999,
130
+ initial protocol equal to the bulk ramp plus Gaussian noise of standard
131
+ deviation 0.05. The genetic algorithm (`GAConfig`) uses 150 individuals, 30
132
+ generations at 500 trajectories followed by 70 at 2000, 10% elites, tournament
133
+ size 10 and mutation annealed from 0.2 to 0.005; `hifi_top` and `elite_traj`
134
+ set how many candidates are re-evaluated at high fidelity in each generation.
135
+
@@ -0,0 +1,13 @@
1
+ pymonge/__init__.py,sha256=FxuecQ_xDaJsy8UncdinUyRL3T2NnhX9ffiRwKeyXt4,1796
2
+ pymonge/gradient.py,sha256=U47IcSAUWuiZOHpbO5Gbghbqe7t4a0kXXsL_ovU_YBg,3570
3
+ pymonge/model.py,sha256=niitdYZ_a9mydEOV6WNXjvD_bBOgyDj3Q4ED539glak,6405
4
+ pymonge/optimize.py,sha256=1vKWRf8xoYmeu4YjUqPT54rWcELBLxiE7FZjVMksO30,11047
5
+ pymonge/plotting.py,sha256=dZJSiwG4XcrNjr_d0qjOR0NhwcXzyyxbCWprvF7kJRo,4823
6
+ pymonge/problem.py,sha256=MLw7TAzxgftMrXukviROMyLtziNYohi7bbh_mEf16vs,2075
7
+ pymonge/protocol.py,sha256=GGuyRffP_uHKTUxzVeKexpZfMCIohMJ-bJuVLS--3HA,5937
8
+ pymonge/simulate.py,sha256=tRdC12UQUMnWMTHDMWw_oYFDsDzDb7k319K8kAljJxQ,7455
9
+ pymonge-0.1.0.dist-info/licenses/LICENSE,sha256=owrMkz8txKLyk-bZWYMfh2YjDRV2xlzXyv6tiS4B1sg,1067
10
+ pymonge-0.1.0.dist-info/METADATA,sha256=CQCaE1v_t8sTAxg6n7U59ojHxKp4DnxMfSetuNDn-Wc,6470
11
+ pymonge-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ pymonge-0.1.0.dist-info/top_level.txt,sha256=cWz7FSyZijUCJp9st28-kEueYCxSLJmX5lf-E3_otu4,8
13
+ pymonge-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 IIT Madras
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pymonge