pacrunner 0.5.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.
Files changed (162) hide show
  1. pacrunner/__init__.py +55 -0
  2. pacrunner/_artifacts.py +259 -0
  3. pacrunner/_env.py +260 -0
  4. pacrunner/_libraries.py +314 -0
  5. pacrunner/_literal.py +52 -0
  6. pacrunner/_mad.py +276 -0
  7. pacrunner/_madgraph.py +357 -0
  8. pacrunner/_mgrun.py +110 -0
  9. pacrunner/_pyamplicol.py +134 -0
  10. pacrunner/_runtime.py +142 -0
  11. pacrunner/c/cuda/pool.cu +151 -0
  12. pacrunner/c/cuda/pool.h +55 -0
  13. pacrunner/c/cuda/uirgpu.c +103 -0
  14. pacrunner/c/cuda/uirgpu.h +70 -0
  15. pacrunner/c/cuda/uirgpu_pool.c +89 -0
  16. pacrunner/c/cuda/uirgpu_provider.c +103 -0
  17. pacrunner/c/cuda/uirgpu_umami.c +108 -0
  18. pacrunner/c/metal/PLAN.md +248 -0
  19. pacrunner/c/metal/df64.h +185 -0
  20. pacrunner/c/metal/metalpool.h +47 -0
  21. pacrunner/c/metal/metalpool.m +93 -0
  22. pacrunner/c/metal/msl_shim.h +86 -0
  23. pacrunner/c/metal/pacops.metal +472 -0
  24. pacrunner/c/metal/uirmetal.h +42 -0
  25. pacrunner/c/metal/uirmetal.m +222 -0
  26. pacrunner/c/metal/uirvm.metal +491 -0
  27. pacrunner/c/metal/umami_metal.c +230 -0
  28. pacrunner/c/pacops.c +498 -0
  29. pacrunner/c/pacops.h +210 -0
  30. pacrunner/c/uirvm.c +408 -0
  31. pacrunner/c/uirvm.h +165 -0
  32. pacrunner/c/umami.h +334 -0
  33. pacrunner/c/umami_finish.h +109 -0
  34. pacrunner/c/umami_pac.c +558 -0
  35. pacrunner/codegen/__init__.py +21 -0
  36. pacrunner/codegen/common.py +355 -0
  37. pacrunner/codegen/compile.py +245 -0
  38. pacrunner/codegen/compile_metal.py +246 -0
  39. pacrunner/codegen/compile_simd.py +1006 -0
  40. pacrunner/codegen/compile_split.py +443 -0
  41. pacrunner/codegen/compile_vm.py +236 -0
  42. pacrunner/kernels/__init__.py +18 -0
  43. pacrunner/kernels/kernel_c.py +744 -0
  44. pacrunner/kernels/kernel_msl.py +84 -0
  45. pacrunner/kernels/mir.py +368 -0
  46. pacrunner/simd/__init__.py +3 -0
  47. pacrunner/simd/elf.py +177 -0
  48. pacrunner/simd/handgen.py +235 -0
  49. pacrunner/simd/lib/closure_1.json +1 -0
  50. pacrunner/simd/lib/closure_2.json +1 -0
  51. pacrunner/simd/lib/closure_3.json +1 -0
  52. pacrunner/simd/lib/closure_4.json +1 -0
  53. pacrunner/simd/lib/closure_5.json +1 -0
  54. pacrunner/simd/lib/closure_6.json +1 -0
  55. pacrunner/simd/lib/config.json +37 -0
  56. pacrunner/simd/lib/propagator_vector.json +1 -0
  57. pacrunner/simd/lib/propagator_weyl_a.json +1 -0
  58. pacrunner/simd/lib/propagator_weyl_b.json +1 -0
  59. pacrunner/simd/lib/vertex_tensor_vector_add.json +1 -0
  60. pacrunner/simd/lib/vertex_tensor_vector_set.json +1 -0
  61. pacrunner/simd/lib/vertex_three_vector_add.json +1 -0
  62. pacrunner/simd/lib/vertex_three_vector_set.json +1 -0
  63. pacrunner/simd/lib/vertex_vector_wedge_add.json +1 -0
  64. pacrunner/simd/lib/vertex_vector_wedge_set.json +1 -0
  65. pacrunner/simd/lib/vertex_weyl_vector_a_add.json +1 -0
  66. pacrunner/simd/lib/vertex_weyl_vector_a_set.json +1 -0
  67. pacrunner/simd/lib/vertex_weyl_vector_b_add.json +1 -0
  68. pacrunner/simd/lib/vertex_weyl_vector_b_set.json +1 -0
  69. pacrunner/simd/lib/wave_dirac_anti_1_massive.json +1 -0
  70. pacrunner/simd/lib/wave_dirac_anti_1_massless.json +1 -0
  71. pacrunner/simd/lib/wave_dirac_anti_m1_massive.json +1 -0
  72. pacrunner/simd/lib/wave_dirac_anti_m1_massless.json +1 -0
  73. pacrunner/simd/lib/wave_dirac_part_1_massive.json +1 -0
  74. pacrunner/simd/lib/wave_dirac_part_1_massless.json +1 -0
  75. pacrunner/simd/lib/wave_dirac_part_m1_massive.json +1 -0
  76. pacrunner/simd/lib/wave_dirac_part_m1_massless.json +1 -0
  77. pacrunner/simd/lib/wave_gluon_1.json +1 -0
  78. pacrunner/simd/lib/wave_gluon_m1.json +1 -0
  79. pacrunner/simd/lib/wave_massive_vector_0.json +1 -0
  80. pacrunner/simd/lib/wave_massive_vector_1.json +1 -0
  81. pacrunner/simd/lib/wave_massive_vector_m1.json +1 -0
  82. pacrunner/simd/lib/wave_weyl_anti_1_1.json +1 -0
  83. pacrunner/simd/lib/wave_weyl_anti_1_m1.json +1 -0
  84. pacrunner/simd/lib/wave_weyl_anti_m1_1.json +1 -0
  85. pacrunner/simd/lib/wave_weyl_anti_m1_m1.json +1 -0
  86. pacrunner/simd/lib/wave_weyl_part_1_1.json +1 -0
  87. pacrunner/simd/lib/wave_weyl_part_1_m1.json +1 -0
  88. pacrunner/simd/lib/wave_weyl_part_m1_1.json +1 -0
  89. pacrunner/simd/lib/wave_weyl_part_m1_m1.json +1 -0
  90. pacrunner/simd/lib_hand_avx2/closure_1.json +1 -0
  91. pacrunner/simd/lib_hand_avx2/closure_2.json +1 -0
  92. pacrunner/simd/lib_hand_avx2/closure_3.json +1 -0
  93. pacrunner/simd/lib_hand_avx2/closure_4.json +1 -0
  94. pacrunner/simd/lib_hand_avx2/closure_5.json +1 -0
  95. pacrunner/simd/lib_hand_avx2/closure_6.json +1 -0
  96. pacrunner/simd/lib_hand_avx2/propagator_vector.json +1 -0
  97. pacrunner/simd/lib_hand_avx2/propagator_weyl_a.json +1 -0
  98. pacrunner/simd/lib_hand_avx2/propagator_weyl_b.json +1 -0
  99. pacrunner/simd/lib_hand_avx2/vertex_tensor_vector_add.json +1 -0
  100. pacrunner/simd/lib_hand_avx2/vertex_tensor_vector_set.json +1 -0
  101. pacrunner/simd/lib_hand_avx2/vertex_three_vector_add.json +1 -0
  102. pacrunner/simd/lib_hand_avx2/vertex_three_vector_set.json +1 -0
  103. pacrunner/simd/lib_hand_avx2/vertex_vector_wedge_add.json +1 -0
  104. pacrunner/simd/lib_hand_avx2/vertex_vector_wedge_set.json +1 -0
  105. pacrunner/simd/lib_hand_avx2/vertex_weyl_vector_a_add.json +1 -0
  106. pacrunner/simd/lib_hand_avx2/vertex_weyl_vector_a_set.json +1 -0
  107. pacrunner/simd/lib_hand_avx2/vertex_weyl_vector_b_add.json +1 -0
  108. pacrunner/simd/lib_hand_avx2/vertex_weyl_vector_b_set.json +1 -0
  109. pacrunner/simd/lib_hand_avx512/closure_1.json +1 -0
  110. pacrunner/simd/lib_hand_avx512/closure_2.json +1 -0
  111. pacrunner/simd/lib_hand_avx512/closure_3.json +1 -0
  112. pacrunner/simd/lib_hand_avx512/closure_4.json +1 -0
  113. pacrunner/simd/lib_hand_avx512/closure_5.json +1 -0
  114. pacrunner/simd/lib_hand_avx512/closure_6.json +1 -0
  115. pacrunner/simd/lib_hand_avx512/propagator_vector.json +1 -0
  116. pacrunner/simd/lib_hand_avx512/propagator_weyl_a.json +1 -0
  117. pacrunner/simd/lib_hand_avx512/propagator_weyl_b.json +1 -0
  118. pacrunner/simd/lib_hand_avx512/vertex_tensor_vector_add.json +1 -0
  119. pacrunner/simd/lib_hand_avx512/vertex_tensor_vector_set.json +1 -0
  120. pacrunner/simd/lib_hand_avx512/vertex_three_vector_add.json +1 -0
  121. pacrunner/simd/lib_hand_avx512/vertex_three_vector_set.json +1 -0
  122. pacrunner/simd/lib_hand_avx512/vertex_vector_wedge_add.json +1 -0
  123. pacrunner/simd/lib_hand_avx512/vertex_vector_wedge_set.json +1 -0
  124. pacrunner/simd/lib_hand_avx512/vertex_weyl_vector_a_add.json +1 -0
  125. pacrunner/simd/lib_hand_avx512/vertex_weyl_vector_a_set.json +1 -0
  126. pacrunner/simd/lib_hand_avx512/vertex_weyl_vector_b_add.json +1 -0
  127. pacrunner/simd/lib_hand_avx512/vertex_weyl_vector_b_set.json +1 -0
  128. pacrunner/simd/lib_hand_neon/closure_1.json +1 -0
  129. pacrunner/simd/lib_hand_neon/closure_2.json +1 -0
  130. pacrunner/simd/lib_hand_neon/closure_3.json +1 -0
  131. pacrunner/simd/lib_hand_neon/closure_4.json +1 -0
  132. pacrunner/simd/lib_hand_neon/closure_5.json +1 -0
  133. pacrunner/simd/lib_hand_neon/closure_6.json +1 -0
  134. pacrunner/simd/lib_hand_neon/propagator_vector.json +1 -0
  135. pacrunner/simd/lib_hand_neon/propagator_weyl_a.json +1 -0
  136. pacrunner/simd/lib_hand_neon/propagator_weyl_b.json +1 -0
  137. pacrunner/simd/lib_hand_neon/vertex_tensor_vector_add.json +1 -0
  138. pacrunner/simd/lib_hand_neon/vertex_tensor_vector_set.json +1 -0
  139. pacrunner/simd/lib_hand_neon/vertex_three_vector_add.json +1 -0
  140. pacrunner/simd/lib_hand_neon/vertex_three_vector_set.json +1 -0
  141. pacrunner/simd/lib_hand_neon/vertex_vector_wedge_add.json +1 -0
  142. pacrunner/simd/lib_hand_neon/vertex_vector_wedge_set.json +1 -0
  143. pacrunner/simd/lib_hand_neon/vertex_weyl_vector_a_add.json +1 -0
  144. pacrunner/simd/lib_hand_neon/vertex_weyl_vector_a_set.json +1 -0
  145. pacrunner/simd/lib_hand_neon/vertex_weyl_vector_b_add.json +1 -0
  146. pacrunner/simd/lib_hand_neon/vertex_weyl_vector_b_set.json +1 -0
  147. pacrunner/simd/library.py +495 -0
  148. pacrunner/simd/mir.py +233 -0
  149. pacrunner/simd/split_kernel.py +308 -0
  150. pacrunner/uir/__init__.py +25 -0
  151. pacrunner/uir/encode.py +212 -0
  152. pacrunner/uir/export.py +482 -0
  153. pacrunner/uir/passes.py +69 -0
  154. pacrunner/uir/types.py +318 -0
  155. pacrunner/uir/validate.py +333 -0
  156. pacrunner/umami.py +636 -0
  157. pacrunner-0.5.1.dist-info/METADATA +453 -0
  158. pacrunner-0.5.1.dist-info/RECORD +162 -0
  159. pacrunner-0.5.1.dist-info/WHEEL +5 -0
  160. pacrunner-0.5.1.dist-info/licenses/LICENSE +21 -0
  161. pacrunner-0.5.1.dist-info/licenses/pacrunner/c/UMAMI_LICENSE +41 -0
  162. pacrunner-0.5.1.dist-info/top_level.txt +1 -0
pacrunner/_madgraph.py ADDED
@@ -0,0 +1,357 @@
1
+ """An end-to-end MadGraph7 run (event generation, the cross section) on PacRunner's UMAMI libraries.
2
+
3
+ Given a PacRunner folder (the output of PacRunner's umami_libraries) and the pyAmpliCol artifact it
4
+ was built from, `run` starts MadGraph7's generate_events on the mg7 output that holds the artifact,
5
+ with that subprocess's stock pyAmpliCol library replaced by the PacRunner libraries: one MadSpace
6
+ matrix element per library, MadSpace splitting each batch by flavour (every library sees flavour 0).
7
+ MadGraph7 does the rest as usual (phase space, PDFs, scales, cuts, the survey, unweighting, the
8
+ event files), and `run` returns the cross section:
9
+
10
+ from pacrunner._madgraph import run # Provider.run and Output.run wrap it
11
+ result = run("OUTPUT/lib/pacrunner/A1_pp_jjj_p0", "OUTPUT/SubProcesses/A1_pp_jjj/lc")
12
+ print(result["cross_section"], "+-", result["error"], "pb;", result["events"])
13
+
14
+ or from the shell, with the python of the mg7 output (the shebang of OUTPUT/bin/generate_events):
15
+
16
+ python -m pacrunner._madgraph LIBRARIES ARTIFACT [generate_events arguments, default -f]
17
+
18
+ (the repository on PYTHONPATH when pacrunner is not installed in that python)
19
+
20
+ Several (libraries, artifact) pairs of one output: run([(LIBRARIES, ARTIFACT), ...]); a subprocess
21
+ without a pair keeps its stock library.
22
+
23
+ What it needs:
24
+ - the artifact inside an mg7 output (OUTPUT/SubProcesses/<subprocess>/lc, as MadGraph7's
25
+ `output mg7` writes it with [amplicol]): the run uses that output's cards and phase space;
26
+ - libraries exported with the output's model parameters (the param card: `pyamplicol
27
+ export-recurrence ... --model-parameters`; test/mg7_run.py's prepare does it): a library refuses
28
+ any other value MadGraph7 sets;
29
+ - the device the libraries were built for (umami_pac.json's "device"): cpu, cuda and metal
30
+ libraries are CPU providers (run.device = ["cpu"]); cuda_provider libraries need run.device =
31
+ ["cuda"], color_accuracy = "lc" and MadSpace's CUDA build in MADGRAPH7/madspace/install-cuda;
32
+ - several flavours per UMAMI channel: color_accuracy = "lc" (the full-colour ratio pass receives
33
+ the remapped flavour).
34
+
35
+ The run is in this process (generate_events' main, with the subprocess class replaced), so call it
36
+ once per process (Provider.run runs it in a process of its own).
37
+
38
+ A channel whose flavours are on several libraries splits each batch by library, so its matrix
39
+ elements draw the helicity choice's random numbers over their parts of the batch: the cross section
40
+ and the weights are the stock run's, an event's sampled helicity (its LHE spins) may not be."""
41
+
42
+ import glob
43
+ import json
44
+ import os
45
+ import re
46
+ import sys
47
+
48
+
49
+ def mg5_dir(output):
50
+ """MadGraph7's folder, as the output's bin/generate_events appends it to sys.path"""
51
+ text = open(os.path.join(output, "bin", "generate_events")).read()
52
+ return re.search(r"sys\.path\.append\('([^']*)'\)", text).group(1)
53
+
54
+
55
+ def mg7_output(artifact):
56
+ """the mg7 output holding `artifact` (the first parent with bin/generate_events)"""
57
+ d = os.path.abspath(artifact)
58
+ while d != os.path.dirname(d):
59
+ d = os.path.dirname(d)
60
+ if os.path.isfile(os.path.join(d, "bin", "generate_events")):
61
+ return d
62
+ raise ValueError(f"{artifact}: not inside an mg7 output (no bin/generate_events above it); the run needs "
63
+ "MadGraph7's output of the process (`generate ... [amplicol]`, `output mg7 OUTPUT`)")
64
+
65
+
66
+ def read_table(libraries):
67
+ """umami_pac.json of a PacRunner folder (or the file itself), with its folder"""
68
+ path = libraries if libraries.endswith(".json") else os.path.join(libraries, "umami_pac.json")
69
+ with open(path) as f:
70
+ table = json.load(f)
71
+ if table.get("kind") != "pacrunner-umami-libraries":
72
+ raise ValueError(f"{path}: not the output of PacRunner's umami_libraries")
73
+ return table, os.path.dirname(os.path.abspath(path))
74
+
75
+
76
+ def provider_id(metadata_path):
77
+ with open(metadata_path) as f:
78
+ return json.load(f)["provider"].get("id")
79
+
80
+
81
+ class Pair:
82
+ """one PacRunner folder and its artifact: the table, the provider, the device"""
83
+
84
+ def __init__(self, libraries, artifact):
85
+ self.table, self.dir = read_table(libraries)
86
+ self.artifact = os.path.realpath(artifact)
87
+ with open(os.path.join(self.artifact, "artifact.json")) as f:
88
+ artifact_id = json.load(f)["artifact_id"]
89
+ if artifact_id != self.table["artifact_id"]:
90
+ raise ValueError(f"{self.dir}: built from artifact {self.table['artifact_id']}, but {artifact} is "
91
+ f"{artifact_id}")
92
+ # the provider the libraries were built for, in this artifact (the table's metadata path, or
93
+ # the artifact's own metadata.json beside the same file name if the folders moved)
94
+ meta = self.table["metadata"]
95
+ if not os.path.isfile(meta):
96
+ meta = os.path.join(self.artifact, "API", "umami", os.path.basename(meta))
97
+ self.provider = provider_id(meta)
98
+ self.device = self.table["device"]
99
+
100
+ def matches(self, meta):
101
+ """whether a subprocess (its mg7 metadata) is this pair's: the same artifact and provider"""
102
+ if os.path.realpath(meta["artifact"]) != self.artifact:
103
+ return False
104
+ stem = re.fullmatch(r"libamplicol_(.*)\.so", os.path.basename(meta["me_path"])).group(1)
105
+ return self.provider is None or stem.endswith("_" + str(self.provider))
106
+
107
+
108
+ def install(pairs, errors):
109
+ """MadGraph7's AmplicolSubprocess replaced (in madgraph_process, which instantiates it) by
110
+ PacRunnerSubprocess: the subprocesses of `pairs` run on their PacRunner libraries; the exceptions of
111
+ generate_events appended to `errors`"""
112
+ import madspace as ms
113
+ import madgraph.mg7.madgraph_process as mp
114
+ import madgraph.mg7.subprocess_madmatrix as smm
115
+ from madgraph.mg7.subprocess_amplicol import AmplicolSubprocess, amplicol_parameters
116
+
117
+ layout = {"first": None} # whether subprocess 0's integrands give their events a subprocess_index
118
+
119
+ class PacRunnerSubprocess(AmplicolSubprocess):
120
+ def pac_pair(self):
121
+ found = [p for p in pairs if p.matches(self.meta)]
122
+ return found[0] if found else None
123
+
124
+ def load_matrix_elements(self, api_path_formats, member_metas):
125
+ """AmplicolSubprocess.load_matrix_elements (its checks and attributes, the stock ratio
126
+ library), with the PacRunner libraries instead of the stock LC library (not loaded)"""
127
+ pair = self.pac_pair()
128
+ if pair is None: # not one of ours: the stock library
129
+ self.pac_matrix_elements = None
130
+ return super().load_matrix_elements(api_path_formats, member_metas)
131
+ process = self.process
132
+ table = pair.table
133
+ provider = pair.device == "cuda_provider"
134
+ want = "cuda" if provider else "cpu"
135
+ if any(d != want for d in process.device_types):
136
+ raise RuntimeError(f"PacRunner libraries of device {pair.device} ({pair.dir}) need run.device = "
137
+ f"[\"{want}\"], not {process.run_card['run']['device']}")
138
+ lc = process.run_card["amplicol"]["color_accuracy"] == "lc"
139
+ if provider and not lc:
140
+ raise RuntimeError("PacRunner on a CUDA device: color_accuracy = \"lc\" only (the stock "
141
+ "full-colour ratio library is a CPU one)")
142
+ channel = table["channels"][self.meta["umami_channel"]]
143
+ libs = channel["libraries"]
144
+ flavors = self.meta["flavors"]
145
+ if len(libs) > 1 and not lc:
146
+ raise RuntimeError("PacRunner libraries: several flavours per UMAMI channel need "
147
+ "color_accuracy = \"lc\" (the ratio pass gets the remapped flavour)")
148
+ # MadGraph7's own method, seeing CPU devices (its only refusal we lift) and not loading
149
+ # the stock LC library
150
+ real_load, types = self.load, process.device_types
151
+ self.load = lambda path, artifact, parameters: (
152
+ None if path == self.meta["me_path"] else real_load(path, artifact, parameters))
153
+ process.device_types = ["cpu"] * len(types)
154
+ try:
155
+ super().load_matrix_elements(api_path_formats, member_metas)
156
+ finally:
157
+ process.device_types = types
158
+ del self.load
159
+ # loaded through MadGraph7 (every context, recorded for gridpacks), with the card's
160
+ # parameters: a library refuses a value other than the exported one
161
+ parameters = amplicol_parameters(self.meta, process)
162
+ self.pac_matrix_elements = [
163
+ self.load(os.path.join(pair.dir, table["libraries"][k]["path"]), self.meta["artifact"], parameters)
164
+ for k in libs]
165
+ # per mg7 flavour: its library's position among the channel's
166
+ self.pac_diff_xs = [libs.index(channel["flavor_libraries"][f["index"]]) for f in flavors]
167
+ self.matrix_elements = self.pac_matrix_elements[:1] # what AmplicolSubprocess reads
168
+ print(f"PacRunner: subprocess {self.subproc_id} channel {self.channel_index}: "
169
+ f"{len(flavors)} flavours on {len(libs)} libraries ({pair.device})", flush=True)
170
+
171
+ def integrand_matrix_elements(self):
172
+ if self.pac_matrix_elements is None:
173
+ return super().integrand_matrix_elements()
174
+ stock = super().integrand_matrix_elements()[0]
175
+ return [ms.MatrixElement(api.index(), self.particle_count, stock.inputs(), stock.outputs(), 1,
176
+ True, self.process.me_frame, self.process.incoming_count,
177
+ self.channel_index)
178
+ for api in self.pac_matrix_elements]
179
+
180
+ def build_integrands(self, *args, **kwargs):
181
+ ours = self.pac_matrix_elements is not None
182
+ n = len(self.meta["flavors"])
183
+ stock_remap = [f["index"] for f in self.meta["flavors"]]
184
+ real = ms.Integrand
185
+
186
+ def integrand(*a, **kw):
187
+ a = list(a)
188
+ # positional cross_sections (1), flavor_remap (21), flavor_diff_xs_indices (24),
189
+ # flavor_subproc_indices (25), flavor_per_subproc_remap (26) (subprocess_madmatrix.build_integrands)
190
+ if ours:
191
+ assert a[21] == stock_remap and a[24] == [] and a[25] == [] and a[26] == [], "Integrand layout"
192
+ a[21] = [0] * n
193
+ if len(self.pac_matrix_elements) > 1:
194
+ a[24], a[25], a[26] = self.pac_diff_xs, [self.subproc_id] * n, list(range(n))
195
+ # MadSpace writes every event with channel 0's layout (subprocess 0's integrand): an
196
+ # integrand of several cross sections gives its events a subprocess_index, one of a
197
+ # single cross section none, which the event writer then reads anyway (an index -1).
198
+ # When subprocess 0's has one, every other integrand of one cross section gets the same
199
+ # cross section twice, all its events on the first: its events carry their subprocess.
200
+ carries = len(a[1]) > 1
201
+ if self.subproc_id == 0:
202
+ if layout["first"] is None:
203
+ layout["first"] = carries
204
+ elif layout["first"] is None:
205
+ raise RuntimeError(f"PacRunner: subprocess {self.subproc_id}'s integrands built before "
206
+ "subprocess 0's (the event layout is subprocess 0's)")
207
+ elif layout["first"] and not carries:
208
+ if a[24] or a[25] or a[26]:
209
+ raise RuntimeError(f"PacRunner: subprocess {self.subproc_id}: flavour tables without "
210
+ "several cross sections")
211
+ a[1] = [a[1][0], a[1][0]]
212
+ a[24], a[25], a[26] = [0] * n, [self.subproc_id] * n, list(range(n))
213
+ return real(*a, **kw)
214
+
215
+ smm.ms.Integrand = integrand
216
+ try:
217
+ return super().build_integrands(*args, **kwargs)
218
+ finally:
219
+ smm.ms.Integrand = real
220
+
221
+ mp.AmplicolSubprocess = PacRunnerSubprocess
222
+
223
+ # generate_events' errors: MadGraph7's command loop reports them and returns (exit code 0)
224
+ real_generate = mp.MadgraphProcess.generate_events
225
+
226
+ def generate_events(self, *a, **kw):
227
+ try:
228
+ return real_generate(self, *a, **kw)
229
+ except BaseException as e:
230
+ errors.append(e)
231
+ raise
232
+
233
+ mp.MadgraphProcess.generate_events = generate_events
234
+
235
+
236
+ def latest_run(output):
237
+ runs = sorted(glob.glob(os.path.join(output, "Events", "run_*")), key=lambda d: int(d.rsplit("_", 1)[1]))
238
+ return runs[-1] if runs else None
239
+
240
+
241
+ def run(libraries, artifact=None, args=None):
242
+ """An end-to-end MadGraph7 run on PacRunner's libraries: `libraries` a PacRunner folder and
243
+ `artifact` its pyAmpliCol artifact (inside an mg7 output), or a list of such pairs; `args`
244
+ generate_events' arguments (default ["-f"]). Returns {"cross_section", "error" (pb), "events",
245
+ "run" (the run's folder in OUTPUT/Events), "output"}."""
246
+ pairs = [Pair(lib, art) for lib, art in ([(libraries, artifact)] if artifact is not None else libraries)]
247
+ outputs = {mg7_output(p.artifact) for p in pairs}
248
+ if len(outputs) != 1:
249
+ raise ValueError(f"the artifacts are in {len(outputs)} mg7 outputs: one run is one output")
250
+ output = outputs.pop()
251
+ devices = {p.device for p in pairs}
252
+ if len(devices) != 1:
253
+ raise ValueError(f"libraries of several devices {sorted(devices)}: one run is one device")
254
+ device = devices.pop()
255
+ _madspace(output, device == "cuda_provider", "cuda_provider libraries")
256
+ errors = []
257
+ install(pairs, errors)
258
+ return _launch(output, args, errors)
259
+
260
+
261
+ def run_stock(output, args=None):
262
+ """The output's own run (every subprocess on its stock library), with MadSpace as run() chooses it:
263
+ the CUDA build (madspace/install-cuda) when the run card's run.device names cuda (MadGraph7 runs
264
+ a stock [amplicol] subprocess on the CPU only: on cuda it refuses with "[amplicol] processes are
265
+ only supported on CPUs"). Returns run()'s dictionary."""
266
+ output = os.path.abspath(output)
267
+ _madspace(output, "cuda" in run_card_devices(output), "a run on cuda (run.device)")
268
+ return _launch(output, args, [])
269
+
270
+
271
+ def run_card_devices(output):
272
+ """the run card's run.device kinds (cpu, cuda, hip; without a device index)"""
273
+ import tomllib
274
+ with open(os.path.join(output, "Cards", "run_card.toml"), "rb") as f:
275
+ devices = tomllib.load(f).get("run", {}).get("device", ["cpu"])
276
+ return {d.split(":")[0] for d in ([devices] if isinstance(devices, str) else devices)}
277
+
278
+
279
+ def _madspace(output, cuda, why):
280
+ """MadGraph7's MadSpace first on sys.path (the CUDA build when `cuda`)"""
281
+ sys.path.append(mg5_dir(output))
282
+ from madgraph.mg7 import bootstrap
283
+ bootstrap.ensure_madspace(interactive=False) # MadGraph7's madspace first on sys.path
284
+ if cuda:
285
+ # MadSpace built with CUDA (ENABLE_CUDA) beside the CPU build: madspace/install-cuda
286
+ path = os.path.join(mg5_dir(output), "madspace", "install-cuda")
287
+ if not os.path.isdir(os.path.join(path, "madspace")):
288
+ raise RuntimeError(f"{why}: needs a CUDA build of MadSpace in {path}")
289
+ sys.path.insert(0, path)
290
+
291
+
292
+ def _launch(output, args, errors):
293
+ """generate_events in this process; run()'s dictionary"""
294
+ from madgraph.mg7.launch import main
295
+ before = latest_run(output)
296
+ cwd, argv = os.getcwd(), sys.argv
297
+ os.chdir(output)
298
+ sys.argv = [os.path.join(output, "bin", "generate_events")] + list(args or ["-f"])
299
+ try:
300
+ main()
301
+ finally:
302
+ os.chdir(cwd)
303
+ sys.argv = argv
304
+ folder = latest_run(output)
305
+ if errors:
306
+ raise RuntimeError(f"{output}: generate_events failed in {folder}: {type(errors[0]).__name__}: "
307
+ f"{errors[0]}") from errors[0]
308
+ if folder is None or folder == before:
309
+ raise RuntimeError(f"{output}: generate_events made no new run")
310
+ with open(os.path.join(folder, "info.json")) as f:
311
+ process = json.load(f)["process"]
312
+ return {"cross_section": float(process["mean"]), "error": float(process["error"]),
313
+ "events": int(process["count_unweighted"]), "run": folder, "output": output}
314
+
315
+
316
+ def _result_json(result):
317
+ return {k: result[k] for k in ("cross_section", "error", "events", "run", "output")}
318
+
319
+
320
+ def main(argv):
321
+ """python -m pacrunner._madgraph [--json FILE] LIBRARIES ARTIFACT [LIBRARIES ARTIFACT ...] [-- ARGS]
322
+ (without "--": LIBRARIES ARTIFACT [ARGS], the earlier form);
323
+ python -m pacrunner._madgraph [--json FILE] --stock OUTPUT [-- ARGS]: the output's own run"""
324
+ json_path = None
325
+ if argv[:1] == ["--json"]:
326
+ json_path, argv = argv[1], argv[2:]
327
+ if argv[:1] == ["--stock"]:
328
+ try:
329
+ result = run_stock(argv[1], args=(argv[3:] if argv[2:3] == ["--"] else argv[2:]) or None)
330
+ except RuntimeError as e:
331
+ sys.exit(f"PacRunner: {e}")
332
+ if json_path:
333
+ with open(json_path, "w") as f:
334
+ json.dump(_result_json(result), f)
335
+ print(f"stock: cross section {result['cross_section']!r} +- {result['error']:.4g} pb, "
336
+ f"{result['events']} events in {result['run']}")
337
+ return
338
+ if "--" in argv:
339
+ k = argv.index("--")
340
+ names, args = argv[:k], argv[k + 1:]
341
+ else:
342
+ names, args = argv[:2], argv[2:]
343
+ if len(names) < 2 or len(names) % 2:
344
+ sys.exit(__doc__)
345
+ try:
346
+ result = run(list(zip(names[0::2], names[1::2])), args=args or None)
347
+ except RuntimeError as e:
348
+ sys.exit(f"PacRunner: {e}")
349
+ if json_path:
350
+ with open(json_path, "w") as f:
351
+ json.dump(_result_json(result), f)
352
+ print(f"PacRunner: cross section {result['cross_section']!r} +- {result['error']:.4g} pb, "
353
+ f"{result['events']} events in {result['run']}")
354
+
355
+
356
+ if __name__ == "__main__":
357
+ main(sys.argv[1:])
pacrunner/_mgrun.py ADDED
@@ -0,0 +1,110 @@
1
+ """Provider.run and Output.run: generate_events on PacRunner's libraries, by default in a process of
2
+ its own (MadGraph7's run is global state, once per process): the output's python (bin/generate_events'
3
+ shebang) runs `python -m pacrunner._madgraph` with this repository on its PYTHONPATH, the result back
4
+ through a JSON file; Ctrl-C stops it. in_process=True runs pacrunner._madgraph.run here instead."""
5
+
6
+ import json
7
+ import os
8
+ import signal
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import time
13
+ from pathlib import Path
14
+ from typing import NamedTuple
15
+
16
+ from . import _env
17
+
18
+
19
+ class RunResult(NamedTuple):
20
+ cross_section: float # pb
21
+ error: float # pb
22
+ events: int # unweighted events
23
+ run_dir: Path # OUTPUT/Events/run_N
24
+ output: Path
25
+ wall_seconds: float
26
+
27
+
28
+ def output_python(output):
29
+ """the python of an mg7 output: bin/generate_events' shebang"""
30
+ with open(Path(output) / "bin" / "generate_events") as f:
31
+ line = f.readline()
32
+ if not line.startswith("#!"):
33
+ return sys.executable
34
+ parts = line[2:].split()
35
+ if parts and os.path.basename(parts[0]) == "env" and len(parts) > 1:
36
+ return parts[1]
37
+ return parts[0] if parts else sys.executable
38
+
39
+
40
+ def run_libraries(output, libraries, args=None, in_process=False, log=None, python=None):
41
+ """generate_events of `output` with `libraries` (Providers) in place of their stock libraries (a
42
+ stock Provider: its subprocess stays stock; none of PacRunner's: the output's own run);
43
+ `args` generate_events' arguments (default -f); `log` a file for the run's output (default: this
44
+ process's stdout and stderr); `python` the interpreter (default: the output's). Returns a RunResult."""
45
+ from . import _madgraph
46
+ libraries = list(libraries)
47
+ if not libraries:
48
+ raise _env.PacRunnerError("no libraries to run")
49
+ pairs = [(os.fspath(lib.folder), os.fspath(lib.artifact)) for lib in libraries if not lib.stock]
50
+ if not pairs:
51
+ if in_process:
52
+ raise _env.PacRunnerError("in_process: for PacRunner's providers only (the stock run is bin/generate_events)")
53
+ return run_stock(output, args=args, log=log, python=python)
54
+ start = time.time()
55
+ if in_process:
56
+ r = _madgraph.run(pairs, args=args)
57
+ else:
58
+ runner = [a for lib, art in pairs for a in (lib, art)]
59
+ r = _runner(output, runner, args, log, python, "generate_events on PacRunner's libraries")
60
+ return RunResult(float(r["cross_section"]), float(r["error"]), int(r["events"]), Path(r["run"]),
61
+ Path(r["output"]), time.time() - start)
62
+
63
+
64
+ def run_stock(output, args=None, log=None, python=None):
65
+ """the output's own generate_events (every subprocess on its stock library), in a process of its own
66
+ (the output's python), with MadSpace as PacRunner's runs choose it (the CUDA build for a run on
67
+ cuda); a RunResult"""
68
+ start = time.time()
69
+ r = _runner(output, ["--stock", os.fspath(Path(output).resolve())], args, log, python, "generate_events")
70
+ return RunResult(float(r["cross_section"]), float(r["error"]), int(r["events"]), Path(r["run"]),
71
+ Path(r["output"]), time.time() - start)
72
+
73
+
74
+ def _runner(output, runner_args, args, log, python, what):
75
+ """python -m pacrunner._madgraph --json RESULT RUNNER_ARGS -- ARGS in the output (its python); the
76
+ result's dictionary"""
77
+ with tempfile.TemporaryDirectory() as tmp:
78
+ result = Path(tmp) / "result.json"
79
+ command = [python or output_python(output), "-m", "pacrunner._madgraph", "--json", os.fspath(result),
80
+ *runner_args, "--", *(args or ["-f"])]
81
+ # this pacrunner first on the output python's path, alone: a folder with a link to the package
82
+ # (not its parent, which for an installed copy is all of site-packages)
83
+ path = Path(tmp) / "path"
84
+ path.mkdir()
85
+ (path / "pacrunner").symlink_to(_env.PACKAGE, target_is_directory=True)
86
+ env = dict(os.environ)
87
+ env["PYTHONPATH"] = os.pathsep.join([os.fspath(path)] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
88
+ env.setdefault("XDG_RUNTIME_DIR", os.path.expanduser("~/.cache/xdg-runtime"))
89
+ os.makedirs(env["XDG_RUNTIME_DIR"], exist_ok=True)
90
+ out = open(log, "w") if log is not None else None
91
+ try:
92
+ p = subprocess.Popen(command, env=env, cwd=os.fspath(output), stdout=out,
93
+ stderr=subprocess.STDOUT if out else None)
94
+ try:
95
+ code = p.wait()
96
+ except KeyboardInterrupt:
97
+ p.send_signal(signal.SIGINT)
98
+ try:
99
+ p.wait(timeout=30)
100
+ except subprocess.TimeoutExpired:
101
+ p.kill()
102
+ raise
103
+ finally:
104
+ if out is not None:
105
+ out.close()
106
+ if code != 0 or not result.is_file():
107
+ where = f" (its output: {log})" if log is not None else ""
108
+ raise _env.PacRunnerError(f"{output}: {what} failed, exit code {code}{where}")
109
+ with open(result) as f:
110
+ return json.load(f)
@@ -0,0 +1,134 @@
1
+ """A pyAmpliCol installation: a virtual environment's python, or an install folder (MadGraph7's
2
+ pyamplicol/install: the package and bin/rusticol-config in it) with a python. pacrunner runs pyAmpliCol's
3
+ commands (export-recurrence) and builds its UMAMI bundles (rusticol-config) with the installation that
4
+ produced an artifact: artifact.json's producer.git_revision is the installation's
5
+ pyamplicol/_build_info.json source_revision (a newer or older one may not read the artifact: e.g.
6
+ "payloads[N].role is unsupported").
7
+
8
+ Candidates, in order: configure(pyamplicol=...), PACRUNNER_PYAMPLICOL (either a python executable or an
9
+ install folder), the MadGraph7 checkout's pyamplicol/install (configured, or the artifact's mg7 output's),
10
+ and this python's own pyamplicol."""
11
+
12
+ import json
13
+ import os
14
+ import subprocess
15
+ import sys
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+
19
+ from . import _env
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class PyAmpliCol:
24
+ python: str # the interpreter to run it with
25
+ path: str | None # a folder to put on PYTHONPATH (an install folder), or None
26
+ package: str # the pyamplicol package folder
27
+ revision: str | None # its source revision (_build_info.json)
28
+ version: str | None
29
+
30
+ @property
31
+ def rusticol_config(self):
32
+ """rusticol-config of this installation (builds API/umami bundles)"""
33
+ for candidate in ((Path(self.path) / "bin" / "rusticol-config") if self.path else None,
34
+ Path(self.python).parent / "rusticol-config"):
35
+ if candidate is not None and candidate.is_file():
36
+ return os.fspath(candidate)
37
+ raise _env.PacRunnerError(f"pyAmpliCol at {self.package}: no rusticol-config beside it")
38
+
39
+ def env(self):
40
+ env = dict(os.environ)
41
+ if self.path:
42
+ env["PYTHONPATH"] = os.pathsep.join([self.path] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
43
+ env.setdefault("XDG_RUNTIME_DIR", os.path.expanduser("~/.cache/xdg-runtime")) # Symbolica's lock folder
44
+ os.makedirs(env["XDG_RUNTIME_DIR"], exist_ok=True)
45
+ return env
46
+
47
+ def run(self, *args):
48
+ """`python -m pyamplicol ARGS` with this installation; raises with its output on failure"""
49
+ r = subprocess.run([self.python, "-m", "pyamplicol", *map(os.fspath, args)], env=self.env(),
50
+ capture_output=True, text=True)
51
+ if r.returncode != 0:
52
+ raise _env.PacRunnerError(f"pyamplicol {' '.join(map(str, args[:1]))} failed (pyAmpliCol {self.version} "
53
+ f"at {self.package}):\n{(r.stderr or r.stdout)[-3000:]}")
54
+ return r.stdout
55
+
56
+
57
+ def _build_info(package):
58
+ try:
59
+ with open(Path(package) / "_build_info.json") as f:
60
+ info = json.load(f)
61
+ return info.get("source_revision"), info.get("version")
62
+ except (OSError, ValueError):
63
+ return None, None
64
+
65
+
66
+ def from_folder(folder, python=None):
67
+ """an install folder (holding pyamplicol/), run with `python` (default: this one)"""
68
+ package = Path(folder) / "pyamplicol"
69
+ if not (package / "__init__.py").is_file():
70
+ return None
71
+ revision, version = _build_info(package)
72
+ return PyAmpliCol(python or sys.executable, os.fspath(Path(folder).resolve()), os.fspath(package.resolve()),
73
+ revision, version)
74
+
75
+
76
+ def from_python(python):
77
+ """the pyamplicol a python imports (a virtual environment's)"""
78
+ r = subprocess.run([python, "-c", "import os, pyamplicol; print(os.path.dirname(pyamplicol.__file__))"],
79
+ capture_output=True, text=True)
80
+ if r.returncode != 0:
81
+ return None
82
+ package = r.stdout.strip().splitlines()[-1]
83
+ revision, version = _build_info(package)
84
+ return PyAmpliCol(python, None, package, revision, version)
85
+
86
+
87
+ def _from_spec(spec):
88
+ spec = os.path.expanduser(os.fspath(spec))
89
+ return from_folder(spec) if os.path.isdir(spec) else from_python(spec)
90
+
91
+
92
+ def candidates(near=None):
93
+ """the pyAmpliCol installations to consider, in order (`near`: an artifact, whose mg7 output's
94
+ MadGraph7 counts)"""
95
+ found = []
96
+ for spec in (_env.CONFIG.pyamplicol, os.environ.get("PACRUNNER_PYAMPLICOL")):
97
+ if spec:
98
+ p = _from_spec(spec)
99
+ if p is None:
100
+ raise _env.PacRunnerError(f"{spec}: no pyAmpliCol there (a python that imports pyamplicol, or an install "
101
+ "folder holding pyamplicol/)")
102
+ found.append(p)
103
+ try:
104
+ mg7 = _env.madgraph7_for(near)
105
+ except _env.PacRunnerError:
106
+ mg7 = None
107
+ if mg7 is not None:
108
+ p = from_folder(mg7 / "pyamplicol" / "install")
109
+ if p is not None:
110
+ found.append(p)
111
+ p = from_python(sys.executable)
112
+ if p is not None:
113
+ found.append(p)
114
+ return found
115
+
116
+
117
+ def producer_of(artifact_json, near=None, strict=True):
118
+ """the installation that produced an artifact (its producer.git_revision); with strict=False the
119
+ first candidate when none matches (a warning is the caller's)"""
120
+ with open(artifact_json) as f:
121
+ producer = json.load(f).get("producer", {})
122
+ revision, version = producer.get("git_revision"), producer.get("version")
123
+ found = candidates(near)
124
+ for p in found:
125
+ if revision is not None and p.revision == revision:
126
+ return p
127
+ if not strict and found:
128
+ return found[0]
129
+ have = "; ".join(f"{p.version} at {p.revision or '?'} ({p.package})" for p in found) or "none found"
130
+ raise _env.PacRunnerError(
131
+ f"{Path(artifact_json).parent}: made by pyAmpliCol {version} at revision {revision}, and no installation of that "
132
+ f"revision is known ({have}). Point pacrunner at it: pacrunner.configure(pyamplicol=PYTHON or INSTALL_FOLDER) "
133
+ "or PACRUNNER_PYAMPLICOL (MadGraph7's is MADGRAPH7/pyamplicol/install), or regenerate the artifact with an "
134
+ "installation you have")