pymonge 0.1.0__tar.gz

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-0.1.0/LICENSE ADDED
@@ -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.
pymonge-0.1.0/PKG-INFO ADDED
@@ -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,120 @@
1
+ # pymonge
2
+
3
+ Minimum-work transport protocols for trapped colloidal particles, found with the
4
+ **Ritz method**: the trap protocol λ(t) is expanded in Chebyshev polynomials and
5
+ its coefficients are optimised with **Adam** (exact pathwise gradients through
6
+ the stochastic integrator) or a **genetic algorithm**. Only the ability to
7
+ simulate stochastic trajectories is needed. The built-in model is an active
8
+ particle (stresslet) near a plane no-slip wall.
9
+
10
+ ## Why Monge
11
+
12
+ Gaspard Monge (1746–1818) was a French mathematician, the founder of descriptive
13
+ geometry. In his 1781 memoir *Mémoire sur la théorie des déblais et des
14
+ remblais* he asked how to move a pile of earth into an excavation of the same
15
+ volume while doing the least total work of transport. This is the first
16
+ optimal-transport problem, and the question this package answers is of the same
17
+ kind: how to move a colloidal particle from one place to another, in a fixed
18
+ time, with the least work. The link is more than an analogy: for overdamped
19
+ dynamics, the minimum dissipation of a finite-time process is set by an
20
+ optimal-transport distance between the initial and final distributions.
21
+
22
+ Companion code for *Optimal protocols for the transport of an active particle
23
+ near a plane wall* (Maurya, Swaminathan, Ashraf & Singh).
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ pip install -e . # from this folder; needs numpy and matplotlib
29
+ pip install -e .[test] # with pytest
30
+ pytest # 12 tests, a few seconds
31
+ ```
32
+
33
+ ## Quick start
34
+
35
+ ```python
36
+ import pymonge as pm
37
+
38
+ model = pm.NearWallModel.paper(alpha=25) # puller near a wall
39
+ problem = pm.TransportProblem(model, H0=2.0, dH=5.0) # trap moves from 2 to 7
40
+
41
+ res = pm.optimize_adam(problem, n_trials=6, epochs=100)
42
+ lam = problem.protocol(res.coeffs.mean(0)) # full protocol, jumps included
43
+
44
+ opt = problem.evaluate(res.coeffs.mean(0), n_traj=100_000)
45
+ ss = problem.evaluate(problem.ansatz.ramp_coeffs(), n_traj=100_000) # bulk protocol
46
+ print(opt.mean / problem.W_star, ss.mean / problem.W_star)
47
+ ```
48
+
49
+ ## What is in the package
50
+
51
+ | module | contents |
52
+ |---|---|
53
+ | `model` | `NearWallModel` with pluggable `BrennerMobility` / `BulkMobility` and `StressletDrift` / `NoDrift`; `NearWallModel.paper(alpha)` builds the model of the paper |
54
+ | `protocol` | `TimeGrid`, `ChebyshevProtocol`, `PiecewiseLinearProtocol`, `schmiedl_seifert`, `schmiedl_seifert_work` |
55
+ | `simulate` | Itô–Euler–Maruyama integrator, `simulate` for trajectories, `WorkEvaluator` (Monte-Carlo ⟨W⟩ with common random numbers, multi-process) |
56
+ | `gradient` | `work_and_grad`: hand-written adjoint of the integrator; exact gradient of the discretised ⟨W⟩ with respect to every protocol value |
57
+ | `problem` | `TransportProblem`: physics, end points, time grid and ansatz in one object |
58
+ | `optimize` | `optimize_adam` (trials vectorised), `evaluate_history`, `optimize_ga` (two-stage genetic algorithm) |
59
+ | `plotting` | small matplotlib helpers used by the examples |
60
+
61
+ ## Folders
62
+
63
+ | folder | contents |
64
+ |---|---|
65
+ | `src/pymonge/` | the package |
66
+ | `tests/` | unit tests (derivatives, adjoint against finite differences, bulk limit, reproducibility) |
67
+ | `examples/` | four short tutorials; each takes `--quick` |
68
+ | `paper/` | scripts, data and figures of the paper; see `paper/README.md` |
69
+
70
+ Examples:
71
+
72
+ | file | what it shows |
73
+ |---|---|
74
+ | `01_bulk_validation.py` | Adam started from a straight line recovers the Schmiedl–Seifert ramp and W* = 6.25 |
75
+ | `02_activity_near_wall.py` | pushers, passive particles and pullers close to the wall |
76
+ | `03_symmetry_breaking.py` | away against towards transport |
77
+ | `04_custom_physics.py` | adding your own drift (gravity) to the model |
78
+
79
+ ## Conventions
80
+
81
+ **Notation.** Lengths are in units of the particle radius. In the paper the
82
+ initial trap position is Λ₀ and the displacement ΔΛ; in the code these are the
83
+ arguments `H0` and `dH` of `TransportProblem` (the name is historical: `H0`
84
+ is a trap position, not a particle height).
85
+
86
+ **Activity.** `alpha > 0` is a puller, whose wall-induced drift is towards the
87
+ wall; `alpha < 0` is a pusher, drifting away from the wall.
88
+
89
+ **Dynamics.** `dh = [−μ(h) k (h − λ) + v_A(h) + k_BT μ'(h)] dt + √(2 k_BT μ(h)) dB`
90
+ (Itô; the term k_BT μ' makes a passive particle relax to the Boltzmann distribution).
91
+
92
+ **Discretisation.** A protocol on `n_steps` steps is an array of length
93
+ `n_steps + 2`: `[λ_i, λ(t_1), …, λ(t_N), λ_f]`. At each step the trap moves
94
+ first, with the particle fixed, and then the particle moves for `dt`. The end
95
+ points are not part of the Chebyshev expansion, so the jumps at t = 0 and
96
+ t = t_f come out of the optimisation.
97
+
98
+ **Wall.** Trajectories are reflected at contact, `h_min = 1`. Change it with
99
+ `NearWallModel(..., h_min=...)`.
100
+
101
+ **Initial condition.** `TransportProblem(initial=...)`: `"boltzmann"` (default;
102
+ equilibrium in the initial trap, cut off at the wall), `"relaxed"` (relaxed with
103
+ the active dynamics) or `"trap"` (all particles at the trap centre). Near the
104
+ wall the work depends noticeably on this choice.
105
+
106
+ **Common random numbers.** `WorkEvaluator` with the same `seed` uses the same
107
+ initial positions and noise for every protocol, so differences between
108
+ protocols are resolved far better than each absolute value (whose standard
109
+ error is about 0.002 W* at 100,000 trajectories).
110
+
111
+ ## Optimiser settings
112
+
113
+ Adam defaults (`AdamConfig`): 1000 trajectories per step, learning rate 0.05
114
+ with cosine decay to 10⁻³, gradient-norm clipping at 5, β₁ = 0.9, β₂ = 0.999,
115
+ initial protocol equal to the bulk ramp plus Gaussian noise of standard
116
+ deviation 0.05. The genetic algorithm (`GAConfig`) uses 150 individuals, 30
117
+ generations at 500 trajectories followed by 70 at 2000, 10% elites, tournament
118
+ size 10 and mutation annealed from 0.2 to 0.005; `hifi_top` and `elite_traj`
119
+ set how many candidates are re-evaluated at high fidelity in each generation.
120
+
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pymonge"
7
+ version = "0.1.0"
8
+ description = "Minimum-work transport protocols for trapped active colloids near a wall (Ritz method with Adam and a genetic algorithm)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ dependencies = ["numpy>=1.22", "matplotlib>=3.5"]
12
+ authors = [
13
+ {name = "Utkarsh Maurya"}, {name = "Kavya Swaminathan"}, {name = "Ejaz Ashraf"}, {name = "Rajesh Singh"},
14
+ ]
15
+ keywords = ["stochastic thermodynamics", "optimal control", "active matter", "optical tweezers"]
16
+
17
+ [project.optional-dependencies]
18
+ test = ["pytest"]
19
+
20
+ [tool.setuptools.packages.find]
21
+ where = ["src"]
22
+
23
+ [tool.pytest.ini_options]
24
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
+ ]
@@ -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
@@ -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)