kac-zwanzig 0.4.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.
- kac_zwanzig/__init__.py +81 -0
- kac_zwanzig/bath.py +460 -0
- kac_zwanzig/estimate.py +375 -0
- kac_zwanzig/propagate.py +190 -0
- kac_zwanzig/sample.py +90 -0
- kac_zwanzig/system.py +395 -0
- kac_zwanzig-0.4.0.dist-info/METADATA +359 -0
- kac_zwanzig-0.4.0.dist-info/RECORD +11 -0
- kac_zwanzig-0.4.0.dist-info/WHEEL +5 -0
- kac_zwanzig-0.4.0.dist-info/licenses/LICENSE +21 -0
- kac_zwanzig-0.4.0.dist-info/top_level.txt +1 -0
kac_zwanzig/__init__.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""kac_zwanzig: an exactly solvable Kac-Zwanzig bath.
|
|
2
|
+
|
|
3
|
+
A particle linearly coupled to ``N`` harmonic oscillators is a quadratic system, so its
|
|
4
|
+
dynamics, its memory kernel and its velocity autocorrelation function are all available
|
|
5
|
+
in closed form (up to one symmetric eigensolve). This package generates:
|
|
6
|
+
|
|
7
|
+
* spectral densities and their discretizations -> :func:`ohmic`, :func:`debye`, :meth:`Bath.from_spectral_density`
|
|
8
|
+
* the exact finite-bath kernel and its continuum -> :meth:`Bath.kernel`, :meth:`Bath.kernel_continuum`
|
|
9
|
+
* the exact correlation function and derivative -> :meth:`System.vacf`, :meth:`System.vacf_dot`
|
|
10
|
+
* the exact memory kernel of the velocity GLE -> :meth:`System.memory_kernel`
|
|
11
|
+
* exact trajectories (velocity, acceleration, position, random force) from canonical
|
|
12
|
+
initial conditions -> :meth:`System.trajectory`
|
|
13
|
+
* sampled correlation functions from ``n`` trajectories, with derivative estimators,
|
|
14
|
+
standard errors and a bootstrap -> :meth:`System.sampled_vacf`
|
|
15
|
+
* a bundle of ``C``, ``dC/dt`` and the exact kernel for testing any kernel-extraction method
|
|
16
|
+
-> :meth:`System.inversion_data`
|
|
17
|
+
|
|
18
|
+
The package depends only on numpy and knows nothing about any particular solver.
|
|
19
|
+
|
|
20
|
+
Quick start
|
|
21
|
+
-----------
|
|
22
|
+
>>> import numpy as np
|
|
23
|
+
>>> import kac_zwanzig as kz
|
|
24
|
+
>>> bath = kz.ohmic(eta=1.0, omega_c=1.0, N=2000) # J = eta w exp(-w/omega_c), uniform grid
|
|
25
|
+
>>> s = kz.System(bath, M=1.0, kT=1.0) # free particle
|
|
26
|
+
>>> t = np.arange(0, 20, 0.05)
|
|
27
|
+
>>> C, Cdot, Gamma = s.vacf(t), s.vacf_dot(t), s.memory_kernel(t)
|
|
28
|
+
>>> traj = s.trajectory(t, n_traj=1, seed=0, random_force=True) # traj.v, traj.a, traj.q, traj.F
|
|
29
|
+
>>> est = s.sampled_vacf(t, n_traj=10_000, seed=1) # est.C ~ C +- sqrt((1 - C^2)/10_000)
|
|
30
|
+
>>> boot = est.bootstrap(1000) # replicate curves, boot.std(), boot.band()
|
|
31
|
+
>>> data = s.inversion_data(t, est, derivative="acc") # data.C, data.Cdot, data.memory_kernel
|
|
32
|
+
|
|
33
|
+
Conventions
|
|
34
|
+
-----------
|
|
35
|
+
Units are the user's; the presets are natural with ``M = kT = omega_c = 1``. The
|
|
36
|
+
correlation function is normalized, ``C(0) = 1``. The memory kernel ``Gamma`` is defined by
|
|
37
|
+
|
|
38
|
+
dC/dt = -int_0^t Gamma(t - s) C(s) ds, Gamma(t) = (K_N(t) + M Omega^2)/M,
|
|
39
|
+
|
|
40
|
+
so ``Gamma(0) > 0``; a solver that writes the equation with the opposite sign wants ``-Gamma``.
|
|
41
|
+
|
|
42
|
+
See ``README.md`` for the API table, ``docs/theory.md`` for the derivations and
|
|
43
|
+
``docs/frequency_grids.pdf`` for the frequency-grid analysis.
|
|
44
|
+
"""
|
|
45
|
+
from .bath import Bath, bath_from_spectral_density, cos_sum, debye, debye_vacf_continuum, ohmic, sin_sum
|
|
46
|
+
from .estimate import (
|
|
47
|
+
BootstrapResult,
|
|
48
|
+
VACFEstimate,
|
|
49
|
+
fd_weights,
|
|
50
|
+
finite_difference,
|
|
51
|
+
predicted_covariance,
|
|
52
|
+
predicted_variance,
|
|
53
|
+
predicted_variance_derivative,
|
|
54
|
+
time_average_floor,
|
|
55
|
+
vacf_direct,
|
|
56
|
+
vacf_ensemble,
|
|
57
|
+
vacf_time_average,
|
|
58
|
+
)
|
|
59
|
+
from .propagate import Trajectory, acceleration, gle_residual, initial_position, position, random_force, velocity
|
|
60
|
+
from .sample import ModeState, default_chunk, iter_sample_modes, sample_modes, sample_state
|
|
61
|
+
from .system import InversionData, System
|
|
62
|
+
|
|
63
|
+
__version__ = "0.4.0"
|
|
64
|
+
|
|
65
|
+
sampled_vacf = vacf_ensemble
|
|
66
|
+
"""Alias: ``kac_zwanzig.sampled_vacf(system, t, n_traj, rng)`` is :func:`vacf_ensemble`."""
|
|
67
|
+
|
|
68
|
+
__all__ = [
|
|
69
|
+
# baths
|
|
70
|
+
"Bath", "ohmic", "debye", "debye_vacf_continuum", "bath_from_spectral_density", "cos_sum", "sin_sum",
|
|
71
|
+
# particle + bath
|
|
72
|
+
"System", "InversionData",
|
|
73
|
+
# sampling and propagation
|
|
74
|
+
"sample_modes", "sample_state", "ModeState", "iter_sample_modes", "default_chunk",
|
|
75
|
+
"velocity", "acceleration", "position", "initial_position", "random_force", "gle_residual", "Trajectory",
|
|
76
|
+
# estimators
|
|
77
|
+
"VACFEstimate", "BootstrapResult", "vacf_ensemble", "sampled_vacf", "vacf_direct",
|
|
78
|
+
"vacf_time_average", "time_average_floor",
|
|
79
|
+
"finite_difference", "fd_weights", "predicted_variance", "predicted_covariance", "predicted_variance_derivative",
|
|
80
|
+
"__version__",
|
|
81
|
+
]
|
kac_zwanzig/bath.py
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
"""Harmonic baths for the Kac-Zwanzig model: spectral densities, frequency grids, kernels.
|
|
2
|
+
|
|
3
|
+
Overview
|
|
4
|
+
--------
|
|
5
|
+
A bath is two arrays: frequencies ``omega_j`` (ascending) and *kernel weights*
|
|
6
|
+
``k_j = c_j**2 / (m_j * omega_j**2) >= 0``. Bath masses are set to one without loss of
|
|
7
|
+
generality (they only rescale the bath coordinates). Everything the particle ever feels
|
|
8
|
+
is the memory kernel
|
|
9
|
+
|
|
10
|
+
K_N(t) = sum_j k_j cos(omega_j t), (exact for the finite bath)
|
|
11
|
+
|
|
12
|
+
whose continuum counterpart is the cosine transform of the spectral density,
|
|
13
|
+
|
|
14
|
+
K_inf(t) = (2/pi) int_0^inf J(w)/w cos(w t) dw, J(w) = (pi/2) sum_j k_j w_j delta(w - w_j)
|
|
15
|
+
|
|
16
|
+
(Caldeira-Leggett convention: strictly Ohmic ``J = eta w`` gives friction exactly ``eta``).
|
|
17
|
+
|
|
18
|
+
Three ways to build a bath:
|
|
19
|
+
|
|
20
|
+
* presets :func:`ohmic` and :func:`debye` (closed-form grids and continuum kernels),
|
|
21
|
+
* any callable ``J(omega)`` through :meth:`Bath.from_spectral_density` (numerical quantiles),
|
|
22
|
+
* arbitrary arrays through :class:`Bath` itself.
|
|
23
|
+
|
|
24
|
+
Grids
|
|
25
|
+
-----
|
|
26
|
+
``"uniform"``
|
|
27
|
+
midpoints ``w_j = (j - 1/2) dw`` on ``[0, omega_max]``, weights ``k_j = (2/pi) J(w_j)/w_j dw``.
|
|
28
|
+
A midpoint rule for the cosine transform. By Poisson summation the error is a sum of
|
|
29
|
+
smooth, alternating-sign images of the kernel, ``K_N - K_inf = sum_{m != 0} (-1)^m
|
|
30
|
+
K_inf(t - 2 pi m/dw)``, about ``2 K_inf(2 pi/dw)`` in the window ``t < pi/dw``.
|
|
31
|
+
Second order in ``dw`` when ``J/w`` has a kink at ``w = 0`` (Ohmic), spectral when it is
|
|
32
|
+
analytic (Debye). Use midpoints: the endpoint grid ``w_j = j dw`` carries a constant
|
|
33
|
+
bias ``dw * J'(0)/pi``.
|
|
34
|
+
``"invcdf"``
|
|
35
|
+
quantiles of the density ``rho(w) ~ J(w)/w`` with equal weights ``k_j = K(0)/N``.
|
|
36
|
+
No truncation and ``K(0)`` exact, but the highest few modes have scrambled phases and
|
|
37
|
+
leave a high-frequency ripple in ``K_N`` that decays only like ``N**-1`` (Ohmic) or
|
|
38
|
+
``N**-3/4`` (Debye). This is the grid of the "Discrete Oscillators" notebook.
|
|
39
|
+
|
|
40
|
+
See ``notes/frequency_grids.pdf`` for derivations and measurements.
|
|
41
|
+
"""
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
from collections.abc import Callable
|
|
45
|
+
from dataclasses import dataclass, field
|
|
46
|
+
from typing import Optional
|
|
47
|
+
|
|
48
|
+
import numpy as np
|
|
49
|
+
|
|
50
|
+
_T_CHUNK = 512
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def cos_sum(weights: np.ndarray, freqs: np.ndarray, t, chunk: int = _T_CHUNK) -> np.ndarray:
|
|
54
|
+
"""Evaluate ``sum_j weights_j cos(freqs_j t)`` for every ``t`` (any shape), chunked over ``t``."""
|
|
55
|
+
t = np.asarray(t, dtype=float)
|
|
56
|
+
flat = t.ravel()
|
|
57
|
+
out = np.empty(flat.size)
|
|
58
|
+
for s in range(0, flat.size, chunk):
|
|
59
|
+
out[s:s + chunk] = np.cos(np.multiply.outer(flat[s:s + chunk], freqs)) @ weights
|
|
60
|
+
return out.reshape(t.shape)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def sin_sum(weights: np.ndarray, freqs: np.ndarray, t, chunk: int = _T_CHUNK) -> np.ndarray:
|
|
64
|
+
"""Evaluate ``sum_j weights_j sin(freqs_j t)`` for every ``t`` (any shape), chunked over ``t``."""
|
|
65
|
+
t = np.asarray(t, dtype=float)
|
|
66
|
+
flat = t.ravel()
|
|
67
|
+
out = np.empty(flat.size)
|
|
68
|
+
for s in range(0, flat.size, chunk):
|
|
69
|
+
out[s:s + chunk] = np.sin(np.multiply.outer(flat[s:s + chunk], freqs)) @ weights
|
|
70
|
+
return out.reshape(t.shape)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _uniform_grid(N: int, omega_max: float, midpoint: bool = True):
|
|
74
|
+
dw = omega_max / N
|
|
75
|
+
j = np.arange(1, N + 1, dtype=float)
|
|
76
|
+
omega = (j - 0.5) * dw if midpoint else j * dw
|
|
77
|
+
return omega, dw
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class Bath:
|
|
82
|
+
"""A discrete harmonic bath.
|
|
83
|
+
|
|
84
|
+
Parameters
|
|
85
|
+
----------
|
|
86
|
+
omega : array_like, shape (N,)
|
|
87
|
+
Oscillator frequencies, positive and distinct (sorted on construction).
|
|
88
|
+
k : array_like, shape (N,)
|
|
89
|
+
Kernel weights ``k_j = c_j**2/(m_j omega_j**2) >= 0``. ``K_N(t) = sum_j k_j cos(omega_j t)``.
|
|
90
|
+
name : str, optional
|
|
91
|
+
Label used by :meth:`describe`.
|
|
92
|
+
params : dict, optional
|
|
93
|
+
Parameters the bath was built from (recorded for provenance only).
|
|
94
|
+
kernel_continuum : callable, optional
|
|
95
|
+
``K_inf(t)`` of the underlying continuum, if known.
|
|
96
|
+
spectral_density_continuum : callable, optional
|
|
97
|
+
``J(omega)`` of the underlying continuum, if known.
|
|
98
|
+
|
|
99
|
+
Attributes
|
|
100
|
+
----------
|
|
101
|
+
N : int
|
|
102
|
+
Number of oscillators.
|
|
103
|
+
K0 : float
|
|
104
|
+
``K_N(0) = sum_j k_j``, the total counter-term stiffness.
|
|
105
|
+
|
|
106
|
+
Examples
|
|
107
|
+
--------
|
|
108
|
+
>>> import numpy as np
|
|
109
|
+
>>> import kac_zwanzig as kz
|
|
110
|
+
>>> b = kz.Bath(omega=[0.5, 1.0, 2.0], k=[0.2, 0.3, 0.1])
|
|
111
|
+
>>> float(b.kernel(0.0)), b.N
|
|
112
|
+
(0.6, 3)
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
omega: np.ndarray
|
|
116
|
+
k: np.ndarray
|
|
117
|
+
name: str = "custom"
|
|
118
|
+
params: dict = field(default_factory=dict)
|
|
119
|
+
kernel_continuum: Optional[Callable] = None
|
|
120
|
+
spectral_density_continuum: Optional[Callable] = None
|
|
121
|
+
|
|
122
|
+
def __post_init__(self):
|
|
123
|
+
omega = np.array(self.omega, dtype=float, copy=True).ravel()
|
|
124
|
+
k = np.array(self.k, dtype=float, copy=True).ravel()
|
|
125
|
+
if omega.shape != k.shape:
|
|
126
|
+
raise ValueError("omega and k must have the same shape")
|
|
127
|
+
if np.any(omega <= 0):
|
|
128
|
+
raise ValueError("all bath frequencies must be positive")
|
|
129
|
+
if np.any(k < 0):
|
|
130
|
+
raise ValueError("kernel weights must be non-negative")
|
|
131
|
+
order = np.argsort(omega, kind="stable")
|
|
132
|
+
omega, k = omega[order], k[order]
|
|
133
|
+
if np.any(np.diff(omega) <= 0):
|
|
134
|
+
raise ValueError("bath frequencies must be distinct")
|
|
135
|
+
object.__setattr__(self, "omega", omega)
|
|
136
|
+
object.__setattr__(self, "k", k)
|
|
137
|
+
|
|
138
|
+
# ------------------------------------------------------------------ construction
|
|
139
|
+
@classmethod
|
|
140
|
+
def from_spectral_density(cls, J: Callable, N: int = 2000, grid: str = "uniform",
|
|
141
|
+
omega_max: Optional[float] = None, name: str = "custom",
|
|
142
|
+
n_quad: int = 200_000, params: Optional[dict] = None) -> Bath:
|
|
143
|
+
"""Discretize an arbitrary continuum spectral density ``J(omega)``.
|
|
144
|
+
|
|
145
|
+
Parameters
|
|
146
|
+
----------
|
|
147
|
+
J : callable
|
|
148
|
+
Vectorized ``J(omega)`` for ``omega > 0``. Must vanish at least linearly at
|
|
149
|
+
``omega -> 0`` so that ``J(omega)/omega`` is integrable there.
|
|
150
|
+
N : int
|
|
151
|
+
Number of oscillators.
|
|
152
|
+
grid : {"uniform", "invcdf"}
|
|
153
|
+
See the module docstring.
|
|
154
|
+
omega_max : float
|
|
155
|
+
Upper limit of the uniform grid, or of the numerical cumulative integral used to
|
|
156
|
+
place the ``"invcdf"`` nodes and to evaluate :meth:`kernel_continuum`. Choose it
|
|
157
|
+
where ``J(omega)/omega`` is negligible.
|
|
158
|
+
n_quad : int
|
|
159
|
+
Points of the linear quadrature grid on ``(0, omega_max]`` used for the
|
|
160
|
+
cumulative integral and for the numerical continuum kernel.
|
|
161
|
+
|
|
162
|
+
Returns
|
|
163
|
+
-------
|
|
164
|
+
Bath
|
|
165
|
+
With :meth:`kernel_continuum` evaluated by quadrature on the same grid (accurate
|
|
166
|
+
while ``omega_max * t / n_quad`` stays small, i.e. for ``t`` up to a few hundred
|
|
167
|
+
in units of ``1/omega_max`` times ``n_quad``).
|
|
168
|
+
|
|
169
|
+
Notes
|
|
170
|
+
-----
|
|
171
|
+
The presets :func:`ohmic` and :func:`debye` use closed-form grids and kernels and
|
|
172
|
+
should be preferred when they apply. This constructor reproduces them to quadrature
|
|
173
|
+
accuracy; it exists so that any ``J`` (super-Ohmic, structured, tabulated) can be
|
|
174
|
+
used with the same downstream machinery.
|
|
175
|
+
|
|
176
|
+
Examples
|
|
177
|
+
--------
|
|
178
|
+
>>> import numpy as np
|
|
179
|
+
>>> import kac_zwanzig as kz
|
|
180
|
+
>>> J = lambda w: 0.5 * w**3 * np.exp(-w) # super-Ohmic
|
|
181
|
+
>>> b = kz.Bath.from_spectral_density(J, N=500, omega_max=30)
|
|
182
|
+
>>> round(float(b.K0), 4) # (2/pi) * 0.5 * int w^2 e^{-w} dw = 2/pi
|
|
183
|
+
0.6366
|
|
184
|
+
"""
|
|
185
|
+
if omega_max is None:
|
|
186
|
+
raise ValueError("omega_max is required (the uniform grid's cutoff, or the range of the numerical CDF)")
|
|
187
|
+
if grid not in ("uniform", "invcdf"):
|
|
188
|
+
raise ValueError(f"unknown grid {grid!r}; use 'uniform' or 'invcdf'")
|
|
189
|
+
|
|
190
|
+
def f(w):
|
|
191
|
+
w = np.asarray(w, dtype=float)
|
|
192
|
+
return (2.0 / np.pi) * np.asarray(J(w), dtype=float) / w
|
|
193
|
+
|
|
194
|
+
wq = np.linspace(0.0, omega_max, n_quad + 1)[1:]
|
|
195
|
+
fq = f(wq)
|
|
196
|
+
dq = wq[1] - wq[0]
|
|
197
|
+
# cumulative integral from 0, taking f flat on the first sliver (0, wq[0])
|
|
198
|
+
F = np.empty(n_quad + 1)
|
|
199
|
+
F[0] = 0.0
|
|
200
|
+
F[1:] = fq[0] * wq[0] + np.concatenate([[0.0], np.cumsum(0.5 * (fq[1:] + fq[:-1]) * dq)])
|
|
201
|
+
wgrid = np.concatenate([[0.0], wq])
|
|
202
|
+
K0 = float(F[-1])
|
|
203
|
+
|
|
204
|
+
if grid == "uniform":
|
|
205
|
+
omega, dw = _uniform_grid(N, omega_max, True)
|
|
206
|
+
k = f(omega) * dw
|
|
207
|
+
else:
|
|
208
|
+
u = (np.arange(1, N + 1, dtype=float) - 0.5) / N
|
|
209
|
+
omega = np.interp(u * K0, F, wgrid)
|
|
210
|
+
k = np.full(N, K0 / N)
|
|
211
|
+
|
|
212
|
+
wts = np.full(n_quad, dq) # trapezoid on [wq[0], omega_max] ...
|
|
213
|
+
wts[0] = 0.5 * dq + wq[0] # ... plus the first sliver (0, wq[0]) with f taken flat
|
|
214
|
+
wts[-1] = 0.5 * dq
|
|
215
|
+
fw = fq * wts
|
|
216
|
+
|
|
217
|
+
def K_inf(t, _chunk=32):
|
|
218
|
+
t = np.asarray(t, dtype=float)
|
|
219
|
+
flat = t.ravel()
|
|
220
|
+
out = np.empty(flat.size)
|
|
221
|
+
for s in range(0, flat.size, _chunk):
|
|
222
|
+
out[s:s + _chunk] = np.cos(np.multiply.outer(flat[s:s + _chunk], wq)) @ fw
|
|
223
|
+
return out.reshape(t.shape)
|
|
224
|
+
|
|
225
|
+
p = dict(params or {}, N=N, grid=grid, omega_max=omega_max, n_quad=n_quad)
|
|
226
|
+
return cls(omega, k, name, p, K_inf, lambda w: np.asarray(J(w), dtype=float))
|
|
227
|
+
|
|
228
|
+
# ------------------------------------------------------------------ basic quantities
|
|
229
|
+
@property
|
|
230
|
+
def N(self) -> int:
|
|
231
|
+
return self.omega.size
|
|
232
|
+
|
|
233
|
+
@property
|
|
234
|
+
def K0(self) -> float:
|
|
235
|
+
"""``K_N(0) = sum_j k_j``: total counter-term stiffness; ``2 x`` the reorganization energy."""
|
|
236
|
+
return float(self.k.sum())
|
|
237
|
+
|
|
238
|
+
@property
|
|
239
|
+
def omega_max(self) -> float:
|
|
240
|
+
return float(self.omega[-1])
|
|
241
|
+
|
|
242
|
+
def kernel(self, t) -> np.ndarray:
|
|
243
|
+
"""Exact finite-bath memory kernel ``K_N(t) = sum_j k_j cos(omega_j t)``.
|
|
244
|
+
|
|
245
|
+
Parameters
|
|
246
|
+
----------
|
|
247
|
+
t : array_like
|
|
248
|
+
Times, any shape.
|
|
249
|
+
|
|
250
|
+
Returns
|
|
251
|
+
-------
|
|
252
|
+
ndarray
|
|
253
|
+
Same shape as ``t``. This is the exact friction kernel of the finite bath, the
|
|
254
|
+
one multiplying ``v`` in the equation of motion (units of mass/time^2); the
|
|
255
|
+
memory kernel per unit mass is ``System.memory_kernel(t) = (K_N(t) + M Omega^2)/M``.
|
|
256
|
+
"""
|
|
257
|
+
return cos_sum(self.k, self.omega, t)
|
|
258
|
+
|
|
259
|
+
def kernel_dot(self, t) -> np.ndarray:
|
|
260
|
+
"""``dK_N/dt = -sum_j k_j omega_j sin(omega_j t)``."""
|
|
261
|
+
return -sin_sum(self.k * self.omega, self.omega, t)
|
|
262
|
+
|
|
263
|
+
def kernel_integral(self, t) -> np.ndarray:
|
|
264
|
+
"""``int_0^t K_N(s) ds = sum_j (k_j/omega_j) sin(omega_j t)`` (the running friction)."""
|
|
265
|
+
return sin_sum(self.k / self.omega, self.omega, t)
|
|
266
|
+
|
|
267
|
+
def J(self, omega) -> np.ndarray:
|
|
268
|
+
"""Continuum spectral density ``J(omega)`` the bath was built from (raises if unknown)."""
|
|
269
|
+
if self.spectral_density_continuum is None:
|
|
270
|
+
raise ValueError("this bath has no continuum spectral density attached")
|
|
271
|
+
return self.spectral_density_continuum(np.asarray(omega, dtype=float))
|
|
272
|
+
|
|
273
|
+
def spectral_density_histogram(self, bins=60) -> tuple[np.ndarray, np.ndarray]:
|
|
274
|
+
"""Histogram estimate of ``J(omega)`` from the discrete bath, for plotting.
|
|
275
|
+
|
|
276
|
+
The discrete ``J`` is a sum of deltas, ``(pi/2) sum_j k_j omega_j delta(omega - omega_j)``;
|
|
277
|
+
binning that weight and dividing by the bin width gives a density comparable to the
|
|
278
|
+
continuum ``J``.
|
|
279
|
+
|
|
280
|
+
Parameters
|
|
281
|
+
----------
|
|
282
|
+
bins : int or array_like
|
|
283
|
+
Number of equal bins on ``[0, omega_max]`` or explicit bin edges.
|
|
284
|
+
|
|
285
|
+
Returns
|
|
286
|
+
-------
|
|
287
|
+
centers, values : ndarray
|
|
288
|
+
Bin centers and the binned spectral density.
|
|
289
|
+
"""
|
|
290
|
+
edges = np.linspace(0.0, self.omega_max, int(bins) + 1) if np.isscalar(bins) else np.asarray(bins, dtype=float)
|
|
291
|
+
hist, _ = np.histogram(self.omega, bins=edges, weights=0.5 * np.pi * self.k * self.omega)
|
|
292
|
+
return 0.5 * (edges[1:] + edges[:-1]), hist / np.diff(edges)
|
|
293
|
+
|
|
294
|
+
def describe(self) -> str:
|
|
295
|
+
p = ", ".join(f"{a}={b}" for a, b in self.params.items())
|
|
296
|
+
return (f"{self.name} bath, N={self.N}, K0={self.K0:.6g}, "
|
|
297
|
+
f"omega in [{self.omega[0]:.3g}, {self.omega_max:.3g}] ({p})")
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
# ---------------------------------------------------------------------- shared helper
|
|
301
|
+
|
|
302
|
+
def bath_from_spectral_density(J: Callable, K0: float, quantile: Callable, N: int, grid: str,
|
|
303
|
+
omega_max: Optional[float], midpoint: bool = True):
|
|
304
|
+
"""Build ``(omega, k)`` for a continuum ``J`` with a *known* closed-form quantile function.
|
|
305
|
+
|
|
306
|
+
Used by the presets. ``quantile(u)`` returns the frequency below which the fraction
|
|
307
|
+
``u`` of the density ``rho(w) ~ J(w)/w`` lies (either tail convention works, the
|
|
308
|
+
midpoints are symmetric). For arbitrary ``J`` use :meth:`Bath.from_spectral_density`.
|
|
309
|
+
"""
|
|
310
|
+
if grid == "uniform":
|
|
311
|
+
if omega_max is None:
|
|
312
|
+
raise ValueError("omega_max is required for the uniform grid")
|
|
313
|
+
omega, dw = _uniform_grid(N, omega_max, midpoint)
|
|
314
|
+
k = (2.0 / np.pi) * J(omega) / omega * dw
|
|
315
|
+
elif grid == "invcdf":
|
|
316
|
+
u = (np.arange(1, N + 1, dtype=float) - 0.5) / N
|
|
317
|
+
omega = np.sort(quantile(u))
|
|
318
|
+
k = np.full(N, K0 / N)
|
|
319
|
+
else:
|
|
320
|
+
raise ValueError(f"unknown grid {grid!r}; use 'uniform' or 'invcdf'")
|
|
321
|
+
return omega, k
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
# ---------------------------------------------------------------------- presets
|
|
325
|
+
|
|
326
|
+
def ohmic(eta: float = 1.0, omega_c: float = 1.0, N: int = 2000, grid: str = "uniform",
|
|
327
|
+
omega_max: Optional[float] = None, midpoint: bool = True) -> Bath:
|
|
328
|
+
"""Ohmic bath with exponential cutoff, ``J(omega) = eta * omega * exp(-omega/omega_c)``.
|
|
329
|
+
|
|
330
|
+
Parameters
|
|
331
|
+
----------
|
|
332
|
+
eta : float
|
|
333
|
+
Friction coefficient: ``int_0^inf K_inf dt = eta``.
|
|
334
|
+
omega_c : float
|
|
335
|
+
Cutoff frequency; the kernel decays on the time scale ``1/omega_c``.
|
|
336
|
+
N : int
|
|
337
|
+
Number of oscillators.
|
|
338
|
+
grid : {"uniform", "invcdf"}
|
|
339
|
+
``"uniform"`` (recommended) or the notebook's inverse-CDF grid
|
|
340
|
+
``omega_j = -omega_c ln((j - 1/2)/N)`` with equal weights.
|
|
341
|
+
omega_max : float, optional
|
|
342
|
+
Cutoff of the uniform grid; default ``25 omega_c`` (``e^-25 ~ 1e-11``).
|
|
343
|
+
midpoint : bool
|
|
344
|
+
Midpoint (default) or endpoint placement on the uniform grid. Keep ``True``.
|
|
345
|
+
|
|
346
|
+
Returns
|
|
347
|
+
-------
|
|
348
|
+
Bath
|
|
349
|
+
With ``kernel_continuum(t) = (2 eta omega_c/pi) / (1 + (omega_c t)**2)`` and
|
|
350
|
+
``K0 = 2 eta omega_c/pi`` (up to the midpoint-rule error ``~dw**2/24``).
|
|
351
|
+
|
|
352
|
+
Notes
|
|
353
|
+
-----
|
|
354
|
+
For the free particle the normalized VACF depends on ``eta``, ``M`` and ``omega_c`` only
|
|
355
|
+
through ``eta/(M omega_c)``; ``omega_c`` otherwise just sets the unit of time. In units
|
|
356
|
+
``M = omega_c = 1``: ``eta = 1`` gives a single shallow negative dip (MD-like),
|
|
357
|
+
``eta = 5`` a clearly caged oscillation, ``eta = 20`` many oscillations.
|
|
358
|
+
|
|
359
|
+
Examples
|
|
360
|
+
--------
|
|
361
|
+
>>> import kac_zwanzig as kz
|
|
362
|
+
>>> b = kz.ohmic(eta=1.0, N=2000)
|
|
363
|
+
>>> round(b.K0, 4), b.N, round(b.omega_max, 3)
|
|
364
|
+
(0.6366, 2000, 24.994)
|
|
365
|
+
"""
|
|
366
|
+
if omega_max is None and grid == "uniform":
|
|
367
|
+
omega_max = 25.0 * omega_c
|
|
368
|
+
K0 = 2.0 * eta * omega_c / np.pi
|
|
369
|
+
|
|
370
|
+
def J(w):
|
|
371
|
+
w = np.asarray(w, dtype=float)
|
|
372
|
+
return eta * w * np.exp(-w / omega_c)
|
|
373
|
+
|
|
374
|
+
def quantile(u):
|
|
375
|
+
return -omega_c * np.log(u)
|
|
376
|
+
|
|
377
|
+
def K_inf(t):
|
|
378
|
+
t = np.asarray(t, dtype=float)
|
|
379
|
+
return K0 / (1.0 + (omega_c * t) ** 2)
|
|
380
|
+
|
|
381
|
+
omega, k = bath_from_spectral_density(J, K0, quantile, N, grid, omega_max, midpoint)
|
|
382
|
+
params = dict(eta=eta, omega_c=omega_c, N=N, grid=grid, omega_max=omega_max, midpoint=midpoint)
|
|
383
|
+
return Bath(omega, k, "ohmic", params, K_inf, J)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def debye(lmbda: float = 1.0, omega_c: float = 1.0, N: int = 2000, grid: str = "invcdf",
|
|
387
|
+
omega_max: Optional[float] = None, midpoint: bool = True) -> Bath:
|
|
388
|
+
"""Debye bath, ``J(omega) = 2 lmbda omega_c omega / (omega_c**2 + omega**2)``.
|
|
389
|
+
|
|
390
|
+
Parameters
|
|
391
|
+
----------
|
|
392
|
+
lmbda : float
|
|
393
|
+
Reorganization energy ``(1/pi) int J/omega domega``; ``K0 = 2 lmbda``.
|
|
394
|
+
omega_c : float
|
|
395
|
+
Kernel decay rate: ``K_inf(t) = 2 lmbda exp(-omega_c t)``.
|
|
396
|
+
N : int
|
|
397
|
+
Number of oscillators.
|
|
398
|
+
grid : {"invcdf", "uniform"}
|
|
399
|
+
``"invcdf"`` (default) is the notebook's tan grid ``omega_c tan(pi (j-1/2)/(2N))``:
|
|
400
|
+
no truncation and ``K0`` exact, but a kernel ripple of a few ``1e-3`` at ``N = 4000``.
|
|
401
|
+
``"uniform"`` with a large ``omega_max`` is much smoother for ``t > 1/omega_max`` but
|
|
402
|
+
misses ``(2/pi) K0 arctan(omega_c/omega_max)`` of ``K0`` at the cusp.
|
|
403
|
+
omega_max : float, optional
|
|
404
|
+
Cutoff of the uniform grid; default ``100 omega_c``.
|
|
405
|
+
|
|
406
|
+
Returns
|
|
407
|
+
-------
|
|
408
|
+
Bath
|
|
409
|
+
|
|
410
|
+
Notes
|
|
411
|
+
-----
|
|
412
|
+
The continuum VACF of a free particle in this bath is closed-form, see
|
|
413
|
+
:func:`debye_vacf_continuum`; the dimensionless control parameter is ``lmbda/(M omega_c**2)``
|
|
414
|
+
with critical damping at ``1/8``.
|
|
415
|
+
"""
|
|
416
|
+
if omega_max is None and grid == "uniform":
|
|
417
|
+
omega_max = 100.0 * omega_c
|
|
418
|
+
K0 = 2.0 * lmbda
|
|
419
|
+
|
|
420
|
+
def J(w):
|
|
421
|
+
w = np.asarray(w, dtype=float)
|
|
422
|
+
return 2.0 * lmbda * omega_c * w / (omega_c ** 2 + w ** 2)
|
|
423
|
+
|
|
424
|
+
def quantile(u):
|
|
425
|
+
return omega_c * np.tan(0.5 * np.pi * u)
|
|
426
|
+
|
|
427
|
+
def K_inf(t):
|
|
428
|
+
t = np.asarray(t, dtype=float)
|
|
429
|
+
return K0 * np.exp(-omega_c * t)
|
|
430
|
+
|
|
431
|
+
omega, k = bath_from_spectral_density(J, K0, quantile, N, grid, omega_max, midpoint)
|
|
432
|
+
params = dict(lmbda=lmbda, omega_c=omega_c, N=N, grid=grid, omega_max=omega_max, midpoint=midpoint)
|
|
433
|
+
return Bath(omega, k, "debye", params, K_inf, J)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def debye_vacf_continuum(t, lmbda: float = 1.0, omega_c: float = 1.0, M: float = 1.0) -> np.ndarray:
|
|
437
|
+
"""Closed-form continuum velocity autocorrelation of a free particle in a Debye bath.
|
|
438
|
+
|
|
439
|
+
From ``C~(s) = 1/(s + K~(s)/M)`` with ``K~(s) = 2 lmbda/(s + omega_c)``:
|
|
440
|
+
``C~(s) = (s + omega_c)/(s**2 + omega_c s + 2 lmbda/M)``, two exponentials with
|
|
441
|
+
``s_pm = (-omega_c pm sqrt(omega_c**2 - 8 lmbda/M))/2`` (complex when underdamped).
|
|
442
|
+
|
|
443
|
+
Parameters
|
|
444
|
+
----------
|
|
445
|
+
t : array_like
|
|
446
|
+
lmbda, omega_c, M : float
|
|
447
|
+
|
|
448
|
+
Returns
|
|
449
|
+
-------
|
|
450
|
+
ndarray
|
|
451
|
+
Normalized ``C(t)``, ``C(0) = 1``.
|
|
452
|
+
"""
|
|
453
|
+
t = np.asarray(t, dtype=float)
|
|
454
|
+
disc = omega_c ** 2 - 8.0 * lmbda / M
|
|
455
|
+
if abs(disc) < 1e-14 * omega_c ** 2: # critically damped double root
|
|
456
|
+
return np.exp(-0.5 * omega_c * t) * (1.0 + 0.5 * omega_c * t)
|
|
457
|
+
r = np.sqrt(disc + 0j)
|
|
458
|
+
sp, sm = (-omega_c + r) / 2, (-omega_c - r) / 2
|
|
459
|
+
C = ((sp + omega_c) * np.exp(sp * t) - (sm + omega_c) * np.exp(sm * t)) / (sp - sm)
|
|
460
|
+
return C.real
|