lfox 0.0.1__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.
- lfox/__about__.py +12 -0
- lfox/__init__.py +6 -0
- lfox/action.py +131 -0
- lfox/evolution/__init__.py +18 -0
- lfox/evolution/base.py +199 -0
- lfox/evolution/hmc.py +107 -0
- lfox/evolution/integrators.py +91 -0
- lfox/fermions/__init__.py +8 -0
- lfox/fermions/solver.py +34 -0
- lfox/fermions/spin.py +111 -0
- lfox/fermions/wilson.py +43 -0
- lfox/lattice.py +204 -0
- lfox-0.0.1.dist-info/METADATA +167 -0
- lfox-0.0.1.dist-info/RECORD +16 -0
- lfox-0.0.1.dist-info/WHEEL +4 -0
- lfox-0.0.1.dist-info/licenses/LICENSE.txt +9 -0
lfox/__about__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present Ethan Neil <ethan.neil@colorado.edu>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
# The version lives in pyproject.toml and is read back out of the installed
|
|
6
|
+
# distribution metadata, so there is exactly one place to bump it.
|
|
7
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
__version__ = version("lfox")
|
|
11
|
+
except PackageNotFoundError: # running from a source tree without an install
|
|
12
|
+
__version__ = "0.0.0+unknown"
|
lfox/__init__.py
ADDED
lfox/action.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import dataclasses
|
|
3
|
+
from abc import abstractmethod
|
|
4
|
+
|
|
5
|
+
import equinox as eqx
|
|
6
|
+
import jax
|
|
7
|
+
import jax.numpy as jnp
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Action(eqx.Module):
|
|
11
|
+
# An action needs the following to be created:
|
|
12
|
+
# - An ordered list of lattice field names
|
|
13
|
+
# - [optional] A dictionary of non-field parameters the action depends on (e.g. couplings)
|
|
14
|
+
# - [optional] A list of "sub_actions", which will be added in whenever S or S_field is computed
|
|
15
|
+
|
|
16
|
+
# Although most functions of fields use dictionaries in lfox, we use lists in action definitions.
|
|
17
|
+
# This is to make "aliasing" easy - defining copies of the action with different field names,
|
|
18
|
+
# for example to create a many-flavor fermion action.
|
|
19
|
+
|
|
20
|
+
# There is a single abstract method in this class, the action functional _S. This
|
|
21
|
+
# functional should depend on the fields and the parameters, and must be implemented
|
|
22
|
+
# by any inheriting subclass as a STATIC method. It should have signature:
|
|
23
|
+
# @staticmethod
|
|
24
|
+
# def _S(fields, params):
|
|
25
|
+
# (...)
|
|
26
|
+
#
|
|
27
|
+
# where `fields` is a list of fields. The functions S(self, fields) and S_field(self, fields)
|
|
28
|
+
# take dictionaries of fields, mapping them to lists for _S(fields, params) using
|
|
29
|
+
# Action.field_names.
|
|
30
|
+
|
|
31
|
+
# JIT compilation of the action is HIGHLY RECOMMENDED! This can be done simply
|
|
32
|
+
# by adding the jax.jit decorator, i.e.
|
|
33
|
+
#
|
|
34
|
+
# @staticmethod
|
|
35
|
+
# @jax.jit
|
|
36
|
+
# def _S(fields, params):
|
|
37
|
+
# (...)
|
|
38
|
+
#
|
|
39
|
+
# (Note that the order of decorators is important, don't swap them!)
|
|
40
|
+
|
|
41
|
+
# Actions can be created by combining two actions together using += or +.
|
|
42
|
+
# This uses the sub_actions parameter.
|
|
43
|
+
|
|
44
|
+
field_names: list = eqx.field(static=True)
|
|
45
|
+
params: dict = eqx.field(static=True)
|
|
46
|
+
sub_actions: list
|
|
47
|
+
|
|
48
|
+
def __init__(self, field_names, params=None, sub_actions=None):
|
|
49
|
+
self.field_names = field_names
|
|
50
|
+
|
|
51
|
+
if params is None:
|
|
52
|
+
self.params = {}
|
|
53
|
+
else:
|
|
54
|
+
self.params = params
|
|
55
|
+
|
|
56
|
+
if sub_actions is None:
|
|
57
|
+
self.sub_actions = []
|
|
58
|
+
else:
|
|
59
|
+
self.sub_actions = sub_actions
|
|
60
|
+
|
|
61
|
+
# Action density functional; returns S as a LatticeField, i.e. not summed.
|
|
62
|
+
@jax.jit
|
|
63
|
+
def S_field(self, fields):
|
|
64
|
+
# Evaluate main action functional
|
|
65
|
+
field_call = [fields[fname] for fname in self.field_names]
|
|
66
|
+
|
|
67
|
+
S_tot = self._S(fields=field_call, params=self.params)
|
|
68
|
+
|
|
69
|
+
# Add action functionals for any subclasses
|
|
70
|
+
for action in self.sub_actions:
|
|
71
|
+
field_call = [fields[fname] for fname in action.field_names]
|
|
72
|
+
S_tot += action._S(fields=field_call, params=self.params)
|
|
73
|
+
|
|
74
|
+
return S_tot
|
|
75
|
+
|
|
76
|
+
# Total action
|
|
77
|
+
# Note that we DON'T have to be careful about extra indices here;
|
|
78
|
+
# the action density must already be a scalar per-site, so a simple
|
|
79
|
+
# jnp.sum is guaranteed to be a sum over the lattice sites.
|
|
80
|
+
@jax.jit
|
|
81
|
+
def S(self, fields):
|
|
82
|
+
S_density = self.S_field(fields)
|
|
83
|
+
return jnp.sum(S_density.F)
|
|
84
|
+
|
|
85
|
+
@jax.jit
|
|
86
|
+
def dS(self, fields):
|
|
87
|
+
return jax.grad(self.S)(fields)
|
|
88
|
+
|
|
89
|
+
@staticmethod
|
|
90
|
+
@abstractmethod
|
|
91
|
+
def _S(fields, params):
|
|
92
|
+
# This method interfaces to a function which can be JIT compiled and which is friendly
|
|
93
|
+
# to computing JAX gradients.
|
|
94
|
+
# Call signature (fields and params) MUST match the names
|
|
95
|
+
# in the dictionaries.
|
|
96
|
+
# This is meant to be maximally flexible; can always be overridden to be more efficient
|
|
97
|
+
# by a subclass.
|
|
98
|
+
pass
|
|
99
|
+
|
|
100
|
+
# Overload addition with composition
|
|
101
|
+
def __iadd__(self, other):
|
|
102
|
+
self.add_subaction(other)
|
|
103
|
+
return self
|
|
104
|
+
|
|
105
|
+
def __add__(self, other):
|
|
106
|
+
newAct = self.__copy__()
|
|
107
|
+
newAct.add_subaction(other)
|
|
108
|
+
|
|
109
|
+
return newAct
|
|
110
|
+
|
|
111
|
+
def __copy__(self):
|
|
112
|
+
new_subact = copy.deepcopy(self.sub_actions)
|
|
113
|
+
return dataclasses.replace(self, sub_actions=new_subact)
|
|
114
|
+
|
|
115
|
+
def copy(self):
|
|
116
|
+
return self.__copy__()
|
|
117
|
+
|
|
118
|
+
def add_subaction(self, other):
|
|
119
|
+
# Combine the parameters
|
|
120
|
+
# TODO: warn in case of collision, which will overwrite...
|
|
121
|
+
self.params.update(other.params)
|
|
122
|
+
|
|
123
|
+
# If there are subactions within the other field, promote them up to the current subaction list
|
|
124
|
+
if len(other.sub_actions) > 0:
|
|
125
|
+
for subact in other.sub_actions:
|
|
126
|
+
self.sub_actions.append(subact)
|
|
127
|
+
|
|
128
|
+
other.sub_actions = []
|
|
129
|
+
|
|
130
|
+
# Register the subaction
|
|
131
|
+
self.sub_actions.append(other)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from lfox.action import Action
|
|
2
|
+
from lfox.evolution.base import Chain, Evolver
|
|
3
|
+
from lfox.evolution.hmc import HMC
|
|
4
|
+
from lfox.evolution.integrators import (
|
|
5
|
+
LeapfrogIntegrator,
|
|
6
|
+
MDIntegrator,
|
|
7
|
+
OmelyanIntegrator,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Action",
|
|
12
|
+
"Chain",
|
|
13
|
+
"Evolver",
|
|
14
|
+
"HMC",
|
|
15
|
+
"LeapfrogIntegrator",
|
|
16
|
+
"MDIntegrator",
|
|
17
|
+
"OmelyanIntegrator",
|
|
18
|
+
]
|
lfox/evolution/base.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import math
|
|
2
|
+
from abc import abstractmethod
|
|
3
|
+
from functools import partial
|
|
4
|
+
|
|
5
|
+
import equinox as eqx
|
|
6
|
+
import jax
|
|
7
|
+
import numpy as np
|
|
8
|
+
from equinox import AbstractVar
|
|
9
|
+
|
|
10
|
+
from lfox.action import Action
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Evolver(eqx.Module):
|
|
14
|
+
# A Markov transition kernel: given a set of fields and an RNG key, produce a
|
|
15
|
+
# new set of fields that leaves the target distribution exp(-S) invariant.
|
|
16
|
+
#
|
|
17
|
+
# Evolvers are PURE. They carry only what is constant across the chain (the
|
|
18
|
+
# action, and whatever hyperparameters the algorithm needs). The evolving
|
|
19
|
+
# state -- the fields and the RNG key -- flows through `evolve` as arguments
|
|
20
|
+
# and back out as return values. This is what makes `evolve` jittable; do
|
|
21
|
+
# not add mutable state to an Evolver subclass.
|
|
22
|
+
#
|
|
23
|
+
# The chain-level bookkeeping that used to live here (seed, observables,
|
|
24
|
+
# field history, save frequency) belongs to `Chain`, which drives an Evolver
|
|
25
|
+
# from the host side.
|
|
26
|
+
#
|
|
27
|
+
# Subclasses implement a single method:
|
|
28
|
+
#
|
|
29
|
+
# evolve(fields, rng_key) -> (fields, monitor, rng_key)
|
|
30
|
+
#
|
|
31
|
+
# where `monitor` is a dict of per-step diagnostics. Its keys are up to the
|
|
32
|
+
# algorithm (HMC reports delta_H / P_acc / accept; a cluster update might
|
|
33
|
+
# report cluster size). Every value must be a JAX array so that
|
|
34
|
+
# `evolve_many` can stack them.
|
|
35
|
+
#
|
|
36
|
+
# This interface is deliberately thin. HMC, heatbath and cluster algorithms
|
|
37
|
+
# share almost nothing beyond it: HMC needs dS (free, via autodiff), while
|
|
38
|
+
# heatbath needs local conditional distributions and cluster updates need
|
|
39
|
+
# bond weights. Those requirements belong on the Action, not here.
|
|
40
|
+
|
|
41
|
+
action: AbstractVar[Action]
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def evolve(self, fields, rng_key):
|
|
45
|
+
# One Markov step. Returns (new_fields, monitor, new_rng_key).
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
def as_warmup(self):
|
|
49
|
+
# Return a variant of this kernel suitable for thermalization. The
|
|
50
|
+
# default is to change nothing; algorithms with an accept/reject step
|
|
51
|
+
# override this to skip it. A warmup kernel does NOT preserve the
|
|
52
|
+
# target distribution, so never measure on configurations it produced.
|
|
53
|
+
return self
|
|
54
|
+
|
|
55
|
+
@partial(jax.jit, static_argnums=(3,), static_argnames=("traj",))
|
|
56
|
+
def evolve_many(self, fields, rng_key, traj=1):
|
|
57
|
+
# Run `traj` steps inside a single lax.scan. scan stacks the per-step
|
|
58
|
+
# monitor pytree for us, so this works for any monitor layout without
|
|
59
|
+
# the base class needing to know the keys in advance.
|
|
60
|
+
|
|
61
|
+
def step(carry, _):
|
|
62
|
+
fields, rng_key = carry
|
|
63
|
+
fields, monitor, rng_key = self.evolve(fields, rng_key)
|
|
64
|
+
|
|
65
|
+
return (fields, rng_key), monitor
|
|
66
|
+
|
|
67
|
+
(fields, rng_key), monitor = jax.lax.scan(
|
|
68
|
+
step, (fields, rng_key), xs=None, length=traj
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
return fields, monitor, rng_key
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _normalize_observables(observables):
|
|
75
|
+
# Accept either {'name': fn} (measured every trajectory) or
|
|
76
|
+
# {'name': [fn, freq]}, and normalize to {'name': (fn, freq)}.
|
|
77
|
+
normalized = {}
|
|
78
|
+
for name, spec in (observables or {}).items():
|
|
79
|
+
if callable(spec):
|
|
80
|
+
normalized[name] = (spec, 1)
|
|
81
|
+
else:
|
|
82
|
+
obs_f, freq = spec
|
|
83
|
+
normalized[name] = (obs_f, int(freq))
|
|
84
|
+
|
|
85
|
+
return normalized
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class Chain:
|
|
89
|
+
# Host-side driver for an Evolver. Owns everything the transition kernel
|
|
90
|
+
# deliberately does not: the RNG key, the current fields, the Markov chain of
|
|
91
|
+
# saved configurations, per-step diagnostics, and observable measurements.
|
|
92
|
+
#
|
|
93
|
+
# This is an ordinary Python class, not an eqx.Module -- it is stateful and
|
|
94
|
+
# lives entirely outside any jit boundary. All the compiled work happens in
|
|
95
|
+
# `evolver.evolve_many`.
|
|
96
|
+
#
|
|
97
|
+
# chain = Chain(evolver=HMC(...), seed=42, init_fields={'phi': phi})
|
|
98
|
+
# chain.warmup(100)
|
|
99
|
+
# chain.run(500)
|
|
100
|
+
#
|
|
101
|
+
# `observables` maps a name to either a function f(fields, params) or a pair
|
|
102
|
+
# [f, freq] measuring every `freq` trajectories.
|
|
103
|
+
#
|
|
104
|
+
# Trajectory numbering counts production trajectories only; `warmup` advances
|
|
105
|
+
# `warmup_traj` instead and saves nothing.
|
|
106
|
+
|
|
107
|
+
def __init__(self, evolver, seed, init_fields, observables=None, save_freq=1):
|
|
108
|
+
self.evolver = evolver
|
|
109
|
+
self.seed = seed
|
|
110
|
+
self.rng_key = jax.random.PRNGKey(seed)
|
|
111
|
+
self.fields = dict(init_fields)
|
|
112
|
+
self.save_freq = save_freq
|
|
113
|
+
self.observables = _normalize_observables(observables)
|
|
114
|
+
|
|
115
|
+
# Every field must correspond to something in the action, and vice versa
|
|
116
|
+
field_names = set(evolver.action.field_names)
|
|
117
|
+
if set(self.fields) != field_names:
|
|
118
|
+
raise ValueError(
|
|
119
|
+
f"Field names {sorted(self.fields)} do not match the action's "
|
|
120
|
+
f"field names {sorted(field_names)}."
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
self.traj = 0
|
|
124
|
+
self.warmup_traj = 0
|
|
125
|
+
|
|
126
|
+
self.traj_chain = [0]
|
|
127
|
+
self.field_chain = {fname: [self.fields[fname]] for fname in self.fields}
|
|
128
|
+
|
|
129
|
+
self.monitor = {}
|
|
130
|
+
self.obs_chain = {name: [] for name in self.observables}
|
|
131
|
+
self.obs_traj = {name: [] for name in self.observables}
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def N_fields(self):
|
|
135
|
+
return len(self.fields)
|
|
136
|
+
|
|
137
|
+
def _block_size(self):
|
|
138
|
+
# Step in blocks large enough to keep the scan busy, but small enough
|
|
139
|
+
# that we never step over a trajectory at which something must be
|
|
140
|
+
# recorded. Every save/measurement frequency is a multiple of this.
|
|
141
|
+
block = self.save_freq
|
|
142
|
+
for _, freq in self.observables.values():
|
|
143
|
+
block = math.gcd(block, freq)
|
|
144
|
+
|
|
145
|
+
return max(block, 1)
|
|
146
|
+
|
|
147
|
+
def _record_monitor(self, monitor):
|
|
148
|
+
for key, vals in monitor.items():
|
|
149
|
+
self.monitor.setdefault(key, []).extend(np.asarray(vals).tolist())
|
|
150
|
+
|
|
151
|
+
def _record_step(self):
|
|
152
|
+
if self.traj % self.save_freq == 0:
|
|
153
|
+
for fname in self.fields:
|
|
154
|
+
self.field_chain[fname].append(self.fields[fname])
|
|
155
|
+
self.traj_chain.append(self.traj)
|
|
156
|
+
|
|
157
|
+
for name, (obs_f, freq) in self.observables.items():
|
|
158
|
+
if self.traj % freq == 0:
|
|
159
|
+
self.obs_chain[name].append(
|
|
160
|
+
obs_f(self.fields, self.evolver.action.params)
|
|
161
|
+
)
|
|
162
|
+
self.obs_traj[name].append(self.traj)
|
|
163
|
+
|
|
164
|
+
def warmup(self, ntraj):
|
|
165
|
+
# Thermalize. Diagnostics are recorded; configurations and observables
|
|
166
|
+
# are not, since a warmup kernel does not sample the target distribution.
|
|
167
|
+
evolver = self.evolver.as_warmup()
|
|
168
|
+
self.fields, monitor, self.rng_key = evolver.evolve_many(
|
|
169
|
+
self.fields, self.rng_key, ntraj
|
|
170
|
+
)
|
|
171
|
+
self.warmup_traj += ntraj
|
|
172
|
+
self._record_monitor(monitor)
|
|
173
|
+
|
|
174
|
+
return self
|
|
175
|
+
|
|
176
|
+
def run(self, ntraj):
|
|
177
|
+
block = self._block_size()
|
|
178
|
+
if ntraj % block != 0:
|
|
179
|
+
raise ValueError(
|
|
180
|
+
f"ntraj={ntraj} must be a multiple of {block}, the greatest common "
|
|
181
|
+
f"divisor of save_freq and the observable frequencies."
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
for _ in range(ntraj // block):
|
|
185
|
+
self.fields, monitor, self.rng_key = self.evolver.evolve_many(
|
|
186
|
+
self.fields, self.rng_key, block
|
|
187
|
+
)
|
|
188
|
+
self.traj += block
|
|
189
|
+
self._record_monitor(monitor)
|
|
190
|
+
self._record_step()
|
|
191
|
+
|
|
192
|
+
return self
|
|
193
|
+
|
|
194
|
+
def acceptance(self):
|
|
195
|
+
# Mean acceptance over production trajectories, if the kernel reports it.
|
|
196
|
+
if "accept" not in self.monitor or self.traj == 0:
|
|
197
|
+
return None
|
|
198
|
+
|
|
199
|
+
return float(np.mean(self.monitor["accept"][-self.traj :]))
|
lfox/evolution/hmc.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import dataclasses
|
|
2
|
+
|
|
3
|
+
import equinox as eqx
|
|
4
|
+
import jax
|
|
5
|
+
import jax.numpy as jnp
|
|
6
|
+
|
|
7
|
+
from lfox.action import Action
|
|
8
|
+
from lfox.evolution.base import Evolver
|
|
9
|
+
from lfox.evolution.integrators import MDIntegrator
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class HMC(Evolver):
|
|
13
|
+
# Hybrid Monte Carlo. Refresh momenta from a Gaussian heatbath, integrate
|
|
14
|
+
# Hamilton's equations along a molecular-dynamics trajectory, then accept or
|
|
15
|
+
# reject on exp(-delta_H).
|
|
16
|
+
#
|
|
17
|
+
# `warmup` is a static field rather than a call argument: "always accept" is a
|
|
18
|
+
# different transition kernel, not a flag on this one. Build a warmup variant
|
|
19
|
+
# with `as_warmup()`.
|
|
20
|
+
|
|
21
|
+
action: Action
|
|
22
|
+
integrator: MDIntegrator
|
|
23
|
+
warmup: bool = eqx.field(static=True, default=False)
|
|
24
|
+
|
|
25
|
+
def as_warmup(self):
|
|
26
|
+
return dataclasses.replace(self, warmup=True)
|
|
27
|
+
|
|
28
|
+
def H_density(self, S_field, pi_fields):
|
|
29
|
+
H_field = S_field.copy()
|
|
30
|
+
for fname in pi_fields.keys():
|
|
31
|
+
H_field += 0.5 * pi_fields[fname] ** 2
|
|
32
|
+
|
|
33
|
+
return H_field
|
|
34
|
+
|
|
35
|
+
def H(self, S_field, pi_fields):
|
|
36
|
+
H_field = self.H_density(S_field, pi_fields)
|
|
37
|
+
|
|
38
|
+
return jnp.sum(H_field.F)
|
|
39
|
+
|
|
40
|
+
def momentum_refresh(self, fields, rng_key):
|
|
41
|
+
pi_fields = {}
|
|
42
|
+
for fname in fields.keys():
|
|
43
|
+
rng_key, subkey = jax.random.split(rng_key)
|
|
44
|
+
pi_fields[fname] = jax.random.normal(subkey, shape=fields[fname].F.shape)
|
|
45
|
+
|
|
46
|
+
return pi_fields, rng_key
|
|
47
|
+
|
|
48
|
+
def delta_fields(self):
|
|
49
|
+
def delta_X(X, P):
|
|
50
|
+
return P
|
|
51
|
+
|
|
52
|
+
return delta_X
|
|
53
|
+
|
|
54
|
+
def delta_mom(self):
|
|
55
|
+
def delta_P(X, P):
|
|
56
|
+
result = {}
|
|
57
|
+
derivs = self.action.dS(X)
|
|
58
|
+
for field in self.action.field_names:
|
|
59
|
+
result[field] = -1 * derivs[field]
|
|
60
|
+
|
|
61
|
+
return result
|
|
62
|
+
|
|
63
|
+
return delta_P
|
|
64
|
+
|
|
65
|
+
def MD_traj(self, fields, pi_fields):
|
|
66
|
+
S_old = self.action.S_field(fields)
|
|
67
|
+
H_old = self.H_density(S_old, pi_fields)
|
|
68
|
+
|
|
69
|
+
fields, pi_fields = self.integrator.integrate(
|
|
70
|
+
delta_X=self.delta_fields(),
|
|
71
|
+
delta_P=self.delta_mom(),
|
|
72
|
+
X=fields,
|
|
73
|
+
P=pi_fields,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
S_new = self.action.S_field(fields)
|
|
77
|
+
H_new = self.H_density(S_new, pi_fields)
|
|
78
|
+
|
|
79
|
+
delta_H = jnp.sum(H_new.F - H_old.F)
|
|
80
|
+
P_acc = jnp.exp(-delta_H)
|
|
81
|
+
|
|
82
|
+
return fields, pi_fields, delta_H, P_acc
|
|
83
|
+
|
|
84
|
+
@jax.jit
|
|
85
|
+
def evolve(self, fields, rng_key):
|
|
86
|
+
# Refresh momentum. Note that rng_key is advanced past every momentum
|
|
87
|
+
# draw; the accept/reject uniform must be drawn from the advanced key, or
|
|
88
|
+
# it is a deterministic function of the momenta it is meant to test.
|
|
89
|
+
pi_fields, rng_key = self.momentum_refresh(fields, rng_key)
|
|
90
|
+
|
|
91
|
+
# Integrate forward
|
|
92
|
+
new_fields, new_pi_fields, delta_H, P_acc = self.MD_traj(fields, pi_fields)
|
|
93
|
+
|
|
94
|
+
monitor = {"delta_H": delta_H, "P_acc": P_acc}
|
|
95
|
+
|
|
96
|
+
if self.warmup: # Warmups always accept!
|
|
97
|
+
accept = jnp.array(True)
|
|
98
|
+
else:
|
|
99
|
+
rng_key, subkey = jax.random.split(rng_key)
|
|
100
|
+
r = jax.random.uniform(subkey)
|
|
101
|
+
|
|
102
|
+
accept = r < P_acc
|
|
103
|
+
new_fields = jax.lax.cond(accept, lambda: new_fields, lambda: fields)
|
|
104
|
+
|
|
105
|
+
monitor["accept"] = accept
|
|
106
|
+
|
|
107
|
+
return new_fields, monitor, rng_key
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
from abc import abstractmethod
|
|
2
|
+
from functools import partial
|
|
3
|
+
|
|
4
|
+
import equinox as eqx
|
|
5
|
+
import jax
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MDIntegrator(eqx.Module):
|
|
9
|
+
eps: float
|
|
10
|
+
Nstep: int
|
|
11
|
+
|
|
12
|
+
def traj_length(self):
|
|
13
|
+
return self.eps * self.Nstep
|
|
14
|
+
|
|
15
|
+
@staticmethod
|
|
16
|
+
@jax.jit
|
|
17
|
+
def update(fields, delta, dt):
|
|
18
|
+
new_fields = {}
|
|
19
|
+
for fname in fields.keys():
|
|
20
|
+
new_fields[fname] = fields[fname] + dt * delta[fname]
|
|
21
|
+
|
|
22
|
+
return new_fields
|
|
23
|
+
|
|
24
|
+
@abstractmethod
|
|
25
|
+
def integrate(self, delta_X, delta_P, X, P):
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class LeapfrogIntegrator(MDIntegrator):
|
|
30
|
+
|
|
31
|
+
# Temporary intermediate function for profiling
|
|
32
|
+
def integrate(self, delta_X, delta_P, X, P):
|
|
33
|
+
return self._integrate(delta_X, delta_P, X, P)
|
|
34
|
+
|
|
35
|
+
@partial(jax.jit, static_argnums=(1, 2))
|
|
36
|
+
def _integrate(self, delta_X, delta_P, X, P):
|
|
37
|
+
# Note that X and P should both be dictionaries
|
|
38
|
+
# of fields (like in Action()) with matching keys.
|
|
39
|
+
|
|
40
|
+
X = self.update(X, delta_X(X, P), self.eps / 2.0)
|
|
41
|
+
P = self.update(P, delta_P(X, P), self.eps)
|
|
42
|
+
|
|
43
|
+
def mid_step(i, XP):
|
|
44
|
+
Xint, Pint = XP
|
|
45
|
+
Xint = self.update(Xint, delta_X(Xint, Pint), self.eps)
|
|
46
|
+
Pint = self.update(Pint, delta_P(Xint, Pint), self.eps)
|
|
47
|
+
|
|
48
|
+
return (Xint, Pint)
|
|
49
|
+
|
|
50
|
+
X, P = jax.lax.fori_loop(0, self.Nstep - 1, mid_step, (X, P))
|
|
51
|
+
|
|
52
|
+
X = self.update(X, delta_X(X, P), self.eps / 2.0)
|
|
53
|
+
|
|
54
|
+
return X, P
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class OmelyanIntegrator(MDIntegrator):
|
|
58
|
+
xi: float = 0.1931833
|
|
59
|
+
|
|
60
|
+
# Temporary intermediate function for profiling
|
|
61
|
+
def integrate(self, delta_X, delta_P, X, P):
|
|
62
|
+
return self._integrate(delta_X, delta_P, X, P)
|
|
63
|
+
|
|
64
|
+
@partial(jax.jit, static_argnums=(1, 2))
|
|
65
|
+
def _integrate(self, delta_X, delta_P, X, P):
|
|
66
|
+
# Note that X and P should both be dictionaries
|
|
67
|
+
# of fields (like in Action()) with matching keys.
|
|
68
|
+
|
|
69
|
+
xiEps = self.xi * self.eps
|
|
70
|
+
middle_step = (1 - 2 * self.xi) * self.eps
|
|
71
|
+
|
|
72
|
+
def mid_step(i, XP):
|
|
73
|
+
Xint, Pint = XP
|
|
74
|
+
|
|
75
|
+
Xint = self.update(Xint, delta_X(Xint, Pint), 2 * xiEps)
|
|
76
|
+
Pint = self.update(Pint, delta_P(Xint, Pint), self.eps / 2.0)
|
|
77
|
+
Xint = self.update(Xint, delta_X(Xint, Pint), middle_step)
|
|
78
|
+
Pint = self.update(Pint, delta_P(Xint, Pint), self.eps / 2.0)
|
|
79
|
+
|
|
80
|
+
return (Xint, Pint)
|
|
81
|
+
|
|
82
|
+
X = self.update(X, delta_X(X, P), xiEps)
|
|
83
|
+
P = self.update(P, delta_P(X, P), self.eps / 2.0)
|
|
84
|
+
X = self.update(X, delta_X(X, P), middle_step)
|
|
85
|
+
P = self.update(P, delta_P(X, P), self.eps / 2.0)
|
|
86
|
+
|
|
87
|
+
X, P = jax.lax.fori_loop(0, self.Nstep - 1, mid_step, (X, P))
|
|
88
|
+
|
|
89
|
+
X = self.update(X, delta_X(X, P), xiEps)
|
|
90
|
+
|
|
91
|
+
return X, P
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-present Ethan Neil <ethan.neil@colorado.edu>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
#
|
|
5
|
+
# Experimental and incomplete: the modules in this subpackage have not yet been
|
|
6
|
+
# migrated off the legacy LatticeField pytree registration, so importing
|
|
7
|
+
# lfox.fermions.spin (and therefore .wilson / .solver) currently fails. Nothing
|
|
8
|
+
# is re-exported here so that `import lfox` stays clean; see PLAN.md step 4.
|
lfox/fermions/solver.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import jax
|
|
2
|
+
import jax.numpy as jnp
|
|
3
|
+
from functools import partial
|
|
4
|
+
|
|
5
|
+
class MRSolver():
|
|
6
|
+
|
|
7
|
+
def __init__(self, dirac_op, target_resid, omega_OR=1.1, max_iter=1000):
|
|
8
|
+
self.dirac_op = dirac_op
|
|
9
|
+
self.target_resid = target_resid
|
|
10
|
+
self.omega_OR = omega_OR
|
|
11
|
+
self.max_iter = max_iter
|
|
12
|
+
|
|
13
|
+
def solve(self, chi, psi_0):
|
|
14
|
+
r = chi - self.dirac_op.op(psi_0)
|
|
15
|
+
psi = psi_0.copy()
|
|
16
|
+
iter = 0
|
|
17
|
+
resid = r.norm_sq()
|
|
18
|
+
|
|
19
|
+
while (iter < self.max_iter) and (resid > self.target_resid):
|
|
20
|
+
psi, r = self._MR_step(psi, r)
|
|
21
|
+
resid = r.norm_sq()
|
|
22
|
+
|
|
23
|
+
return (psi, resid, iter)
|
|
24
|
+
|
|
25
|
+
@partial(jax.jit, static_argnums=(0,))
|
|
26
|
+
def _MR_step(self, psi, r):
|
|
27
|
+
p = self.dirac_op.op(r)
|
|
28
|
+
p_norm = p.norm_sq()
|
|
29
|
+
alpha = self.omega_OR * p.dot(r) / p_norm
|
|
30
|
+
|
|
31
|
+
psi_new = psi + alpha * r
|
|
32
|
+
r_new = r - alpha * p
|
|
33
|
+
|
|
34
|
+
return (psi_new, r_new)
|
lfox/fermions/spin.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import jax
|
|
3
|
+
import jax.numpy as jnp
|
|
4
|
+
from lfox.lattice import Lattice, LatticeField
|
|
5
|
+
|
|
6
|
+
Pauli_X = np.array([[0,1],[1,0]])
|
|
7
|
+
Pauli_Y = np.array([[0,-1j],[1j,0]])
|
|
8
|
+
Pauli_Z = np.array([[1,0],[0,-1]])
|
|
9
|
+
|
|
10
|
+
# DeGrand-Rossi gamma basis
|
|
11
|
+
|
|
12
|
+
Gamma_0 = np.array([
|
|
13
|
+
[0, 0, 0, 1j],
|
|
14
|
+
[0, 0, 1j, 0],
|
|
15
|
+
[0, -1j, 0, 0],
|
|
16
|
+
[-1j, 0, 0, 0],
|
|
17
|
+
])
|
|
18
|
+
Gamma_1 = np.array([
|
|
19
|
+
[0, 0, 0, -1],
|
|
20
|
+
[0, 0, 1, 0],
|
|
21
|
+
[0, 1, 0, 0],
|
|
22
|
+
[-1, 0, 0, 0],
|
|
23
|
+
])
|
|
24
|
+
Gamma_2 = np.array([
|
|
25
|
+
[0, 0, 1j, 0],
|
|
26
|
+
[0, 0, 0, -1j],
|
|
27
|
+
[-1j, 0, 0, 0],
|
|
28
|
+
[0, 1j, 0, 0],
|
|
29
|
+
])
|
|
30
|
+
Gamma_3 = np.array([
|
|
31
|
+
[0, 0, 1, 0],
|
|
32
|
+
[0, 0, 0, 1],
|
|
33
|
+
[1, 0, 0, 0],
|
|
34
|
+
[0, 1, 0, 0],
|
|
35
|
+
])
|
|
36
|
+
Gamma_5 = np.array([
|
|
37
|
+
[1, 0, 0, 0],
|
|
38
|
+
[0, 1, 0, 0],
|
|
39
|
+
[0, 0, -1, 0],
|
|
40
|
+
[0, 0, 0, -1],
|
|
41
|
+
])
|
|
42
|
+
|
|
43
|
+
SigmaMatrix = {
|
|
44
|
+
'X': Pauli_X,
|
|
45
|
+
'Y': Pauli_Y,
|
|
46
|
+
'Z': Pauli_Z,
|
|
47
|
+
'I': np.eye(2),
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
GammaMatrix = {
|
|
51
|
+
0: Gamma_0,
|
|
52
|
+
1: Gamma_1,
|
|
53
|
+
2: Gamma_2,
|
|
54
|
+
3: Gamma_3,
|
|
55
|
+
5: Gamma_5,
|
|
56
|
+
'I': np.eye(4),
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
# TODO: add some algebraic tests to verify the above constants
|
|
60
|
+
|
|
61
|
+
# TODO: mark this all as 4D and/or generalize...
|
|
62
|
+
|
|
63
|
+
class Dirac4DFermionField(LatticeField):
|
|
64
|
+
|
|
65
|
+
def __init__(self, lattice: Lattice, F=None, bc=None, indices=None):
|
|
66
|
+
# "Indices" is being ignored, there is probably a better way...
|
|
67
|
+
|
|
68
|
+
indices = (4,)
|
|
69
|
+
|
|
70
|
+
super().__init__(lattice=lattice, indices=indices, F=F, bc=bc)
|
|
71
|
+
|
|
72
|
+
def bilinear(self, other, spin_mat=None):
|
|
73
|
+
new_fermion = self.copy()
|
|
74
|
+
|
|
75
|
+
if spin_mat is None:
|
|
76
|
+
new_fermion.F = self._inner_product(self.F, other.F)
|
|
77
|
+
else:
|
|
78
|
+
new_fermion.F = self._inner_spin_product(self.F, spin_mat, other.F)
|
|
79
|
+
|
|
80
|
+
return new_fermion
|
|
81
|
+
|
|
82
|
+
def conj(self):
|
|
83
|
+
self.F = self.F.conj()
|
|
84
|
+
return self
|
|
85
|
+
|
|
86
|
+
def dot(self, other):
|
|
87
|
+
return jnp.sum(self._inner_product(self.F, other.F))
|
|
88
|
+
|
|
89
|
+
def norm_sq(self):
|
|
90
|
+
return jnp.sum(self._inner_product(self.F, self.F))
|
|
91
|
+
|
|
92
|
+
@staticmethod
|
|
93
|
+
@jax.jit
|
|
94
|
+
def _inner_product(psi_L, psi_R):
|
|
95
|
+
return jnp.einsum('...i,...i', psi_L.conj(), psi_R)
|
|
96
|
+
|
|
97
|
+
@staticmethod
|
|
98
|
+
@jax.jit
|
|
99
|
+
def _inner_spin_product(psi_L, spin_mat, psi_R):
|
|
100
|
+
return jnp.einsum('...i,ij,...j', psi_L.conj(), spin_mat, psi_R)
|
|
101
|
+
|
|
102
|
+
@staticmethod
|
|
103
|
+
@jax.jit
|
|
104
|
+
def _spin_product(spin_mat, psi):
|
|
105
|
+
return jnp.einsum('ij,...j', spin_mat, psi)
|
|
106
|
+
|
|
107
|
+
jax.tree_util.register_pytree_node(
|
|
108
|
+
Dirac4DFermionField,
|
|
109
|
+
Dirac4DFermionField._tree_flatten,
|
|
110
|
+
Dirac4DFermionField._tree_unflatten,
|
|
111
|
+
)
|
lfox/fermions/wilson.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from functools import partial
|
|
3
|
+
import jax
|
|
4
|
+
import jax.numpy as jnp
|
|
5
|
+
import lfox.lattice
|
|
6
|
+
import lfox.fermions.spin as spin
|
|
7
|
+
from lfox.fermions.spin import Dirac4DFermionField as dirac
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class WilsonDiracOp():
|
|
11
|
+
|
|
12
|
+
def __init__(self, kappa):
|
|
13
|
+
self.kappa = kappa
|
|
14
|
+
|
|
15
|
+
@staticmethod
|
|
16
|
+
def shift_fermion(psi, axis, shift):
|
|
17
|
+
# Overload me to add gauge fields!
|
|
18
|
+
return psi.nn_field(axis=axis, shift=shift)
|
|
19
|
+
|
|
20
|
+
@partial(jax.jit, static_argnums=(0,))
|
|
21
|
+
def Dslash(self, psi):
|
|
22
|
+
Dpsi = psi.copy()
|
|
23
|
+
Dpsi = Dpsi.zero_fill()
|
|
24
|
+
|
|
25
|
+
for mu in range(psi.lattice.d):
|
|
26
|
+
proj_minus = (spin.GammaMatrix['I'] - spin.GammaMatrix[mu])
|
|
27
|
+
proj_plus = (spin.GammaMatrix['I'] + spin.GammaMatrix[mu])
|
|
28
|
+
|
|
29
|
+
Dpsi += dirac._spin_product(proj_minus, self.shift_fermion(psi, mu, 1).F)
|
|
30
|
+
Dpsi += dirac._spin_product(proj_plus, self.shift_fermion(psi, mu, -1).F)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
return Dpsi
|
|
34
|
+
|
|
35
|
+
@partial(jax.jit, static_argnums=(0,))
|
|
36
|
+
def op(self, psi):
|
|
37
|
+
chi = psi.copy()
|
|
38
|
+
chi -= self.kappa * self.Dslash(psi)
|
|
39
|
+
|
|
40
|
+
return chi
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
|
lfox/lattice.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import dataclasses
|
|
3
|
+
import operator
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
from functools import partial
|
|
6
|
+
from typing import ClassVar, Optional
|
|
7
|
+
|
|
8
|
+
import equinox as eqx
|
|
9
|
+
import jax
|
|
10
|
+
import jax.numpy as jnp
|
|
11
|
+
import numpy as np
|
|
12
|
+
from jax import tree_util
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Lattice(eqx.Module):
|
|
16
|
+
st_dims: tuple[int]
|
|
17
|
+
_dims: tuple[int] = eqx.field(init=False)
|
|
18
|
+
|
|
19
|
+
def __post_init__(self):
|
|
20
|
+
# Dimensions of the physical lattice
|
|
21
|
+
# May differ from space-time dims (e.g.
|
|
22
|
+
# non-trivial unit cell)
|
|
23
|
+
self._dims = self.st_dims
|
|
24
|
+
|
|
25
|
+
def bc_coord(self, axis):
|
|
26
|
+
# Per-axis coordinate grid for boundary-condition winding factors.
|
|
27
|
+
# Computed on demand so the Lattice carries no JAX arrays (it's used
|
|
28
|
+
# as a static field on LatticeField).
|
|
29
|
+
return jnp.meshgrid(*[jnp.arange(Li) for Li in self.st_dims], indexing="ij")[
|
|
30
|
+
axis
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SquareLattice(Lattice):
|
|
35
|
+
def shift(self, field, axis, shift=1):
|
|
36
|
+
return jnp.roll(field, shift=shift, axis=axis)
|
|
37
|
+
|
|
38
|
+
# Red-black checkerboarding
|
|
39
|
+
# rb fields are defined on a sublattice with 1/2 size.
|
|
40
|
+
def rb_split(self, field):
|
|
41
|
+
# The goal is to figure this out efficiently, but
|
|
42
|
+
# it seems very tricky especially with boundary conditions...
|
|
43
|
+
# Return to it later.
|
|
44
|
+
|
|
45
|
+
pass
|
|
46
|
+
# return cb_red, cb_black
|
|
47
|
+
|
|
48
|
+
def rb_combine(self, field_cb_red, field_cb_black):
|
|
49
|
+
# Inverse of rb_split, however that ends up being implemented!
|
|
50
|
+
pass
|
|
51
|
+
# return field
|
|
52
|
+
|
|
53
|
+
@staticmethod
|
|
54
|
+
@jax.jit
|
|
55
|
+
def _set_checkerboard(dims):
|
|
56
|
+
cb_black = jnp.indices(dims).sum(axis=0) % 2
|
|
57
|
+
cb_red = (cb_black + 1) % 2
|
|
58
|
+
|
|
59
|
+
return [cb_black, cb_red]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class HoneycombLattice(Lattice):
|
|
63
|
+
# A/B unit cell structure, automatically in the dim-0 direction.
|
|
64
|
+
# Note that this means that the number of lattice sites in dimension
|
|
65
|
+
# 0 is actually 2*dims[0].
|
|
66
|
+
unit_cell: ClassVar[tuple[int]] = (0, 1)
|
|
67
|
+
|
|
68
|
+
def __post_init__(self):
|
|
69
|
+
self._dims = self.st_dims + (len(self.unit_cell),)
|
|
70
|
+
|
|
71
|
+
def shift(self, field, axis, shift=1):
|
|
72
|
+
# Shift within the unit cell too if we are moving in axis 0
|
|
73
|
+
if axis == 0:
|
|
74
|
+
shift_field = jnp.roll(field, shift=shift, axis=-1)
|
|
75
|
+
# FIXME: THIS IS WRONG, figure out the correct way to do this
|
|
76
|
+
# (Only sites which are now on unit cell position 0 should be
|
|
77
|
+
# rolled in x.)
|
|
78
|
+
shift_field = jnp.roll(shift_field, shift=shift, axis=0)
|
|
79
|
+
return shift_field
|
|
80
|
+
else:
|
|
81
|
+
# Other axes shift normally
|
|
82
|
+
return jnp.roll(field, shift=shift, axis=axis)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class LatticeField(eqx.Module):
|
|
86
|
+
lattice: Lattice = eqx.field(static=True)
|
|
87
|
+
F: jax.Array = eqx.field(converter=jax.numpy.asarray)
|
|
88
|
+
# bc: Optional[jax.Array] = eqx.field(default=(), converter=jax.numpy.asarray)
|
|
89
|
+
bc: Optional[tuple[int]] = eqx.field(default=(), static=True)
|
|
90
|
+
indices: Optional[tuple[int]] = eqx.field(default=(), static=True)
|
|
91
|
+
|
|
92
|
+
def __post_init__(self):
|
|
93
|
+
# Allow e.g. unit field by just passing 1,
|
|
94
|
+
# broadcast to size of lattice
|
|
95
|
+
|
|
96
|
+
if type(self.F) != jnp.array:
|
|
97
|
+
# if self.F.shape == ():
|
|
98
|
+
self.F = self.F * jnp.ones(self.dims())
|
|
99
|
+
|
|
100
|
+
self._set_default_BC()
|
|
101
|
+
|
|
102
|
+
if type(self.lattice) is dict:
|
|
103
|
+
# Workaround for using dataclasses.asdict
|
|
104
|
+
self.lattice = Lattice(**self.lattice)
|
|
105
|
+
|
|
106
|
+
def _set_default_BC(self):
|
|
107
|
+
if len(self.bc) == 0:
|
|
108
|
+
# Default is periodic BC = [1,1,1,...]
|
|
109
|
+
self.bc = (1,) * len(self.lattice.st_dims)
|
|
110
|
+
# self.bc = jnp.ones(len(self.lattice.st_dims))
|
|
111
|
+
else:
|
|
112
|
+
assert len(self.bc) == len(self.lattice.st_dims)
|
|
113
|
+
|
|
114
|
+
def dims(self):
|
|
115
|
+
if len(self.indices) > 0:
|
|
116
|
+
return self.lattice._dims + tuple(self.indices)
|
|
117
|
+
else:
|
|
118
|
+
return self.lattice._dims
|
|
119
|
+
|
|
120
|
+
def st_dims(self):
|
|
121
|
+
# For broadcasting against spacetime indices
|
|
122
|
+
return self.lattice._dims + (1,) * len(self.indices)
|
|
123
|
+
|
|
124
|
+
def d(self):
|
|
125
|
+
# Return number of space-time dimensions
|
|
126
|
+
return len(self.lattice._dims)
|
|
127
|
+
|
|
128
|
+
@staticmethod
|
|
129
|
+
def _field_op(f, rev=False):
|
|
130
|
+
if rev:
|
|
131
|
+
|
|
132
|
+
def op(self, other):
|
|
133
|
+
o = getattr(other, "F", other)
|
|
134
|
+
new_F = f(o, self.F)
|
|
135
|
+
|
|
136
|
+
return self.copy_new_F(new_F)
|
|
137
|
+
else:
|
|
138
|
+
|
|
139
|
+
def op(self, other):
|
|
140
|
+
o = getattr(other, "F", other)
|
|
141
|
+
new_F = f(self.F, o)
|
|
142
|
+
|
|
143
|
+
return self.copy_new_F(new_F)
|
|
144
|
+
|
|
145
|
+
return op
|
|
146
|
+
|
|
147
|
+
__add__ = _field_op(operator.add)
|
|
148
|
+
__radd__ = _field_op(operator.add, rev=True)
|
|
149
|
+
__sub__ = _field_op(operator.sub)
|
|
150
|
+
__mul__ = _field_op(operator.mul)
|
|
151
|
+
__rmul__ = _field_op(operator.mul, rev=True)
|
|
152
|
+
__truediv__ = _field_op(operator.truediv)
|
|
153
|
+
__pow__ = _field_op(operator.pow)
|
|
154
|
+
|
|
155
|
+
def conj(self):
|
|
156
|
+
new_F = self.F.conj()
|
|
157
|
+
return self.copy_new_F(new_F)
|
|
158
|
+
|
|
159
|
+
# TODO: more arithmetic?
|
|
160
|
+
|
|
161
|
+
@staticmethod
|
|
162
|
+
@partial(jax.jit, static_argnums=(1, 2, 3, 4, 5))
|
|
163
|
+
def _nn_field(field, lattice, axis, shift, bc, st_dims):
|
|
164
|
+
nn_shift = lattice.shift(field, axis=axis, shift=shift)
|
|
165
|
+
|
|
166
|
+
# Apply boundary conditions globally with some arcane NumPy manipulations
|
|
167
|
+
BC_factor = bc[axis]
|
|
168
|
+
coords_ax = lattice.bc_coord(axis)
|
|
169
|
+
|
|
170
|
+
# Minus signs show up at target, not source, so subtract shift.
|
|
171
|
+
winding, _ = jnp.divmod(coords_ax - shift, st_dims[axis])
|
|
172
|
+
BC_field = (BC_factor) ** (winding)
|
|
173
|
+
|
|
174
|
+
return nn_shift * BC_field.reshape(st_dims)
|
|
175
|
+
|
|
176
|
+
def nn_field(self, axis, shift=1):
|
|
177
|
+
shifted_field = self._nn_field(
|
|
178
|
+
self.F,
|
|
179
|
+
lattice=self.lattice,
|
|
180
|
+
axis=axis,
|
|
181
|
+
shift=shift,
|
|
182
|
+
bc=self.bc,
|
|
183
|
+
st_dims=self.st_dims(),
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
return self.copy_new_F(shifted_field)
|
|
187
|
+
|
|
188
|
+
def __copy__(self):
|
|
189
|
+
cls = self.__class__
|
|
190
|
+
new = cls.__new__(cls)
|
|
191
|
+
new.__dict__.update(self.__dict__)
|
|
192
|
+
|
|
193
|
+
return new
|
|
194
|
+
|
|
195
|
+
def copy_new_F(self, F):
|
|
196
|
+
# Unsure if this is the best way to do this?
|
|
197
|
+
cls = self.__class__
|
|
198
|
+
new = cls.__new__(cls)
|
|
199
|
+
new.__dict__.update(self.__dict__)
|
|
200
|
+
|
|
201
|
+
return dataclasses.replace(new, F=F)
|
|
202
|
+
|
|
203
|
+
def copy(self):
|
|
204
|
+
return self.__copy__()
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lfox
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Lattice Fields Over jaX
|
|
5
|
+
Keywords: lattice field theory,lattice qcd,hybrid monte carlo,jax,physics
|
|
6
|
+
Author: Ethan Neil
|
|
7
|
+
Author-email: Ethan Neil <ethan.neil@colorado.edu>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE.txt
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
|
15
|
+
Requires-Dist: equinox>=0.13.7
|
|
16
|
+
Requires-Dist: jax>=0.10.0
|
|
17
|
+
Requires-Dist: numpy>=1.26
|
|
18
|
+
Requires-Dist: jax-mps>=0.10.10 ; extra == 'mps'
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Project-URL: Homepage, https://github.com/etneil/lfox
|
|
21
|
+
Project-URL: Repository, https://github.com/etneil/lfox
|
|
22
|
+
Project-URL: Issues, https://github.com/etneil/lfox/issues
|
|
23
|
+
Provides-Extra: mps
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# lfox
|
|
27
|
+
|
|
28
|
+
**L**attice **F**ields **O**ver ja**X** — a JAX-based library for lattice field theory
|
|
29
|
+
simulations: Markov-chain field evolution (HMC), lattice operators, and observable
|
|
30
|
+
measurement.
|
|
31
|
+
|
|
32
|
+
_Why?_ JAX provides two very useful things for lattice simulations:
|
|
33
|
+
|
|
34
|
+
1. __Autodiff__. Implement the action as a Python function, JAX computes the
|
|
35
|
+
necessary gradients for HMC or other algorithms automatically.
|
|
36
|
+
2. __Flexible backend__. JAX can target GPUs and its backend for sharding can
|
|
37
|
+
handle communications and scale up beyond a single machine.
|
|
38
|
+
|
|
39
|
+
Since JAX is focused on supporting machine learning applications, `lfox` is also
|
|
40
|
+
naturally interoperable with machine-learning workflows implemented in JAX.
|
|
41
|
+
|
|
42
|
+
The code being fully Python-based also means that it should be easy to work with and to
|
|
43
|
+
modify; this will probably never be the most efficient lattice code out there, but
|
|
44
|
+
the goal is "good enough for prototyping" or working with toy or exotic theory targets.
|
|
45
|
+
|
|
46
|
+
The core abstraction is an [Equinox](https://github.com/patrick-kidger/equinox)-backed
|
|
47
|
+
`Lattice` + `LatticeField` pair that participates in JAX pytrees, so everything composes
|
|
48
|
+
with `jax.jit` and `jax.grad`.
|
|
49
|
+
|
|
50
|
+
> **Status: early alpha.** This is a research codebase under active development. The API is not
|
|
51
|
+
> stable, and `lfox.fermions` is incomplete (see [Roadmap](#roadmap)). Pin an exact
|
|
52
|
+
> version if you depend on it.
|
|
53
|
+
|
|
54
|
+
## Installation
|
|
55
|
+
|
|
56
|
+
```console
|
|
57
|
+
pip install lfox
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
or, with [uv](https://docs.astral.sh/uv/):
|
|
61
|
+
|
|
62
|
+
```console
|
|
63
|
+
uv add lfox
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
On Apple Silicon you can optionally pull in the experimental Metal backend:
|
|
67
|
+
|
|
68
|
+
```console
|
|
69
|
+
pip install "lfox[mps]"
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
JAX is installed as a plain CPU build by default. For CUDA or TPU, install the
|
|
73
|
+
appropriate [JAX wheel](https://docs.jax.dev/en/latest/installation.html) for your
|
|
74
|
+
platform alongside `lfox`.
|
|
75
|
+
|
|
76
|
+
## Quickstart
|
|
77
|
+
|
|
78
|
+
A phi^4 scalar field on a 4³ lattice, evolved with hybrid Monte Carlo:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
import jax
|
|
82
|
+
import jax.numpy as jnp
|
|
83
|
+
|
|
84
|
+
import lfox.lattice as lat
|
|
85
|
+
from lfox.action import Action
|
|
86
|
+
from lfox.evolution import HMC, Chain, LeapfrogIntegrator
|
|
87
|
+
|
|
88
|
+
jax.config.update("jax_enable_x64", True)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class ScalarAction(Action):
|
|
92
|
+
# NOTE: @staticmethod must sit *above* @jax.jit, or tracing breaks.
|
|
93
|
+
@staticmethod
|
|
94
|
+
@jax.jit
|
|
95
|
+
def _S(fields, params):
|
|
96
|
+
phi = fields[0]
|
|
97
|
+
S = phi**2
|
|
98
|
+
for ax in range(phi.d()):
|
|
99
|
+
S -= 2 * params["kappa"] * phi * phi.nn_field(ax)
|
|
100
|
+
S += params["lambda"] * (phi**2 - 1) ** 2
|
|
101
|
+
return S
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
lattice = lat.SquareLattice(st_dims=(4, 4, 4))
|
|
105
|
+
phi = lat.LatticeField(lattice=lattice, F=jnp.ones((4, 4, 4)))
|
|
106
|
+
|
|
107
|
+
action = ScalarAction(field_names=["phi"], params={"kappa": 0.18169, "lambda": 1.3282})
|
|
108
|
+
hmc = HMC(action=action, integrator=LeapfrogIntegrator(eps=0.1, Nstep=10))
|
|
109
|
+
|
|
110
|
+
chain = Chain(
|
|
111
|
+
evolver=hmc,
|
|
112
|
+
seed=1,
|
|
113
|
+
init_fields={"phi": phi},
|
|
114
|
+
observables={"magn": lambda fields, params: float(jnp.mean(fields["phi"].F))},
|
|
115
|
+
)
|
|
116
|
+
chain.warmup(100)
|
|
117
|
+
chain.run(1000)
|
|
118
|
+
|
|
119
|
+
print(f"acceptance: {chain.acceptance():.3f}")
|
|
120
|
+
print(f"<phi>: {sum(chain.obs_chain['magn']) / len(chain.obs_chain['magn']):.5f}")
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Note that only `_S` was written by hand. The force `dS` used by the integrator is
|
|
124
|
+
obtained by differentiating it.
|
|
125
|
+
|
|
126
|
+
## What's in the box
|
|
127
|
+
|
|
128
|
+
- **`lfox.lattice`** — `Lattice` and `LatticeField`, with overloaded arithmetic
|
|
129
|
+
and `nn_field(axis, shift)` for nearest-neighbor hops with (anti-)periodic boundary conditions.
|
|
130
|
+
- **`lfox.action`** — `Action`, the action functional. Subclass it and implement `_S`;
|
|
131
|
+
you get `S`, `S_field`, and autodiff `dS` for free. Actions compose with `+`.
|
|
132
|
+
- **`lfox.evolution`** — `HMC` (a pure, jittable Markov transition kernel),
|
|
133
|
+
`LeapfrogIntegrator` / `OmelyanIntegrator`, and `Chain`, the host-side driver that owns
|
|
134
|
+
the RNG key, saved configurations, diagnostics, and observable measurement.
|
|
135
|
+
- **`lfox.fermions`** — Dirac spin structure, the Wilson operator, and a minimal-residual
|
|
136
|
+
solver. **Experimental and currently non-functional** — this subpackage has not yet been
|
|
137
|
+
migrated to the current `LatticeField`, and importing it raises.
|
|
138
|
+
|
|
139
|
+
## Roadmap
|
|
140
|
+
|
|
141
|
+
- Fermions!
|
|
142
|
+
- Gauge fields!
|
|
143
|
+
- Group/representation machinery
|
|
144
|
+
- Other update algorithms
|
|
145
|
+
- Proper testing of scaling and GPU backend
|
|
146
|
+
- A richer measurement / analysis layer
|
|
147
|
+
|
|
148
|
+
## Development
|
|
149
|
+
|
|
150
|
+
```console
|
|
151
|
+
git clone https://github.com/etneil/lfox
|
|
152
|
+
cd lfox
|
|
153
|
+
uv sync # installs the package plus test and notebook dependencies
|
|
154
|
+
uv run pytest
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
The test suite pins physics invariants rather than implementation details: action
|
|
158
|
+
normalization, autodiff force against the analytic force, `<exp(-ΔH)> = 1`, RNG key
|
|
159
|
+
threading, and `Chain` bookkeeping.
|
|
160
|
+
|
|
161
|
+
Exploratory work lives in Jupyter notebooks at the repo root, paired to `py:percent`
|
|
162
|
+
scripts via [jupytext](https://jupytext.readthedocs.io/). Launch with `uv run jupyter lab`.
|
|
163
|
+
|
|
164
|
+
## License
|
|
165
|
+
|
|
166
|
+
`lfox` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html)
|
|
167
|
+
license.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
lfox/__about__.py,sha256=V1F3Sz4iaaP1F5UNz7PeEGtZJP593q8whTBHIPXpYKc,466
|
|
2
|
+
lfox/__init__.py,sha256=8PcFTfan2xeydR4GyLS2WdxmSZN6GvKmYhdFS3ia7fI,175
|
|
3
|
+
lfox/action.py,sha256=1deqeEw59E8qcbIZE7SBftT2FZonyyvkfi7sV0SV5e8,4479
|
|
4
|
+
lfox/evolution/__init__.py,sha256=oMHAxfy_aZYRNVM5QkYKS6QNtpd1D8WMJUtf6SybuWA,360
|
|
5
|
+
lfox/evolution/base.py,sha256=qqBepq7AnjhDu4C9Uk6cR_iVMm0NFBwK-uKhO6A_eXc,7618
|
|
6
|
+
lfox/evolution/hmc.py,sha256=uY3K8qTG_MrS80SH0YUUw5nCjBYAjBF3VUga50wRZ4M,3248
|
|
7
|
+
lfox/evolution/integrators.py,sha256=KV8cbZf2IO7PISLBbp4m8WMmKg4E858LMVNiLJSbkSI,2691
|
|
8
|
+
lfox/fermions/__init__.py,sha256=Ni96Ch3ZxTh6LS3dKi827cKGrQ0Me82d-5qiyLwrySc,421
|
|
9
|
+
lfox/fermions/solver.py,sha256=8sOYhbtP6C4_xOELMfhQDvVEEawhPShJMGu0FVd5Tzk,915
|
|
10
|
+
lfox/fermions/spin.py,sha256=stDd_FrNVxKJ7oSezT_nU1Nepi6skdVZvYnfxJd2Iss,2459
|
|
11
|
+
lfox/fermions/wilson.py,sha256=BaOfr6XuGb0Nw_A0HZ95TqbNzhpsXeE9BTkwicpOcck,1130
|
|
12
|
+
lfox/lattice.py,sha256=csqhcFfaihG6RkuCz9stKqDb5eYlLV4OCJhKNqWO5AM,6307
|
|
13
|
+
lfox-0.0.1.dist-info/licenses/LICENSE.txt,sha256=Lzg-pZAQCsldFl_IOxTU_oKU3tJVCUVdWAjqPUqpGb0,1101
|
|
14
|
+
lfox-0.0.1.dist-info/WHEEL,sha256=EmLkUISDECbcUx3FMCYOqokNOJqNp2r0d4mJzjErvvs,80
|
|
15
|
+
lfox-0.0.1.dist-info/METADATA,sha256=NaqUVCs_ZET1nDQ9De9ZyofqtyMpy0wCw6dUFVa7ybQ,5828
|
|
16
|
+
lfox-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023-present Ethan Neil <ethan.neil@colorado.edu>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|