## User Hooks

Sometimes it may be convenient to step in during the generation process: to modify the built-in cross sections, to veto undesirable events or simply to collect statistics at various stages of the evolution. There is a base class `UserHooks` that gives you this access at a few selected places. This class in itself does nothing; the idea is that you should write your own derived class for your task. One simple derived class (`SuppressSmallPT`) comes with the program, mainly as illustration, and the `main10.cc` program provides a complete (toy) example how a derived class could be set up and used.

There are ten sets of routines, that give you different kinds of freedom. They are, in no particular order:
(i) Ones that give you access to the event record in between the process-level and parton-level steps, or in between the parton-level and hadron-level ones. You can study the event record and decide whether to veto this event.
(ii) Ones that allow you to set a scale at which the combined parton-level MPI+ISR+FSR downwards evolution in pT is temporarily interrupted, so the event can be studied and either vetoed or allowed to continue the evolution.
(iii) Ones that allow you to to study the event after the first few ISR/FSR emissions, or first few MPI, so the event can be vetoed or allowed to continue the evolution.
(iv) Ones that allow you to study the latest initial- or final-state emission and veto that emission, without vetoing the event as a whole.
(v) Ones that give you access to the properties of the trial hard process, so that you can modify the internal Pythia cross section, alternatively the phase space sampling, by your own correction factors.
(vi) Ones that allow you to reject the decay sequence of resonances at the process level.
(vii) Ones that let you set the scale of shower evolution, specifically for matching in resonance decays.
(viii) Ones that allow colour reconnection, notably in connection with resonance decays.
(ix) Ones that allow an enhanced rate of rare shower splittings.
(x) Ones that give you access to to hadronization parameters in each step in the hadronization process, and allows for a veto of individual hadrons.

They are described further in the following numbered subsections.

All the possibilities above can be combined freely and also be combined with the standard flags. An event would then survive only if it survived each of the possible veto methods. There are no hidden interdependencies in this game, but of course some combinations may not be particularly meaningful. For instance, if you set `PartonLevel:all = off` then the `doVetoPT(...)` and `doVetoPartonLevel(...)` locations in the code are not even reached, so they would never be called.

Normally you would gather all your changes into one derived class. In some cases it may be more convenient to separate different functionalities. Therefore it is possible to hand in several user hooks. See the section on "Multiple user hooks" at the bottom of this page for further information on this possibility.

The effect of the vetoes of types (i), (ii) and (iii) can be studied in the output of the `Pythia::stat()` method. The "Selected" column represents the number of events that were found acceptable by the internal Pythia machinery, whereas the "Accepted" one are the events that also survived the user cuts. The cross section is based on the latter number, and so is reduced by the amount associated by the vetoed events. Also type (v) modifies the cross section, while types (iv), (vi) and (vii) do not.

A warning. When you program your own derived class, do remember that you must exactly match the arguments of the base-class methods you overload. If not, your methods will be considered as completely new ones, and compile without any warnings, but not be used inside `Pythia`. So, at the debug stage, do insert some suitable print statements to check that the new methods are called (and do what they should).

### The basic components

For a derived `UserHooks` class to be called during the execution, a pointer to an object of this class should be handed in with the
Pythia::setUserHooksPtr( UserHooks*)
method. The first step therefore is to construct your own derived class, of course. This must contain a constructor and a destructor. The `initPtr` method comes "for free", and is set up without any intervention from you.

The constructor and destructor do not need to do anything.
this (non-virtual) method is automatically called during the initialization stage to set several useful pointers, and to set up the `workEvent` below. The corresponding objects can later be used to extract some useful information.
Info
: general event and run information, including some loop counters.
Settings
: the settings used to determine the character of the run.
ParticleData
: the particle data used in the event record (including `workEvent` below).
Rndm
: the random number generator, that you could also use in your code.
BeamParticle
: the `beamAPtr` and `beamBPtr` beam particles contain info on partons extracted from the two incoming beams, on the PDFs used, and more. In cases when diffraction is simulated, also special Pomeron beams `beamPomAPtr` and `beamPomBPtr` are introduced, for the Pomerons residing inside the respective proton.
CoupSM
: Standard Model couplings.
PartonSystems
: the list of partons that belong to each individual subcollision system.
SigmaTotal
: total/elastic/diffractive cross section parametrizations.

Next you overload the desired methods listed in the sections below. These often come in pairs or triplets, where the first must return true for the last method to be called. This latter method typically hands you a reference to the event record, which you then can use to decide whether or not to veto. Often the event record can be quite lengthy and difficult to overview. The following methods and data member can then come in handy.

is a protected method that you can make use of in your own methods to extract a simplified list of the hard process, where all resonance decay chains are omitted. Intended for the `can/doVetoProcessLevel` routines. Note that the normal process-level generation does include resonance decays. That is, if a top quark is produced in the hard process, then also decays such as t → b W+, W+ → u dbar will be generated and stored in `process`. The `omitResonanceDecays` routine will take the input `process` and copy it to `workEvent` (see below), minus the resonance decay chains. All particles produced in the hard process, such as the top, will be considered final-state ones, with positive status and no daughters, just as it is before resonances are allowed to decay.
(In the `PartonLevel` routines, these decay chains will initially not be copied from `process` to `event`. Instead the combined MPI, ISR and FSR evolution is done with the top above as final particle. Only afterwards will the resonance decay chains be copied over, with kinematics changes reflecting those of the top, and showers in the decays carried out.)
For the default `finalOnly = false` the beam particles and incoming partons are retained, so the event looks like a normal event record up to the point of resonance decays, with a normal history setup.
With `finalOnly = true` only the final-state partons are retained in the list. It therefore becomes similar in functionality to the `subEvent` method below, with the difference that `subEvent` counts the decay products of the resonances as the final state, whereas here the resonances themselves are the final state. Since the history has been removed in this option, `mother1()` and `mother2()` return 0, while `daughter1()` and `daughter2()` both return the index of the same parton in the original event record.
is a protected method that you can make use of in your own methods to extract a brief list of the current partons of interest, with all irrelevant ones omitted. It is primarily intended to track the evolution at the parton level, notably the shower evolution of the hardest (i.e. first) interaction.
For the default `isHardest = true` only the outgoing partons from the hardest interaction (including the partons added to it by ISR and FSR) are extracted, as relevant e.g. for `doVetoPT( iPos, event)` with `iPos = 0 - 4`. With `isHardest = false` instead the outgoing partons of the latest "subprocess" are extracted, as relevant when `iPos = 5`, where it corresponds to the outgoing partons in the currently considered decay.
The method also works at the process level, but there simply extracts all final-state partons in the event, and thus offers no extra functionality.
The result is stored in `workEvent` below. Since the history has been removed, `mother1()` and `mother2()` return 0, while `daughter1()` and `daughter2()` both return the index of the same parton in the original event record (`event`; possibly `process`), so that you can trace the full history, if of interest.
This protected class member contains the outcome of the above `omitResonanceDecays(...)` and `subEvent(...)` methods. Alternatively you can use it for whatever temporary purposes you wish. You are free to use standard operations, e.g. to boost the event to its rest frame before analysis, or remove particles that should not be analyzed. The `workEvent` can also be sent on to a jet clustering algorithm.

### (i) Interrupt between the main generation levels

This routine is called by Pythia::init(), after the beams have been set up, but before any other initialisation. Therefore, at this stage, it is still possible to modify settings (apart from `Beams:*`) and particle data. This is mainly intended to be used in conjunction with Les Houches Event files, where headers are read in during beam initialisation, see the header functions in the Info class. In the base class this method returns true. By returning false, PYTHIA initialisation will be aborted.
In the base class this method returns false. If you redefine it to return true then the method `doVetoProcessLevel(...)` will be called immediately after a hard process (and associated resonance decays) has been selected and stored in the `process` event record.
At this stage, the `process` record typically contains the two beams in slots 1 and 2, the two incoming partons to the hard process in slots 3 and 4, the N (usually 1, 2 or 3) primary produced particles in slots 5 through 4 + N, and thereafter recursively the resonance decay chains, if any. Use the method `omitResonanceDecays(...)` if you want to skip these decay chains. There are exceptions to this structure, for soft QCD processes (where the partonic process may not yet have been selected at this stage), and when a second hard process has been requested (where two hard processes are bookkept). In general it is useful to begin the development work by listing a few `process` records, to clarify what the structure is for the cases of interest.
can optionally be called, as described above. You can study the `process` event record of the hard process. Based on that you can decide whether to veto the event, true, or let it continue to evolve, false. If you veto, then this event is not counted among the accepted ones, and does not contribute to the estimated cross section. The `Pytha::next()` method will begin a completely new event, so the vetoed event will not appear in the output of `Pythia::next()`.

Warning:

Normally you should not modify the `process` event record. However, for some matrix-element-matching procedures it may become unavoidable. If so, be very careful, since there are many pitfalls. Only to give one example: if you modify the incoming partons then also the information stored in the beam particles may need to be modified.

Note:

the above veto is different from setting the flag `PartonLevel:all = off`. Also in the latter case the event generation will stop after the process level, but an event generated up to this point is considered perfectly acceptable. It can be studied and it contributes to the cross section. That is, `PartonLevel:all = off` is intended for simple studies of hard processes, where one can save a lot of time by not generating the rest of the story. By contrast, the `doVetoProcessLevel()` method allows you to throw away uninteresting events at an early stage to save time, but those events that do survive the veto are allowed to develop into complete final states (unless flags have been set otherwise).
In the base class this method returns false. If you redefine it to return true then the method `doVetoPartonLevel(...)` will be called immediately after the parton level has been generated and stored in the `event` event record. Thus showers, multiparton interactions and beam remnants have been set up, but hadronization and decays have not yet been performed. This is already a fairly complete event, possibly with quite a complex parton-level history. Therefore it is usually only meaningful to study the hardest interaction, e.g. using `subEvent(...)` introduced above, or fairly generic properties, such as the parton-level jet structure.
can optionally be called, as described above. You can study, but not modify, the `event` event record of the partonic process. Based on that you can decide whether to veto the event, true, or let it continue to evolve, false. If you veto, then this event is not counted among the accepted ones, and does not contribute to the estimated cross section. The `Pytha::next()` method will begin a completely new event, so the vetoed event will not appear in the output of `Pythia::next()`.

Note:

the above veto is different from setting the flag `HadronLevel:all = off`. Also in the latter case the event generation will stop after the parton level, but an event generated up to this point is considered perfectly acceptable. It can be studied and it contributes to the cross section. That is, `HadronLevel:all = off` is intended for simple studies of complete partonic states, where one can save time by not generating the complete hadronic final state. By contrast, the `doVetoPartonLevel()` method allows you to throw away uninteresting events to save time that way, but those events that do survive the veto are allowed to develop into complete final states (unless flags have been set otherwise).
is very similar to `canVetoPartonLevel()` above, except that the chance to veto appears somewhat earlier in the generation chain, after showers and multiparton interactions, but before the beam remnants and resonance decays have been added. It is therefore somewhat more convenient for many matrix element strategies, where the primordial kT added along with the beam remnants should not be included.
is very similar to `doVetoPartonLevel(...)` above, but the veto can be done earlier, as described for `canVetoPartonLevelEarly()`.

### (ii) Interrupt during the parton-level evolution, at a pT scale

During the parton-level evolution, multiparton interactions (MPI), initial-state radiation (ISR) and final-state radiation (FSR) are normally evolved downwards in one interleaved evolution sequence of decreasing pT values. For some applications, e.g matrix-element-matching approaches, it may be convenient to stop the evolution temporarily when the "hard" emissions have been considered, but before continuing with the more time-consuming soft activity. Based on these hard partons one can make a decision whether the event at all falls in the intended event class, e.g. has the "right" number of parton-level jets. If yes then, as for the methods above, the evolution will continue all the way up to a complete event. Also as above, if no, then the event will not be considered in the final cross section.

Recall that the new or modified partons resulting from a MPI, ISR or FSR step are always appended to the end of the then-current event record. Previously existing partons are not touched, except for the status, mother and daughter values, which are updated to reflect the modified history. It is therefore straightforward to find the partons associated with the most recent occurrence.
An MPI results in four new partons being appended, two incoming and two outgoing ones.
An ISR results in the whole affected system being copied down, with one of the two incoming partons being replaced by a new one, and one more outgoing parton.
An FSR results in three new partons, two that come from the branching and one that takes the recoil.
The story becomes more messy when rescattering is allowed as part of the MPI machinery. Then there will not only be a new system, as outlined above, but additionally some existing systems will undergo cascade effects, and be copied down with changed kinematics.

In this subsection we outline the possibility to interrupt at a given pT scale, in the next to interrupt after a given number of emissions.

In the base class this method returns false. If you redefine it to return true then the method `doVetoPT(...)` will interrupt the downward evolution at `scaleVetoPT()`.
In the base class this method returns 0. You should redefine it to return the pT scale at which you want to study the event.
can optionally be called, as described above. You can study, but not modify, the `event` event record of the partonic process. Based on that you can decide whether to veto the event, true, or let it continue to evolve, false. If you veto, then this event is not counted among the accepted ones, and does not contribute to the estimated cross section. The `Pytha::next()` method will begin a completely new event, so the vetoed event will not appear in the output of `Pythia::next()`. is the position/status when the routine is called, information that can help you decide your course of action: when no MPI, ISR or FSR occurred above the veto scale; when inside the interleaved MPI + ISR + FSR evolution, after an MPI process; when inside the interleaved MPI + ISR + FSR evolution, after an ISR emission; when inside the interleaved MPI + ISR + FSR evolution, after an FSR emission; for the optional case where FSR is deferred from the interleaved evolution and only considered separately afterward (then alternative 3 would never occur); is for subsequent resonance decays, and is called once for each decaying resonance in a chain such as t → b W, W → u dbar. the event record contains a list of all partons generated so far, also including intermediate ones not part of the "current final state", and also those from further multiparton interactions. This may not be desirable for comparisons with matrix-element calculations. You may want to make use of the `subEvent(...)` method below to obtain a simplified event record `workEvent`.

### (iii) Interrupt during the parton-level evolution, after a step

These options are closely related to the ones above in section (ii), so we do not repeat the introduction, nor the possibilities to study the event record, also by using `subEvent(...)` and `workEvent`. What is different is that the methods in this section give access to the event as it looks like after each of the first few steps in the downwards evolution, irrespective of the pT scales of these branchings. Furthermore, it is here assumed that the focus normally is on the hardest subprocess, so that ISR/FSR emissions associated with additional MPI's are not considered. For MPI studies, however, a separate simpler alternative is offered to consider the event after a given number of interactions.

In the base class this method returns false. If you redefine it to return true then the method `doVetoStep(...)` will interrupt the downward ISR and FSR evolution the first `numberVetoStep()` times.
Returns the number of steps n each of ISR and FSR, for the hardest interaction, that you want to be able to study. That is, the method will be called after the first n ISR emissions, irrespective of the number of FSR ones at the time, and after the first n FSR emissions, irrespective of the number of ISR ones. The number of steps defaults to the first one only, but you are free to pick another value. Note that double diffraction is handled as two separate Pomeron-proton collisions, and thus has two sequences of emissions.
can optionally be called, as described above. You can study, but not modify, the `event` event record of the partonic process. Based on that you can decide whether to veto the event, true, or let it continue to evolve, false. If you veto, then this event is not counted among the accepted ones, and does not contribute to the estimated cross section. The `Pytha::next()` method will begin a completely new event, so the vetoed event will not appear in the output of `Pythia::next()`. is the position/status when the routine is called, information that can help you decide your course of action. Agrees with options 2 - 5 of the `doVetoPT(...)` routine above, while options 0 and 1 are not relevant here. is the number of ISR emissions in the hardest process so far. For resonance decays, `iPos = 5`, it is 0. is the number of FSR emissions in the hardest process so far. For resonance decays, `iPos = 5`, it is the number of emissions in the currently studied system. the event record contains a list of all partons generated so far, also including intermediate ones not part of the "current final state", and also those from further multiparton interactions. This may not be desirable for comparisons with matrix-element calculations. You may want to make use of the `subEvent(...)` method above to obtain a simplified event record.
In the base class this method returns false. If you redefine it to return true then the method `doVetoMPIStep(...)` will interrupt the downward MPI evolution the first `numberVetoMPIStep()` times.
Returns the number of steps in the MPI evolution that you want to be able to study, right after each new step has been taken and the subcollision has been added to the event record. The number of steps defaults to the first one only, but you are free to pick another value. Note that the hardest interaction of an events counts as the first multiparton interaction. For most hard processes it thus at the first step offers nothing not available with the `VetoProcessLevel` functionality above. For the minimum-bias and diffractive systems the hardest interaction is not selected at the process level, however, so there a check after the first multiparton interaction offers new functionality. Note that double diffraction is handled as two separate Pomeron-proton collisions, and thus has two sequences of interactions. Also, if you have set up a second hard process then a check is made after these first two, and the first interaction coming from the MPI machinery would have sequence number 3.
can optionally be called, as described above. You can study, but not modify, the `event` event record of the partonic process. Based on that you can decide whether to veto the event, true, or let it continue to evolve, false. If you veto, then this event is not counted among the accepted ones, and does not contribute to the estimated cross section. The `Pytha::next()` method will begin a completely new event, so the vetoed event will not appear in the output of `Pythia::next()`. is the number of MPI subprocesses has occurred so far. the event record contains a list of all partons generated so far, also including intermediate ones not part of the "current final state", e.g. leftovers from the ISR and FSR evolution of previously generated systems. The most recently added one has not had time to radiate, of course.

### (iv) Veto emissions

The methods in this group are intended to allow the veto of an emission in ISR, FSR or MPI, without affecting the evolution in any other way. If an emission is vetoed, the event record is "rolled back" to the way it was before the emission occurred, and the evolution in pT is continued downwards from the rejected value. The decision can be based on full knowledge of the kinematics of the shower branching or MPI.

To identify where shower emissions originated, the ISR/FSR veto routines are passed the system from which the radiation occurred, according to the Parton Systems class (see Advanced Usage). Note, however, that inside the veto routines only the event record has been updated; all other information, including the Parton Systems, reflects the event before the shower branching or MPI has taken place.

In the base class this method returns false. If you redefine it to return true then the method `doVetoISREmission(...)` will interrupt the initial-state shower immediately after each emission and allow that emission to be vetoed.
can optionally be called, as described above. You can study, but not modify, the `event` event record of the partonic process. Based on that you can decide whether to veto the emission, true, or not, false. If you veto, then the latest emission is removed from the event record. In either case the evolution of the shower will continue from the point where it was left off. is the size of the event record before the latest emission was added to it. It will also become the new size if the emission is vetoed. the event record contains a list of all partons generated so far. Of special interest are the ones associated with the most recent emission, which are stored in entries from `sizeOld` through `event.size() - 1` inclusive. If you veto the emission these entries will be removed, and the history info in the remaining partons will be restored to a state as if the emission had never occurred. the system where the radiation occurs, according to Parton Systems.
In the base class this method returns false. If you redefine it to return true then the method `doVetoFSREmission(...)` will interrupt the final-state shower immediately after each emission and allow that emission to be vetoed.
can optionally be called, as described above. You can study, but not modify, the `event` event record of the partonic process. Based on that you can decide whether to veto the emission, true, or not, false. If you veto, then the latest emission is removed from the event record. In either case the evolution of the shower will continue from the point where it was left off. is the size of the event record before the latest emission was added to it. It will also become the new size if the emission is vetoed. the event record contains a list of all partons generated so far. Of special interest are the ones associated with the most recent emission, which are stored in entries from `sizeOld` through `event.size() - 1` inclusive. If you veto the emission these entries will be removed, and the history info in the remaining partons will be restored to a state as if the emission had never occurred. the system where the radiation occurs, according to Parton Systems. `true` if the emission takes place in a resonance decay, subsequent to the hard process.
In the base class this method returns false. If you redefine it to return true then the method `doVetoMPIEmission(...)` will interrupt the MPI machinery immediately after each multiparton interaction and allow it to be vetoed.
can optionally be called, as described above. You can study, but not modify, the `event` event record of the partonic process. Based on that you can decide whether to veto the MPI, true, or not, false. If you veto, then the latest MPI is removed from the event record. In either case the interleaved evolution will continue from the point where it was left off. is the size of the event record before the latest MPI was added to it. It will also become the new size if the MPI is vetoed. the event record contains a list of all partons generated so far. Of special interest are the ones associated with the most recent MPI, which are stored in entries from `sizeOld` through `event.size() - 1` inclusive. If you veto the MPI these entries will be removed.

### (v) Modify cross-sections or phase space sampling

This section addresses two related but different topics. In both cases the sampling of events in phase space is modified, so that some regions are more populated while others are depleted. In the first case, this is assumed to be because the physical cross section should be modified relative to the built-in Pythia form. Therefore not only the relative population of phase space is changed, but also the integrated cross section of the process. In the second case the repopulation is only to be viewed as a technical trick to sample some phase-space regions better, so as to reduce the statistical error. There each event instead obtains a compensating weight, the inverse of the differential cross section reweighting factor, in such a way that the integrated cross section is unchanged. Below these two cases are considered separately, but note that they share many points.

In the base class this method returns false. If you redefine it to return true then the method `multiplySigmaBy(...)` will allow you to modify the cross section weight assigned to the current event.
when called this method should provide the factor by which you want to see the cross section weight of the current event modified. If you return unity then the normal cross section is obtained. Note that, unlike the methods above, these modifications do not lead to a difference between the number of "selected" events and the number of "accepted" ones, since the modifications occur already before the "selected" level. The integrated cross section of a process is modified, of course. Note that the cross section is only modifiable for normal hard processes. It does not affect the cross section in further multiparton interactions, nor in elastic/diffractive/minimum-bias events. : what makes this routine somewhat tricky to write is that the hard-process event has not yet been constructed, so one is restricted to use the information available in the phase-space and cross-section objects currently being accessed. Which of their methods are applicable depends on the process, in particular the number of final-state particles. The `multiplySigmaBy` code in `UserHooks.cc` contains explicit instructions about which methods provide meaningful information, and so offers a convenient starting point. : this flag is true when the method is called from within the event-generation machinery and false when it is called at the initialization stage of the run, when the cross section is explored to find a maximum for later Monte Carlo usage. Cross-section modifications should be independent of this flag, for consistency, but if `multiplySigmaBy(...)` is used to collect statistics on the original kinematics distributions before cuts, then it is important to be able to exclude the initialization stage from comparisons.

One derived class is supplied as an example how this facility can be used to reweight cross sections in the same spirit as is done with QCD cross sections for the minimum-bias/underlying-event description:

suppress small-pT production for 2 → 2 processes only, while leaving other processes unaffected. The basic suppression factor is pT^4 / ((k*pT0)^2 + pT^2)^2, where pT refers to the current hard subprocess and pT0 is the same energy-dependent dampening scale as used for multiparton interactions. This class contains `canModifySigma()` and `multiplySigmaBy()` methods that overload the base class ones.

The optional arguments of the constructor provides further variability. corresponds to the additional factor k in the above formula. It is by default equal to 1 but can be used to explore deviations from the expected value. if this number n is bigger than the default 0, the corresponding number of alpha_strong factors is also reweighted from the normal renormalization scale to a modified one, i.e. a further suppression factor ( alpha_s((k*pT0)^2 + Q^2_ren) / alpha_s(Q^2_ren) )^n is introduced. regulates which kind of new alpha_strong value is evaluated for the numerator in the above expression. It is by default the same as set for multiparton interactions (i.e. same starting value at M_Z and same order of running), but if `false` instead the one for hard subprocesses. The denominator alpha_s(Q^2_ren) is always the value used for the "original", unweighted cross section.

The second main case of the current section involves three methods, as follows.

In the base class this method returns false. If you redefine it to return true then the method `biasSelectionBy(...)` will allow you to modify the phase space sampling, with a compensating event weight, such that the cross section is unchanged. You cannot combine this kind of reweighting with the selection of a second hard process.
when called this method should provide the factor by which you want to see the phase space sampling of the current event modified. Events are assigned a weight being the inverse of this, such that the integrated cross section of a process is unchanged. Note that the selection is only modifiable for normal hard processes. It does not affect the selection in further multiparton interactions, nor in elastic/diffractive/minimum-bias events. : what makes this routine somewhat tricky to write is that the hard-process event has not yet been constructed, so one is restricted to use the information available in the phase-space and cross-section objects currently being accessed. Which of their methods are applicable depends on the process, in particular the number of final-state particles. The `biasSelectionBy` code in `UserHooks.cc` contains explicit instructions about which methods provide meaningful information, and so offers a convenient starting point. : this flag is true when the method is called from within the event-generation machinery and false when it is called at the initialization stage of the run, when the cross section is explored to find a maximum for later Monte Carlo usage. Cross-section modifications should be independent of this flag, for consistency, but if `biasSelectionBy(...)` is used to collect statistics on the original kinematics distributions before cuts, then it is important to be able to exclude the initialization stage from comparisons.
Returns the weight you should assign to the event, to use e.g. when you histogram results. It is the exact inverse of the weight you used to modify the phase-space sampling, a weight that must be stored in the `selBias` member variable, such that this routine can return `1/selBias`. The weight is also returned by the `Info::weight()` method, which may be more convenient to use.

### (vi) Reject the decay sequence of resonances

Resonance decays are performed already at the process level, as an integrated second step of the hard process itself. One reason is that the matrix element of many processes encode nontrivial decay angular distributions. Another is to have equivalence with Les Houches input, where resonance decays typically are provided from the onset. The methods in this section allow you to veto that decay sequence and try a new one. Unlike the veto of the whole process-level step, in point (i), the first step of the hard process is retained, i.e. where the resonances are produced. For this reason the cross section is not affected here but, depending on context, you may want to introduce your own counters to check how often a new set of decay modes and kinematics is selected, and correct accordingly.

The main method below is applied after all decays. For the production of a t tbar pair this typically means after four decays, namely those of the t, the tbar, the W+ and the W-. If Les Houches events are processed, the rollback is to the level of the originally read events. For top, that might mean either to the tops, or to the W bosons, or no rollback at all, depending on how the process generation was set up.

In the base class this method returns false. If you redefine it to return true then the method `doVetoResonanceDecays(...)` will be called immediately after the resonance decays have been selected and stored in the `process` event record, as described above for `canVetoProcessLevel()`.
can optionally be called, as described above. You can study the `process` event record of the hard process. Based on that you can decide whether to reject the sequence of resonance decays that was not already fixed by the production step of the hard process (which can vary depending on how a process has been set up, see above). If you veto, then a new resonance decay sequence is selected, but the production step remains unchanged. The cross section remains unaffected by this veto, for better or worse.

Warning:

Normally you should not modify the `process` event record. However, as an extreme measure, parts or the complete decay chain could be overwritten. If so, be very careful.

### (vii) Modify scale in shower evolution

The choice of maximum shower scale in resonance decays is normally not a big issue, since the shower here is expected to cover the full phase space. In some special cases a matching scheme is intended, where hard radiation is covered by matrix elements, and only softer by showers. The below two methods support such an approach. Note that the two methods are not used in the `TimeShower` class itself, but when showers are called from the `PartonLevel` generation. Thus user calls directly to `TimeShower` are not affected.

In the base class this method returns false. If you redefine it to return true then the method `scaleResonance(...)` will set the initial scale of downwards shower evolution.
can optionally be called, as described above. You should return the maximum scale, in GeV, from which the shower evolution will begin. The base class method returns 0, i.e. gives no shower evolution at all. You can study, but not modify, the `event` event record of the partonic process to check which resonance is decaying, and into what. is the location in the event record of the resonance that decayed to the particles that now will shower. the event record contains a list of all partons generated so far, specifically the decaying resonance and its immediate decay products.

### (viii) Allow colour reconnection

PYTHIA contains only a limites set of possibilities for colour reconnection, and none of them are geared specifically towards rapidly decaying resonances. Notably, with the default `PartonLevel:earlyResDec = off`, resonances will only decay after colour reconnection has already been considered. Thus a coloured parton like the top may be reconnected but, apart from this external connection with the rest of the event, the top decay products undergo no colour reconnection. For `PartonLevel:earlyResDec = on` the resonance will decay earlier, and thus the decay products may undergo reconnections, but not necessarily by models that are specifically geared towards this kind of events. For tryout purposes, a user hook can be called directly after the resonance decays, and there modify the colour flow. This holds whether the resonance decay is handled early or late, but is especially appropriate for the latter default possibility. While intended specifically for resonance decays, alternatively it is possible to switch off the built-in colour reconnection and here implement your own reconnection model for the whole event.

In the base class this method returns false. If you redefine it to return true then the method `doReconnectResonanceSystems(...)` will be called immediately after the resonance decays and their associated final-state showers have been added to the event record.
can optionally be called, as described above, to reconnect colours in the event. The method should normally return true, but false if the colour-reconnected event is unphysical and to be rejected. (If this is likely to happen, having a safety copy to restore to is a good idea, so that false can be avoided to the largest extent possible.) the size of the event record before resonance decay products and their associated final-state showers have been added to the event. Can thus be used to easily separate the resonance-decay partons from those in the rest of the event. the event record contains a list of all particles generated so far. You are allowed to freely modify this record, but with freedom comes responsibility. Firstly, it is only meaningful to modify the colour indices of final-state (at the time) partons; all other event properties had better be left undisturbed. Secondly, it is up to you to ensure that the new colour topology is meaningful, e.g. that no gluon has obtained the same colour as anticolour index and thereby forms a singlet on its own.

### (ix) Enhanced rate of rare shower splittings

PYTHIA also offers possibilities to enhance the frequency of rare splittings. This is not a trivial task, since a simple "upweighting" of splittings would produce a mismatch between emission and no-emission probabilities, leading to a violation of the principle that the parton shower should not change the inclusive (input) cross section. Nevertheless, a general algorithm that allows for increased emission probabilities, while keeping no-emission factors intact, was presented in Lon13a.

In Lon13a two types of enhancements are proposed: those of "regular" shower emissions, and those of trial shower emissions, the latter as part of the mandatory Sudakov reweighting in ME+PS merging schemes. Both of these possibilities are accessible through `UserHooks`, but cannot be used at the same time.

The price to pay for these enhancements is that events come with a compensatory weight. The advantages of obtaining higher statistics for rare branchings thus is mitigated, and the usefulness has to be evaluated case by case.

Currently enhancements of ISR and FSR branchings have been included. These enhancements are currently not phase-space dependent, i.e. emissions will be enhanced uniformly in phase space. It should also be noted that the threshold region for gluon branchings to a pair of heavy quarks, specifically g → c + cbar and g → b + bbar, are not enhanced in this algorithm. Technically it is because this case is handled separately in the code, but there also remain some physics issues to understand.

To increase statistics of rare emissions in the showers, e.g. QED or weak radiation, Pythia supplies the following functions implementing the strategy of section 4 in Lon13a.

In the base class this method returns false. If you redefine it to return true then the method `enhanceFactor(...)` will be used to rescale an initial-state splitting probability. Both `enhanceFactor(...)` and `vetoProbability(...)` will have to be derived to allow for a branching enhancement.
This function should return the enhancement factor for the splitting probability with identifier `name`. It should return 1. by default, i.e. for all input strings it does not propose to handle. the name of the splitting that can enhanced. Currently, the following input names are recognized by the PYTHIA showers, and can thus be used to enhance the respective splittings.

ISR QCD branchings:
`isr:G2GG` for g → g + g,
`isr:G2QQ` for g → q + qbar with q a light quark,
`isr:G2QQ:cc` for g → c + cbar
`isr:G2QQ:bb` for g → b + bbar
`isr:Q2QG` for q → q + g,
`isr:Q2GQ` for q → g + q;

ISR QED branchings:
`isr:Q2QA` for q → q + photon,
`isr:Q2AQ` for q → photon + q;

ISR weak shower branchings:
`isr:Q2QW` for q → q + W or q → q + Z;

FSR QCD branchings:
`fsr:G2GG` for g → g + g,
`fsr:G2QQ` for g → q + qbar with q a light quark,
`fsr:G2QQ:cc` for g → c + cbar
`fsr:G2QQ:bb` for g → b + bbar
`fsr:Q2QG` for q → q + g;

FSR QED branchings:
`fsr:Q2QA` for q → q + photon,
`fsr:A2QQ` for photon → q + qbar,
`fsr:A2LL` for photon → lepton + antilepton,

FSR weak shower branchings:
`fsr:Q2QW` for q → q + W or q → q + Z;

FSR hidden valley branchings:
`fsr:Q2QHV` for all hidden valley branchings.
Charge-conjugated branchings are included whenever relevant. Note that the order of the daughters matters: in the backwards evolution machinery the step is from the first daughter to the mother by the emission of the second daughter.

Let's consider some examples. The evolution step changing the partonic state from q qbar → e+ e- to g qbar → e+ e- qbar through an initial state splitting can be enhanced by allowing a non-unity return value for the splitting with `name` equalling `isr:G2QQ`. Another evolution step changing g qbar → e+ e- qbar to g qbar → e+ e- qbar gluon through FSR (ISR) can be enhanced by allowing a non-unity return value for the splitting with `name` equalling `fsr:Q2QG` (`isr:Q2QG`). Yet another ISR branching converting g qbar → e+ e- qbar to q qbar → e+ e- qbar q can be enhanced by non-unity return value for the splitting with `name` equalling `isr:Q2GQ` (note the ordering in the branching name).
This function should return the probability of an emission that has been enhanced with the help of `enhanceFactor(...)`, for the same `name` arguments as above. An optimal choice depends on your personal needs. Using 0.5 as a baseline is perfectly acceptable. It should return 0. by default, i.e. for all input strings it does not propose to handle.
If you use enhanced emissions, it is paramount to attribute a corrective weight to each event containing enhanced emissions. This function returns this weight. In the presence of enhancements, all histograms and output events must account for this weight.

In the context of merging, it can be beneficial to allow for enhanced trial emissions. As discussed in section 3 of Lon13a, this means that the Sudakov factors that are commonly generated by event vetoes based on trial emissions (see e.g. Lon11) are instead given by small but non-vanishing event weights. This can have advantages, since all events of an input sample will be retained. Pythia allows users to enhance trial emissions by using the following functions.

In the base class this method returns false. If you redefine it to return true then the method `enhanceFactor(...)` (see above) will be used to rescale an initial-state trial splitting probability.

Trial emission enhancements also necessitate corrective weights. These are handled internally, so that users only have to ensure that `Info::mergingWeight()` or `Info::mergingWeightNLO()` are correctly taken into account.

A simple example of enhanced regular emissions is provided in `main63.cc`.

### (x) Modified hadronization

The methods in this group are intended to allow for modifications of the string hadronization model, involving changes to hadronization parameters based on local properties of the string. Given information on the hadronization history of a single string, parameters can be changed to control the selection of quark flavour, z and pT in string breaks. Furthermore there is a option to veto the creation of a hadron before it is added to the event record, thus repeating a step in the hadronization procedure.

In the base class this method returns false. If you redefine it to return true, it will enable the methods `doChangeFragPar(...)`, `doVetoFragmentation(...)` and `setStringEnds(...)`.
This is the method for changing fragmentation parameters. If all parameters are changed as they should, the method should return true. In case of errors the method returns false and a warning is printed. The method takes as argument pointers to three objects that hold the fragmentation parameters, and three arguments that give information about the string currently being hadronized. is a pointer to a `StringFlav` object, which selects quark and diquark flavours and hadron species formed in the string breaks. The parameters can be changed by setting new parameters in a `Settings` object and reinitializing with `flavPtr->init(settings,randomPtr)`, where `settings` is the settings object and `randomPtr` is a pointer to the desired random number generator. Note that the `UserHooks` base class already holds pointers to the `Settings` and `Random` objects. is a pointer to a `StringZ` object, which selects the hadron momentum fraction z using the Lund fragmentation function. Parameters are changed by `zPtr->init(settings,particleData,randomPtr)` in the same way as above. is a pointer to a `StringPT` object which selects the hadron pT from a Gaussian distribution. Parameters are changed by `pTPtr->init(settings,particleData,randomPtr)` in the same way as above. gives the code of the parton (quark, diquark or gluon) in the string end that we are currently hadronizing from. gives the invariant mass squared of all hadrons produced from the current end of the string up to this point. Used to keep track of where we are on the string. contains the indices in the standard event record for all the partons in the string currently being hadronized. is a pointer to a `StringEnd` object containing additional information about the string break.
This method can veto the production of a hadron, whereby the current string break is redone. is a (copy of) the hadron being produced, just before it is added to the event record. is a pointer to a `StringEnd` object containing additional information about the string break.
This method can veto the production of the final hadrons produced in the fragmentation of a string. are (copies of) the two final hadrons being produced, just before they are added to the event record. are pointers to `StringEnd` objects containing additional information about the string break.
In the base class this method returns false. If you redefine it to return true, it will enable the method `doSetImpactParameter()` .
This method allows the user to select a particular impact parameter in the MPI machinery in the generation of minimum-bias events. The function takes no arguments and is intended for situations where the impact parameter is generated from the outside, as is the case in the Angantyr model for Heavy Ion collisions. Note that it does not modify the `MultipartonInteractions:bProfile` used in the MPI machinery, and that currently it will only affect the `SoftQCD` processes.

### Multiple user hooks

In addition to the
Pythia::setUserHooksPtr( UserHooks*)
method there is a second
Pythia::addUserHooksPtr( UserHooks*)
method that works almost like the former, but it allows the addition of further user hooks. These are stored as a vector and all of them will be called consecutively at the respective locations where they are set up to be active.

If two or more of them are active at the same location it is up to the user to ensure that the joint action is the one intended. In cases where weights are assigned the net result will be a weight that is is the product of them. In cases where vetoes are involved, a veto will be returned if either hook wants to veto, i.e. the no-veto survival probability is combined multiplicatively. It is not meaningful to let two hooks set the resonance scale or change fragmentation parameters, so warnings will be issued if this occurs.