-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChPT.py
More file actions
executable file
·1803 lines (1504 loc) · 84.6 KB
/
Copy pathChPT.py
File metadata and controls
executable file
·1803 lines (1504 loc) · 84.6 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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import re
import sys,os
import subprocess
import traceback
from collections.abc import Mapping
from copy import copy, deepcopy
from datetime import datetime
from fractions import Fraction
from itertools import chain
from pathlib import Path
from textwrap import TextWrapper, indent, dedent, fill
import sympy as sp
from sympy.parsing.sympy_parser import parse_expr
from permute import Permutation, Span, Sn, Trivial, Distributions
import logging
logger = logging.getLogger("ChPT")
logextra = {'where': ''}
VERBOSE = logging.INFO - 1
logging.addLevelName(VERBOSE, "VERBOSE")
# From https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output
# ... with some customization
class ColorFormatter(logging.Formatter):
def __init__(self, format):
super().__init__()
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
RESET = "\033[0m"
COLOR = "\033[3%dm"
BOLD = "\033[1m"
REVERSE = "\033[7m"
self.formats = {
logging.DEBUG: COLOR%BLUE + format + RESET,
VERBOSE: COLOR%WHITE + format + RESET,
logging.INFO: COLOR%WHITE + BOLD + format + RESET,
logging.WARNING: COLOR%YELLOW + BOLD + format + RESET,
logging.ERROR: COLOR%RED + BOLD + format + RESET,
logging.CRITICAL: COLOR%RED + REVERSE + format + RESET,
None: format
}
def format(self, record):
return logging.Formatter(fmt=self.formats.get(record.levelno, self.formats[None])).format(record)
AUTHOR = "ChPTlib, by Mattias Sjö 2025"
PARTICLES = {
'M': 'meson',
'V': 'vector',
'A': 'axial vector',
'S': 'scalar',
'P': 'pseudoscalar'}
# Since \n is not allowed in f-strings, use this instead.
# Supports various indentation options as well for convenience.
def newline(indent=0, *, prefix='', infix='', suffix='', indent_str=' '*4):
return prefix + '\n' + infix + indent_str*indent + suffix
# Like ', '.join(items) but with final "and" (Oxford comma by default)
def and_join(items, oxford=True):
items = list(items)
match len(items):
case 0:
return ""
case 1:
return items[0]
case 2:
return f"{items[0]} and {items[1]}"
case _:
return f"{', '.join(items[:-1])}{',' if oxford else ''} and {items[-1]}"
class ChPTError(Exception):
pass
# Convert power-counting orders between O(p^X) format and NXLO format
def order_OtoN(order):
if order < 2 or order % 2:
raise ChPTError(f"Invalid power-counting order: O(p^{order})")
if order > 6:
return f"N{order//2-1}LO"
else:
return f"{'N'*(order//2-1)}LO"
def order_NtoO(order):
if re.fullmatch('N*LO', order):
return 2*len(order) - 2
elif re.fullmatch('N[0-9]+LO', order):
return 2*int(order[1:-2]) + 2
else:
raise ChPTError(f"Invalid power-counting order: '{order}'")
class Diagram:
def __init__(self, name, n_ext):
logger.debug(f"Initializing {n_ext}-leg diagram {name}", extra=logextra)
self.name = name
self.n_legs = n_ext
self.symmetry_factor = {None: '1'}
self.permutation_group = None
self.flags = []
self.source = []
self.vertices = []
self.vertex_name_map = {}
self.edges = []
self.external = []
def get_vertex(self, name_or_index):
if string in self.vertex_name_map:
return self.vertices[ self.vertex_name_map[name_or_index] ]
else:
return self.vertices[int(name_or_index) - 1]
def add_vertex(self, vertex):
if vertex.name:
if vertex.name in self.vertex_name_map:
raise ChPTError(f"Ambiguous vertex name: '{vertex.name}'")
self.vertex_name_map[vertex.name] = len(self.vertices)
self.vertices.append(vertex)
logger.debug(f"Added vertex {len(self.vertices)}{f' ({vertex.name})' if vertex.name else ''}: {vertex}", extra=logextra)
# This should not carry over when copying a vertex,
# and it's easier to zero it here than to mess with copy()
vertex.ingoing_momenta = []
def add_edge(self, edge):
# Edge constructor performs bounds checks but imports can circumvent them
if edge.source >= len(self.vertices) or edge.destination >= len(self.vertices):
raise ChPTError(f"Importing edge {edge} into {len(self.vertices)}-vertex diagram")
self.edges.append(edge)
logger.debug(f"Added edge {edge}", extra=logextra)
def set_symmetry_factor(self, tokens):
self.symmetry_factor[None] = tokens[0];
for token in tokens[1:]:
split = token.split(':')
if len(split) != 2 or not split[0] or not split[1]:
raise ChPTError("Alternative symmetry factor should be of the format VARIABLE:FACTOR")
self.symmetry_factor[split[0]] = split[1]
def set_permutation_group(self, tokens):
if self.permutation_group is not None:
raise ChPTError("Multiple symmetry group specifications in the same diagram")
if not tokens or not tokens[0]:
raise ChPTError("Empty symmetry group specification")
if tokens[0][0] == '[':
if len(tokens) != 1:
raise ChPTError("Only a single distribution may be specified")
if tokens[0][-1] != ']' or '[' in tokens[0][1:] or ']' in tokens[0][:-1]:
raise ChPTError(f"Sincle bracket-enclosed list expected, got '{tokens[0]}'")
sets = []
equiv = []
for token in tokens[0][1:-1].split(','):
if not token or not token[0].isdigit():
raise ChPTError(f"Number (and possible label) expected, got '{tokens}'")
index = 1
while index < len(token) and token[index].isdigit():
index += 1
sets.append(int(token[:index]))
if index >= len(token):
equiv.append(True)
elif token[index:] == '*':
equiv.append(False)
elif token[index:].isalnum():
equiv.append(token[index:])
else:
raise ChPTError(f"Malformed set label: expected '*' or alphanumeric string, got '{token[index:]}'")
if sum(sets) != self.n_legs:
raise ChPTError(f"Distribution should distribute {self.n_legs} external momenta, got {sum(sets)}")
self.permutation_group = Distributions(sets, equiv)
else:
self.permutation_group = Span(
Permutation.parse_cycles(size=self.n_legs, string=token, sep=',', base=1) for token in tokens
).permutations()
def add_flags(self, tokens):
for token in tokens:
eq = token.find('=')
if eq < 0:
self.flags.append((token, None))
else:
self.flags.append((token[:eq], token[eq+1:]))
def legs_up_to(self, legs, particle):
count = 0
for p in PARTICLES:
count += legs.get(p, 0)
if p == particle:
return count
def connect_edge(self, edge, placeholder=False):
if placeholder:
self.vertices[edge.source] .ingoing_momenta.append(None)
self.vertices[edge.destination].ingoing_momenta.append(None)
else:
self.vertices[edge.source] .ingoing_momenta.append(
Momentum(f"-({edge.propagator.momentum})", implicit=True))
self.vertices[edge.destination].ingoing_momenta.append(
Momentum(f"+({edge.propagator.momentum})", implicit=True))
def connect_momenta(self, propagators, ext_legs, momenta):
# Clear things in case this diagram is partly copied from another
self.external.clear()
for vertex in self.vertices:
vertex.ingoing_momenta.clear()
needs_resolution = False
for edge in self.edges:
if edge.unresolved:
needs_resolution = True
self.connect_edge(edge, placeholder=True)
else:
self.connect_edge(edge)
for particle in PARTICLES:
for i, vertex in enumerate(self.vertices):
count = self.legs_up_to(vertex.legs, particle)
if count < len(vertex.ingoing_momenta):
raise ChPTError(f"Mismatched number of external {PARTICLES[particle]} legs in diagram '{self.name}' (discovered at vertex '{i+1}')")
for _ in range(count - len(vertex.ingoing_momenta)):
self.external.append(i);
vertex.ingoing_momenta.append(Momentum(f"+p{len(self.external)}", implicit=True))
logger.debug(f"Connected external leg {len(self.external)} ({PARTICLES[particle]}) to vertex {i+1}", extra=logextra)
if len(self.external) != self.legs_up_to(ext_legs, particle):
raise ChPTError(f"Mismatched number of external {PARTICLES[particle]} legs in diagram '{self.name}'")
if needs_resolution:
self.resolve_momenta(momenta)
def resolve_momenta(self, momenta):
# Remove placeholders for unresolved propagators
# These were used to get the number of external momenta right
# but are just in the way now
for vertex in self.vertices:
vertex.ingoing_momenta = [q for q in vertex.ingoing_momenta if q is not None]
while True:
more_needed = False
made_progress = False
for edge in self.edges:
if not edge.unresolved:
continue
# Looking only at source vertices for simplicity
# There should be no scenario where this hinders resolution
vertex = self.vertices[edge.source]
deficit = vertex.n_legs() - len(vertex.ingoing_momenta)
if deficit < 0:
raise ChPTError(f"{-deficit} too many momenta in vertex {vertex}")
elif deficit > 1:
more_needed = True
elif deficit == 1:
made_progress = True
edge.propagator = Propagator(
[sum(vertex.ingoing_momenta), edge.propagator],
momenta)
edge.unresolved = False
logger.debug(f"Resolved momentum routing for edge {edge}", extra=logextra)
self.connect_edge(edge)
if not more_needed:
break
if not made_progress:
raise ChPTError(f"Failed to resolve momentum routing in {self.name}")
def check_CoM(self, propagators, symbols, replacements, shortcircuit=False):
locals().update(symbols)
violations = []
for perm in self.permutation_group:
for i, vertex in enumerate(self.vertices):
zero = sum(vertex.ingoing_momenta)
logging.debug(f"CoM, diagram {self.name}, vertex {i+1}, permutation {perm}: {zero}", extra=logextra)
zero.substitute({f'p{j+1}' : f'p{perm[j]+1}' for j in range(len(perm))})
zero.substitute(replacements)
if zero != 0:
if shortcircuit:
return False
violations.append( (i+1, perm, str(zero)) )
return True if shortcircuit else violations
def print_CoM(self, propagators, formfile):
for i, vertex in enumerate(self.vertices):
print(f"local [{self.name}:{vertex.name or i+1}] = {'+'.join(str(p) for p in vertex.ingoing_momenta)};", file=formfile)
def print_graph(self, propagators, mathfile):
VertexShapeMap = { 2 : '"Circle"', 4 : '"Circle"', 6 : '"Square"', 8 : '"Triangle"' }
VertexSizeMap = { 2 : 0.001, 4 : 0.1, 6 : 0.15, 8 : 0.2 }
print(indent(dedent(f"""
{self.name} -> EdgeTaggedGraph[
{{
{newline(5, prefix=',').join(
[f"DirectedEdge[{edge.source+1}, {edge.destination+1}, {edge.propagator.momentum}]"
for edge in self.edges]
+
[f"DirectedEdge[mu{ext+1}, {vertex+1}, p{ext+1}]"
for ext, vertex in enumerate(self.external)]
)}
}},
VertexShapeFunction -> {{
{newline(5, prefix=',').join(
[f'{i+1} -> {VertexShapeMap[vertex.order]}'
for i,vertex in enumerate(self.vertices)]
+
[f'mu{ext+1} -> "Circle"'
for ext in range(len(self.external))]
)}
}},
VertexSize -> {{
{newline(5, prefix=',').join(
[f'{i+1} -> {VertexSizeMap[vertex.order]}'
for i,vertex in enumerate(self.vertices)]
+
[f'mu{ext+1} -> 0.001'
for ext in range(len(self.external))]
)}
}},
VertexLabels -> None,
VertexStyle -> Black,
EdgeStyle -> Black,
EdgeLabels -> "EdgeTag"
]"""), " "*4), file=mathfile, end='')
def list_vertices(self):
vertex_roster = {}
for vertex in self.vertices:
vertex_roster[vertex] = (vertex_roster.get(vertex, 0)) + 1
return vertex_roster
@staticmethod
def symmetry_factor_FORM(factor):
return re.sub(r'([0-9]+)!', r'fac_(\1)', factor)
def permute_FORM(self, perm, legs):
replace = ', '.join(f'p{i+1},p{perm[i]+1}' for i in range(len(perm)))
for p in PARTICLES:
if p not in legs:
continue
try:
restricted = perm.on_range(self.legs_up_to(legs, p) - legs[p], self.legs_up_to(legs, p))
except ValueError:
raise ChPTError(f"External leg permutation {perm} exchanges {PARTICLES[p]}s and non-{PARTICLES[p]}s")
match p:
case 'M':
array = 'extflav'
case 'V'|'A':
array = 'external'
case _:
continue
#logger.debug(f"Permutation {perm} on {p} -> replace {restricted}", extra=logextra)
replace += ',\n' + ' '*(4 + len('+ replace_(')) + ', '.join(f'{array}[{i+1}],{array}[{restricted[i]+1}]' for i in range(legs[p]))
return f"replace_({replace})"
def define_FORM(self, global_vertex_roster, propagators, legs, loops, formdir, prefix = ''):
vertex_roster = {}
vertex_tag_map = {}
# Figure out how many vertices of each kind are needed in the diagram,
# and map the local vertex tag (as used by the diagram) to the global one
# (as used by the set of identical vertices of the given kind defined in FORM)
for index, vertex in enumerate(self.vertices):
vertex_tag_map[index] = vertex_roster.get(vertex, 0)
vertex_roster[vertex] = vertex_tag_map[index] + 1
# Update the global vertex roster
for vertex, count in vertex_roster.items():
if (global_vertex_roster.get(vertex, 0)) < count:
global_vertex_roster[vertex] = count
diagram = f"{prefix}diagram{self.name}"
# Write the diagram's flags
with open(f"{formdir}/flags/on_{diagram}.hf", 'w') as on, open(f"{formdir}/flags/off_{diagram}.hf", 'w') as off:
print_info_FORM(on, f"This file enables the flags for {diagram}")
print_info_FORM(off, f"This file disables the flags for {diagram}")
for flag,value in self.flags:
if value is None:
print(f'#define {flag}', file=on)
else:
print(f'#define {flag} "{value}"', file=on)
print(f'#undefine {flag}', file=off)
logger.log(VERBOSE, f"Wrote output file {on.name}", extra=logextra)
logger.log(VERBOSE, f"Wrote output file {off.name}", extra=logextra)
# Define the diagram as the product of its vertices
with open(f"{formdir}/diagrams/{diagram}.hf", 'w') as formfile:
print_info_FORM(formfile, f"This file defines and assembles {diagram}{newline()}defined as follows, starting at {newline(1).join(self.source)}")
# Compose diagram
print(dedent(f"""\
global {diagram} = {' * '.join(
f'i_*vert{v.name_FORM(vertex_tag_map[i])}'
for i,v in enumerate(self.vertices))
}"""), file=formfile, end='')
# Divide by symmetry factor
if len(self.symmetry_factor) > 2 or self.symmetry_factor[None] != '1':
print(indent(dedent(f"""
#ifdef `NOSYMFACT'{''.join(f'''
#elseif isdefined({var})
/ ({self.symmetry_factor_FORM(sym)})'''
for var,sym in self.symmetry_factor.items() if var)}
#else
/ ({self.symmetry_factor_FORM(self.symmetry_factor[None])})
#endif
;"""),' '*4), file=formfile)
else:
print(';', file=formfile)
# Connect external lines
ext = 0
for particle in PARTICLES:
for _ in range( legs.get(particle, 0) ):
tag = self.vertices[self.external[ext]].name_FORM(vertex_tag_map[self.external[ext]])
ext += 1
match particle:
case 'M':
print(f"id,all phi(flav?f{tag}x, ?lorentz) = replace_(flav, extflav[{ext}]) * derivs(p{ext}, ?lorentz);", file=formfile)
case 'V':
# NOTE: the use of ext is to ensure that Schoonschip notation doesn't spoil the
# pattern matching of subsequent id's, which it would with a naked vector
# NOTE: QED uses A for the photon, otherwise that is the axial vector
print('\n'.join([
"#ifdef `QED'",
f" id,all A(?lorentz, mu?mu{tag}x) = ext(external[{ext}], mu) * derivs(p{ext}, ?lorentz);",
"#else",
f" id,all V(?lorentz, mu?mu{tag}x) = ext(external[{ext}], mu) * derivs(p{ext}, ?lorentz);",
"#endif"
]), file=formfile)
case 'A':
print(f"id,all A(?lorentz, mu?mu{tag}x) = ext(external[{ext}], mu) * derivs(p{ext}, ?lorentz);", file=formfile)
case 'S' | 'P':
print(f"id,all {particle}(?lorentz) = derivs(p{ext}, ?lorentz);", file=formfile)
case _:
raise ChPTError(f"Particle type '{particle}' not implemented for pickout")
# Connect the edges, picking out fields from the respective vertices
for i,edge in enumerate(self.edges):
src_tag = self.vertices[edge.source ].name_FORM(vertex_tag_map[edge.source ])
dst_tag = self.vertices[edge.destination].name_FORM(vertex_tag_map[edge.destination])
momentum = edge.propagator.momentum
if edge.propagator.flav_dependent:
idxa = f'index{i+1}a'
idxb = f'index{i+1}b'
prop = f'propmatrix({edge.propagator.momentum}, {idxa}, {idxb})'
else:
idxa = f'index{i+1}'
idxb = idxa
prop = f'prop({edge.propagator.momentum},{edge.propagator.mass_squared})'
print(dedent(f"""\
multiply i_ * {prop};
id,all phi(flav?f{src_tag}x, ?lorentz) = replace_(flav, {idxa}) * derivs(-({momentum}), ?lorentz);
id,all phi(flav?f{dst_tag}x, ?lorentz) = replace_(flav, {idxb}) * derivs(+({momentum}), ?lorentz);"""
), file=formfile)
# Do all contractions, etc.
print(dedent(f"""\
id ext(ext1?, mu?) = ext1(mu);
#call doderivs
#call dotrace({diagram})"""), file=formfile)
logger.log(VERBOSE, f"Wrote output file {formfile.name}", extra=logextra)
# If necessary, permute external legs
with open(f"{formdir}/permute/{diagram}.hf", 'w') as formfile:
if len(self.permutation_group) > 1:
logger.debug(f"Permutation group of {self.name} [size {len(self.permutation_group)}] is {', '.join(perm.oneline_string(sep=',', base=1) for perm in self.permutation_group)}", extra=logextra)
print_info_FORM(formfile, f"This file permutes the external legs of {diagram}.")
print(dedent(f"""\
#call nskip({diagram})
multiply (1"""), file=formfile)
for perm in self.permutation_group:
if perm.is_identity():
continue
print(f" + {self.permute_FORM(perm, legs)}", file=formfile)
print(dedent(f"""\
);
.sort:>>permute {diagram}<<;"""), file=formfile)
else:
print_info_FORM(formfile, f"This file is an empty placeholder, since the permutation group is trivial.")
logger.log(VERBOSE, f"Wrote output file {formfile.name}", extra=logextra)
with open(f"{formdir}/loops/{diagram}.hf", 'w') as formfile:
print_info_FORM(formfile, f"This file identifies the loop integrals in {diagram}.")
# Identify loop integrals FIXME
loops_present = self.get_loop_momenta(loops)
if loops_present:
# Function representing integral over all present loop momenta
integral = f"i_^{len(loops_present)} * int{''.join(sorted(loops_present))}"
# All propagators that contain only the present loop momenta
props_present = [i for i,p in enumerate(propagators)
if (p.momentum.vectors() & loops) <= loops_present]
print(dedent(f"""\
#call nskip({diagram})
id {'*'.join(f'prop{i+1}^n{i+1}?' for i in props_present)}
= {integral}({','.join(f'n{i+1}' for i in props_present)});
"""),
file=formfile)
logger.log(VERBOSE, f"Wrote output file {formfile.name}", extra=logextra)
return diagram
def get_loop_momenta(self, loops):
return {l for edge in self.edges for l in edge.propagator.momentum.vectors() if l in loops}
def get_order(self, loops):
return 2 + 2*len(self.get_loop_momenta(loops)) + sum(vert.order - 2 for vert in self.vertices)
def get_particle_content(self):
return {p for vert in self.vertices for p in vert.legs.keys()}
def specify_legs(token, legs):
try:
if token.isnumeric():
particle = 'M'
number = int(token)
elif token[0].isnumeric():
particle = token[-1]
number = int(token[:-1])
elif token in PARTICLES:
particle = token
number = 1
else:
return False
except ValueError as err:
raise ChPTError(f"Failed to read number of {PARTICLES[particle]}s: {err}")
if particle not in PARTICLES:
raise ChPTError(f"Invalid particle type: {particle}")
if particle in legs:
raise ChPTError(f"Number of {PARTICLES[particle]} legs already specified")
legs[particle] = number
return True
class Momentum:
def __init__(self, momentum, vectors=set(), implicit=False):
if isinstance(momentum, Momentum):
self.components = copy(momentum.components)
elif isinstance(momentum, str):
self.components = Momentum.parse_momentum(momentum, vectors, implicit)
elif isinstance(momentum, Mapping):
self.components = momentum
elif momentum == 0:
self.components = {}
@staticmethod
def parse_momentum(string, vectors, implicit):
# This could be done using an auxiliary parser class, but the amount of state is
# so puny (just the index and copies of the arguments of this method) that it's
# easier to just put the class methods as inner methods and make the necessary
# variables nonlocal.
index = 0
# Location in string, for error reporting
def where():
nonlocal string, index
return f"in '{string}' (character {index})"
# Parses an expression up to end-of-string or close-paren
def get_expression(depth):
nonlocal string, index
result = None
term = get_term(depth)
# Obtain terms until none remain, add them together
while term is not None:
if result is None:
result = term
else:
if isinstance(result, Momentum) != isinstance(term, Momentum):
#print(f"{term=}")
raise ChPTError(f"Attempting to add scalar and vector {where()}")
result = result + term
term = get_term(depth)
if result is None:
raise ChPTError(f"Empty expression {where()}")
if depth == 0 and index < len(string):
raise ChPTError(f"Unexpected ')' {where()}")
index += 1
return result
# Parses a term (product of factors preceded by a string of +/-
# The +/- string is always optional but the previous term will not end correctly
# unless at least one +/- is used as a separator.
# Returns None if the expression ends
def get_term(depth):
nonlocal string, index, vectors, implicit
term = Fraction(1)
has_sign = False
has_factor = False
while index < len(string):
char = string[index]
if char.isspace():
pass
elif char == '+':
has_sign = True
elif char == '-':
has_sign = True
term *= -1
else:
# Obtain factors until none remain, multiply them together
factor, oper = get_factor(depth, first=True)
while factor is not None:
has_factor = True
if isinstance(factor, Momentum):
if oper == '/':
raise ChPTError(f"Division by vector {where()}")
if isinstance(term, Momentum):
raise ChPTError(f"Product of vectors {where()}")
term = term * factor
elif isinstance(factor, str):
if oper == '/':
raise ChPTError(f"Division by vector {where()}")
if isinstance(term, Momentum):
raise ChPTError(f"Product of vectors {where()}")
if factor not in vectors:
if not implicit:
raise ChPTError(f"Unknown vector: {factor}")
vectors.add(factor)
term = Momentum({factor: term})
else:
term = term * (Fraction(factor,1) if (oper == '*') else Fraction(1,factor))
factor, oper = get_factor(depth)
break
index += 1
if not has_factor:
if has_sign:
raise ChPTError(f"Expected term following '+' or '-' {where()}")
return None
return term
# Parses a factor (a number, a momentum, or a parenthesized expression)
# and returns it along with the preceding operator (* or /)
# The operator is an implicit * if the factor is the first in the term
# Returns None,None if the term (and possibly the expression) ends
def get_factor(depth, first=False):
nonlocal string, index
oper = '*' if first else None
while True:
char = string[index] if index < len(string) else 'end-of-string'
if char.isspace():
pass
elif char == '*' or char == '/':
if oper:
raise ChPTError(f"Unexpected {char} {where()}")
oper = char
elif char == '(':
index += 1
return get_expression(depth+1), oper if oper else '*'
elif char == '+' or char == '-' or char == ')' or char == 'end-of-string':
if oper and not first:
raise ChPTError(f"Expected factor between '{oper}' and '{char}' {where()}")
return None, None
elif char.isalnum():
start = index
index += 1
while index < len(string) and string[index].isalnum():
index += 1
# try-except is inefficient, but the only foolproof way I know of figuring out
# if a string is a valid int is to try to convert it to one
try:
factor = int(string[start:index])
#print(f"Numeric factor of {factor}")
except ValueError:
factor = string[start:index].strip()
#print(f"Vector factor of {factor}")
return factor, oper if oper else '*'
else:
raise ChPTError(f"Invalid operator '{char}' {where()}")
index += 1
# End of inner methods.
# This just wraps the initial call to get_expression
result = get_expression(depth=0)
if not isinstance(result, Momentum):
if result == 0:
result = Momentum(result)
else:
raise ChPTError(f"Expected momentum, but expression is scalar: '{string}'")
return result.components
def vectors(self):
return {vec for vec,coeff in self.components.items() if coeff != 0}
def substitute(self, substitutions):
for tries in range(len(substitutions)+1):
done = True
for vec,replacement in substitutions:
if vec in self.components and self.components[vec] != 0:
done = False
coeff = self.components.pop(vec)
self += coeff * Momentum(replacement)
if done:
return self
raise ChPTError(f"Infinite loop of substitutions encountered")
def substituted(self, substitutions):
return Momentum(self).substitute(substitutions)
def __pos__(self):
return Momentum({vec: +(self.components[vec]) for vec in self.vectors()})
def __neg__(self):
return Momentum({vec: -(self.components[vec]) for vec in self.vectors()})
def __iadd__(self, othr):
if isinstance(othr, Momentum):
for vec, coeff in othr.components.items():
self.components[vec] = self.components.get(vec, Fraction(0)) + coeff
elif othr != 0:
raise TypeError(f"Attempting to add scalar to momentum")
return self
def __add__(self, othr):
sum = Momentum(self)
sum += othr
return sum
def __radd__(self, othr):
return self + othr
def __isub__(self, othr):
if isinstance(othr, Momentum):
for vec, coeff in othr.components().items():
self.components[vec] = self.components.get(vec, Fraction(0)) - coeff
elif othr != 0:
raise TypeError(f"Attempting to add scalar to momentum")
return self
def __sub__(self, othr):
sum = Momentum(self)
sum -= othr
return sum
def __rsub__(self, othr):
return (self - othr) * -1
def __imul__(self, othr):
if isinstance(othr, Momentum):
raise TypeError(f"Momentum does not allow scalar products")
self.components = {vec : coeff*othr for vec,coeff in self.components.items()}
return self
def __mul__(self, othr):
prod = Momentum(self)
prod *= othr
return prod
def __rmul__(self, othr):
return self * othr
def __idiv__(self, othr):
if isinstance(othr, Momentum):
raise TypeError(f"Momentum does not allow division")
self.components = {vec : coeff*othr for vec,coeff in self.components.items()}
return self
def __div__(self, othr):
quot = Momentum(self)
quot /= othr
return quot
def __eq__(self, othr):
if isinstance(othr, Momentum):
svecs = self.vectors()
ovecs = othr.vectors()
return svecs == ovecs and all(self.components(v) == othr.components(v) for v in svecs)
else:
return othr == 0 and all(coeff == 0 for coeff in self.components.values())
def __str__(self):
return (lambda s : (s[1:] if s[0]=='+' else s) if s else '0')(''.join(f"{'-' if coeff < 0 else '+'}{f'{abs(coeff)}*' if abs(coeff) != 1 else ''}{vec}" for vec,coeff in self.components.items() if coeff != 0))
def __repr__(self):
return str(self)
def __hash__(self):
return hash(tuple(sorted((vec,self.components[vec]) for vec in self.vectors())))
class Vertex:
def __init__(self, tokens):
if not tokens:
raise ChPTError("Expected vertex definition after 'V'")
self.order = self.name = None
self.legs = {}
self.ingoing_momenta = []
for token in tokens:
if specify_legs(token, self.legs):
pass
elif token[-2:] == 'LO':
if self.order:
raise ChPTError("Order already specified")
self.order = order_NtoO(token)
else:
if self.name:
raise ChPTError("Vertex name already specified")
if token.strip().isnumeric():
raise ChPTError("Vertex name could be confused for vertex index")
self.name = token
if not self.order:
self.order = 2
if not self.legs:
raise ChPTError("No number of legs specified for vertex")
def n_legs(self):
return sum(self.legs.values())
def __str__(self):
return f"{order_OtoN(self.order)}.{'.'.join(f'{n}{p}' for p,n in self.legs.items())}"
def __repr__(self):
return str(self)
def __eq__(self, other):
# Note that names are not compared
return self.order == other.order and self.legs == other.legs
def __hash__(self):
return hash((self.order, *self.legs.items()))
def define_FORM(self, formfile, tag):
if set(self.legs.keys()) > set(PARTICLES.keys()):
raise ChPTError(f"Particles other than {and_join(list(PARTICLES.values()))} not supported by ChPT_vertex.hf")
name = self.name_FORM(tag)
print(f"#call makevertex({name},{self.order},{','.join(str(self.legs.get(p, 0)) for p in PARTICLES)})", file=formfile)
return f"vert{name}"
def name_FORM(self, tag=None):
return f"{order_OtoN(self.order)}x{''.join(f'{p}{n}' for p,n in self.legs.items() if n or p == 'M')}{'' if tag is None else f'x{tag+1}'}"
class Propagator:
def __init__(self, tokens, momenta):
if len(tokens) != 2:
raise ChPTError("Invalid propagator specification: expected momentum and mass")
self.momentum = Momentum(tokens[0], vectors=momenta, implicit=False)
self.mass_squared = tokens[1]
self.flav_dependent = (self.mass_squared == '*')
def __str__(self):
return f"({self.momentum})^2 - {'(flav-dependent)' if self.flav_dependent else self.mass_squared}"
class Edge:
def __init__(self, vertices, vertex_name_map, propagators, propagator_name_map, tokens):
if len(tokens) != 3 or any(not token for token in tokens):
raise ChPTError("Invalid edge specification: expected source, destination and propagator indices/names")
def get_index(token, list, name_map, type):
if token in name_map:
index = name_map(token)
elif token.isnumeric():
index = int(token) - 1
if index < 0 or index >= len(list):
raise ChPTError(f"Index for {type} out of bounds: {token}")
else:
raise ChPTError(f"Unknown {type}: {token}")
return index
self.source = get_index(tokens[0], vertices, vertex_name_map, "vertex")
self.destination = get_index(tokens[1], vertices, vertex_name_map, "vertex")
self.unresolved = (tokens[2][0] == '*')
if self.unresolved:
self.propagator = tokens[2][1:]
else:
self.propagator = propagators[get_index(tokens[2], propagators, propagator_name_map, "propagator")]
def __str__(self):
return f"{self.source+1}-[{'(unresolved)' if self.unresolved else self.propagator}]->{self.destination+1}"
DEFAULT_STEPS = {
'includes': [
"* [includes]",
"#include- {0}/definitions.hf",
"#include- {0}/kinematics.hf"],
'replarg': [
"* [replarg] This flag enables replacements also inside function arguments",
"* Remove if e.g. propagators are to be handled separately",
"#define REPLARG"],
'vertices': [
"* [vertices] This creates all the vertices, and may be a bit time-consuming.",
"* The extraction from the Lagrangian is cached, so it should run faster in subsequent runs.",
"#include- {0}/vertices.hf"],
'diagram': [
"* [diagram] This sets up the Feynman rules of the diagram and contracts the flavor indices",
" #include- {0}/diagrams/`DIAGRAM'.hf"],
'permute': [
"* [permute] This performs all permutations of the diagram's external legs",
" #include- {0}/permute/`DIAGRAM'.hf"],
'replace': [
"* [replace] This enacts all replacements specified with 'R'",
" #call replacements(`DIAGRAM')"],
'loops': [
"* [loops] This identifies loop integrals",
" #call fullkinematics(`DIAGRAM')",
" #include- {0}/loops/`DIAGRAM'.hf"],
'check': [
"* [check] Check that all propagators were substituted",
" #call checkprops"],
'postprocess': ["* [postprocess]"],
'print': [
"* [print] Print the results",
"bracket `BRACKETS';",
"print +s;"]
}
DEFAULT_PROCEDURES = {
'nskip': ([], []),
'trivialkinematics': (
[".sort", "#call nskip(`DIAGRAM')"],
[".sort:>>trivial kinematics<<;"]
),
'fullkinematics': (
[".sort", "#call trivialkinematics(`DIAGRAM')", "#call nskip(`DIAGRAM')"],
[".sort:>>full kinematics<<;", "#call replacements(`DIAGRAM')"]
),
'replacements': (
[".sort", "#call nskip(`DIAGRAM')"],
[".sort:>>replacements<<;"]
),
'replacementlist': ("", "")
}
class Customization:
def __init__(self):
self.before = []
self.after = []
self.keep_default = True
class DiagramSet:
def __init__(self, filename, options=[]):
self.name = None
self.order = None
self.diagrams = {}
self.propagators = []
self.propagator_name_map = {}
self.vector_replacements = []
self.other_replacements = []
self.scalar_products = {}
self.loop_momenta = []
self.independent_momenta = []
self.independent_products = []