diff --git a/docs/source/madevent_to_mg7.rst b/docs/source/madevent_to_mg7.rst index 515e6df8a4..4b9118cc94 100644 --- a/docs/source/madevent_to_mg7.rst +++ b/docs/source/madevent_to_mg7.rst @@ -17,7 +17,8 @@ and ``use_syst``. The shortcuts ``set lhc``, ``set lep``, ``set fixed_scale``, ``set no_parton_cut`` and ``set dynamical_scale_choice HT/n`` work as before, and so does ``set iseed``. The beam settings ``ebeam``, ``ebeam1``, ``ebeam2``, ``lpp``, ``lpp1``, ``lpp2``, ``pdlabel``, ``pdlabel1``, ``pdlabel2`` and ``lhaid`` are translated as in the -table below. MadEvent draws a random seed for ``iseed = 0``. MG7 does the same for +table below, and so are the EVA settings ``polbeam1``, ``polbeam2``, ``ievo_eva``, +``evaorder`` and ``eva_xcut``. MadEvent draws a random seed for ``iseed = 0``. MG7 does the same for ``seed = -1`` and treats ``0`` as an ordinary fixed seed, so ``set iseed 0`` is translated. The cut names of the `Cuts`_ table are translated as well, so ``set mmll 200`` sets @@ -62,6 +63,24 @@ Beams and PDFs - ``beam.pdf1``, ``beam.pdf2`` - One set per beam. A beam without PDF exists only for a lepton collider, as ``beam.leptonic``. + * - ``pdlabel = eva``, ``lpp1``, ``lpp2`` = ±3, ±4 + - ``beam.eva``, ``beam.lepton1``, ``beam.lepton2`` + - The W, Z and photons of two electron or muon beams (Effective Vector boson + Approximation), on both beams only. ``beam.leptonic`` stays ``true`` (no PDF set, + :math:`\alpha_s` from the param card), but the momentum fractions are sampled. The + density of each incoming vector boson is taken for the helicity its matrix element + picks, and the W and Z are put on their mass shell, as MadEvent does. A process + with a W or Z on both beams, such as ``w+ w- > t t~``, gets these beams by default: + e+ e- at 2 × 15 TeV with a fixed factorization scale. + * - ``polbeam1``, ``polbeam2`` + - ``beam.polarization1``, ``beam.polarization2`` + - The polarization of the beam leptons of an EVA run, from -100 (left-handed) to 100 + (right-handed). MG7 has no other beam polarization. + * - ``evaorder``, ``ievo_eva``, ``eva_xcut`` + - ``beam.eva_order``, ``beam.eva_evolution``, ``beam.eva_xcut`` + - The EVA densities at leading log (0), leading power (1) or next-to-leading power + (2); evolved in ``"q2"`` or ``"pt"`` (``ievo_eva = 1``); with or without the + :math:`x > M_V / E_\text{beam}` restriction. Scales ------ @@ -456,9 +475,9 @@ The following MadEvent features have no MG7 equivalent. Settings for them are ig ``pdgs_for_merging_cut``): ``highestmult``, ``ktscheme``, ``alpsfact``, ``chcluster``, ``pdfwgt``, ``asrwgtflavor``, ``clusinfo``. * Biasing: ``bias_module`` and ``bias_parameters``. -* Beam polarization and heavy-ion or equivalent-photon beams: ``polbeam1``, ``polbeam2``, - ``nb_proton1``, ``nb_proton2``, ``nb_neutron1``, ``nb_neutron2``, ``mass_ion1``, - ``mass_ion2``, ``ievo_eva``, ``evaorder``, ``eva_xcut``. +* Beam polarization other than that of EVA beams (``polbeam1``, ``polbeam2``), EVA on one + beam only, and heavy-ion or equivalent-photon beams: ``nb_proton1``, ``nb_proton2``, + ``nb_neutron1``, ``nb_neutron2``, ``mass_ion1``, ``mass_ion2``. * Fixed factorization scales for the two beams, and the scale parameters ``mue_over_ref``, ``mue_ref_fixed`` and ``fixed_extra_scale``. * Cuts that are not a bound on a single observable: ``cutuse = 1``, which accepts an event if diff --git a/madgraph/mg7/madgraph_process.py b/madgraph/mg7/madgraph_process.py index e2987bdca5..6f1e3f83db 100644 --- a/madgraph/mg7/madgraph_process.py +++ b/madgraph/mg7/madgraph_process.py @@ -290,6 +290,10 @@ class MadgraphProcess: # reweighting with instead of evaluating it again; set before survey() store_matrix_elements = False + # monochromatic beams of massive incoming particles: s per subprocess, + # see beam_kinematics; set by init_beam + massive_beams = False + # set by a cluster job, which only writes the data/ of a gridpack: the rest # is the same for all of them, and written once for the merged gridpack gridpack_data_only = False @@ -459,13 +463,16 @@ def init_decay_mode(self) -> None: self.decaying_mass = None single = [meta["outgoing"] for meta in self.subprocess_data if len(clean_pids(meta["outgoing"])) == 1] - # a gamma-UPC luminosity samples s_hat whatever beam.leptonic says - if single and self.run_card["beam"]["leptonic"] \ - and not self.run_card["beam"]["upc_flux"]: + # EVA beams are leptonic but sample x, as a PDF does, and a + # gamma-UPC luminosity samples s_hat whatever beam.leptonic says + if (single and self.run_card["beam"]["leptonic"] + and not self.run_card["beam"].get("eva", False) + and not self.run_card["beam"]["upc_flux"]): raise ValueError( f"2 -> 1 processes ({single[0]} ...) need beams with a PDF " - "(leptonic = false in [beam]): with fixed beam energies the " - "one-particle phase space is a delta function in s_hat" + "(leptonic = false in [beam], or beam.eva): with fixed beam " + "energies the one-particle phase space is a delta function " + "in s_hat" ) return @@ -678,7 +685,7 @@ def helicity_choice(self, path_format: str, param_card: str, parameters: dict): backend, fptype = self.helicity_choice_build spread = not self.is_decay and ( not self.leptonic or bool(self._lepton_density_name) - or bool(self.upc_flux)) + or getattr(self, "eva", False) or bool(self.upc_flux)) choice = helicity_choice_module.choose( path_format.format(device=backend, fptype=fptype), param_card, parameters, self.e_cm, self.beam_rapidity, spread) @@ -1062,6 +1069,23 @@ def init_beam(self) -> None: self.beam_rapidity = 0.5 * math.log(ebeam1 / ebeam2) self.leptonic = beam_args["leptonic"] + # EVA (beam.eva): the W, Z and photons of two lepton beams. No PDF set + # and alpha_s from the param card, so 'leptonic' in that sense, but x + # is sampled (MadgraphSubprocess.ps_leptonic) and the densities are + # applied per helicity inside the DifferentialCrossSection (eva_flux). + self.eva = (not self.is_decay) and bool(beam_args.get("eva", False)) + self._eva_flux = None + if self.eva: + self.leptonic = True + logger.info( + "EVA beams: W/Z/photons from %s (%g GeV) and %s (%g GeV), " + "order %s, %s evolution%s", beam_args["lepton1"], + self.beam_energies[0], beam_args["lepton2"], + self.beam_energies[1], + ("LLA", "LP", "NLP")[int(beam_args["eva_order"])], + beam_args["eva_evolution"], + "" if beam_args["eva_xcut"] else ", no x cut") + # gamma-UPC (beam.upc_flux): one tabulated two-photon luminosity # replaces the PDFs, as a dressed-lepton density does, so the run is # 'leptonic' in the sense of "no PDF" (alpha_s from the param card). @@ -1081,6 +1105,18 @@ def init_beam(self) -> None: "gamma-UPC %s photon-photon luminosity: sqrt(s_NN) = %g GeV " "(Z,N = %s, %s)", self.upc_flux, self.e_cm, *self.upc_ions) + # Monochromatic beams of massive particles (W/Z without EVA, muons of + # a model with a muon mass): s and the rapidity of the beams are those + # of the massive beam momenta, as madevent's stot (genps.f, lpp = 0), + # not 4 E1 E2, for each subprocess (beam_kinematics). The incoming + # momenta are then put on their mass shell by the Integrand. + self.massive_beams = ( + self.leptonic and not self.is_decay and not self.eva + and not self.upc_flux + and not beam_args.get("lepton_density", "")) + if self.massive_beams: + self._massive_beams() + # A dressed-lepton density is not the same thing as beam.leptonic: # 'leptonic' means no parton luminosity at all (monochromatic beams), # while a density brings ISR and, for the collider-specific sets, @@ -2786,6 +2822,131 @@ def lepton_density(self): raise ValueError(error) return self._lepton_density + def _massive_beams(self) -> None: + """e_cm and beam_rapidity of the process for monochromatic beams of + massive incoming particles, see init_beam. With different incoming + masses in different subprocesses (madevent: one stot per P directory) + each subprocess has its own, see beam_kinematics, and the process + keeps s = 4 E1 E2 for what is not per subprocess (logs, helicity + choice).""" + masses = {tuple(abs(self.get_mass(pid)) + for pid in clean_pids(meta["incoming"])) + for meta in self.subprocess_data} + vector_beams = [meta for meta in self.subprocess_data + if any(abs(pid) in (23, 24) + for pid in clean_pids(meta["incoming"]))] + if vector_beams: + # a legitimate setup, but rarely the one meant + logger.warning( + "%s > %s runs with monochromatic W/Z beams of %g and %g GeV: " + "for W/Z from lepton beams (madevent's pdlabel = eva) set " + "beam.eva = true", vector_beams[0]["incoming"], + vector_beams[0]["outgoing"], *self.beam_energies) + for pair in masses: + # raises for beam energies below the masses + self.beam_kinematics(pair) + if len(masses) == 1: + pair = masses.pop() + if any(pair): + self.e_cm, self.beam_rapidity = self.beam_kinematics(pair) + logger.info("massive beams (%g, %g GeV): sqrt(s) = %.10g GeV", + *pair, self.e_cm) + elif any(any(pair) for pair in masses): + logger.info("massive beams: sqrt(s) %s GeV for the incoming " + "masses %s of the subprocesses", + ", ".join("%.10g" % self.beam_kinematics(pair)[0] + for pair in sorted(masses)), + ", ".join("(%g, %g)" % pair for pair in sorted(masses))) + + def beam_kinematics(self, incoming_masses) -> tuple[float, float]: + """(e_cm, beam_rapidity) of a subprocess with these incoming masses. + + Those of the process, except for monochromatic beams of massive + particles: s = m1^2 + m2^2 + 2 (E1 E2 + p1 p2) and the rapidity of the + massive beam momenta, as madevent's stot (genps.f, lpp = 0).""" + if not self.massive_beams or len(incoming_masses) != 2: + return self.e_cm, self.beam_rapidity + m1, m2 = (abs(float(m)) for m in incoming_masses) + e1, e2 = self.beam_energies + if m1 == 0. and m2 == 0.: + return 2.0 * math.sqrt(e1 * e2), 0.5 * math.log(e1 / e2) + if e1 < m1 or e2 < m2: + raise ValueError( + "beam energies %g, %g GeV below the masses %g, %g GeV of the " + "incoming particles" % (e1, e2, m1, m2)) + p1 = math.sqrt(e1 * e1 - m1 * m1) + p2 = math.sqrt(e2 * e2 - m2 * m2) + e_tot, p_tot = e1 + e2, p1 - p2 + e_cm = math.sqrt(m1 * m1 + m2 * m2 + 2. * (e1 * e2 + p1 * p2)) + return e_cm, 0.5 * math.log((e_tot + p_tot) / (e_tot - p_tot)) + + def eva_flux(self, api=None): + """The ms.EvaFlux of an EVA run (beam.eva), None otherwise. Its + electroweak inputs are those of the matrix element: M_W, M_Z and e^2, + read from the loaded library ``api`` (umami_get_parameter) when it has + them, else from the param card; e^2 as madevent's gal(1)^2 (4 pi / + aEWM1, or the G_mu value without aEWM1).""" + if not self.eva: + return None + if self._eva_flux is None: + beam = self.run_card["beam"] + mw, mz, e2 = self._eva_ew_inputs(api) + self._eva_flux = ms.EvaFlux( + [int(beam["lepton1"]), int(beam["lepton2"])], + [float(e) for e in self.beam_energies], + mw, mz, e2, + # madevent's setrun.f: fLpol = 0.5 - polbeam / 200 + [0.5 - float(beam["polarization%d" % i]) / 200. for i in (1, 2)], + int(beam["eva_order"]), + beam["eva_evolution"] == "pt", + bool(beam["eva_xcut"]), + ) + logger.info("EVA couplings from M_W = %.6g GeV, M_Z = %.6g GeV, " + "1/alpha = %.6g", mw, mz, 4 * math.pi / e2) + return self._eva_flux + + def _eva_ew_inputs(self, api): + """(M_W, M_Z, e^2) of the model, see eva_flux.""" + def from_api(*names): + if api is None or not api.supports_get_parameter(): + return None + for name in names: + try: + return float(api.get_parameter(name)[0]) + except RuntimeError as error: + # a model without this parameter name: try the next one; + # any other error of the library is a real one + if "unknown or non-settable parameter" not in str(error): + raise + return None + + def from_card(block, pid): + try: + return float(self.param_card.get_value(block, pid)) + except KeyError: + # no such block or entry in the param card + return None + + mw = from_api("mdl_MW", "MW") or from_card("mass", 24) + mz = from_api("mdl_MZ", "MZ") or from_card("mass", 23) + if not mw or not mz: + raise RuntimeError("EVA needs M_W and M_Z, found neither in the " + "matrix-element library nor in the param card") + aewm1 = from_api("mdl_aEWM1", "aEWM1") or from_card("sminputs", 1) + gf = from_api("mdl_Gf", "Gf") + if aewm1: + e2 = 4 * math.pi / aewm1 + elif gf: + # madevent's gal(1) in the G_mu scheme + e2 = 4 * math.sqrt(2.) * mw ** 2 * (1 - mw ** 2 / mz ** 2) * gf + else: + ee = from_api("mdl_ee", "ee") + if not ee: + raise RuntimeError("EVA needs alpha_EW: found neither aEWM1, " + "Gf nor ee") + e2 = ee ** 2 + return mw, mz, e2 + def upc_luminosity(self): """The gamma-UPC luminosity (upc_luminosity.UPCLuminosity) of the run, or None without beam.upc_flux: one table, down to the lowest @@ -2851,6 +3012,11 @@ def _beam_info(self): if not self.leptonic: # hadronic collider: proton beams (p-pbar is not distinguished) return [2212, 2212], list(self.beam_energies) + if getattr(self, "eva", False): + # the leptons radiating the vector bosons + beam = self.run_card["beam"] + return ([int(beam["lepton1"]), int(beam["lepton2"])], + list(self.beam_energies)) data = self.subprocess_data[0] incoming = data["incoming"] flavor0 = event_flavors(data, self)[0]["options"][0] diff --git a/madgraph/mg7/subprocess_amplicol.py b/madgraph/mg7/subprocess_amplicol.py index f3813849e3..f3f2c2a735 100644 --- a/madgraph/mg7/subprocess_amplicol.py +++ b/madgraph/mg7/subprocess_amplicol.py @@ -646,6 +646,13 @@ def build_multichannel_phasespace(self) -> PhaseSpace: "dressed-lepton beams (beam.lepton_density) are not supported " "with the AmpliCol output; use the madmatrix one" ) + if getattr(self.process, "eva", False): + # the same for the effective vector bosons, whose densities need + # the helicity the matrix element picks + raise NotImplementedError( + "EVA beams (beam.eva) are not supported with the AmpliCol " + "output; use the madmatrix one" + ) if self.process.upc_flux: # the same for the gamma-UPC luminosity raise NotImplementedError( @@ -658,14 +665,14 @@ def build_multichannel_phasespace(self) -> PhaseSpace: for topology, color_order, _ in channel_topologies(self.meta, self.process): mappings.append(ms.PhaseSpaceMapping( topology, - self.process.e_cm, + self.e_cm, leptonic=self.process.leptonic, invariant_power=self.process.run_card["phasespace"]["invariant_power"], t_channel_mode=ms.PhaseSpaceMapping.color_ordered, cuts=self.cuts, permutations=[list(range(particle_count))], color_ordered=ms.ColorOrderedMapping.Options(color_order), - beam_rapidity=self.process.beam_rapidity, + beam_rapidity=self.beam_rapidity, mirror_beams=self.mirror_beams, )) if any(flavor["channels"][0] != 0 for flavor in flavors): diff --git a/madgraph/mg7/subprocess_madmatrix.py b/madgraph/mg7/subprocess_madmatrix.py index ac349262e2..6d09433496 100644 --- a/madgraph/mg7/subprocess_madmatrix.py +++ b/madgraph/mg7/subprocess_madmatrix.py @@ -9,7 +9,8 @@ from typing import Literal, NamedTuple, TYPE_CHECKING from madgraph.mg7 import lepton_density as lepton_density_module -from madgraph.mg7.common import logger, me_parameters, mlm_clustering_history, ms +from madgraph.mg7.common import (interference_helicities_summed, logger, me_parameters, + mlm_clustering_history, ms) from madgraph.iolibs.template_files.mg7.custom_function_loader import load_surrogate from madgraph.mg7.observables import _flavor_options, build_observable, clean_pids, decay_products, observable_pids, pid_is_qcd @@ -330,6 +331,10 @@ def __init__( self.process.get_mass(pid) for pid in clean_pids(self.meta["outgoing"]) ] self.particle_count = len(self.incoming_masses) + len(self.outgoing_masses) + # s and the boost of the beams: per subprocess for monochromatic beams + # of massive particles, see MadgraphProcess.beam_kinematics + self.e_cm, self.beam_rapidity = self.process.beam_kinematics( + self.incoming_masses) # MadEvent's cut_decays = F: the decay products of on-shell propagators # are left out of every cut selection (a pair cut then needs both # members to be cut), while the histograms still see them @@ -434,7 +439,7 @@ def build_mlm_scale(self, min_scale: float, max_scale: float): ckkwl = getattr(self.process, "ckkwl_scale", False) beam = self.process.run_card["beam"] options = dict( - cm_energy=self.process.e_cm, + cm_energy=self.e_cm, jet_scale_scheme=getattr( ms.MLMClustering.JetScaleScheme, beam["jet_scale_scheme"]), scale_scheme=getattr( @@ -648,14 +653,14 @@ def build_multichannel_phasespace(self) -> PhaseSpace: ) mapping = ms.PhaseSpaceMapping( topo, - self.process.e_cm, + self.e_cm, t_channel_mode=t_channel_mode, cuts=self.cuts, invariant_power=self.process.run_card["phasespace"]["invariant_power"], permutations=chan_permutations, leptonic=self.ps_leptonic, lepton_sampling_power=self.lepton_sampling_power, - beam_rapidity=self.process.beam_rapidity, + beam_rapidity=self.beam_rapidity, mirror_beams=self.mirror_beams, ) prefix = f"subproc{self.subproc_id}.channel{channel_id}" @@ -725,12 +730,12 @@ def has_mirrored_flavors(self) -> bool: def build_flat_phasespace(self) -> PhaseSpace: mapping = ms.PhaseSpaceMapping( self.incoming_masses + self.outgoing_masses, - self.process.e_cm, + self.e_cm, mode=self.t_channel_mode(self.process.run_card["phasespace"]["flat_mode"]), cuts=self.cuts, leptonic=self.ps_leptonic, lepton_sampling_power=self.lepton_sampling_power, - beam_rapidity=self.process.beam_rapidity, + beam_rapidity=self.beam_rapidity, mirror_beams=self.mirror_beams, ) prefix = f"subproc{self.subproc_id}.flat" @@ -1027,7 +1032,7 @@ def drop_empty_channels(self, mcdata: MultiChannelData) -> MultiChannelData: empty = [ ms.PhaseSpaceMapping( chan_topologies[0], - self.process.e_cm, + self.e_cm, t_channel_mode=t_channel_mode, cuts=self.cuts, invariant_power=self.process.run_card["phasespace"]["invariant_power"], @@ -1361,7 +1366,9 @@ def build_discrete( # both u- and d-type rows discrete_flavor = ms.DiscreteSampler( [flavor_count], f"{prefix}.discrete_flavor", - [] if self.process.leptonic else [0] + # EVA beams have densities, so a prior + [] if self.process.leptonic and not getattr(self.process, "eva", False) + else [0] ) for context in self.process.contexts: discrete_flavor.initialize_globals(context) @@ -1397,8 +1404,75 @@ def ps_leptonic(self) -> bool: mapping still has to sample x. The two senses of the word part here. """ return (self.process.leptonic and self.process.lepton_density is None + and not getattr(self.process, "eva", False) and not self.process.upc_flux) + def eva_flux(self): + """The EVA beams (ms.EvaFlux) of an EVA run, None otherwise, after + checking that this subprocess can have them: two incoming W, Z or + photons, a matrix element that picks the helicity of the event (no + [surrogate]), and a helicity that means something (not the helicity + sum of an interference).""" + incoming = clean_pids(self.meta["incoming"]) + if not getattr(self.process, "eva", False): + return None + options = [flav["options"][0] for flav in self.meta["flavors"]] + if self.unmerged_meta is not None: + options = [ + self.unmerged_meta[self.meta["subprocesses"][flav["subprocess"]]] + ["flavors"][flav["flavor"]]["options"][0] + for flav in self.meta["flavors"]] + if len(incoming) != 2 or any( + abs(pid) not in (22, 23, 24) for option in options + for pid in option[:2]): + raise ValueError( + "beam.eva: subprocess %s > %s has an incoming particle that is " + "not a W, Z or photon; EVA beams need vector bosons on both " + "incoming legs (set beam.eva = false for other processes)" + % (self.meta["incoming"], self.meta["outgoing"])) + # the incoming W/Z are put on their mass shell (as madevent), which a + # single outgoing particle lighter than them cannot reach + incoming_mass = sum(self.incoming_masses) + if len(self.outgoing_masses) == 1 and \ + self.outgoing_masses[0] <= incoming_mass: + raise ValueError( + "beam.eva: %s > %s is below the threshold of its on-shell " + "incoming vector bosons (%g <= %g GeV), so it has no phase " + "space" % (self.meta["incoming"], self.meta["outgoing"], + self.outgoing_masses[0], incoming_mass)) + if self.unmerged_meta is not None and len({ + tuple(self.process.get_mass(pid) + for pid in clean_pids(self.unmerged_meta[index]["incoming"])) + for index in self.meta["subprocesses"]}) > 1: + # the phase-space channels put one set of masses on shell + raise NotImplementedError( + "beam.eva with merged subprocesses whose incoming vector bosons " + "have different masses: set phasespace.merge_subprocesses = false") + if self.process.surrogate is not None: + raise NotImplementedError( + "beam.eva cannot be combined with a [surrogate]: the EVA " + "densities need the helicity the full matrix element picks") + members = [self.meta] if self.unmerged_meta is None else [ + self.unmerged_meta[index] for index in self.meta["subprocesses"]] + if interference_helicities_summed(self.process.run_card) and any( + meta.get("interference") for meta in members): + raise NotImplementedError( + "beam.eva with [generation] interference_helicity = \"summed\": " + "the EVA densities need the helicity of the event; use \"exact\"") + api = next((me for me in self.matrix_elements if me is not None), None) + return self.process.eva_flux(api) + + def eva_helicities(self) -> list: + """Per flavour of the integrand, the helicity table of its matrix + element (the rows its helicity index counts, the incoming legs first).""" + tables = [] + for flav in self.meta["flavors"]: + meta = self.meta + if self.unmerged_meta is not None: + meta = self.unmerged_meta[self.meta["subprocesses"][flav["subprocess"]]] + tables.append([[int(h) for h in row] for row in meta["helicities"]]) + return tables + def upc_tau_min(self) -> float: """A lower bound on s_hat / s of this subprocess, which the table of a gamma-UPC luminosity has to reach: from the outgoing masses and the pt @@ -1583,6 +1657,8 @@ def build_integrands( cross_sections = [] dressed = self.process.lepton_density + eva = self.eva_flux() + eva_helicities = self.eva_helicities() if eva is not None else [] upc = self.process.upc_luminosity() for mat in self.integrand_matrix_elements(): pdf_grid = None if self.process.leptonic else self.process.pdf_grid @@ -1593,16 +1669,23 @@ def build_integrands( # lepton_density.pdf_factor for why beam 2 stays empty pdf_arg = ms.CachedPdf() pdf_arg2 = None + if eva is not None: + # the integrand computes the helicity sums of the densities + # (flavour prior, pdf1/pdf2), the cross section the densities + # of the helicities its matrix element picks + pdf_grid = eva + pdf_arg = pdf_arg2 = ms.CachedPdf() cross_sections.append( ms.DifferentialCrossSection( matrix_element=mat, # For a decay this is the decaying particle's mass, and the # flux becomes 1/(2M): the result is a partial width in # GeV, not a cross section in pb. - cm_energy=self.process.e_cm, + cm_energy=self.e_cm, running_coupling=None, energy_scale=ms.CachedScale(), - pid_options=[], + # EVA reads the incoming vector bosons of each flavour + pid_options=flavors if eva is not None else [], pdf1=pdf_arg, pdf2=pdf_arg2, input_momentum_fraction=True, @@ -1611,6 +1694,8 @@ def build_integrands( return_matrix_element=( self.has_weighting_steps() or self.process.store_matrix_elements ), + eva=eva, + eva_helicities=eva_helicities, ) ) partial_weights = self.process.systematics_enabled() diff --git a/madgraph/various/banner.py b/madgraph/various/banner.py old mode 100644 new mode 100755 index 97b258aed1..3539e404fb --- a/madgraph/various/banner.py +++ b/madgraph/various/banner.py @@ -7574,6 +7574,36 @@ def default_setup(self): self.add_toml_param('beam', 'lepton_density', "", comment="dressed-lepton density (a directory of Source/PDF/lep_densities) " "or \"\" for none: ISR and, for the collider-specific sets, beamstrahlung") + # EVA (madevent: pdlabel = eva on e/mu beams, lpp = +-3/+-4): the W, Z + # and photon content of the lepton beams lepton1/lepton2. No PDF and + # alpha_s from the param card, as a lepton collider, but x is sampled, + # and the density of an incoming vector boson depends on the helicity + # its matrix element picks (madspace EvaFlux). + self.add_toml_param('beam', 'eva', False, + comment="effective vector bosons (W, Z, photon) from the lepton beams " + "lepton1/lepton2, as madevent's pdlabel = eva", + hidden=True) + for i, lepton in ((1, -11), (2, 11)): + self.add_toml_param('beam', 'lepton%d' % i, lepton, + comment="lepton of beam %d with eva: +-11 (e) or +-13 (mu), " + "madevent's lpp%d = +-3 / +-4" % (i, i), + allowed=[11, -11, 13, -13], hidden=True) + self.add_toml_param('beam', 'polarization%d' % i, 0.0, + comment="polarisation of the beam-%d lepton with eva, in %%: " + "-100 left-handed, 0 unpolarised, 100 right-handed " + "(madevent's polbeam%d)" % (i, i), + hidden=True) + self.add_toml_param('beam', 'eva_order', 0, + comment="eva: 0 = leading log (LLA), 1 = full leading power, " + "2 = next-to-leading power (madevent's evaorder)", + allowed=[0, 1, 2], hidden=True) + self.add_toml_param('beam', 'eva_evolution', "q2", + comment="eva: evolution of the densities in q2 or pt (pt^2, which " + "lowers the scale floor by 1-x; madevent's ievo_eva = 1)", + allowed=['q2', 'pt'], hidden=True) + self.add_toml_param('beam', 'eva_xcut', True, + comment="eva: no W/Z below x = M_V / E_beam (madevent's eva_xcut)", + hidden=True) # gamma-UPC (madevent: lpp = 2 on both beams with an 'ed*'/'ch*' # pdlabel): the coherent photons of two protons or ions, with the # probability that the beams do not break up. Like a dressed-lepton @@ -9047,6 +9077,7 @@ def set_collider(self, name, arg, masses=None): # madevent beam settings understood by set_lo_beam_param lo_beam_params = ('ebeam', 'ebeam1', 'ebeam2', 'lpp', 'lpp1', 'lpp2', 'pdlabel', 'pdlabel1', 'pdlabel2', 'lhaid', + 'polbeam1', 'polbeam2', 'ievo_eva', 'evaorder', 'eva_xcut', 'nb_proton', 'nb_proton1', 'nb_proton2', 'nb_neutron', 'nb_neutron1', 'nb_neutron2') @@ -9063,7 +9094,13 @@ def set_lo_beam_param(self, name, value, masses=None, data_paths=()): 'none' on both beams is a lepton collider. * lpp: mg7 has one switch for both beams, beam.leptonic, true for 0 (no PDF) and +-3/+-4 (e/mu), false for +-1 and +-2 (elastic - photons, only through a gamma-UPC pdlabel: beam.upc_flux). + photons, only through a gamma-UPC pdlabel: beam.upc_flux). +-3/+-4 + also sets the lepton of the beam (beam.lepton1/2), which EVA uses. + * pdlabel eva: beam.eva, on both beams (mg7 has no EVA on one beam + only); any other label, and lpp 0, +-1 or +-2, switches it off, with + the beam polarisations (_switch_eva_off). + * polbeam1/2, ievo_eva, evaorder, eva_xcut: the EVA settings + beam.polarization1/2, eva_evolution, eva_order, eva_xcut. * a gamma-UPC pdlabel (edff, chff, ...) sets beam.upc_flux, for both beams; any other pdlabel clears it. * nb_proton / nb_neutron: the ions of a gamma-UPC run. @@ -9074,6 +9111,39 @@ def set_lo_beam_param(self, name, value, masses=None, data_paths=()): which = 'beam ' + beams[0] if len(beams) == 1 else 'both beams' value = str(value).strip() + if name in ('polbeam1', 'polbeam2', 'ievo_eva', 'evaorder', 'eva_xcut'): + try: + number = float(value) + except ValueError: + raise InvalidRunCard('%s = %s: not a number' % (name, value)) + if name.startswith('polbeam'): + if not -100. <= number <= 100.: + raise InvalidRunCard('%s = %s: not in [-100, 100]' % (name, value)) + self.set('beam.polarization' + beams[0], number, user=True) + if number != 0. and not self['beam']['eva']: + logger.warning('%s: mg7 polarises the lepton beams of an EVA ' + 'run only: the card is invalid until ' + 'pdlabel eva (beam.eva) is set', name) + return 'beam.polarization%s = %s' % (beams[0], number) + if number != int(number): + raise InvalidRunCard('%s = %s: not an integer' % (name, value)) + number = int(number) + if name == 'ievo_eva': + if number not in (0, 1): + raise InvalidRunCard('ievo_eva = %s: 0 or 1' % value) + evolution = 'pt' if number else 'q2' + self.set('beam.eva_evolution', evolution, user=True) + return 'beam.eva_evolution = %s' % evolution + if name == 'evaorder': + if number not in (0, 1, 2): + raise InvalidRunCard('evaorder = %s: 0, 1 or 2' % value) + self.set('beam.eva_order', number, user=True) + return 'beam.eva_order = %s' % number + if number not in (0, 1): + raise InvalidRunCard('eva_xcut = %s: 0 or 1' % value) + self.set('beam.eva_xcut', bool(number), user=True) + return 'beam.eva_xcut = %s' % bool(number) + if name.startswith('ebeam'): energy = self.evaluate(value, masses) if isinstance(energy, str): @@ -9111,8 +9181,10 @@ def set_lo_beam_param(self, name, value, masses=None, data_paths=()): 'gamma-UPC pdlabel chooses another flux', name, lpp, self.default_upc_flux) self.set('beam.leptonic', False, user=True) - return ('beam.leptonic = False, beam.upc_flux = %s (elastic ' - 'photons from gamma-UPC)' % self['beam']['upc_flux']) + eva_off = self._switch_eva_off('%s = %s' % (name, lpp)) + return ', '.join(filter(None, [ + eva_off, 'beam.leptonic = False, beam.upc_flux = %s (elastic ' + 'photons from gamma-UPC)' % self['beam']['upc_flux']])) if abs(lpp) not in (0, 1, 3, 4): raise InvalidRunCard('%s = %s: beam type not representable in mg7' % (name, lpp)) @@ -9130,7 +9202,18 @@ def set_lo_beam_param(self, name, value, masses=None, data_paths=()): logger.warning('%s = -1: mg7 has no antiproton beam and keeps ' 'the proton PDF', name) self.set('beam.leptonic', leptonic, user=True) - return 'beam.leptonic = %s' % leptonic + if abs(lpp) in (3, 4): + # the beam lepton, which only EVA needs to know (madevent: an + # electron for lpp = 3, a positron for -3) + lepton = (11 if abs(lpp) == 3 else 13) * (1 if lpp > 0 else -1) + for beam in beams: + self.set('beam.lepton' + beam, lepton, user=True) + return 'beam.leptonic = True, beam.lepton%s = %s' % ( + '/'.join(beams), lepton) + # proton beams, or fixed-energy beams of the incoming particles + # (lpp = 0, madevent ignores pdlabel then): no EVA + eva_off = self._switch_eva_off('%s = %s' % (name, lpp)) + return ', '.join(filter(None, [eva_off, 'beam.leptonic = %s' % leptonic])) if name == 'lhaid': label, lhaid = 'lhapdf', value.split()[0] if value else value @@ -9140,10 +9223,21 @@ def set_lo_beam_param(self, name, value, masses=None, data_paths=()): raise InvalidRunCard('lhaid = %s: not an integer' % value) else: label, lhaid = value, None + if label.lower() == 'eva': + if len(beams) == 1 and self['beam']['eva'] is not True: + logger.info('%s = eva: mg7 has EVA on both beams only; ' + 'beam.eva applies to both' % name) + self.set('beam.eva', True, user=True) + self.set('beam.leptonic', True, user=True) + return 'beam.eva = True (both beams, leptons %s, %s)' % ( + self['beam']['lepton1'], self['beam']['lepton2']) if is_upc_label(label.lower()): # one label for both beams (PDLabelBlock does the same) + eva_off = self._switch_eva_off('%s = %s' % (name, value)) self.set('beam.upc_flux', label.lower(), user=True) - return 'beam.upc_flux = %s (gamma-UPC, both beams)' % label.lower() + return ', '.join(filter(None, [ + eva_off, + 'beam.upc_flux = %s (gamma-UPC, both beams)' % label.lower()])) if self['beam']['upc_flux']: # lpp = 2: madevent also has the EPA (iww) and replaces any other # pdlabel by chff; mg7 refuses it rather than guess, and leaving @@ -9155,6 +9249,10 @@ def set_lo_beam_param(self, name, value, masses=None, data_paths=()): % (name, value, self['beam']['upc_flux'])) if name != 'lhaid': if label.lower() == 'lhapdf': + eva_off = self._switch_eva_off('%s = %s' % (name, value)) + if eva_off: + return eva_off + ' (the PDF set is chosen with lhaid or ' \ + 'beam.pdf1/pdf2)' return ('unchanged: mg7 always uses LHAPDF, the set is chosen ' 'with lhaid or beam.pdf1/pdf2') if label.lower() in ('none', 'no'): @@ -9162,14 +9260,42 @@ def set_lo_beam_param(self, name, value, masses=None, data_paths=()): raise InvalidRunCard('%s = none: only a lepton collider has ' 'no PDF in mg7, on both beams' % name) self.set('beam.leptonic', True, user=True) - return 'beam.leptonic = True' + eva_off = self._switch_eva_off('%s = %s' % (name, value)) + return ', '.join(filter(None, [eva_off, 'beam.leptonic = True'])) pdf = self._resolve_pdf_label(label, lhaid, [], data_paths) if pdf is None: raise UnknownPDFSet('%s = %s: unknown %s' % ( name, value, 'LHAPDF id' if name == 'lhaid' else 'PDF label')) for beam in beams: self.set('beam.pdf' + beam, pdf, user=True) - return 'PDF of %s: %s' % (which, pdf) + # a PDF label (not an lhaid, which only picks the set) is no EVA + eva_off = '' if name == 'lhaid' else \ + self._switch_eva_off('%s = %s' % (name, value)) + return ', '.join(filter(None, [eva_off, 'PDF of %s: %s' % (which, pdf)])) + + def _switch_eva_off(self, setting): + """Switch beam.eva off, as the madevent setting `setting` asks, and + return what changed ('' if EVA was off). The beam polarisations, + which only an EVA run has (check_eva_validity), go back to 0. A card + still leptonic then has monochromatic beams of the incoming particles + themselves (W beams for w+ w- > X), which is said as a warning.""" + if not self['beam']['eva']: + return '' + self.set('beam.eva', False, user=True) + changes = ['beam.eva = False'] + for i in (1, 2): + key = 'polarization%d' % i + if float(self['beam'][key]) != 0.: + self.set('beam.' + key, 0.0, user=True) + changes.append('beam.%s = 0' % key) + if self['beam']['leptonic']: + logger.warning( + '%s: EVA switched off, so the beams are now monochromatic beams ' + 'of the incoming particles (beam.leptonic = true); set lpp 1 for ' + 'proton beams, or pdlabel eva to go back to EVA', setting) + else: + logger.info('%s: EVA switched off', setting) + return ', '.join(changes) def set_fixed_scale(self, value, masses=None): """``set fixed_scale X``: switch to fixed scales and set them all to X @@ -9243,6 +9369,42 @@ def cluster_pass_card(self, name): card.check_devices(card['run']['device'], '[%s] run.device' % section) return card + def check_eva_validity(self): + """beam.eva: lepton beams (leptonic = true) without another density + replacing the PDFs, polarisations in [-100, 100] that only an EVA run + uses, and no merging (the MLM/CKKW-L clustering assumes hadron beams + or no beam density).""" + beam = self['beam'] + for i in (1, 2): + pol = float(beam['polarization%d' % i]) + if not -100. <= pol <= 100.: + raise InvalidRunCard( + "beam.polarization%d = %s is not in [-100, 100]" % (i, pol)) + if pol != 0. and not beam['eva']: + raise InvalidRunCard( + "beam.polarization%d = %s: mg7 polarises the beam leptons " + "of an EVA run only (beam.eva); for a polarised lepton " + "beam, generate the process with polarised leptons, e.g. " + "e-{L}" % (i, pol)) + if not beam['eva']: + return + if not beam['leptonic']: + raise InvalidRunCard( + "beam.eva needs lepton beams: set beam.leptonic = true (and " + "beam.lepton1/lepton2)") + if beam['lepton_density']: + raise InvalidRunCard( + "beam.eva and beam.lepton_density both replace the PDFs: set " + "only one of them") + if beam.get('upc_flux'): + raise InvalidRunCard( + "beam.eva and beam.upc_flux both replace the PDFs: set only one " + "of them") + if beam['dynamical_scale_choice'] in ('mlm', 'ckkwl'): + raise InvalidRunCard( + "beam.eva cannot be combined with MLM/CKKW-L merging " + "(dynamical_scale_choice = %s)" % beam['dynamical_scale_choice']) + # beam.upc_flux of 'set lpp 2' before any gamma-UPC pdlabel default_upc_flux = 'chff' @@ -9305,6 +9467,7 @@ def check_validity(self): beam = self['beam'] if float(beam['scale_factor']) <= 0.: raise InvalidRunCard("scale_factor must be strictly positive") + self.check_eva_validity() self.check_upc_validity() self.check_ckkwl_validity() if (float(beam['scale_factor']) != 1. and beam['fixed_ren_scale'] @@ -9558,6 +9721,25 @@ def write_gridpack_card(self, output_file): # multiplicities, madevent's default_mlm_xqcut = 30.0 + @staticmethod + def eva_beams(proc_def): + """Whether the processes of proc_def collide W/Z on both beams + (madevent's condition for EVA beams by default: a W or Z among the + particles of each incoming leg), with only W, Z and photons there.""" + beams = [set(), set()] + try: + for proc in proc_def: + for oneproc in proc: + initial = [leg for leg in oneproc['legs'] if not leg['state']] + if len(initial) != 2: + return False + for ids, leg in zip(beams, initial): + ids.update(leg['ids'] if 'ids' in leg else [leg['id']]) + except (TypeError, KeyError, IndexError): + return False + return all(any(abs(i) in (23, 24) for i in ids) and + all(abs(i) in (22, 23, 24) for i in ids) for ids in beams) + def create_default_for_process(self, proc_characteristic, history, proc_def): """Adjust default values depending on the process, then read the site/user default file (``input/default_run_card_mg7.toml``).""" @@ -9590,7 +9772,22 @@ def create_default_for_process(self, proc_characteristic, history, proc_def): # particle self._sync_jet_group(old, self['beam']['max_jet_flavor']) - if beam_id and beam_id <= leptons: + if beam_id and self.eva_beams(proc_def): + # W/Z (and photons) on both beams: effective vector bosons from + # e+ e- beams, as madevent sets it up (lpp1 = -3, lpp2 = 3, + # pdlabel = eva, 15 TeV beams, a fixed factorisation scale). Not + # monochromatic W/Z beams, which would run without a word. + self['beam']['leptonic'] = True + self['beam']['eva'] = True + self['beam']['ebeam1'] = 15000.0 + self['beam']['ebeam2'] = 15000.0 + self['beam']['fixed_fact_scale'] = True + # written out, so that the card shows the EVA settings + for key in ('eva', 'lepton1', 'lepton2', 'polarization1', + 'polarization2', 'eva_order', 'eva_evolution', + 'eva_xcut'): + self.user_set.add('beam.' + key) + elif beam_id and beam_id <= leptons: # lepton collider: no PDF, lower default energy. The jet cuts stay, # as in madevent's run_card (ptj/etaj/drjj are not hadron-collider # specific): without them e+ e- > j j j (j) is infrared divergent, @@ -10255,6 +10452,36 @@ def nondefault(name): # lpp 0 = fixed-energy beam with no PDF, typically a lepton collider mg7.set('beam.leptonic', all(l == 0 for l in lpps) or any(is_lep(l) for l in lpps)) + # EVA: pdlabel eva, or pdlabel1/2 eva, on two e/mu beams (pdlabel1/2 + # follow pdlabel only once the LO card is checked, so both are read); + # one EVA beam only has no mg7 equivalent + eva_labels = [ + (str(lo['pdlabel']).lower() if 'pdlabel' in lo else '') == 'eva' + or (str(lo['pdlabel%d' % i]).lower() + if 'pdlabel%d' % i in lo else '') == 'eva' + for i in (1, 2)] + eva = all(eva_labels) and all(is_lep(l) for l in lpps) + eva_keys = set() + if eva: + mg7.set('beam.eva', True) + for i, lpp in ((1, lpps[0]), (2, lpps[1])): + mg7.set('beam.lepton%d' % i, + (11 if abs(lpp) == 3 else 13) * (1 if lpp > 0 else -1)) + if 'polbeam%d' % i in lo: + mg7.set('beam.polarization%d' % i, float(lo['polbeam%d' % i])) + if 'ievo_eva' in lo: + mg7.set('beam.eva_evolution', 'pt' if int(lo['ievo_eva']) else 'q2') + if 'evaorder' in lo: + mg7.set('beam.eva_order', int(lo['evaorder'])) + if 'eva_xcut' in lo: + mg7.set('beam.eva_xcut', bool(int(lo['eva_xcut']))) + eva_keys = {'polbeam1', 'polbeam2', 'ievo_eva', 'evaorder', 'eva_xcut'} + elif any(eva_labels): + dropped.append( + 'pdlabel1=%s, pdlabel2=%s with lpp1=%s, lpp2=%s (mg7 has EVA on ' + 'two electron/muon beams only)' % ( + 'eva' if eva_labels[0] else 'other', + 'eva' if eva_labels[1] else 'other', lpps[0], lpps[1])) # gamma-UPC: |lpp| = 2 on both beams with a gamma-UPC pdlabel (the # PDLabelBlock makes it the same on both) upc_keys = set() @@ -10275,7 +10502,7 @@ def nondefault(name): # the ion masses only enter madevent's LHE header upc_keys.update(('mass_ion1', 'mass_ion2')) for i, lpp in ((1, lpps[0]), (2, lpps[1])): - if upc_keys: + if eva or upc_keys: continue if isinstance(lpp, int) and abs(lpp) not in (0, 1, 3, 4): dropped.append('lpp%d=%s (beam type not representable in mg7)' % (i, lpp)) @@ -10332,7 +10559,7 @@ def nondefault(name): # clustering scales are used whatever dynamical_scale_choice said. ickkw = int(lo['ickkw']) if 'ickkw' in lo else 0 # unsupported LO names transferred all the same in this context - transferred = set(upc_keys) + transferred = set(eva_keys) | set(upc_keys) if ickkw == 1: xqcut = float(lo['xqcut']) if 'xqcut' in lo else 0. if xqcut > 0: @@ -10405,10 +10632,10 @@ def nondefault(name): mg7.set('run.me_frame', list(lo['me_frame']) or [1, 2]) # --- PDF --- - # a gamma-UPC label, like a dressed-lepton one, is no PDF set: it was - # carried as beam.upc_flux above - pdf_names = cls._resolve_pdf(lo, dropped, - dressed=bool(dressed) or bool(upc_keys)) + # an EVA or gamma-UPC label, like a dressed-lepton one, is no PDF set: + # it was carried as beam.eva or beam.upc_flux above + pdf_names = cls._resolve_pdf( + lo, dropped, dressed=bool(dressed) or eva or bool(upc_keys)) for beam, pdf_name in zip((1, 2), pdf_names): if pdf_name: mg7.set('beam.pdf%d' % beam, pdf_name) diff --git a/madspace/CMakeLists.txt b/madspace/CMakeLists.txt index 0e1ab77688..cf4e067654 100644 --- a/madspace/CMakeLists.txt +++ b/madspace/CMakeLists.txt @@ -284,6 +284,7 @@ add_library( src/phasespace/mlm_clustering.cpp src/phasespace/merging_scale.cpp src/phasespace/cross_section.cpp + src/phasespace/eva.cpp src/phasespace/scale.cpp src/phasespace/weighting_step.cpp include/madspace/util.hpp diff --git a/madspace/include/madspace/phasespace.hpp b/madspace/include/madspace/phasespace.hpp index 477a41a44b..ac29ae8c9b 100644 --- a/madspace/include/madspace/phasespace.hpp +++ b/madspace/include/madspace/phasespace.hpp @@ -12,6 +12,7 @@ #include "phasespace/discrete_flavor_levels.hpp" #include "phasespace/discrete_flow.hpp" #include "phasespace/discrete_sampler.hpp" +#include "phasespace/eva.hpp" #include "phasespace/flow.hpp" #include "phasespace/histograms.hpp" #include "phasespace/integrand.hpp" diff --git a/madspace/include/madspace/phasespace/cross_section.hpp b/madspace/include/madspace/phasespace/cross_section.hpp index eec7bfbd8b..4337ac1a9a 100644 --- a/madspace/include/madspace/phasespace/cross_section.hpp +++ b/madspace/include/madspace/phasespace/cross_section.hpp @@ -1,5 +1,6 @@ #pragma once +#include "madspace/phasespace/eva.hpp" #include "madspace/phasespace/matrix_element.hpp" #include "madspace/phasespace/pdf.hpp" #include "madspace/phasespace/scale.hpp" @@ -20,6 +21,17 @@ namespace madspace { * @f$M@f$ = @p cm_energy, in GeV, rather than a hadronic cross section in pb. * There are no beams, hence no PDFs; declared `x1`, `x2` inputs are ignored. * + * With @p eva the beams are effective vector bosons (@ref EvaFlux), whose + * densities depend on their helicity. The cached `pdf1`, `pdf2` (helicity + * sums) are then replaced, after the matrix element picked the helicity row + * of the event with a probability proportional to its @f$|M_h|^2@f$, by + * @f$x_i n_i f_{\lambda_i}(x_i, \mu_i)@f$ with @f$\lambda_i@f$ the + * helicity of incoming leg @f$i@f$ in that row of @p eva_helicities and + * @f$n_i@f$ its number of helicity states: the helicity-averaged + * @f$|M|^2@f$ times these is an unbiased estimate of + * @f$\sum_h f_{\lambda_1(h)} f_{\lambda_2(h)} |M_h|^2@f$. Leg @f$i@f$ + * comes from beam @f$i@f$, or from the other one for `mirror_index` 1. + * * `batch` is the leading batch dimension. * * **Arguments** @@ -31,6 +43,10 @@ namespace madspace { * `CachedPdf` argument). * - `alpha_s` – `float`, shape `(batch,)` – cached coupling (with a * `CachedScale` argument). + * - `fact_scale1`, `fact_scale2` – `float`, shape `(batch,)` – factorisation + * scales of the two legs (with @p eva). + * - `mirror_index` – `int`, shape `(batch,)` – 1 for an event whose legs come + * from the other beams (with @p eva). * * **Returns** * - the return values of @p matrix_element, scaled to the differential cross @@ -67,6 +83,14 @@ class DifferentialCrossSection : public FunctionGenerator { * incoming particle instead of a collision. * @param return_matrix_element If true, also return the squared matrix * element itself as `raw_matrix_element`. + * @param eva Effective-vector-boson beams; needs + * `CachedPdf` on both beams, a + * `CachedScale`, @p pid_options and a + * matrix element returning its helicity. + * @param eva_helicities With @p eva, per flavour option, the + * helicity table of the matrix element + * (rows of the particles' helicities, + * indexed by its helicity index). */ DifferentialCrossSection( const MatrixElement& matrix_element, @@ -79,7 +103,9 @@ class DifferentialCrossSection : public FunctionGenerator { const std::variant& pdf2 = std::monostate{}, bool input_momentum_fraction = true, bool decay = false, - bool return_matrix_element = false + bool return_matrix_element = false, + const std::optional& eva = std::nullopt, + const nested_vector3& eva_helicities = {} ); /// The allowed initial-parton flavour combinations. @@ -94,6 +120,9 @@ class DifferentialCrossSection : public FunctionGenerator { } /// Whether the squared matrix element is returned as `raw_matrix_element`. bool returns_matrix_element() const { return _return_matrix_element; } + /// Whether the beams are effective vector bosons (then the arguments end + /// with `fact_scale1`, `fact_scale2` and `mirror_index`). + bool eva() const { return _eva_tables.has_value(); } private: NamedVector build_function_impl( @@ -110,6 +139,7 @@ class DifferentialCrossSection : public FunctionGenerator { bool _input_momentum_fraction; bool _decay; bool _return_matrix_element; + std::optional _eva_tables; }; } // namespace madspace diff --git a/madspace/include/madspace/phasespace/eva.hpp b/madspace/include/madspace/phasespace/eva.hpp new file mode 100644 index 0000000000..cbc310ae83 --- /dev/null +++ b/madspace/include/madspace/phasespace/eva.hpp @@ -0,0 +1,170 @@ +#pragma once + +#include +#include + +#include "madspace/compgraphs/type.hpp" +#include "madspace/util.hpp" + +namespace madspace { + +/** + * Effective Vector boson Approximation (EVA): the W, Z and photon content of + * electron and muon beams, madevent's `pdlabel = eva`. + * + * The density of a vector boson of helicity @f$\lambda@f$ in a lepton with a + * left-handed fraction @f$f_L@f$ is + * @f$f_\lambda = f_L f^L_\lambda + (1-f_L) f^R_\lambda@f$ with the closed + * forms of [1] at leading log (LLA), of [2] at full leading power (LP) and + * next-to-leading power (NLP), evolved in @f$\mu_F^2@f$ or @f$p_T^2@f$. This is + * a port of madevent's `ElectroweakFlux.f` and of the checks of + * `ElectroweakFluxDriver.f`, with the same conventions: + * - the densities vanish outside of @f$10^{-8} < x < 1 - 10^{-8}@f$, and for a + * W or Z below @f$x = M_V / E_\text{beam}@f$ unless `xcut` is zero; + * - @f$\mu^2@f$ is raised to @f$M_V^2@f$ (a photon: @f$m_\ell^2@f$), times + * @f$1-x@f$ with @f$p_T@f$ evolution; + * - the couplings follow from @f$M_W@f$, @f$M_Z@f$ and @f$e^2@f$ of the model + * (@f$s_W^2 = 1 - M_W^2/M_Z^2@f$); a photon is always at leading log; + * - a W whose charge the beam lepton cannot emit (a W- from a positron, say) + * has no density, where madevent stops. + * + * The densities depend on the vector boson's helicity, so the cross section is + * @f$\sum_{\lambda_1\lambda_2} f_{\lambda_1} f_{\lambda_2} + * |M_{\lambda_1\lambda_2}|^2@f$ with the matrix element inside the sum. The + * @ref DifferentialCrossSection takes the helicity picked by the matrix element + * (with a probability proportional to its @f$|M_h|^2@f$) and multiplies the + * helicity-averaged @f$|M|^2@f$ by @f$n_1 f_{\lambda_1} n_2 f_{\lambda_2}@f$, + * @f$n_i@f$ the number of helicity states of leg @f$i@f$: an unbiased estimate + * of the sum, as madevent's `nhel = 1`. The helicity sum + * @f$\sum_\lambda f_\lambda@f$ serves as the beam density where no helicity is + * known (flavour sampling, @ref PartonDensity). + * + * **References** + * - [1] R. Ruiz, A. Costantini, F. Maltoni, O. Mattelaer, "The Effective Vector + * Boson Approximation in high-energy muon collisions", + * https://arxiv.org/abs/2111.02442 + * - [2] I. Bigaran, R. Ruiz, https://arxiv.org/abs/2502.07878 + */ +class EvaFlux { +public: + /// Number of numbers of a parameter row, see @ref parameters. + static constexpr std::size_t parameter_count = 11; + /// The helicity argument asking for the sum over the vector's helicities. + static constexpr int helicity_sum = 2; + + /** + * @param beam_leptons PDG ids of the two beam leptons (+-11, +-13). + * @param beam_energies Energies of the two beams, in GeV. + * @param w_mass @f$M_W@f$, in GeV. + * @param z_mass @f$M_Z@f$, in GeV. + * @param e2 @f$e^2 = 4 \pi \alpha@f$ of the model. + * @param left_fractions Left-handed fraction @f$f_L@f$ of each beam lepton, + * 0.5 unpolarised (madevent: 0.5 - polbeam / 200). + * @param order 0: LLA, 1: full LP, 2: NLP (madevent's evaorder). + * @param pt_evolution Evolution in @f$p_T^2@f$ rather than @f$\mu^2@f$ + * (madevent's ievo_eva = 1). + * @param xcut Whether a W or Z needs @f$x > M_V/E_\text{beam}@f$ + * (madevent's eva_xcut). + */ + EvaFlux( + const std::array& beam_leptons, + const std::array& beam_energies, + double w_mass, + double z_mass, + double e2, + const std::array& left_fractions = {0.5, 0.5}, + int order = 0, + bool pt_evolution = false, + bool xcut = true + ); + + /// Whether a vector boson @p vector_pid (+-24, 23, 22 or 7) of beam + /// @p beam (0 or 1) has a density (it is not charge violating). + bool has_density(int vector_pid, std::size_t beam) const; + /// The parameter row of vector boson @p vector_pid from beam @p beam, as + /// the `eva_density` kernels read it: kind (0 none, 1 W/Z, 2 photon), + /// @f$g^2@f$, @f$g_L^2@f$, @f$g_R^2@f$, @f$f_L@f$, @f$M_V^2@f$, + /// @f$\mu^2_\text{min}@f$, @f$x_\text{min}@f$, @f$E_\text{beam}@f$, order, + /// evolution. A vector boson that is not one of the above throws. + std::vector parameters(int vector_pid, std::size_t beam) const; + /** + * The density @f$f_\lambda(x, \mu)@f$ (not @f$x f@f$), on the host: the + * reference the compute-graph kernels are checked against. + * + * @param vector_pid PDG id of the vector boson. + * @param beam The beam (0 or 1). + * @param helicity -1, 0, 1, or @ref helicity_sum. + * @param x Momentum fraction. + * @param q Factorisation scale @f$\mu@f$, in GeV. + */ + double density( + int vector_pid, std::size_t beam, int helicity, double x, double q + ) const; + + /// PDG ids of the beam leptons. + const std::array& beam_leptons() const { return _beam_leptons; } + /// Beam energies, in GeV. + const std::array& beam_energies() const { return _beam_energies; } + /// Left-handed fractions of the beam leptons. + const std::array& left_fractions() const { return _left_fractions; } + /// 0: LLA, 1: LP, 2: NLP. + int order() const { return _order; } + /// Whether the evolution is in @f$p_T^2@f$. + bool pt_evolution() const { return _pt_evolution; } + /// Whether W and Z need @f$x > M_V/E_\text{beam}@f$. + bool xcut() const { return _xcut; } + /// @f$M_W@f$, @f$M_Z@f$ and @f$e^2@f$. + double w_mass() const { return _w_mass; } + double z_mass() const { return _z_mass; } + double e2() const { return _e2; } + +private: + std::array _beam_leptons; + std::array _beam_energies; + double _w_mass, _z_mass, _e2; + std::array _left_fractions; + int _order; + bool _pt_evolution; + bool _xcut; +}; + +/** + * The incoming-leg tables a @ref DifferentialCrossSection needs to apply the + * EVA densities after its matrix element picked a helicity. + * + * Built once per differential cross section from the beams (@ref EvaFlux), + * the flavour options and, per flavour, the helicity table of its matrix + * element (rows of the incoming legs' helicities, in the order of the matrix + * element's helicity index). Leg @f$i@f$ comes from beam @f$i@f$, or from the + * other beam when the event is mirrored. + */ +struct EvaLegTables { + /// Per leg: per flavour, its first row in leg_helicities. + std::array, 2> row_offsets; + /// Per leg: per flavour, its number of rows. + std::array, 2> row_counts; + /// Per leg: per flavour and row, the leg's helicity. + std::array, 2> leg_helicities; + /// Per leg: per flavour and orientation (2 f + mirror), the row of params. + std::array, 2> configs; + /// Per leg: per flavour, the number of helicity states of the leg. + std::array, 2> helicity_counts; + /// The parameter rows. + nested_vector2 params; + + /** + * @param flux The beams. + * @param pid_options Per flavour, the PDG ids of the particles, the two + * incoming ones first. + * @param helicities Per flavour, the helicity table of its matrix + * element: rows of the helicities of the particles, + * the two incoming ones first. + */ + EvaLegTables( + const EvaFlux& flux, + const nested_vector2& pid_options, + const nested_vector3& helicities + ); +}; + +} // namespace madspace diff --git a/madspace/include/madspace/phasespace/integrand.hpp b/madspace/include/madspace/phasespace/integrand.hpp index 653f41fdf3..6f59a83a0e 100644 --- a/madspace/include/madspace/phasespace/integrand.hpp +++ b/madspace/include/madspace/phasespace/integrand.hpp @@ -76,8 +76,10 @@ class Integrand : public FunctionGenerator { /// The optional adaptive sampler for a set of discrete choices. using AdaptiveDiscrete = std:: variant; - /// The optional parton density: an LHAPDF grid or a user-supplied library. - using PdfSource = std::variant; + /// The optional parton density: an LHAPDF grid, a user-supplied library or + /// effective vector bosons (@ref EvaFlux; the differential cross sections + /// must then be built with the same flux). + using PdfSource = std::variant; /// The @ref MatrixElement inputs an `Integrand` supplies. inline static const std::vector @@ -348,6 +350,10 @@ class Integrand : public FunctionGenerator { nested_vector2 _pid_options; std::array, 2> _pdfs; std::optional _lepton_luminosity; + // effective vector bosons: the beam densities are the helicity sums, and + // the differential cross sections take the helicity of the event (they need + // the factorisation scales and the orientation of the event) + bool _eva = false; std::optional _tabulated_luminosity; // with different PDFs per beam: each leg's density from the other beam, // for the events whose orientation is mirrored diff --git a/madspace/include/madspace/phasespace/pdf.hpp b/madspace/include/madspace/phasespace/pdf.hpp index 4baa554e48..21d6aec299 100644 --- a/madspace/include/madspace/phasespace/pdf.hpp +++ b/madspace/include/madspace/phasespace/pdf.hpp @@ -3,6 +3,7 @@ #include "madspace/driver/context.hpp" #include "madspace/phasespace/base.hpp" #include "madspace/phasespace/custom_function.hpp" +#include "madspace/phasespace/eva.hpp" namespace madspace { @@ -66,7 +67,8 @@ struct PdfGrid { * last q knot, and below the first q knot with the anomalous dimension at that * knot, going over into x f vanishing like q^2. Above the last x knot, where * LHAPDF stops with an error, they are zero. With a @ref CustomPdf, - * the user-supplied library is called for each requested flavour instead. + * the user-supplied library is called for each requested flavour instead, and + * with an @ref EvaFlux the helicity-summed EVA densities are returned. * * `batch` is the leading batch dimension. * @@ -114,6 +116,21 @@ class PartonDensity : public FunctionGenerator { int beam_index, bool dynamic_pid = false ); + /** + * @param eva The effective-vector-boson beams. + * @param pids PDG ids of the vector bosons to return; the density + * is the sum over their helicities, @f$x \sum_\lambda + * f_\lambda(x, q)@f$. + * @param beam_index Index of the beam (0 or 1). + * @param dynamic_pid If true, the single flavour of @p pids selected per + * event by `flavor_index` is returned. + */ + PartonDensity( + const EvaFlux& eva, + const std::vector& pids, + int beam_index, + bool dynamic_pid = false + ); private: NamedVector build_function_impl( @@ -123,6 +140,9 @@ class PartonDensity : public FunctionGenerator { std::vector _pid_indices; std::vector _pids; std::optional _custom_pdf; + // EVA: one parameter row per pid (EvaFlux::parameters) + nested_vector2 _eva_params; + bool _eva = false; me_int_t _beam_index = 0; bool _dynamic_pid; std::string _prefix; diff --git a/madspace/include/madspace/phasespace/phasespace.hpp b/madspace/include/madspace/phasespace/phasespace.hpp index a264e11265..a0983ddd88 100644 --- a/madspace/include/madspace/phasespace/phasespace.hpp +++ b/madspace/include/madspace/phasespace/phasespace.hpp @@ -259,6 +259,12 @@ class PhaseSpaceMapping : public Mapping { double beam_rapidity() const { return _beam_rapidity; } /// Whether the mapping takes the `mirror_index` condition. bool mirror_beams() const { return _mirror_beams; } + /// Masses of the incoming particles. The mapping hands them out massless + /// (along the beams, at the sampled s_hat); @ref Integrand puts massive + /// ones on their mass shell, with the massive flux. + const std::vector& incoming_masses() const { + return _topology.incoming_masses(); + } /// The cuts, applied to the lab-frame momenta. const Cuts& cuts() const { return _cuts; } /// True when the cuts exclude the whole region this mapping samples: a diff --git a/madspace/instruction_set.yaml b/madspace/instruction_set.yaml index cf0ae1daf4..3a39c5cbc7 100644 --- a/madspace/instruction_set.yaml +++ b/madspace/instruction_set.yaml @@ -725,6 +725,24 @@ com_p_in: desc: "incoming momentum along -z" desc: "Builds the two incoming momenta for a given center-of-mass energy." +incoming_on_shell: + inputs: + - name: p_ext + type: [float, n, 4] + desc: "external momenta, the two incoming ones first, along the beam axis" + - name: masses + type: [float, single, 2] + desc: "masses of the two incoming particles" + outputs: + - name: p_out + type: [float, n, 4] + desc: "the same momenta with the incoming ones on their mass shell" + - name: flux_ratio + type: [float] + desc: "s_hat / sqrt(lambda(s_hat, m1^2, m2^2)), zero below threshold" + vectorized: False + desc: "Puts the two incoming momenta on their mass shell, with the same sum (so the same s_hat and rapidity) and the same directions, and returns the ratio of the massive flux 1/(2 sqrt(lambda)) to the massless 1/(2 s_hat), as madevent's genps.f has them for massive partons. Below the threshold (m1 + m2)^2 the momenta are unchanged and the ratio is zero." + r_to_x1x2: inputs: - name: r @@ -3172,6 +3190,72 @@ interpolate_pdf: vectorized: False desc: "Evaluates parton densities by bicubic interpolation of a log-x / log-Q2 grid, and outside of it by the continuation extrapolator of LHAPDF (zero above the last x knot). See @ref PartonDensity." +eva_density: + inputs: + - name: x + type: [float] + desc: "momentum fraction" + - name: q + type: [float] + desc: "factorization scale" + - name: helicity + type: [int] + desc: "vector-boson helicity (-1, 0, 1), any other value for the sum over helicities" + - name: config + type: [int] + desc: "row of params: the (vector boson, parent lepton, beam) combination; < 0 for none" + - name: params + type: [float, single, n, 11] + desc: "EVA parameter rows, see EvaFlux::parameters" + outputs: + - name: pdf + type: [float] + desc: "x f(x, q) of that helicity" + vectorized: False + desc: "Effective-vector-boson density of a W, Z or photon in an electron or muon (madevent's pdlabel eva). See @ref EvaFlux." + +eva_leg_density: + inputs: + - name: x + type: [float] + desc: "momentum fraction of the leg" + - name: q + type: [float] + desc: "factorization scale of the leg" + - name: flavor + type: [int] + desc: "flavour index of the event" + - name: helicity + type: [int] + desc: "helicity row picked by the matrix element" + - name: mirror + type: [int] + desc: "1 if the leg comes from the other beam" + - name: row_offsets + type: [int, single, a] + desc: "per flavour, the first entry of its rows in leg_helicities" + - name: row_counts + type: [int, single, a] + desc: "per flavour, its number of helicity rows" + - name: leg_helicities + type: [int, single, b] + desc: "per flavour and row, the helicity of the leg" + - name: configs + type: [int, single, c] + desc: "per flavour and orientation (2 f + mirror), the row of params, < 0 for none" + - name: helicity_counts + type: [float, single, a] + desc: "per flavour, the number of helicity states of the leg" + - name: params + type: [float, single, n, 11] + desc: "EVA parameter rows, see EvaFlux::parameters" + outputs: + - name: pdf + type: [float] + desc: "x n f_lambda(x, q) for the helicity lambda of the leg in the picked row" + vectorized: False + desc: "The EVA density of an incoming leg for the helicity its matrix element picked, times the leg's number of helicity states, so that the helicity-averaged matrix element times both gives an unbiased estimate of the helicity sum. See @ref DifferentialCrossSection." + interpolate_alpha_s: inputs: - name: q diff --git a/madspace/src/kernels/eva.hpp b/madspace/src/kernels/eva.hpp new file mode 100644 index 0000000000..87b2ed8779 --- /dev/null +++ b/madspace/src/kernels/eva.hpp @@ -0,0 +1,239 @@ +#pragma once + +#include "definitions.hpp" + +// The Effective Vector boson Approximation (EVA): the densities of a W, Z or +// photon of helicity -1, 0 or +1 in an electron or muon, at leading log (LLA), +// full leading power (LP) or next-to-leading power (NLP). A line-by-line port +// of madevent's Template/LO/Source/PDF/ElectroweakFlux.f (R. Ruiz, +// arXiv:2111.02442, Bigaran & Ruiz arXiv:2502.07878) and of the checks of +// ElectroweakFluxDriver.f; the couplings of a (vector, parent lepton, beam) +// combination are computed on the host by EvaFlux::parameters, one row of +// eva_param_count numbers laid out as below. See @ref EvaFlux. + +namespace madspace { +namespace kernels { + +// layout of a parameter row (EvaFlux::parameters) +inline constexpr int eva_kind = 0; // 0: no density, 1: W/Z, 2: photon +inline constexpr int eva_gg2 = 1; // squared universal coupling +inline constexpr int eva_gl2 = 2; // squared left chiral coupling of the parent +inline constexpr int eva_gr2 = 3; // squared right chiral coupling of the parent +inline constexpr int eva_flpol = 4; // left-handed fraction of the parent +inline constexpr int eva_mv2 = 5; // vector mass^2 (photon: parent mass^2) +inline constexpr int eva_mu2min = 6; // floor of mu^2, before the (1-x) of ievo +inline constexpr int eva_xmin = 7; // densities vanish below (eva_xcut) +inline constexpr int eva_ebeam = 8; // parent energy +inline constexpr int eva_order = 9; // 0 LLA, 1 LP, 2 NLP (photon: 0) +inline constexpr int eva_evolution = 10; // 0: evolution in q^2, 1: in pt^2 +inline constexpr int eva_param_count = 11; +// a helicity outside -1, 0, 1 asks for the sum over the vector's helicities +inline constexpr int eva_helicity_sum = 2; + +// eva_fL_to_vp (with x the momentum fraction, mu2 the evolution scale squared) +template +KERNELSPEC F +eva_fl_to_vp(F gg2, F gl2, F mv2, F x, F mu2, F ebeam, int ievo, int order) { + const F four_pi_sq = 39.47841760435743; + F coup2 = gg2 * gl2 / four_pi_sq; + F split = (1. - x) / 2. / x; + F ev2 = (x * ebeam) * (x * ebeam); + F mv_o_ev = mv2 / ev2; + F mu_o2ev = mu2 / ev2 / 2.; + F mv_o_mu = mv2 / mu2; + F mu_o_mumv = 1. / (1. + mv_o_mu); + F mumv_o_mv = (mu2 / mv2) + 1.; + F xxlog = log(mumv_o_mv); + F xlp1 = 1. - x; + F xlp2 = xlp1; + F nlp1 = (2. - x) * mv_o_ev; + F nlp2 = nlp1 + (2. - x) * mu_o2ev; + F tmp; + if (order == 2) { + tmp = xxlog * (xlp1 + nlp1) - mu_o_mumv * (xlp2 + nlp2); + } else if (order == 1) { + tmp = xxlog * xlp1 - mu_o_mumv * xlp2; + } else { + xxlog = ievo == 0 ? log(mu2 / mv2) : log(mu2 / mv2) - log(1. - x); + tmp = xlp1 * xxlog; + } + return coup2 * split * tmp; +} + +// eva_fL_to_vm +template +KERNELSPEC F +eva_fl_to_vm(F gg2, F gl2, F mv2, F x, F mu2, F ebeam, int ievo, int order) { + const F four_pi_sq = 39.47841760435743; + F coup2 = gg2 * gl2 / four_pi_sq; + F split = 1. / 2. / x; + F ev2 = (x * ebeam) * (x * ebeam); + F mv_o_ev = mv2 / ev2; + F mu_o2ev = mu2 / ev2 / 2.; + F mv_o_mu = mv2 / mu2; + F mu_o_mumv = 1. / (1. + mv_o_mu); + F mumv_o_mv = (mu2 / mv2) + 1.; + F xxlog = log(mumv_o_mv); + F xlp1 = 1.; + F xlp2 = xlp1; + F nlp1 = (2. - x) * mv_o_ev; + F nlp2 = nlp1 + (2. - x) * mu_o2ev; + F tmp; + if (order == 2) { + tmp = xxlog * (xlp1 + nlp1) - mu_o_mumv * (xlp2 + nlp2); + } else if (order == 1) { + tmp = xxlog * xlp1 - mu_o_mumv * xlp2; + } else { + xxlog = ievo == 0 ? log(mu2 / mv2) : log(mu2 / mv2) - log(1. - x); + tmp = xlp1 * xxlog; + } + return coup2 * split * tmp; +} + +// eva_fL_to_v0. At NLP the helicity-flip term is subtracted as madevent does, +// outside of the coupling and splitting factor (its hflip already carry them). +template +KERNELSPEC F +eva_fl_to_v0(F gg2, F gl2, F mv2, F x, F mu2, F ebeam, int ievo, int order) { + const F four_pi_sq = 39.47841760435743; + F coup2 = gg2 * gl2 / four_pi_sq; + F split = (1. - x) / x; + F ev2 = (x * ebeam) * (x * ebeam); + F mv_o_ev = mv2 / ev2; + F mv_o_mu = mv2 / mu2; + F mu_o_mumv = 1. / (1. + mv_o_mu); + F tmp1, tmp2; + if (order == 2) { + F hflip = eva_fl_to_vm(gg2, gl2, mv2, x, mu2, ebeam, ievo, 1) + + eva_fl_to_vp(gg2, gl2, mv2, x, mu2, ebeam, ievo, 1); + tmp1 = mu_o_mumv; + tmp2 = 0.5 * mv_o_ev * hflip; + } else if (order == 1) { + tmp1 = mu_o_mumv; + tmp2 = 0.; + } else { + tmp1 = 1.; + tmp2 = 0.; + } + return coup2 * split * tmp1 - tmp2; +} + +// f(x) (not x f(x)) of helicity `helicity` (-1, 0, 1, or eva_helicity_sum) +// from the parameter row `p` (eva_get_pdf_by_PID with its checks). `p` is +// anything indexable by an int giving an F. +template +KERNELSPEC F eva_density_value(F x, F q, int helicity, const P& p) { + int kind = static_cast(p[eva_kind]); + if (kind == 0 || !(x >= 1e-8 && x <= 1. - 1e-8)) { + return 0.; + } + if (kind == 2 && helicity == 0) { + return 0.; // a photon has no longitudinal polarisation + } + if (helicity < -1 || helicity > 1) { + F sum = eva_density_value(x, q, -1, p) + + eva_density_value(x, q, 1, p); + if (kind == 1) { + sum = sum + eva_density_value(x, q, 0, p); + } + return sum; + } + if (x < static_cast(p[eva_xmin])) { + return 0.; + } + int ievo = static_cast(p[eva_evolution]); + int order = static_cast(p[eva_order]); + F mu2 = q * q; + F mu2min = p[eva_mu2min]; + if (ievo != 0) { + mu2min = (1. - x) * mu2min; + } + if (mu2 < mu2min) { + mu2 = mu2min; + } + F gg2 = p[eva_gg2], gl2 = p[eva_gl2], gr2 = p[eva_gr2]; + F fl = p[eva_flpol], mv2 = p[eva_mv2], ebeam = p[eva_ebeam]; + // eva_fX_to_vX: fLpol f_L + (1 - fLpol) f_R, with f_R > v_+- = f_L > v_-+ + if (helicity == 1) { + return fl * eva_fl_to_vp(gg2, gl2, mv2, x, mu2, ebeam, ievo, order) + + (1. - fl) * eva_fl_to_vm(gg2, gr2, mv2, x, mu2, ebeam, ievo, order); + } else if (helicity == -1) { + return fl * eva_fl_to_vm(gg2, gl2, mv2, x, mu2, ebeam, ievo, order) + + (1. - fl) * eva_fl_to_vp(gg2, gr2, mv2, x, mu2, ebeam, ievo, order); + } else { + return fl * eva_fl_to_v0(gg2, gl2, mv2, x, mu2, ebeam, ievo, order) + + (1. - fl) * eva_fl_to_v0(gg2, gr2, mv2, x, mu2, ebeam, ievo, order); + } +} + +// x f_helicity(x, q) of the configuration `config` (a row of `params`), zero +// for a configuration < 0 +template +KERNELSPEC void kernel_eva_density( + FIn x, + FIn q, + IIn helicity, + IIn config, + FIn params, + FOut pdf +) { + using F = FVal; + int cfg = static_cast(config); + if (cfg < 0 || cfg >= static_cast(params.size())) { + pdf = 0.; + return; + } + auto row = params[cfg]; + F x_val = x; + pdf = x_val * + eva_density_value(x_val, static_cast(q), static_cast(helicity), row); +} + +// The density of one incoming leg of an event, after its matrix element picked +// a helicity row: x n f_lambda(x, q), with lambda the leg's helicity in row +// `helicity` of the event's flavour `flavor`, n the leg's number of helicity +// states (the matrix element's averaging factor) and f the density of the beam +// the leg comes from (`mirror` = 1: the other one). A row out of range gives +// the helicity-summed density x sum_lambda f_lambda without n. +template +KERNELSPEC void kernel_eva_leg_density( + FIn x, + FIn q, + IIn flavor, + IIn helicity, + IIn mirror, + IIn row_offsets, + IIn row_counts, + IIn leg_helicities, + IIn configs, + FIn helicity_counts, + FIn params, + FOut pdf +) { + using F = FVal; + int flav = static_cast(flavor); + if (flav < 0 || flav >= static_cast(row_counts.size())) { + pdf = 0.; + return; + } + int cfg = static_cast(configs[2 * flav + (static_cast(mirror) != 0)]); + if (cfg < 0 || cfg >= static_cast(params.size())) { + pdf = 0.; + return; + } + auto row = params[cfg]; + int hel_row = static_cast(helicity); + F x_val = x; + F q_val = q; + if (hel_row < 0 || hel_row >= static_cast(row_counts[flav])) { + pdf = x_val * eva_density_value(x_val, q_val, eva_helicity_sum, row); + return; + } + int offset = static_cast(row_offsets[flav]); + int lambda = static_cast(leg_helicities[offset + hel_row]); + F count = helicity_counts[flav]; + pdf = x_val * count * eva_density_value(x_val, q_val, lambda, row); +} + +} // namespace kernels +} // namespace madspace diff --git a/madspace/src/kernels/kernels.hpp b/madspace/src/kernels/kernels.hpp index e06f45fbdb..48de7f65bc 100644 --- a/madspace/src/kernels/kernels.hpp +++ b/madspace/src/kernels/kernels.hpp @@ -3,6 +3,7 @@ #include "chili.hpp" #include "cuts.hpp" #include "discrete.hpp" +#include "eva.hpp" #include "invariants.hpp" #include "kinematics.hpp" #include "math.hpp" diff --git a/madspace/src/kernels/kinematics.hpp b/madspace/src/kernels/kinematics.hpp index 6e56bc8b8c..5a15b26e3d 100644 --- a/madspace/src/kernels/kinematics.hpp +++ b/madspace/src/kernels/kinematics.hpp @@ -635,6 +635,53 @@ KERNELSPEC void kernel_com_p_in(FIn e_cm, FOut p1, FOut p2) { p2[3] = -p_com; } +// The incoming momenta of an event on their mass shell, keeping their sum and +// directions; the ratio s_hat / sqrt(lambda(s_hat, m1^2, m2^2)) of the massive +// flux to the massless one, zero below threshold. madevent's genps.f has +// massive incoming particles so (mom2cx and its flux), the phase-space +// mappings build them massless. +template +KERNELSPEC void kernel_incoming_on_shell( + FIn p_ext, FIn masses, FOut p_out, FOut flux_ratio +) { + using F = FVal; + for (std::size_t i = 0; i < p_ext.size(); ++i) { + for (std::size_t j = 0; j < 4; ++j) { + p_out[i][j] = static_cast(p_ext[i][j]); + } + } + F m1 = masses[0], m2 = masses[1]; + F e_a = p_ext[0][0], z_a = p_ext[0][3]; + F e_b = p_ext[1][0], z_b = p_ext[1][3]; + F e_tot = e_a + e_b, z_tot = z_a + z_b; + F s = e_tot * e_tot - z_tot * z_tot; + F threshold = (m1 + m2) * (m1 + m2); + if (!(s > threshold) || !(e_tot > 0.)) { + flux_ratio = 0.; + return; + } + F sqrt_s = sqrt(s); + F lambda = (s - threshold) * (s - (m1 - m2) * (m1 - m2)); + F p_cm = sqrt(lambda) / (2. * sqrt_s); + F e1 = (s + m1 * m1 - m2 * m2) / (2. * sqrt_s); + F e2 = (s + m2 * m2 - m1 * m1) / (2. * sqrt_s); + // the boost from the rest frame of the pair to the frame of p_ext + F cosh_y = e_tot / sqrt_s, sinh_y = z_tot / sqrt_s; + // direction of the first incoming particle in the rest frame + F z_a_cm = cosh_y * z_a - sinh_y * e_a; + F sign = z_a_cm >= 0. ? 1. : -1.; + F z1 = sign * p_cm, z2 = -sign * p_cm; + p_out[0][0] = cosh_y * e1 + sinh_y * z1; + p_out[0][1] = 0.; + p_out[0][2] = 0.; + p_out[0][3] = cosh_y * z1 + sinh_y * e1; + p_out[1][0] = cosh_y * e2 + sinh_y * z2; + p_out[1][1] = 0.; + p_out[1][2] = 0.; + p_out[1][3] = cosh_y * z2 + sinh_y * e2; + flux_ratio = s / sqrt(lambda); +} + template KERNELSPEC void kernel_r_to_x1x2( FIn r, diff --git a/madspace/src/phasespace/cross_section.cpp b/madspace/src/phasespace/cross_section.cpp index 2cec34747e..b8d3c607d2 100644 --- a/madspace/src/phasespace/cross_section.cpp +++ b/madspace/src/phasespace/cross_section.cpp @@ -12,7 +12,9 @@ DifferentialCrossSection::DifferentialCrossSection( const std::variant& pdf2, bool input_momentum_fraction, bool decay, - bool return_matrix_element + bool return_matrix_element, + const std::optional& eva, + const nested_vector3& eva_helicities ) : FunctionGenerator( "DifferentialCrossSection", @@ -49,6 +51,11 @@ DifferentialCrossSection::DifferentialCrossSection( } arg_types.push_back("alpha_s", batch_float); } + if (eva) { + arg_types.push_back("fact_scale1", batch_float); + arg_types.push_back("fact_scale2", batch_float); + arg_types.push_back("mirror_index", batch_int); + } return arg_types; }(), [&] { @@ -100,6 +107,25 @@ DifferentialCrossSection::DifferentialCrossSection( }; init_pdf(pdf1, 0); init_pdf(pdf2, 1); + if (eva) { + if (decay || !input_momentum_fraction || + !std::holds_alternative(pdf1) || + !std::holds_alternative(pdf2) || + !std::holds_alternative(energy_scale)) { + throw std::invalid_argument( + "EVA needs a collision with input momentum fractions, CachedPdf " + "on both beams and a CachedScale" + ); + } + if (std::find( + outputs.begin(), outputs.end(), MatrixElement::helicity_index_out + ) == outputs.end()) { + throw std::invalid_argument( + "EVA needs a matrix element that returns its helicity index" + ); + } + _eva_tables = EvaLegTables(eva.value(), pid_options, eva_helicities); + } } NamedVector DifferentialCrossSection::build_function_impl( @@ -160,6 +186,9 @@ NamedVector DifferentialCrossSection::build_function_impl( : _running_coupling.value().build_function(fb, {scales.at(0)}).at(0) ); } + if (std::holds_alternative(_energy_scale)) { + ++arg_index; // alpha_s + } auto me_result = _matrix_element.build_function(fb, matrix_args); auto search = std::find( @@ -172,6 +201,33 @@ NamedVector DifferentialCrossSection::build_function_impl( } std::size_t me_index = search - _matrix_element.outputs().begin(); Value raw_matrix_element = me_result.at(me_index); + if (_eva_tables) { + // the densities of the helicities the matrix element picked + auto& tables = _eva_tables.value(); + auto& me_outputs = _matrix_element.outputs(); + std::size_t hel_index = + std::find( + me_outputs.begin(), me_outputs.end(), MatrixElement::helicity_index_out + ) - + me_outputs.begin(); + Value helicity = me_result.at(hel_index); + Value mirror = args.at(arg_index + 2); + for (std::size_t i = 0; i < 2; ++i) { + pdf_outputs.at(i) = fb.eva_leg_density( + x1x2.at(i), + args.at(arg_index + i), + pdf_flavor_id, + helicity, + mirror, + tables.row_offsets.at(i), + tables.row_counts.at(i), + tables.leg_helicities.at(i), + tables.configs.at(i), + tables.helicity_counts.at(i), + tables.params + ); + } + } if (_decay) { // dGamma = |M|^2 dPhi_n / (2 M), in GeV; no GeV^-2 -> pb conversion // since a width is not a cross section. diff --git a/madspace/src/phasespace/eva.cpp b/madspace/src/phasespace/eva.cpp new file mode 100644 index 0000000000..86309de921 --- /dev/null +++ b/madspace/src/phasespace/eva.cpp @@ -0,0 +1,214 @@ +#include "madspace/phasespace/eva.hpp" + +#include +#include +#include +#include +#include + +#include "../kernels/eva.hpp" + +using namespace madspace; + +namespace { + +// lepton masses of madevent's ElectroweakFlux.inc (PDG 2020) +constexpr double electron_mass = 0.5109989461e-3; +constexpr double muon_mass = 105.6583745e-3; + +bool is_photon(int pid) { return pid == 22 || pid == 7; } + +} // namespace + +EvaFlux::EvaFlux( + const std::array& beam_leptons, + const std::array& beam_energies, + double w_mass, + double z_mass, + double e2, + const std::array& left_fractions, + int order, + bool pt_evolution, + bool xcut +) : + _beam_leptons(beam_leptons), + _beam_energies(beam_energies), + _w_mass(w_mass), + _z_mass(z_mass), + _e2(e2), + _left_fractions(left_fractions), + _order(order), + _pt_evolution(pt_evolution), + _xcut(xcut) { + for (std::size_t beam = 0; beam < 2; ++beam) { + int lepton = std::abs(beam_leptons.at(beam)); + if (lepton != 11 && lepton != 13) { + throw std::invalid_argument(std::format( + "EVA needs electron or muon beams, not PDG id {} on beam {}", + beam_leptons.at(beam), + beam + 1 + )); + } + if (!(beam_energies.at(beam) > 0.)) { + throw std::invalid_argument("EVA needs positive beam energies"); + } + double fraction = left_fractions.at(beam); + if (!(fraction >= 0. && fraction <= 1.)) { + throw std::invalid_argument(std::format( + "EVA: left-handed fraction {} of beam {} is not in [0, 1]", + fraction, + beam + 1 + )); + } + } + if (order < 0 || order > 2) { + throw std::invalid_argument("EVA order must be 0 (LLA), 1 (LP) or 2 (NLP)"); + } + if (!(w_mass > 0. && z_mass > w_mass && e2 > 0.)) { + throw std::invalid_argument("EVA needs 0 < M_W < M_Z and e^2 > 0"); + } +} + +bool EvaFlux::has_density(int vector_pid, std::size_t beam) const { + int lepton = _beam_leptons.at(beam); + if (std::abs(vector_pid) == 24) { + // a W+ from a positive lepton (charge +1 - 0), a W- from a negative one + return (vector_pid > 0) == (lepton < 0); + } + return vector_pid == 23 || is_photon(vector_pid); +} + +std::vector EvaFlux::parameters(int vector_pid, std::size_t beam) const { + using namespace kernels; + if (std::abs(vector_pid) != 24 && vector_pid != 23 && !is_photon(vector_pid)) { + throw std::invalid_argument(std::format( + "EVA densities exist for W, Z and photons only, not for PDG id {}", + vector_pid + )); + } + std::vector row(parameter_count, 0.); + int lepton = _beam_leptons.at(beam); + double ebeam = _beam_energies.at(beam); + // ElectroweakFlux.inc: aEM, MW, MZ scheme + double mw2 = _w_mass * _w_mass, mz2 = _z_mass * _z_mass; + double cw2 = mw2 / mz2; + double sw2 = 1. - cw2; + double gw2 = _e2 / sw2; + double gz2 = gw2 / cw2; + double lepton_mass = std::abs(lepton) == 11 ? electron_mass : muon_mass; + double gg2, gl2, gr2, mv2, mu2min, xmin; + int order = _order; + if (!has_density(vector_pid, beam)) { + return row; // kind 0: no density + } + if (std::abs(vector_pid) == 24) { + gg2 = gw2 / 2.; + gl2 = 1.; + gr2 = 0.; + mv2 = mw2; + mu2min = mw2; + xmin = _xcut ? _w_mass / ebeam : 0.; + } else if (vector_pid == 23) { + double zle = -0.5 + sw2; // tLe - qe sw2 + double zre = sw2; // -qe sw2 + gg2 = gz2; + gl2 = zle * zle; + gr2 = zre * zre; + mv2 = mz2; + mu2min = mz2; + xmin = _xcut ? _z_mass / ebeam : 0.; + } else { + gg2 = _e2; // e^2 Q_e^2 + gl2 = 1.; + gr2 = 1.; + mv2 = lepton_mass * lepton_mass; + mu2min = mv2; + xmin = 0.; + order = 0; // m_photon = 0: always LLA + } + if (lepton < 0) { + std::swap(gl2, gr2); // an antilepton: parity inverted + } + row.at(eva_kind) = is_photon(vector_pid) ? 2. : 1.; + row.at(eva_gg2) = gg2; + row.at(eva_gl2) = gl2; + row.at(eva_gr2) = gr2; + row.at(eva_flpol) = _left_fractions.at(beam); + row.at(eva_mv2) = mv2; + row.at(eva_mu2min) = mu2min; + row.at(eva_xmin) = xmin; + row.at(eva_ebeam) = ebeam; + row.at(eva_order) = order; + row.at(eva_evolution) = _pt_evolution ? 1. : 0.; + return row; +} + +double EvaFlux::density( + int vector_pid, std::size_t beam, int helicity, double x, double q +) const { + auto row = parameters(vector_pid, beam); + return kernels::eva_density_value(x, q, helicity, row); +} + +EvaLegTables::EvaLegTables( + const EvaFlux& flux, + const nested_vector2& pid_options, + const nested_vector3& helicities +) { + if (helicities.size() != pid_options.size()) { + throw std::invalid_argument(std::format( + "EVA: {} helicity tables for {} flavours", + helicities.size(), + pid_options.size() + )); + } + std::vector> config_keys; + auto config_index = [&](int pid, std::size_t beam) -> me_int_t { + if (!flux.has_density(pid, beam)) { + return -1; + } + std::pair key{pid, beam}; + auto found = std::find(config_keys.begin(), config_keys.end(), key); + if (found != config_keys.end()) { + return static_cast(found - config_keys.begin()); + } + config_keys.push_back(key); + params.push_back(flux.parameters(pid, beam)); + return static_cast(config_keys.size() - 1); + }; + for (std::size_t flavor = 0; flavor < pid_options.size(); ++flavor) { + auto& option = pid_options.at(flavor); + auto& rows = helicities.at(flavor); + if (option.size() < 2) { + throw std::invalid_argument("EVA needs two incoming particles"); + } + if (rows.empty()) { + throw std::invalid_argument("EVA: empty helicity table"); + } + for (std::size_t leg = 0; leg < 2; ++leg) { + int pid = option.at(leg); + // throws for a particle that is not a vector boson + flux.parameters(pid, 0); + row_offsets.at(leg).push_back( + static_cast(leg_helicities.at(leg).size()) + ); + row_counts.at(leg).push_back(static_cast(rows.size())); + std::set states; + for (auto& row : rows) { + if (row.size() < 2) { + throw std::invalid_argument("EVA: helicity row too short"); + } + leg_helicities.at(leg).push_back(row.at(leg)); + states.insert(row.at(leg)); + } + helicity_counts.at(leg).push_back(static_cast(states.size())); + for (std::size_t mirror = 0; mirror < 2; ++mirror) { + configs.at(leg).push_back(config_index(pid, leg ^ mirror)); + } + } + } + if (params.empty()) { + // the kernels need a table even when no combination has a density + params.push_back(std::vector(EvaFlux::parameter_count, 0.)); + } +} diff --git a/madspace/src/phasespace/integrand.cpp b/madspace/src/phasespace/integrand.cpp index c3e19451e0..de99b20f6d 100644 --- a/madspace/src/phasespace/integrand.cpp +++ b/madspace/src/phasespace/integrand.cpp @@ -358,6 +358,18 @@ Integrand::Integrand( own_grid ? "" : pdf2_prefix ); } + } else if (auto eva = std::get_if(&pdf_grid)) { + if (pdf_grid2) { + throw std::invalid_argument( + "pdf_grid2 cannot be combined with EVA beams" + ); + } + int beam = static_cast(i); + _eva = true; + _pdfs.at(i) = PartonDensity(*eva, pid_vec, beam); + // the two lepton beams differ (charge, polarisation, energy), + // so mirrored events need the other beam's density + _pdfs_swapped.at(i) = PartonDensity(*eva, pid_vec, 1 - beam); } else { if (pdf_grid2) { throw std::invalid_argument( @@ -373,6 +385,21 @@ Integrand::Integrand( } } } + for (auto& xs : diff_xs) { + if (xs.eva() != _eva) { + throw std::invalid_argument( + "EVA beams need EVA differential cross sections, and vice versa" + ); + } + } + if (_eva && energy_scale && energy_scale->is_mlm()) { + throw std::invalid_argument("EVA beams cannot be combined with MLM merging"); + } + if (_eva && !(diff_xs.at(0).has_pdf(0) && diff_xs.at(0).has_pdf(1))) { + throw std::invalid_argument( + "EVA differential cross sections take both beam densities (CachedPdf)" + ); + } if (parton_density_output) { if (std::holds_alternative(pdf_grid) || !energy_scale || !diff_xs.at(0).has_pdf(0) || !diff_xs.at(0).has_pdf(1)) { @@ -658,7 +685,7 @@ NamedVector Integrand::compute_channel_part_ret_types() const { ret.push_back("x1_acc", acc_float); ret.push_back("x2_acc", acc_float); ret.push_back("flavor_id", acc_int); - if (_mapping_chan_weights && _mapping.mirror_beams()) { + if ((_mapping_chan_weights || _eva) && _mapping.mirror_beams()) { ret.push_back("mirror_index_acc", acc_int); } ret.push_back("weight_after_cuts", acc_float); @@ -854,6 +881,16 @@ NamedVector Integrand::build_channel_part( ); weights_before_cuts.push_back(mapping_result["det"]); Value momenta = mapping_result["momenta"]; + // The mapping hands out massless incoming momenta. Massive ones (EVA's W + // and Z, monochromatic W or muon beams, massive partons) go on their mass + // shell, with the same sum, and the flux 1/(2 sqrt(lambda)) replaces the + // massless 1/(2 s_hat) of diff_cross_section, as in madevent. + if (auto& masses = _mapping.incoming_masses(); + masses.size() == 2 && (masses.at(0) > 0. || masses.at(1) > 0.)) { + auto on_shell = fb.incoming_on_shell(momenta, masses); + momenta = on_shell.at(0); + weights_before_cuts.push_back(on_shell.at(1)); + } Value x0 = mapping_result["x1"]; Value x1 = mapping_result["x2"]; // A dressed-lepton mapping also hands back 1-x. It has to: it samples x @@ -1146,7 +1183,7 @@ NamedVector Integrand::build_channel_part( out.push_back("x1_acc", x_acc.at(0)); out.push_back("x2_acc", x_acc.at(1)); out.push_back("flavor_id", flavor_id); - if (_mapping_chan_weights && _mapping.mirror_beams()) { + if ((_mapping_chan_weights || _eva) && _mapping.mirror_beams()) { out.push_back("mirror_index_acc", fb.batch_gather(indices_acc, mirror_index)); } out.push_back("weight_after_cuts", weight_after_cuts); @@ -1539,6 +1576,16 @@ NamedVector Integrand::build_common_part( } } xs_args.push_back(alpha); + if (_diff_xs.at(0).eva()) { + // the densities of the helicity the matrix element picks + xs_args.push_back(fact_scales_acc.at(0)); + xs_args.push_back(fact_scales_acc.at(1)); + xs_args.push_back( + _mapping.mirror_beams() + ? args.at("mirror_index_acc") + : fb.full({static_cast(0), fb.batch_size({momenta_acc})}) + ); + } return xs_args; }; ValueVec xs_args = make_xs_args(pdfs_acc, alpha_qcd_acc); diff --git a/madspace/src/phasespace/pdf.cpp b/madspace/src/phasespace/pdf.cpp index 66a575f630..ece78430ab 100644 --- a/madspace/src/phasespace/pdf.cpp +++ b/madspace/src/phasespace/pdf.cpp @@ -408,11 +408,56 @@ PartonDensity::PartonDensity( _beam_index(beam_index), _dynamic_pid(dynamic_pid) {} +PartonDensity::PartonDensity( + const EvaFlux& eva, + const std::vector& pids, + int beam_index, + bool dynamic_pid +) : + FunctionGenerator( + "PartonDensity", + [&] { + NamedVector arg_types{{"x", batch_float}, {"q", batch_float}}; + if (dynamic_pid) { + arg_types.push_back("flavor_index", batch_int); + } + return arg_types; + }(), + {{"pdf", dynamic_pid ? batch_float : batch_float_array(pids.size())}} + ), + _pids(pids.begin(), pids.end()), + _eva(true), + _beam_index(beam_index), + _dynamic_pid(dynamic_pid) { + if (beam_index != 0 && beam_index != 1) { + throw std::invalid_argument("EVA: the beam index must be 0 or 1"); + } + for (int pid : pids) { + _eva_params.push_back(eva.parameters(pid, beam_index)); + } + if (_eva_params.empty()) { + _eva_params.push_back(std::vector(EvaFlux::parameter_count, 0.)); + } +} + NamedVector PartonDensity::build_function_impl( FunctionBuilder& fb, const NamedVector& args ) const { auto x = args.at(0); auto q = args.at(1); + if (_eva) { + auto batch_size = fb.batch_size({x}); + auto helicity = fb.full({static_cast(EvaFlux::helicity_sum), batch_size}); + if (_dynamic_pid) { + return {{"pdf", fb.eva_density(x, q, helicity, args.at(2), _eva_params)}}; + } + ValueVec pdfs; + for (std::size_t i = 0; i < _pids.size(); ++i) { + auto config = fb.full({static_cast(i), batch_size}); + pdfs.push_back(fb.eva_density(x, q, helicity, config, _eva_params)); + } + return {{"pdf", fb.stack(pdfs)}}; + } if (_custom_pdf) { MatrixElement function( _custom_pdf->function_index, diff --git a/madspace/src/python/madspace.cpp b/madspace/src/python/madspace.cpp index 72507dc9d4..b47933a474 100644 --- a/madspace/src/python/madspace.cpp +++ b/madspace/src/python/madspace.cpp @@ -2647,6 +2647,67 @@ PYBIND11_MODULE(_madspace_py, m) { pydoc::doc("PdfGrid::initialize_globals") ); + py::classh(m, "EvaFlux", pydoc::doc("EvaFlux")) + .def( + py::init< + const std::array&, + const std::array&, + double, + double, + double, + const std::array&, + int, + bool, + bool>(), + py::arg("beam_leptons"), + py::arg("beam_energies"), + py::arg("w_mass"), + py::arg("z_mass"), + py::arg("e2"), + py::arg("left_fractions") = std::array{0.5, 0.5}, + py::arg("order") = 0, + py::arg("pt_evolution") = false, + py::arg("xcut") = true, + pydoc::doc("EvaFlux::EvaFlux") + ) + .def_readonly_static("helicity_sum", &EvaFlux::helicity_sum) + .def( + "has_density", + &EvaFlux::has_density, + py::arg("vector_pid"), + py::arg("beam"), + pydoc::doc("EvaFlux::has_density") + ) + .def( + "parameters", + &EvaFlux::parameters, + py::arg("vector_pid"), + py::arg("beam"), + pydoc::doc("EvaFlux::parameters") + ) + .def( + "density", + &EvaFlux::density, + py::arg("vector_pid"), + py::arg("beam"), + py::arg("helicity"), + py::arg("x"), + py::arg("q"), + pydoc::doc("EvaFlux::density") + ) + .def("beam_leptons", &EvaFlux::beam_leptons, pydoc::doc("EvaFlux::beam_leptons")) + .def( + "beam_energies", &EvaFlux::beam_energies, pydoc::doc("EvaFlux::beam_energies") + ) + .def( + "left_fractions", + &EvaFlux::left_fractions, + pydoc::doc("EvaFlux::left_fractions") + ) + .def("order", &EvaFlux::order, pydoc::doc("EvaFlux::order")) + .def("pt_evolution", &EvaFlux::pt_evolution, pydoc::doc("EvaFlux::pt_evolution")) + .def("xcut", &EvaFlux::xcut, pydoc::doc("EvaFlux::xcut")); + py::classh( m, "PartonDensity", pydoc::doc("PartonDensity") ) @@ -2669,6 +2730,14 @@ PYBIND11_MODULE(_madspace_py, m) { py::arg("beam_index"), py::arg("dynamic_pid") = false, pydoc::doc("PartonDensity::PartonDensity#2") + ) + .def( + py::init&, int, bool>(), + py::arg("eva"), + py::arg("pids"), + py::arg("beam_index"), + py::arg("dynamic_pid") = false, + pydoc::doc("PartonDensity::PartonDensity#3") ); py::classh( @@ -2875,7 +2944,9 @@ PYBIND11_MODULE(_madspace_py, m) { DifferentialCrossSection::CachedPdf>&, bool, bool, - bool>(), + bool, + const std::optional&, + const nested_vector3&>(), py::arg("matrix_element"), py::arg("cm_energy"), py::arg("running_coupling"), @@ -2886,8 +2957,11 @@ PYBIND11_MODULE(_madspace_py, m) { py::arg("input_momentum_fraction") = true, py::arg("decay") = false, py::arg("return_matrix_element") = false, + py::arg("eva") = std::nullopt, + py::arg("eva_helicities") = nested_vector3{}, pydoc::doc("DifferentialCrossSection::DifferentialCrossSection") ) + .def("eva", &DifferentialCrossSection::eva, pydoc::doc("DifferentialCrossSection::eva")) .def( "pid_options", &DifferentialCrossSection::pid_options, diff --git a/tests/unit_tests/interface/test_auto_width_engine.py b/tests/unit_tests/interface/test_auto_width_engine.py index 21a50d827f..d2eacf8aca 100644 --- a/tests/unit_tests/interface/test_auto_width_engine.py +++ b/tests/unit_tests/interface/test_auto_width_engine.py @@ -476,6 +476,8 @@ def init_beam(self, process, beam): process.is_decay = False process.custom_functions = {} process.contexts = [] + # _massive_beams reads the incoming masses of the subprocesses + process.subprocess_data = [] # leptonic beams must not even look for the PDF set process.ensure_pdf_set = mock.Mock( side_effect=AssertionError('PDF set resolved for leptonic beams')) diff --git a/tests/unit_tests/various/test_eva_mg7.py b/tests/unit_tests/various/test_eva_mg7.py new file mode 100644 index 0000000000..a5bd22adba --- /dev/null +++ b/tests/unit_tests/various/test_eva_mg7.py @@ -0,0 +1,474 @@ +################################################################################ +# +# Copyright (c) 2009 The MadGraph5_aMC@NLO Development team and Contributors +# +# This file is a part of the MadGraph5_aMC@NLO project, an application which +# automatically generates Feynman diagrams and matrix elements for arbitrary +# high-energy processes in the Standard Model and beyond. +# +# It is subject to the MadGraph5_aMC@NLO license which should accompany this +# distribution. +# +# For more information, visit madgraph.phys.ucl.ac.be and amcatnlo.web.cern.ch +# +################################################################################ +"""The Effective Vector boson Approximation (pdlabel eva) in mg7/madspace. + + * madspace's EvaFlux (src/kernels/eva.hpp) is a port of madevent's + ElectroweakFlux.f + ElectroweakFluxDriver.f: compiled together with a + driver, the Fortran is the reference, to 1e-12, over the vector bosons, + beam leptons, helicities, polarisations, orders, evolution variables, the + x cut and scales below the floor. + * The compute-graph kernel (PartonDensity built from an EvaFlux) gives the + helicity sum of the same densities. + * The run card: the madevent settings translate into [beam] keys, and a + W/Z-initiated process gets EVA beams by default. +""" +import itertools +import math +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +_file_path = os.path.dirname(os.path.realpath(__file__)) +_root = os.path.abspath(os.path.join(_file_path, '..', '..', '..')) +sys.path.insert(0, _root) + +import madgraph.various.misc as misc +import madgraph.various.banner as banner_mod + +pjoin = os.path.join + +try: + import numpy as np +except ImportError: + np = None + +# the electroweak inputs of the sm model (restrict_default): MZ, aEWM1 = 132.507, +# Gf = 1.16639e-5 give MW and ee +MZ = 91.188 +AEWM1 = 132.507 +GF = 1.16639e-5 +EE = math.sqrt(4 * math.pi / AEWM1) +MW = math.sqrt(MZ ** 2 / 2 + math.sqrt( + MZ ** 4 / 4 - (math.pi / AEWM1 * MZ ** 2) / (GF * math.sqrt(2)))) + + +def _madspace(): + """madspace from madspace/install, None without that build (see + test_eepdf_lhagrid._madspace).""" + install = os.path.join(_root, 'madspace', 'install') + if not os.path.isdir(install): + return None + saved = list(sys.path) + sys.path.insert(0, install) + try: + import madspace + except ImportError: + return None + finally: + sys.path[:] = saved + origin = getattr(madspace, '__file__', None) or '' + if os.path.realpath(install) not in os.path.realpath(origin): + return None + if not hasattr(madspace, 'EvaFlux'): + return None + return madspace + + +class TestEvaFortranReference(unittest.TestCase): + """EvaFlux.density against eva_get_pdf_by_PID of the compiled Fortran.""" + + driver = """ + program eva_driver + implicit none + integer vpid, fpid, vpol, ievo, order, xcut, n, i + double precision flpol, x, q, ebeam, mu2, pdf + double precision eva_get_pdf_by_PID + double precision gal(2) + common/eva_test_gal/gal + integer ievo_eva, evaorder, eva_xcut + common/to_eva/ievo_eva, evaorder, eva_xcut + read(*,*) gal(1) + gal(2) = gal(1) + read(*,*) n + do i = 1, n + read(*,*) vpid, fpid, vpol, flpol, x, q, ebeam, ievo, order, xcut + ievo_eva = ievo + evaorder = order + eva_xcut = xcut + mu2 = q*q + pdf = eva_get_pdf_by_PID(vpid, fpid, vpol, flpol, x, mu2, ebeam) + write(*,'(A,ES26.17E3)') 'RES ', pdf + enddo + end +""" + + @classmethod + def setUpClass(cls): + cls.ms = _madspace() + if cls.ms is None: + raise unittest.SkipTest('madspace build with EvaFlux required') + cls.fc = misc.which('gfortran') + if not cls.fc: + raise unittest.SkipTest('gfortran not available') + cls.tmpdir = tempfile.mkdtemp(prefix='eva_fortran') + pdf_dir = pjoin(_root, 'Template', 'LO', 'Source', 'PDF') + for name in ('ElectroweakFlux.f', 'ElectroweakFluxDriver.f'): + shutil.copy(pjoin(pdf_dir, name), cls.tmpdir) + # the include madevent writes at output (export_v4 create_ewa), with + # the masses as numbers and gal(1) = e from a common block instead of + # the model's coupl.inc + with open(pjoin(_root, 'madgraph', 'iolibs', 'template_files', + 'madevent_electroweakFlux.inc')) as fsock: + inc = fsock.read() % {'MW': '%.17gd0' % MW, 'MZ': '%.17gd0' % MZ} + inc = inc.replace("\tinclude '../vector.inc' ! defines VECSIZE_MEMMAX\n", '') + inc = inc.replace( + "\tinclude '../MODEL/coupl.inc' ! needs VECSIZE_MEMMAX (defined in vector.inc)\n", + "\tdouble precision gal(2)\n\tcommon/eva_test_gal/gal\n") + assert 'coupl.inc' not in inc + with open(pjoin(cls.tmpdir, 'ElectroweakFlux.inc'), 'w') as fsock: + fsock.write(inc) + with open(pjoin(cls.tmpdir, 'eva_driver.f'), 'w') as fsock: + fsock.write(cls.driver) + out = subprocess.run( + [cls.fc, '-O0', '-ffixed-line-length-132', '-o', 'eva_driver', + 'eva_driver.f', 'ElectroweakFlux.f', 'ElectroweakFluxDriver.f'], + cwd=cls.tmpdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True) + if out.returncode: + raise RuntimeError('compiling the EVA driver failed:\n' + out.stdout) + + @classmethod + def tearDownClass(cls): + if getattr(cls, 'tmpdir', None): + shutil.rmtree(cls.tmpdir, ignore_errors=True) + + def fortran(self, points): + """eva_get_pdf_by_PID at each point (vpid, fpid, vpol, flpol, x, q, + ebeam, ievo, order, xcut).""" + lines = ['%.17g' % EE, str(len(points))] + for vpid, fpid, vpol, flpol, x, q, ebeam, ievo, order, xcut in points: + lines.append('%d %d %d %.17g %.17g %.17g %.17g %d %d %d' % ( + vpid, fpid, vpol, flpol, x, q, ebeam, ievo, order, xcut)) + out = subprocess.run([pjoin(self.tmpdir, 'eva_driver')], + input='\n'.join(lines) + '\n', cwd=self.tmpdir, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True) + self.assertEqual(out.returncode, 0, out.stdout[-2000:]) + values = [float(line.split()[1]) for line in out.stdout.splitlines() + if line.startswith('RES ')] + self.assertEqual(len(values), len(points)) + return values + + def test_densities_match_fortran(self): + ms = self.ms + ebeam = 5000. + # x: small, around M_V / E_beam (the x cut), central, near 1; + # q: below the floors (10 GeV < M_W), around them, high + xs = [2e-4, 0.0159, 0.0185, 0.05, 0.3, 0.71, 0.999] + qs = [0.05, 10., 85., 91.188, 500., 4000.] + vectors = [24, -24, 23, 22] + leptons = [11, -11, 13, -13] + points, mine = [], [] + for vpid, lepton, flpol, order, ievo, xcut in itertools.product( + vectors, leptons, (0., 0.5, 0.9, 1.), (0, 1, 2), (0, 1), (0, 1)): + flux = ms.EvaFlux([lepton, lepton], [ebeam, ebeam], MW, MZ, EE ** 2, + [flpol, flpol], order, bool(ievo), bool(xcut)) + if not flux.has_density(vpid, 0): + # madevent stops (stop 24) where mg7 has no density + self.assertEqual(flux.density(vpid, 0, 1, 0.3, 100.), 0.) + continue + pols = (-1, 1) if vpid == 22 else (-1, 0, 1) + for vpol, x, q in itertools.product(pols, xs, qs): + # madevent's photon is pdg 7 + points.append((7 if vpid == 22 else vpid, lepton, vpol, flpol, + x, q, ebeam, ievo, order, xcut)) + mine.append(flux.density(vpid, 0, vpol, x, q)) + ref = self.fortran(points) + self.assertGreater(len(points), 10000) + worst = 0. + for point, a, b in zip(points, mine, ref): + scale = max(abs(b), 1e-300) + if b == 0.: + self.assertEqual(a, 0., point) + continue + rel = abs(a - b) / scale + worst = max(worst, rel) + self.assertLess(rel, 1e-12, '%s: %r vs %r' % (point, a, b)) + # the densities do vanish below the x cut and are nonzero elsewhere + self.assertTrue(any(v == 0. for v in ref)) + self.assertTrue(any(v != 0. for v in ref)) + + def test_charge_violating_w_has_no_density(self): + ms = self.ms + flux = ms.EvaFlux([-11, 13], [7500., 5000.], MW, MZ, EE ** 2) + self.assertTrue(flux.has_density(24, 0)) # W+ from e+ + self.assertFalse(flux.has_density(-24, 0)) # W- from e+ + self.assertTrue(flux.has_density(-24, 1)) # W- from mu- + self.assertFalse(flux.has_density(24, 1)) # W+ from mu- + self.assertTrue(flux.has_density(23, 1)) + self.assertTrue(flux.has_density(22, 0)) + for hel in (-1, 0, 1, ms.EvaFlux.helicity_sum): + self.assertEqual(flux.density(-24, 0, hel, 0.3, 100.), 0.) + with self.assertRaises(Exception): + flux.parameters(21, 0) + + +@unittest.skipIf(np is None, 'numpy required') +class TestEvaKernel(unittest.TestCase): + """The compute-graph kernel against the host densities.""" + + def test_parton_density_is_helicity_sum(self): + ms = _madspace() + if ms is None: + self.skipTest('madspace build with EvaFlux required') + flux = ms.EvaFlux([-13, 13], [5000., 5000.], MW, MZ, EE ** 2, + [0.9, 0.1], 2, True, True) + pids = [24, -24, 23, 22] + rng = np.random.default_rng(3) + n = 500 + x = 10 ** rng.uniform(-4, 0, n) * (1 - 1e-6) + q = 10 ** rng.uniform(0, 3.5, n) + for beam in (0, 1): + got = np.asarray(ms.PartonDensity(flux, pids, beam, False)(x, q)) + self.assertEqual(got.shape, (n, len(pids))) + for j, pid in enumerate(pids): + ref = np.array([ + xi * flux.density(pid, beam, ms.EvaFlux.helicity_sum, xi, qi) + for xi, qi in zip(x, q)]) + np.testing.assert_allclose(got[:, j], ref, rtol=1e-13, atol=0) + # a charge-violating W is zero, an allowed one is not + wrong = 1 if beam == 0 else 0 + self.assertTrue(np.all(got[:, wrong] == 0.)) + self.assertTrue(np.any(got[:, 1 - wrong] > 0.)) + # one flavour per event + index = rng.integers(0, len(pids), n).astype(np.int32) + dyn = np.asarray(ms.PartonDensity(flux, pids, beam, True)(x, q, index)) + np.testing.assert_allclose(dyn, got[np.arange(n), index], rtol=1e-15) + + +class TestEvaRunCard(unittest.TestCase): + """The [beam] EVA keys of the mg7 run card and the madevent translation.""" + + @staticmethod + def proc_def(*initials): + class PC(dict): + def __init__(self): + super().__init__(ninitial=2, loop_induced=False, colored_pdgs=[]) + + procs = [] + for initial in initials: + legs = [{'state': False, 'id': i} for i in initial] + legs += [{'state': True, 'id': 6}, {'state': True, 'id': -6}] + procs.append({'legs': legs}) + return PC(), [procs] + + def test_default_card_of_a_w_w_process_has_eva_beams(self): + """w+ w- > t t~ used to run silently with monochromatic W beams; the + default is now madevent's: e+ e- at 2 x 15 TeV, pdlabel eva, fixed + mu_F""" + charac, proc_def = self.proc_def([24, -24]) + card = banner_mod.RunCardMG7() + card.create_default_for_process(charac, '', proc_def) + beam = card['beam'] + self.assertIs(beam['eva'], True) + self.assertIs(beam['leptonic'], True) + self.assertEqual((beam['lepton1'], beam['lepton2']), (-11, 11)) + self.assertEqual((beam['ebeam1'], beam['ebeam2']), (15000., 15000.)) + self.assertIs(beam['fixed_fact_scale'], True) + card.check_validity() + # the EVA settings are written out + import io + out = io.StringIO() + card.write(out) + self.assertIn('eva = true', out.getvalue()) + self.assertIn('eva_order = 0', out.getvalue()) + # madevent's rule: a W or Z on each beam, photons allowed next to them + for initials, eva in ((([23, 23],), True), (([22, 24], [24, 22]), True), + (([22, 22],), False), (([12, -12],), False), + (([24, 11],), False)): + charac, proc_def = self.proc_def(*initials) + card = banner_mod.RunCardMG7() + card.create_default_for_process(charac, '', proc_def) + self.assertIs(card['beam']['eva'], eva, initials) + + def test_set_madevent_beam_settings(self): + card = banner_mod.RunCardMG7() + card.set_lo_beam_param('lpp1', '-4') + card.set_lo_beam_param('lpp2', '4') + self.assertEqual((card['beam']['lepton1'], card['beam']['lepton2']), (-13, 13)) + self.assertIs(card['beam']['leptonic'], True) + self.assertIs(card['beam']['eva'], False) + card.set_lo_beam_param('pdlabel', 'eva') + self.assertIs(card['beam']['eva'], True) + card.set_lo_beam_param('polbeam1', '-80') + card.set_lo_beam_param('polbeam2', '30') + self.assertEqual(card['beam']['polarization1'], -80.) + self.assertEqual(card['beam']['polarization2'], 30.) + card.set_lo_beam_param('evaorder', '2') + card.set_lo_beam_param('ievo_eva', '1') + card.set_lo_beam_param('eva_xcut', '0') + self.assertEqual(card['beam']['eva_order'], 2) + self.assertEqual(card['beam']['eva_evolution'], 'pt') + self.assertIs(card['beam']['eva_xcut'], False) + card.check_validity() + for name, value in (('evaorder', '3'), ('ievo_eva', '2'), + ('polbeam1', '120'), ('eva_xcut', 'x')): + with self.assertRaises(banner_mod.InvalidRunCard): + card.set_lo_beam_param(name, value) + # another label switches EVA off, with its polarisations + card.set_lo_beam_param('pdlabel', 'none') + self.assertIs(card['beam']['eva'], False) + self.assertEqual(card['beam']['polarization1'], 0.) + self.assertEqual(card['beam']['polarization2'], 0.) + card.check_validity() + # a polarisation without EVA is refused, until EVA is set (in either + # order: the card is checked once the settings are done) + card.set_lo_beam_param('polbeam1', '-80') + with self.assertRaises(banner_mod.InvalidRunCard): + card.check_validity() + card.set_lo_beam_param('pdlabel', 'eva') + card.check_validity() + + def test_settings_that_switch_eva_off(self): + """pdlabel lhapdf / none / a PDF label, lpp 0 / 1 switch EVA off and + say so; the card stays valid; lpp 3/4 and lhaid keep EVA.""" + def eva_card(): + card = banner_mod.RunCardMG7() + card.set_lo_beam_param('lpp1', '-3') + card.set_lo_beam_param('lpp2', '3') + card.set_lo_beam_param('pdlabel', 'eva') + card.set_lo_beam_param('polbeam1', '-80') + return card + + for name, value, leptonic in ( + ('pdlabel', 'lhapdf', True), ('pdlabel', 'none', True), + ('pdlabel', 'nn23lo1', True), ('lpp', '0', True), + ('lpp', '1', False)): + card = eva_card() + with self.assertLogs('madevent.cards', level='INFO') as logs: + done = card.set_lo_beam_param(name, value) + self.assertIn('beam.eva = False', done, (name, value)) + self.assertIn('beam.polarization1 = 0', done, (name, value)) + self.assertNotIn('unchanged', done) + self.assertIs(card['beam']['eva'], False, (name, value)) + self.assertIs(card['beam']['leptonic'], leptonic, (name, value)) + self.assertEqual(card['beam']['polarization1'], 0.) + # still-leptonic beams are no longer EVA: said as a warning + warned = any(r.levelname == 'WARNING' and 'monochromatic' in r.getMessage() + for r in logs.records) + self.assertIs(warned, leptonic, (name, value)) + card.check_validity() + for name, value in (('lpp1', '-4'), ('lpp', '3')): + card = eva_card() + card.set_lo_beam_param(name, value) + self.assertIs(card['beam']['eva'], True, (name, value)) + self.assertEqual(card['beam']['polarization1'], -80.) + # without EVA, pdlabel lhapdf still changes nothing + card = banner_mod.RunCardMG7() + self.assertIn('unchanged', card.set_lo_beam_param('pdlabel', 'lhapdf')) + + def test_invalid_eva_cards(self): + card = banner_mod.RunCardMG7() + card.set('beam.eva', True) + card.set('beam.leptonic', False) + with self.assertRaises(banner_mod.InvalidRunCard): + card.check_validity() # EVA needs lepton beams + card.set('beam.leptonic', True) + card.check_validity() + card.set('beam.lepton_density', 'isronlyll') + with self.assertRaises(banner_mod.InvalidRunCard): + card.check_validity() + card.set('beam.lepton_density', '') + card.set('beam.dynamical_scale_choice', 'mlm') + with self.assertRaises(banner_mod.InvalidRunCard): + card.check_validity() + + def test_from_lo_card(self): + lo = banner_mod.RunCardLO() + for name, value in (('lpp1', -4), ('lpp2', 4), ('ebeam1', 5000.), + ('ebeam2', 5000.), ('pdlabel', 'eva'), + ('polbeam1', -80.), ('evaorder', 2), + ('ievo_eva', 1), ('eva_xcut', 0), + ('fixed_fac_scale', True)): + lo.set(name, value, user=True) + mg7, dropped = banner_mod.RunCardMG7.from_LO(lo, warn=False) + beam = mg7['beam'] + self.assertIs(beam['eva'], True) + self.assertIs(beam['leptonic'], True) + self.assertEqual((beam['lepton1'], beam['lepton2']), (-13, 13)) + self.assertEqual(beam['polarization1'], -80.) + self.assertEqual(beam['eva_order'], 2) + self.assertEqual(beam['eva_evolution'], 'pt') + self.assertIs(beam['eva_xcut'], False) + self.assertFalse([d for d in dropped if 'eva' in d or 'polbeam' in d + or 'lpp' in d or 'pdlabel' in d], dropped) + # EVA on one beam only has no mg7 equivalent: reported + lo = banner_mod.RunCardLO() + for name, value in (('lpp1', -3), ('lpp2', 3), ('pdlabel1', 'eva'), + ('pdlabel2', 'none')): + lo.set(name, value, user=True) + mg7, dropped = banner_mod.RunCardMG7.from_LO(lo, warn=False) + self.assertIs(mg7['beam']['eva'], False) + self.assertTrue(any('EVA' in d for d in dropped), dropped) + + + +class TestEvaElectroweakInputs(unittest.TestCase): + """MadgraphProcess._eva_ew_inputs: M_W, M_Z and e^2 from the library, + else from the param card; only a missing name or entry falls back.""" + + unknown = 'Error in call to matrix element API x.so: ' \ + 'unknown or non-settable parameter' + + class Api: + def __init__(self, values, error): + self.values, self.error = values, error + + def supports_get_parameter(self): + return True + + def get_parameter(self, name): + if name in self.values: + return self.values[name], 0. + raise RuntimeError(self.error) + + class Card: + def __init__(self, values): + self.values = values + + def get_value(self, block, pid): + # as ParamCard.get_value without a default + return self.values[(block, pid)] + + def ew_inputs(self, api, card): + from madgraph.mg7.madgraph_process import MadgraphProcess + process = object.__new__(MadgraphProcess) + process.param_card = self.Card(card) + return process._eva_ew_inputs(api) + + def test_library_then_param_card(self): + card = {('mass', 24): 80.0, ('mass', 23): 91.0, ('sminputs', 1): 128.0} + # the library has M_W only: M_Z and alpha from the card + mw, mz, e2 = self.ew_inputs( + self.Api({'mdl_MW': 79.5}, self.unknown), card) + self.assertEqual((mw, mz), (79.5, 91.0)) + self.assertAlmostEqual(e2, 4 * math.pi / 128.0) + # no library: the card + self.assertEqual(self.ew_inputs(None, card)[:2], (80.0, 91.0)) + + def test_real_errors_are_not_hidden(self): + card = {('mass', 24): 80.0, ('mass', 23): 91.0, ('sminputs', 1): 128.0} + with self.assertRaisesRegex(RuntimeError, 'unspecified error'): + self.ew_inputs(self.Api({}, 'unspecified error'), card) + # a param card without the W mass + with self.assertRaisesRegex(RuntimeError, 'EVA needs M_W and M_Z'): + self.ew_inputs(None, {('mass', 23): 91.0}) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/unit_tests/various/test_mg7_massive_incoming.py b/tests/unit_tests/various/test_mg7_massive_incoming.py new file mode 100644 index 0000000000..901b3de20d --- /dev/null +++ b/tests/unit_tests/various/test_mg7_massive_incoming.py @@ -0,0 +1,176 @@ +################################################################################ +# +# Copyright (c) 2009 The MadGraph5_aMC@NLO Development team and Contributors +# +# This file is a part of the MadGraph5_aMC@NLO project, an application which +# automatically generates Feynman diagrams and matrix elements for arbitrary +# high-energy processes in the Standard Model and beyond. +# +# It is subject to the MadGraph5_aMC@NLO license which should accompany this +# distribution. +# +# For more information, visit madgraph.phys.ucl.ac.be and amcatnlo.web.cern.ch +# +################################################################################ +"""Massive incoming particles in mg7, as madevent has them (genps.f). + +The phase-space mappings of madspace build the incoming momenta massless. The +Integrand puts massive ones on their mass shell, with the same sum, and the +flux 1/(2 sqrt(lambda(s, m1^2, m2^2))) instead of 1/(2 s) (the +incoming_on_shell kernel); for monochromatic beams the run's s and beam +rapidity are those of the massive beam momenta (MadgraphProcess._massive_beams). +Without this, w+ w- > t t~ with 2 x 500 GeV W beams was 10% low. +""" +import math +import os +import sys +import unittest + +_file_path = os.path.dirname(os.path.realpath(__file__)) +_root = os.path.abspath(os.path.join(_file_path, '..', '..', '..')) +sys.path.insert(0, _root) + +try: + import numpy as np +except ImportError: + np = None + +from tests.unit_tests.various.test_eva_mg7 import _madspace + + +@unittest.skipIf(np is None, 'numpy required') +class TestIncomingOnShell(unittest.TestCase): + + def on_shell(self, p, masses): + ms = _madspace() + if ms is None: + self.skipTest('madspace build required') + vec = ms.batch_four_vec_array(p.shape[1]) + fb = ms.FunctionBuilder( + ms.NamedTypes([('p', vec)]), + ms.NamedTypes([('p_out', vec), ('flux_ratio', ms.batch_float)])) + out = fb.incoming_on_shell(fb.input(0), ms.Value(list(masses))) + fb.output(0, out[0]) + fb.output(1, out[1]) + runtime = ms.FunctionRuntime(fb.function(), ms.default_context()) + return [np.from_dlpack(t) for t in runtime.call([p])] + + def test_on_shell_with_the_same_sum(self): + rng = np.random.default_rng(7) + n = 1000 + masses = (80.419, 91.188) + # massless incoming momenta along +-z (some mirrored: the first one + # moving to -z), of a pair above threshold, and two outgoing momenta + e1 = 10 ** rng.uniform(1., 3.5, n) + e2 = 10 ** rng.uniform(1., 3.5, n) + mirror = rng.uniform(size=n) < 0.3 + p = np.zeros((n, 4, 4)) + p[:, 0, 0], p[:, 0, 3] = e1, np.where(mirror, -e1, e1) + p[:, 1, 0], p[:, 1, 3] = e2, np.where(mirror, e2, -e2) + p[:, 2] = [500., 30., -40., 100.] + p[:, 3] = [400., -30., 40., -50.] + p_out, flux = self.on_shell(p, masses) + p_in = p_out[:, :2] + s = (p[:, 0, 0] + p[:, 1, 0]) ** 2 - (p[:, 0, 3] + p[:, 1, 3]) ** 2 + above = s > sum(masses) ** 2 + self.assertTrue(above.any() and (~above).any()) + a = above + # on their mass shell, along the beam axis, in the same directions in + # the rest frame of the pair (in the lab a slow massive one can move + # backwards, as in madevent, which builds them in that frame too) + e_tot = p[:, 0, 0] + p[:, 1, 0] + z_tot = p[:, 0, 3] + p[:, 1, 3] + rest_z = lambda q: (e_tot * q[:, 3] - z_tot * q[:, 0]) + for leg, mass in enumerate(masses): + m2 = p_in[a, leg, 0] ** 2 - p_in[a, leg, 3] ** 2 + np.testing.assert_allclose(m2, mass ** 2, rtol=1e-8) + self.assertTrue(np.all(p_in[a, leg, 1:3] == 0.)) + self.assertTrue(np.all(np.sign(rest_z(p_in[:, leg])[a]) + == np.sign(rest_z(p[:, leg])[a]))) + # the same total momentum, and the outgoing momenta untouched + np.testing.assert_allclose(p_in[a].sum(axis=1), p[a, :2].sum(axis=1), + rtol=1e-12, atol=1e-9) + np.testing.assert_array_equal(p_out[:, 2:], p[:, 2:]) + # the flux ratio s / sqrt(lambda) + m1, m2 = masses + lam = (s - (m1 + m2) ** 2) * (s - (m1 - m2) ** 2) + np.testing.assert_allclose(flux[a], s[a] / np.sqrt(lam[a]), rtol=1e-12) + # below threshold: no weight, momenta as they were + self.assertTrue(np.all(flux[~a] == 0.)) + np.testing.assert_array_equal(p_out[~a], p[~a]) + + def test_monochromatic_beams_come_out_as_madevent_has_them(self): + """With the run's s and rapidity from _massive_beams, the mapping's + massless pair goes on shell into exactly the beam momenta.""" + from madgraph.mg7.madgraph_process import MadgraphProcess + mw = 80.419 + process = self.process([{'incoming': [24, -24], 'outgoing': [6, -6]}], + lambda pid: mw) + process._massive_beams() + p1, p2 = math.sqrt(400. ** 2 - mw ** 2), math.sqrt(600. ** 2 - mw ** 2) + self.assertAlmostEqual(process.e_cm ** 2, + 2 * mw ** 2 + 2 * (400. * 600. + p1 * p2), delta=1e-6) + # the massless incoming pair of the mapping: CM at sqrt(s), boosted + half, y = process.e_cm / 2, process.beam_rapidity + p = np.zeros((1, 3, 4)) + for leg, sign in ((0, 1.), (1, -1.)): + p[0, leg] = [half * math.cosh(y) + sign * half * math.sinh(y), 0., 0., + sign * half * math.cosh(y) + half * math.sinh(y)] + p[0, 2] = p[0, 0] + p[0, 1] + p_out, flux = self.on_shell(p, (mw, mw)) + np.testing.assert_allclose(p_out[0, 0], [400., 0., 0., p1], rtol=1e-12) + np.testing.assert_allclose(p_out[0, 1], [600., 0., 0., -p2], rtol=1e-12) + # massless beams keep s = 4 E1 E2 + process.get_mass = lambda pid: 0. + process.e_cm = 1. + process._massive_beams() + self.assertEqual(process.e_cm, 1.) + + @staticmethod + def process(subprocess_data, get_mass, energies=(400., 600.)): + """A MadgraphProcess with only what _massive_beams reads, as init_beam + leaves it for monochromatic beams.""" + from madgraph.mg7.madgraph_process import MadgraphProcess + process = object.__new__(MadgraphProcess) + process.subprocess_data = subprocess_data + process.get_mass = get_mass + process.beam_energies = energies + process.e_cm = 2. * math.sqrt(energies[0] * energies[1]) + process.beam_rapidity = 0.5 * math.log(energies[0] / energies[1]) + process.massive_beams = True + return process + + def test_each_subprocess_has_the_s_of_its_incoming_masses(self): + """Different incoming masses in different subprocesses (madevent: one + stot per P directory): each subprocess gets the s and rapidity of its + own massive beams, the process keeps 4 E1 E2.""" + mmu = 0.10566 + masses = {13: mmu, -13: mmu, 22: 0., 24: 80.419, -24: 80.419} + process = self.process( + [{'incoming': [-13, 13], 'outgoing': [6, -6]}, + {'incoming': [22, 22], 'outgoing': [6, -6]}, + {'incoming': [24, -24], 'outgoing': [6, -6]}], + lambda pid: masses[pid]) + e_cm, y = process.e_cm, process.beam_rapidity + process._massive_beams() + self.assertEqual((process.e_cm, process.beam_rapidity), (e_cm, y)) + for m in (0., mmu, 80.419): + s, rapidity = process.beam_kinematics([m, m]) + p1 = math.sqrt(400. ** 2 - m ** 2) + p2 = math.sqrt(600. ** 2 - m ** 2) + self.assertAlmostEqual(s ** 2, 2 * m ** 2 + 2 * (400. * 600. + p1 * p2), + delta=1e-6) + self.assertAlmostEqual(rapidity, 0.5 * math.log((1000. + p1 - p2) + / (1000. - p1 + p2))) + self.assertEqual(process.beam_kinematics([0., 0.]), (e_cm, y)) + # a subprocess whose masses are above the beam energies is refused + masses[24] = masses[-24] = 500. + with self.assertRaises(ValueError): + process._massive_beams() + # other beams: the process' s for every subprocess + process.massive_beams = False + self.assertEqual(process.beam_kinematics([500., 500.]), (e_cm, y)) + + +if __name__ == '__main__': + unittest.main()