Repository navigation
Expand file tree
/
Copy pathfields.py
More file actions
436 lines (355 loc) · 17.3 KB
/
Copy pathfields.py
File metadata and controls
436 lines (355 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
"""Particle field classes.
A :class:`Field` is declared with its gauge representations and expands into
explicit **component symbols** (the representation the whole pipeline works
in — commuting SymPy Symbols for bosons, ``IndexedBase`` for fermion flavor
structure).
- :class:`Scalar` — complex (default) or real; supports VEV registration
``φ⁰ → (v + h + i a)/√2`` (explicit 1/√2 per CONVENTIONS.md).
- :class:`Fermion` and its Weyl/Dirac/Majorana subclasses — chirality-aware,
flavor-indexed (dynamics arrive in Phase 4).
- :class:`GaugeBoson` — created by gauge groups, one component per generator.
Discrete-symmetry membership is registered on the group
(``S3.assign('2', H1, H2)``), not in ``reps``, because discrete multiplets
usually span several fields.
"""
import sympy as sp
from .conventions import SQRT2
from .groups.base import GaugeGroup
from .texsymbol import tex_symbol
__all__ = ["Field", "Scalar", "Fermion", "WeylFermion", "DiracFermion",
"MajoranaFermion", "GaugeBoson", "dag", "hc", "conjugate_pair",
"bar_partner"]
#: {component IndexedBase: bar IndexedBase} and its inverse, populated by
#: every Fermion at construction time — lets Bilinear's hermitian conjugate
#: (vertices/bilinear.py) find "the bar of this field" / "the field of this
#: bar" without threading a Fermion reference through every call site.
_BAR_PARTNER = {}
def bar_partner(indexed_base):
"""The paired IndexedBase for a Fermion component or bar component.
``bar_partner(psi) -> psibar`` and ``bar_partner(psibar) -> psi``.
"""
return _BAR_PARTNER[indexed_base]
class Field:
"""Base class for all fields.
Args:
name: field name; used as prefix for auto-generated components.
reps: dict ``{GaugeGroup: representation}`` (charge for a U(1),
dimension label for SU(2)/SU(3)).
component_names: explicit component names (physics-friendly, e.g.
``['H1p', 'H10']`` for an SU(2) doublet). Default:
``name_1 … name_n`` (or just ``name`` for a singlet).
real: whether components are real symbols.
self_conjugate: particle is its own antiparticle.
tex: LaTeX name. For a one-component field without
``component_tex`` it also names the component.
component_tex: LaTeX names for the components (e.g.
``['H^+', 'H^0']``), carried by the component symbols themselves
(:class:`~feynlag.texsymbol.TexSymbol`) so ``sympy.latex`` of any
expression renders them. Default: raw component names.
"""
def __init__(self, name, reps=None, component_names=None, real=False,
self_conjugate=False, tex=None, component_tex=None):
self.name = name
self.tex = tex if tex is not None else name
self.reps = dict(reps) if reps else {}
self.self_conjugate = self_conjugate
self.real = real
for group in self.reps:
if not isinstance(group, GaugeGroup):
raise TypeError(
f"reps keys must be gauge groups; register discrete "
f"multiplets with group.assign(...): got {group!r}")
self.components = self._make_components(component_names, component_tex,
tex)
#: column matrix of components — use in matrix expressions.
self.mat = sp.Matrix(len(self.components), 1, self.components)
# ------------------------------------------------------------------ setup
@property
def dim(self):
"""Total number of gauge components (product over non-abelian reps)."""
d = 1
for group, rep in self.reps.items():
d *= group.rep_dim(rep)
return d
def _component_symbol(self, cname, tex=None):
assumptions = {"real": True} if self.real else {}
return tex_symbol(cname, tex, **assumptions)
def _make_components(self, component_names, component_tex=None, tex=None):
n = self.dim
if component_names is None:
component_names = ([self.name] if n == 1 else
[f"{self.name}_{i + 1}" for i in range(n)])
if len(component_names) != n:
raise ValueError(f"{self.name}: expected {n} component names, "
f"got {len(component_names)}")
if component_tex is None:
component_tex = [tex] if n == 1 else [None] * n
if len(component_tex) != n:
raise ValueError(f"{self.name}: expected {n} component tex names, "
f"got {len(component_tex)}")
return [self._component_symbol(c, t)
for c, t in zip(component_names, component_tex)]
# ------------------------------------------------------------- interface
def dag(self):
"""Hermitian conjugate of the component column: a row Matrix."""
return self.mat.conjugate().T
def generators(self, group):
"""Generator matrices of ``group`` acting on this field's FULL
component space (Kronecker product over all non-abelian reps).
"""
if group not in self.reps:
# singlet: transforms trivially
return [sp.zeros(self.dim, self.dim)] * group.n_generators
# Build the Kronecker factors in declaration order.
factor_dims = [(g, g.rep_dim(r)) for g, r in self.reps.items()]
gens = []
for T in group.generators(self.reps[group]):
M = sp.Matrix([[1]])
for g, d in factor_dims:
block = T if g == group else sp.eye(d)
M = sp.Matrix(sp.kronecker_product(M, block))
gens.append(M)
return gens
def charge(self, u1_group):
"""U(1) charge of this field (0 if not charged under it)."""
return sp.sympify(self.reps.get(u1_group, 0))
def __repr__(self):
return f"{type(self).__name__}({self.name!r})"
def _repr_latex_(self):
name = self.tex if self.tex != self.name else sp.latex(sp.Symbol(self.name))
if len(self.components) == 1:
body = sp.latex(self.components[0])
else:
comps = ", ".join(sp.latex(c) for c in self.components)
body = f"{name} = ({comps})"
return f"$\\displaystyle {body}$"
def __getitem__(self, i):
return self.components[i]
def __len__(self):
return len(self.components)
def named(self):
"""``{name: object}`` of everything reachable as ``field.<name>``:
the components, a fermion's bar components (``<component>bar``) and a
scalar's VEV fluctuations (``<component>_r`` / ``<component>_i``)."""
attrs = self.__dict__
out = {}
for comp in attrs.get("components", ()):
out[str(getattr(comp, "label", comp))] = comp
for bar in attrs.get("bar_components", ()):
out[str(bar.label)] = bar
for _vev, re, im in attrs.get("vev_expansions", {}).values():
out[str(re)] = re
if im is not None:
out[str(im)] = im
return out
def __getattr__(self, name):
"""Access a component by its declared name: ``H.H0``, ``PsiL.EL``,
``PsiL.ELbar``, and after :meth:`Scalar.expand_vev` ``H.H0_r``.
Only reached when ordinary attribute lookup fails, and it returns the
*stored* object, so a tex-carrying symbol keeps its identity (never
rebuild one by name).
"""
if name.startswith("_"):
raise AttributeError(name)
table = self.named()
if name in table:
return table[name]
raise AttributeError(
f"{type(self).__name__} {self.__dict__.get('name', '?')!r} has "
f"no attribute or component {name!r}; components: "
f"{', '.join(table) or '(none)'}")
class Scalar(Field):
"""Spin-0 field.
``vev_expansions`` maps a component symbol to its EWSB decomposition
``(vev, real_part, imag_part)``: complex components expand as
``φ → (v + h + i a)/√2`` (explicit 1/√2, CONVENTIONS.md); real components
shift in place as ``φ → v + φ`` (no 1/√2 — that normalization belongs to
the complex-field decomposition).
"""
spin = 0
def __init__(self, name, reps=None, component_names=None, real=False,
self_conjugate=None, tex=None, component_tex=None):
if self_conjugate is None:
self_conjugate = real
super().__init__(name, reps=reps, component_names=component_names,
real=real, self_conjugate=self_conjugate, tex=tex,
component_tex=component_tex)
#: {component: (vev_symbol, re_symbol, im_symbol_or_None)}
self.vev_expansions = {}
def expand_vev(self, vev_map, tex=None):
"""Register VEVs for components: ``{component_symbol: vev}``.
For a complex component ``phi``, creates real symbols ``phi_r``,
``phi_i`` and registers ``phi → (v + phi_r + i·phi_i)/√2``.
For a real component, registers ``phi → v + phi``.
``vev`` may be a Parameter or a SymPy symbol/expression.
``tex`` optionally maps a new fluctuation's *name* (``phi_r``,
``phi_i``) to a LaTeX name, e.g. ``{"H0_r": "h", "H0_i": "G^0"}``
(see :class:`~feynlag.texsymbol.TexSymbol`).
"""
tex = tex or {}
for comp, vev in vev_map.items():
if comp not in self.components:
raise ValueError(f"{comp} is not a component of {self.name}")
vev_expr = sp.sympify(getattr(vev, "symbol", vev))
if self.real:
self.vev_expansions[comp] = (vev_expr, comp, None)
else:
re = tex_symbol(f"{comp.name}_r", tex.get(f"{comp.name}_r"),
real=True)
im = tex_symbol(f"{comp.name}_i", tex.get(f"{comp.name}_i"),
real=True)
self.vev_expansions[comp] = (vev_expr, re, im)
return self
@property
def shift_map(self):
"""Substitution dict expanding VEV'd components around the vacuum."""
shift = {}
for comp, (vev, re, im) in self.vev_expansions.items():
if im is None:
shift[comp] = vev + comp
else:
shift[comp] = (vev + re + sp.I * im) / SQRT2
return shift
@property
def fluctuations(self):
"""All real fluctuation symbols introduced by :meth:`expand_vev`."""
out = []
for comp, (vev, re, im) in self.vev_expansions.items():
out.append(re)
if im is not None:
out.append(im)
return out
class Fermion(Field):
"""Spin-1/2 field with chirality and flavor structure.
Components are ``IndexedBase`` objects: ``psi[i]`` is flavor ``i`` of a
gauge component. Full fermionic dynamics (bilinear vertex extraction,
SVD/Takagi diagonalization) arrive in Phase 4; the declaration layer
already supports invariance checking through the gauge representations.
"""
spin = sp.Rational(1, 2)
def __init__(self, name, reps=None, component_names=None, chirality=None,
nflavors=1, self_conjugate=False, tex=None, component_tex=None):
if chirality not in (None, "L", "R"):
raise ValueError("chirality must be 'L', 'R' or None")
self.chirality = chirality
self.nflavors = nflavors
super().__init__(name, reps=reps, component_names=component_names,
real=False, self_conjugate=self_conjugate, tex=tex,
component_tex=component_tex)
#: Dirac adjoints ψ̄, one IndexedBase per gauge component
self.bar_components = [sp.IndexedBase(tex_symbol(
f"{c.label}bar",
None if (t := getattr(c.label, "_tex", None)) is None
else rf"\overline{{{t}}}"))
for c in self.components]
for comp, bar in zip(self.components, self.bar_components):
_BAR_PARTNER[comp] = bar
_BAR_PARTNER[bar] = comp
def _component_symbol(self, cname, tex=None):
return sp.IndexedBase(tex_symbol(cname, tex))
def bar(self, component):
"""The ψ̄ IndexedBase matching a gauge component."""
return self.bar_components[self.components.index(component)]
def dag(self):
raise NotImplementedError(
"use the fermion bilinear track (feynlag.vertices.bilinear); "
"fermions have no bosonic dagger")
class WeylFermion(Fermion):
"""Two-component chiral fermion (chirality required)."""
def __init__(self, name, reps=None, chirality="L", **kwargs):
if chirality not in ("L", "R"):
raise ValueError("a Weyl fermion needs chirality 'L' or 'R'")
super().__init__(name, reps=reps, chirality=chirality, **kwargs)
class DiracFermion(Fermion):
"""Four-component fermion (both chiralities) — **not yet supported**.
A genuine 4-component field would need its own mass-sector and
diagonalization path validated against physics; the library deliberately
represents Dirac/vector-like fermions as TWO :class:`WeylFermion`\\ s with
identical reps (one ``chirality='L'``, one ``'R'``) so every stage reuses
the tested Weyl machinery — see ``examples/sm_vll.py``. Constructing this
class raises rather than silently producing unverified vertices.
"""
def __init__(self, *args, **kwargs):
raise NotImplementedError(
"DiracFermion is not supported; model a Dirac or vector-like "
"fermion as two WeylFermions with identical reps (chirality='L' "
"and 'R') — see examples/sm_vll.py. This keeps every stage on the "
"tested Weyl path (mass matrix, SVD diagonalization, bilinear "
"extraction) instead of an unverified 4-component path.")
class MajoranaFermion(Fermion):
"""Self-conjugate fermion; mass matrix is complex symmetric (Takagi)."""
def __init__(self, name, reps=None, **kwargs):
kwargs["self_conjugate"] = True
super().__init__(name, reps=reps, **kwargs)
class GaugeBoson(Field):
"""Spin-1 gauge field; one real component per group generator.
Create through the group: ``SU2L.bosons('W')`` → components W_1..W_3.
"""
spin = 1
def __init__(self, name, group, component_names=None, tex=None,
component_tex=None):
self.group = group
n = group.n_generators
if component_names is None and n > 1:
component_names = [f"{name}_{i + 1}" for i in range(n)]
reps = {}
if not group.abelian:
# adjoint rep, labelled by its dimension (= number of generators);
# SUN.generators resolves the int ``N²−1`` to the adjoint Dynkin
# labels and returns the structure-constant basis ``(T^a)_{bc}=−if``.
reps = {group: n}
super().__init__(name, reps=reps,
component_names=component_names if n > 1 else [name],
real=True, self_conjugate=True, tex=tex,
component_tex=component_tex)
def _gauge_bosons(self, name=None, component_tex=None, tex=None):
"""Create (once) and return this group's gauge boson field.
A later call's ``component_tex``/``tex`` must agree with the first one's
(the field is cached, so a different LaTeX name would be ignored).
"""
if self._gauge_bosons is None:
self._gauge_bosons = GaugeBoson(name or self.name, self, tex=tex,
component_tex=component_tex)
return self._gauge_bosons
W = self._gauge_bosons
if component_tex is not None:
have = [getattr(c, "_tex", None) for c in W.components]
if list(component_tex) != have:
raise ValueError(
f"{self.name}: gauge bosons already created with component "
f"tex {have}, not {list(component_tex)}")
if tex is not None and tex != W.tex:
raise ValueError(f"{self.name}: gauge bosons already created with "
f"tex {W.tex!r}, not {tex!r}")
return W
GaugeGroup.bosons = _gauge_bosons
def dag(obj):
"""Hermitian conjugate: Field → row Matrix; Matrix → ``.H``; expr →
complex conjugate (valid for bosonic expressions)."""
if isinstance(obj, Field):
return obj.dag()
if isinstance(obj, sp.MatrixBase):
return obj.conjugate().T
return sp.conjugate(obj)
def hc(expr):
"""Hermitian conjugate of a bosonic Lagrangian term (complex conjugate).
Write ``term + hc(term)`` for ``term + h.c.``. Fermion bilinears need
the Phase-4 machinery.
"""
return sp.conjugate(expr)
def conjugate_pair(sym, name=None, tex=None):
"""Antiparticle symbol for a complex physical field.
The vertex extractor works on plain Symbols, so ``conjugate(G⁺)`` must be
rewritten as the physical ``G⁻`` symbol first.
Args:
sym: the complex field symbol (e.g. ``Gp``).
name: name for the conjugate symbol (default ``{sym}_c``; pass the
physics name, e.g. ``'Gm'``).
tex: LaTeX name for the conjugate symbol (e.g. ``'G^-'``).
Returns:
``(partner_symbol, {conjugate(sym): partner_symbol})`` — merge the
dicts of several pairs and pass as ``conjugate_map`` to
``Model.interactions`` / ``Model.feynman_rules``.
"""
partner = tex_symbol(name if name is not None else f"{sym.name}_c", tex)
return partner, {sp.conjugate(sym): partner}