pymule reference guide

This section describes all functions and classes in pymule. Most users will not have to view this.

Working with errors

pymule.errortools.addplots(a, b, sa=1.0, sb=1.0)

adds or subtracts two plots

Parameters:
  • a – Nx3 numpy matrix; the first plot

  • b – Nx3 numpy matrix; the second plot

  • sa – float, optional; the coefficient of the first plot

  • sb – float, optional; the coefficient of the second plot

Returns:

a Nx3 numpy matrix with \(s_a\cdot a + s_b\cdot b\)

Note

a and b must share x values, otherwise entries are dropped

Example:

subtract two plots a and b

>>> addplots(a, b, sb=-1)
Example:

Given the LO plots thetaLO and the NLO corrections thetadNLO, we calculate the \(K\) factor as either

>>> thetaNLO = addplots(thetaLO, thetadNLO)
pymule.errortools.chisq(values)

calculates the \(\chi^2/\textrm{d.o.f.}\) of numbers

Parameters:

value – Nx2 numpy matrix or list of lists; the values as [[y1, dy1], [y2, dy2], ...]

Returns:

float; the \(\chi^2/\textrm{d.o.f.} = \frac{1}{n} \sum_{n=1}^n(\frac{y_i-\bar y}{\delta y_i})^2\) with the average value \(\bar y\)

Example:

a good example

>>> chisq([[20.0, 0.8],
...        [21.6, 0.9],
...        [18.7, 1.2]])
1.3348808062205872

and a bad example

>>> chisq([[16.2, 0.8],
...        [22.9, 0.9],
...        [8.81, 1.2]])
30.173852184366673
pymule.errortools.combineNplots(func, plots)

combines a list of plots using a function

Parameters:
  • func – callable with two arguments; the function to combine the plots

  • plots – list of Nx3 numpy matrices

Returns:

a Nx3 numpy matrix \(f(p_0, f(p_1, f(p_2, \cdots)))\)

pymule.errortools.combineplots(a, b, yfunc, efunc, tol=1e-08)

combines two plots using functions for the value and the error

Parameters:
  • a – Nx3 numpy matrix; the first plot

  • b – Nx3 numpy matrix; the second plot

  • yfunc – callable; a function to calculate the value yfunc(a, b)

  • efunc – callable; a function to calculate the error efunc(a, da b, db)

  • tol – float, optional; the difference at which values are considered equal

Returns:

Nx3 numpy matrix; the combined plot np.array([[x1, yfunc(..), efunc(..)], ..])

Note

a and b must share x values, up to the tolerance tol, otherwise values may be dropped

Example:

Add two plots A and B

>>> combineplots(A, B,
...              lambda a, b: a+b,
...              lambda a, da, b, db: sqrt(da**2 + db**2))

Calculate a K factor

>>> combineplots(dnlo, lo,
...              lambda a, b: 1 + a/b,
...              lambda a, da, b, db: np.sqrt(db**2 * a**2 / b**4 + da**2 / b**2)
pymule.errortools.dividenumbers(a, b)

divides numbers

Parameters:
  • a – list of floats; the numerator with error [a, da]

  • b – list of floats; the denominator with error [b, db]

Returns:

the result of the division a/b [y, dy]

Example:

Divide \((2.3\pm0.1) / (45\pm0.01)\)

>>> dividenumbers([2.3, 0.1], [45., 0.01])
array([0.05111111, 0.00222225])
pymule.errortools.divideplots(a, b, offset=0.0)

divides two plots

Parameters:
  • a – Nx3 numpy matrix; the numerator plot

  • b – Nx3 numpy matrix; the denominator plot

  • offset – float, optional; shifts the result

Returns:

a Nx3 numpy matrix with \(a/b + offset\)

Note

a and b must share x values, otherwise entries are dropped

Example:

Given the LO plots thetaLO and the NLO corrections thetadNLO, we calculate the \(K\) factor as either

>>> thetaNLO = addplots(thetaLO, thetadNLO)
>>> thetaK = divideplots(thetaNLO, thetaLO)
>>> thetaK = divideplots(thetadNLO, thetaLO, offset=+1.)
pymule.errortools.integratehistogram(hist)

integrates a histogram

Parameters:

hist – Nx3 numpy matrix; the histogram to integrate \(d\sigma/dx\) as np.array([[x1, y1, e1], [x2, y2, e2], ...])

Returns:

float; the integrated histogram \(\int d\sigma/dx dx\) without error estimate

Example:

Integrate a histogram

>>> hist
array([[          -inf, 0.00000000e+00, 0.00000000e+00],
       [5.00000000e-02, 4.77330751e+01, 2.26798977e-01],
       [1.50000000e-01, 7.40641192e+01, 2.36498021e-01],
       ...,
       [8.85000000e+00, 1.67513948e+00, 1.16218116e-01],
       [8.95000000e+00, 0.00000000e+00, 0.00000000e+00],
       [           inf, 0.00000000e+00, 0.00000000e+00]])
>>> integratehistogram(hist)
4188.519369660588
pymule.errortools.mergebins(p, n)

merges n adjacent bins into one larger bin, reducing the uncertainty.

Parameters:
  • p – Nx3 numpy matrix; the plot

  • n – int; how many bins to merge

Returns:

a (N/n)x3 numpy matrix

Note

This process loses len(p)%n bins at the end of the histogram

Example:

merge five bins

>>> len(p)
200
>>> len(mergebins(p, 5))
40

Bins may be lost

>>> len(p)
203
>>> len(mergebins(p, 5))
40
pymule.errortools.mergenumbers(values, quiet=False)

statistically combines values with uncertainties

Parameters:
  • values – Nx2 numpy matrix or list of lists; the values as [[y1, dy1], [y2, dy2], ...]

  • quiet – bool, optional; whether to print or return the \(\chi^2\) for the combination

Returns:

either answer as numpy array [y, dy] or tuple of \(chi^2\) and answer

Example:

If quiet is not specified this will print the \(chi^2\)

>>> mergenumbers([[20.0, 0.8],
...               [21.6, 0.9],
...               [18.7, 1.2]])
1.3348808062205872
array([20.30718232,  0.53517179])

Otherwise, it will return it

>>> mergenumbers([[20.0, 0.8],
...               [21.6, 0.9],
...               [18.7, 1.2]], quiet=True)
(1.3348808062205872, array([20.30718232,  0.53517179]))
pymule.errortools.mergeplots(ps, returnchi=False)

statistically combines a list of plots

Parameters:
  • ps – list of Nx3 numpy matrices; the plots to combine as [np.array([[x1, y1, e1], [x2, y2, e2], ...]), ...]

  • returnchi – bool, optional; if True returns two plots, the requested combination and the bin-wise \(\chi^2\)

Returns:

a Nx3 numpy matrix if returnchi=False

Example:

Load a number of vegas files and merge them

>>> data = [
...     importvegas(i)['thetae']
...     for i in glob.glob('out/em2em0*')
... ]
>>> mergeplots(data)
pymule.errortools.plusnumbers(*args)

adds numbers and errors

Parameters:

yi – list of floats; a number with error [yi, dyi]

Returns:

the result of the addition [y, dy]

Example:

Adding \((10\pm1)+(20\pm0.5)+(-5\pm2)\)

>>> plusnumbers([10, 1], [20, 0.5], [-5, 2])
array([25.        ,  2.29128785])
pymule.errortools.printnumber(x, prec=0)

returns a string representation of a number with uncertainties to one significant digit

Parameters:
  • x – a list with two floats; the number as [x, dx]

  • prec – int, otpional; number of extra signficant figures

Returns:

str; the formatted string

Example:

printing \(53.2\pm0.1\) to one significant figure

>>> printnumber([53.2, 0.1])
"53.2(1)"
pymule.errortools.scaleplot(a, sx, sy=None)

rescales a plot such that the integrated plot remains unchanged, i.e. rescale \(x\to x/s\) and \(y\to y\cdot s\). This is useful to, for example, change units.

Parameters:
  • a – Nx3 numpy matrix; the plot

  • sx – float; the inverse scale factor for the x direction

  • sy – float, optional; if present, sy will be used for the y direction instead of sx

Returns:

a Nx3 numpy matrix

Example:

rescaling units from rad to mrad

>>> scaleplot(data, 1e-3)
pymule.errortools.timesnumbers(a, b)

multiplies numbers

Parameters:
  • a – list of floats; the first factor with error [a, da]

  • b – list of floats; the second factor with error [b, db]

Returns:

the result of the multiplication a*b [y, dy]

Example:

Divide \((0.5\pm0.02) * (45\pm0.01)\)

>>> timesnumbers([0.5,0.02], [45, 0.1])
array([22.5       ,  0.90138782])

Working with abstract records

Working with vegas records

pymule.vegas.exportvegas(dic, filename='', fp=None)

saves a vegas file

Parameters:
  • dic

    a vegas dataset dictionary containing at least
    • value: the best estimate for the cross section and its error as np.array([y, e])

    • chi2a: the \(\chi^2\) estimate of the integrator

    • all histograms as specified by their name(..) in user.f95

    it may also contain the optional keys
    • runtime: the runtime, defaults to time.clock()

    • msg: any message, defaults to Warning: Generated with Python

    • SHA: the first 5 characters of a hash, defaults to 00000

    • iteration: the number of iterations in the file, defaults to 2

  • filename – file name to open, optional

  • fp – file pointer to write to, optional

  • returnev – bool, optional; return the full vegas file or only usable things

Note

Either filename xor fp need to be specified

Example:

save a random run to disk

>>> dic = {"value": [10, 0.2],
...        "chi2a": 0.2,
...        "Ee": np.array([[1, 5, 0.3], [2, 6, 0.35]])}
>>> exportvegas(dic ,"out.vegas")
pymule.vegas.getplots(s)

removes all the keys that are not distributions from a vegas dataset

Parameters:

s – a vegas dataset or a list of vegas datasets

Returns:

a list of plots appearing in all datasets

pymule.vegas.guess_version(fp, inttype='i')

infers version of the vegas file using either the version string (since v3) or the file length (v1 and v2).

Parameters:
  • fp – file pointer

  • inttype – either 'i' or 'q', optional; the integer type to use for v1 or v2, inferred otherwise

Returns:

tuple of version number and integer type

pymule.vegas.importvegas(filename='', fp=None, inttype='i', returnev=False)

loads a vegas file

Parameters:
  • filename – file name to open, optional

  • fp – file pointer to read, optional

  • inttype – either 'i' or 'q', optional; the integer type to use for v1 or v2, inferred otherwise

  • returnev – bool, optional; return the full vegas file or only usable things

Returns:

a vegas dataset dictionary containing
  • time: the job’s run time (since v2)

  • msg: any message. Usually this contains information on the state of the integrator (since v2)

  • SHA: the first 5 characters of the source-tree’s SHA1 hash at compile time.

  • iteration: the number of iterations completed in this file

  • value: the best estimate for the cross section and its error as np.array([y, e])

  • chi2a: the \(\chi^2\) estimate of the integrator

  • all histograms as specified by their name(..) in user.f95

if returnev is passed, also returns keys
  • ndo

  • xi: the vegas grid

  • randy: the random number seed

Note

Either filename xor fp need to be specified

Note

If less than two iterations have been completed, no histograms will be returned

Example:

Load a file for the muon decay

>>> importvegas('m2ennRR_mu-e_S0000068031X0.50000D0.50000_ITMX080x150M_O12.vegas')
{'time': 103523.659092, 'msg': 'Uninterupted integration. Program SHA isbe42eccf04a8fb0afa5fa2f80be6a492bb2093a4 (git:423084d47038d3dbf51f69459d2e622312eec594)', 'SHA': 'be42e', 'iteration': 44, 'value': array([-3.65282506e+06,  1.89792449e+02]), 'chi2a': 0.8714706523473873, 'Ee': array([[           -inf,  0.00000000e+00,  0.00000000e+00],
       [ 1.30000000e-02,  0.00000000e+00,  0.00000000e+00],
       [ 3.90000000e-02,  0.00000000e+00,  0.00000000e+00],
       ...,
       [ 2.59610000e+01,  0.00000000e+00,  0.00000000e+00],
       [ 2.59870000e+01,  0.00000000e+00,  0.00000000e+00],
       [            inf, -3.65294784e+06,  1.79397543e+02]]), 'cthe': array([[           -inf,  0.00000000e+00,  0.00000000e+00],
       [-9.99000000e-01, -4.77190754e+06,  4.08877779e+03],
       [-9.97000000e-01, -4.76466432e+06,  4.81770106e+03],
       ...,
       [ 9.97000000e-01,  0.00000000e+00,  0.00000000e+00],
       [ 9.99000000e-01,  0.00000000e+00,  0.00000000e+00],
       [            inf,  0.00000000e+00,  0.00000000e+00]])}
pymule.vegas.read_record(fp, typ)

reads a single FORTRAN record

Parameters:
  • fp – file pointer

  • typ

    the type to read, everything that struct understands. Examples are

    • i: 32 bit signed integer (standard integer in Fortran)

    • I: 32 bit unsigned integer

    • q: 64 bit signed integer (integer*8 in Fortran)

    • c: 8 bit charater (character in Fortran)

    • d: 64 bit double precision (real(kind=prec) in Fortran, with default prec)

Records are data structures that are build as follows:

  • 4 byte header: length of the record as a 32 bit unsigned integer, called l1

  • body of length l1

  • 4 byte footer: a repetition of l1 to make sure the record is properly closed.

Records can contain multiple variables.

pymule.vegas.write_record(fp, typ, content)

writes a single FORTRAN record

Parameters:
  • fp – file pointer

  • typ

    the type to read, everything that struct understands. Examples are

    • i: 32 bit signed integer (standard integer in Fortran)

    • I: 32 bit unsigned integer

    • q: 64 bit signed integer (integer*8 in Fortran)

    • c: 8 bit charater (character in Fortran)

    • d: 64 bit double precision (real(kind=prec) in Fortran, with default prec)

  • content – scalar, list, str or bytes; the data to write

Records are data structures that are build as follows:

  • 4 byte header: length of the record as a 32 bit unsigned integer, called l1

  • body of length l1

  • 4 byte footer: a repetition of l1 to make sure the record is properly closed.

Records can contain multiple variables.

Working with records of data

pymule.loader.addsets(s)

adds a list of vegas datasets

Parameters:

s

a list of vegas datasets dictionaries with the keys
  • time

  • value

  • chi2a

  • all histograms as specified by their name(..) in user.f95

Returns:

the resulting sum. The resulting \(\chi^2\) is a list of constituent \(\chi^2\).

pymule.loader.callsanitised(func, **kwargs)

calls a function with arguments from kwargs and those specified in loadargs

Parameters:
  • func – callable; function to call

  • **kwargs

    arguments overriding loadargs

Arguments that don’t match func are discarded.

pymule.loader.commit_cache(cachefolder, full_name, fp)

writes to cache if cachefolder exists

Parameters:
  • cachefolder – path to cache folder

  • full_name – name of file in cache folder

  • fp – file pointer to read from

pymule.loader.hash_file(name)

hashes a files using SHA1

Parameters:

name – file path

Returns:

hex-digested SHA1 hash of the file

pymule.loader.importreg(r, folder='.', filenames=None, cachefolder='', merge={}, types=[<class 'int'>, <class 'float'>, <class 'float'>], sanitycheck=<function <lambda>>)

imports all vegas files matching a regular expression

Parameters:
  • r – str; regular expression to match in file names

  • folder – str, optional; file name, optional; folder or tarball to search for vegas files

  • filenames – list, optional; list of files to loads, defaults to all files in folder (recurisvely if tar ball)

  • cachefolder – folder name, optional; if existing folder, use as cache for compressed tarballs

  • merge – dict, optional: a dict of histograms {'name': n} to merge n bins in the histogram name. defaults to no merging

  • types – list of callables, optional; functions that convert the groups matched by r into python objects. Common examples would be int or float. Default: [int,float, float] as per McMule filename convention

  • sanitycheck – callable, optional; a function that, given a vegas dict, whether to include the file in the output (return True) or to skip (return False).

Returns:

a dictionary of merged vegas datasets, keyed by the groups defined in the regular expression r as parsed by types

pymule.loader.mergefks(*sets, **kwargs)

performs the FKS merge

Parameters:
  • sets – random-seed-merged results (usually from sigma())

  • binwisechi – bool, optional, default False; if set to True, also return extra distributions containing the \(\chi^2\) of the bin-wise FKS merge. This cannot be used together with anyxi and the result should not be passed to scaleset for obvious reasons.

Returns:

the FKS-merged final set containing cross sections, distributions, and run-time information. The chi2a return is a list of the following

  • the \(\chi^2\) of the FKS merge

  • a list of \(\chi^2\) from previous operations, such as random seed merging or the integration.

Note

Optional argument anyxi (or anything starting with anyxi): Sometimes it is necessary to merge \(\xi_c\)-dependent runs (such as a counter term) and \(\xi_c\)-independent runs (such as the one-loop term). Do not use this together with binwisechi

Example:

Load the LO results for the muon decay using sigma()

>>> mergefks(sigma("m2enn0"))

Load the NLO results

>>> mergefks(sigma("m2ennV"), sigma("m2ennR"))

Load the NNLO results where m2ennNF does not depend on \(\xi_c\)

>>> mergefks(sigma("m2ennFF"), sigma("m2ennRF"), sigma("m2ennRR"), anyxi=sigma("m2ennNF"))
pymule.loader.mergeseeds(s, key=<function <lambda>>)

statistically merges the different random seeds of a number of runs, combining cross sections, histograms, and run-time information.

Parameters:
  • s – a list of vegas datasets

  • key – callable; function to define the keys of the resulting dictionary. Usually, this refers to the FKS parameters. In the default notation this is lambda x: (x[1], x[2]) referring to \(\xi_c\) and \(\delta\), resp.

Raises:

KeyError ‘time’: if merge is unsucessfull because no data is found

Todo:

make error handling more useful

Returns:

a merged vegas dataset. The runtime is the sum of individual times. The \(\chi^2\) is a list of

  • the \(\chi^2\) of the cross section combination

  • a list of the individual \(\chi^2\)

pymule.loader.mergeset(s, binwisechi=False)

statistically merges a set of runs, combining cross sections, histograms, and run-time information

Parameters:
  • s – a list of vegas datasets

  • binwisechi – bool, optional; whether to include the bin-wise \(\chi^2\) in the result.

Raises:

KeyError ‘time’: if merge is unsucessfull because no data is found

Todo:

make error handling more useful

Returns:

a merged vegas dataset. The runtime is the sum of individual times. The \(\chi^2\) is a list of

  • the \(\chi^2\) of the cross section combination

  • a list of the individual \(\chi^2\)

pymule.loader.multiintersect(lists)

finds elements that are common to all lists. This is used to find a list of FKS parameters of a given run.

Parameters:

list – list of lists \(l_1\), \(l_2\), …, \(l_n\)

Returns:

the list \(l_1 \cap l_2 \cap \cdots \cap l_n\)

pymule.loader.pattern(piece='.*', flavour='.*', obs='', folderp='.*')

constructs a regular expression to be used in importreg() matching the usual McMule file name convention

Parameters:
  • piece – str, optional; the which_piece to load, defaults to everything

  • flavour – str, optional; the flavour to load, defaults to everything

  • obs – str, optional; the observable to load (the bit after the O), defaults to everything

  • folderp – str, optional; a regular expression to match directory structures of a tar file, defaults to everything

Returns:

a regular expression to be used in importreg()

pymule.loader.scaleset(s, v)

rescales a vegas dataset

Parameters:
  • s

    a vegas datasets dictionaries with the keys
    • time

    • value

    • chi2a

    • all histograms as specified by their name(..) in user.f95

  • v – the value to rescale the y values.

Returns:

the rescaled dataset

Note

This naturally changes the cross section

pymule.loader.scalesets(s, v)

rescales a list of vegas datasets

Parameters:
  • s

    a list of vegas datasets dictionaries with the keys
    • time

    • value

    • chi2a

    • all histograms as specified by their name(..) in user.f95

  • v – the value to rescale the y values.

Returns:

all rescaled datasets

Note

This naturally changes the cross section

pymule.loader.setup(**kwargs)

sets the default arguemnts for sigma().

Parameters:
  • folder – str, optional; file name, optional; folder or tarball to search for vegas files Initialised to current directory (.).

  • flavour – str, optional; the flavour to load, defaults to everything Initialised to everything, i.e. .*.

  • obs – str, optional; the observable to load (the bit after the O), defaults to everything Initialised to everything, i.e. ''.

  • folderp – str, optional; a regular expression to match directory structures of a tar file, defaults to everything Initialised to everything, i.e. .*.

  • filenames – list, optional; list of files to loads, defaults to all files in folder (recurisvely if tar ball) Initialised to None, meaning everything.

  • merge – dict, optional: a dict of histograms {'name': n} to merge n bins in the histogram name. Initialised to to no merging, i.e. {}

  • types – list of callables, optional; functions that convert the groups matched by r into python objects. Common examples would be int or float. Initialised to [int,float, float] as per McMule filename convention.

  • sanitycheck – callable, optional; a function that, given a vegas dict, whether to include the file in the output (return True) or to skip (return False). Initialised to lambda x : True, i.e. include everything.

  • cache – folder name, optional; if existing folder, use as cache for compressed tarballs

Example:

Setup some folders, ensure that /tmp/mcmule exists

>>> setup(folder="path/to/data.tar.bz2", cachefolder="/tmp/mcmule")
Example:

Restrict observable

>>> setup(obs="3")
Example:

Drop runs with a \(\chi^2 > 10\)

>>> setup(sanitycheck=lambda x : x['chi2a'] < 10)
pymule.loader.sigma(piece, **kwargs)

loads a which_piece and statistically combines the random seed.

Parm piece:

str; which_piece to load

Parameters:
  • folder – str, optional; file name, optional; folder or tarball to search for vegas files Initialised to current directory (.).

  • flavour – str, optional; the flavour to load, defaults to everything Initialised to everything, i.e. .*.

  • obs – str, optional; the observable to load (the bit after the O), defaults to everything Initialised to everything, i.e. ''.

  • folderp – str, optional; a regular expression to match directory structures of a tar file, defaults to everything Initialised to everything, i.e. .*.

  • filenames – list, optional; list of files to loads, defaults to all files in folder (recurisvely if tar ball) Initialised to None, meaning everything.

  • merge – dict, optional: a dict of histograms {'name': n} to merge n bins in the histogram name. Initialised to to no merging, i.e. {}

  • types – list of callables, optional; functions that convert the groups matched by r into python objects. Common examples would be int or float. Initialised to [int,float, float] as per McMule filename convention.

  • sanitycheck – callable, optional; a function that, given a vegas dict, whether to include the file in the output (return True) or to skip (return False). Initialised to lambda x : True, i.e. include everything.

  • cache – folder name, optional; if existing folder, use as cache for compressed tarballs

Returns:

a dict with the tuples of FKS parameters as keys and vegas datasets as values.

Note

Use setup() to set the defaults. Arguments provided here override the defaults

Example:

Load the leading order muon decay

>>> sigma("m2enn0")

Load only observable O3

>>> sigma("m2enn0", obs="3")

Working with \(\xi_c\) data

pymule.xicut.addkeyedsets(sets)

adds list of keyed sets using addsets()

pymule.xicut.get_errorbands(x, coeff, covar, ndata, cf=0.9)

evaluates the errorbands of the fit obtained by get_val()

Parameters:
  • x – iterable; values of \(\xi_c\) to evaluate

  • coeff – list; coefficient list [a_0, a_1, ..., a_n]

  • covar – list; the covariance matrix

  • ndata – int; the number of data points used in the fit, required for the \(t\) value estimation

  • cl – float, optional; the confidence level used

Returns:

list; the values and errors of the fit at the presented values as [x, y, y-dy, y+dy]

pymule.xicut.get_val(xs, coeff)

evaluates the fit obtained by get_val()

Parameters:
  • xs – iterable; values of \(\xi_c\) to evaluate

  • coeff – list; coefficient list [a_0, a_1, ..., a_n]

Returns:

list; the values of the fit at the presented values.

pymule.xicut.mergefkswithplot(sets, scale=1.0, showfit=[True, True], xlim=[-7, 0])

performs and FKS merge like mergefks() but it also produces a \(\xi_c\) independence plot

Note

In contrast mergefks(), here phase-space partioned results need to be merged first. This is done by grouping those into an array first, sorted by number of particles in the final state, i.e. we start with the n-particle corrections.

Parameters:
  • sets – list of list of random-seed-merged results (usually from sigma()), starting with the lowest particle number and going up

  • scale – float, optional; rescale factor for the plot and result

  • showfit[bool, bool], optional; whether to show the fit lines in the overview plot (first element) and the zoomed in plot (second element)

  • xlim – tuple of floats, optional; upper and lower bounds for \(\log\xi_c\)

Returns:

a figure and the FKS-merged final set containing cross sections, distributions, and run-time information. The chi2a return is a list of the following

  • the \(\chi^2\) of the FKS merge

  • a list of \(\chi^2\) from previous operations, such as random seed merging or the integration.

Example:

In the partioned muon-electron scattering case

>>> fig, res = mergefkswithplot([
...     [
...         sigma('em2emFEE'), sigma('em2emFMM'), sigma('em2emFEM')
...     ], [
...         sigma('em2emREE15'), sigma('em2emREE35'),
...         sigma('em2emRMM'),
...         sigma('em2emREM')
...     ]
... ])
pymule.xicut.myfit(data, n)

performs a log-polynomial \(\sum_{i=0}^n a_i \log(\xi_c)^i\) fit to date

Parameters:
  • data – numpy array; The different \(\xi_c\) values in the format np.array([[xi1, y1, e1], [xi2, y2, e2], ...]).

  • n – the degree of the polynomial

Result:

the coefficients and covariant matrix

pymule.xicut.xiresidue(sets, n, xlim=[-7, 0], scale=1)

creates a residue plot for a \(\xi_c\) fit

Parameters:
  • sets – dict or list; random-seed-merged results (usually from sigma()) or list thereof

  • n – int; order of the fit, 1 at NLO, 2 at NNLO

  • xlim – tuple of floats, optional; upper and lower bounds for \(\log\xi_c\)

  • scale – float, optional; rescale factor for the plots

Returns:

a figure and the fit coefficients as a matrix

Working with plots

pymule.plot.errorband(p, ax=None, col='default', underflow=False, overflow=False, linestyle='solid')

plots an errorband of a compatible histogram

Parameters:
  • p – Nx3 numpy matrix; the histogram to plot as np.array([[x1, y1, e1], [x2, y2, e2], ...])

  • ax – axes, optional: the axes object to use, defaults to gca() which may create a new axes.

  • col – the colour to be used for the plot. Per default matplotlib decides using the order specified in colours

  • underflow – bool, optional; whether to plot the underflow bin. Either logical or number indicating the how much bigger it shall be

  • overflow – bool, optional; whether to plot the overflow bin. Either logical or number indicating the how much bigger it shall be

  • linestyle – str, optional; which line style to use

Returns:

the artis of the main line but not the one of the errorbars

Example:

Make a simple plot

>>> errorband(dat)

Make a plot in red with dashed lines

>>> errorband(dat, 'red', 'dashed')
pymule.plot.format_label_string_with_exponent(ax, axis='both')

Format the label string with the exponent from the ScalarFormatter

pymule.plot.kplot(sigma, labelx='$x_e$', labelsigma=None, labelknlo='$\\delta K^{(1)}$', labelknnlo='$\\delta K^{(2)}$', legend={'lo': '$\\rm LO$', 'nlo': '$\\rm NLO$', 'nnlo': '$\\rm NNLO$'}, legendopts={'loc': 'upper right', 'what': 'l'}, linestyle2=':', show=[0, -1], showk=[1, 2], nomule=False)

produces a K factor plot in line with McMule’s design, i.e. a two-panel plot showing in the upper panel the cross sections and in the lower panel the K factor defined as

\[K^{(i)} = d\sigma^{(i)} / d\sigma^{(i-1)}\]
Parameters:
  • sigma – dict; the data to plot, given as a dict with keys lo, nlo, and possibly nnlo. Only pass the corrections, not the full distribution

  • labelx – str, optional; label for the x axis (supports LaTeX maths)

  • labelsigma – str, optional; label for the upper y axis (supports LaTeX maths)

  • labelknlo – str, optional; the labels for the NLO K factor

  • labelknnlo – str, optional; the labels for the NNLO K factor

  • show – list, optional; a list which cross sections to show, 0 indicates the LO cross section, 1 the NLO etc. -1 indicates the last given cross section

  • showk – list, optional; a list which K factors to show, 0 indicates the LO cross section, 1 the NLO etc. -1 indicates the last given cross section

  • legend – dict, optional; a dict with the legend for lo, nlo, nnlo. The keys nlo2 and nnlo2 are optional and will be drawn dashed in the lower panel.

  • legendopts

    dict, optional; a kwargs dict of options to be passed to legend(..) as well as the what key indicating whether the legend such be placed in the lower panel (l, default), upper panel (u), or as a figlegend (fig). Notable is the loc-key that places the legend inside the object specified by what. Possible values are (cf. legend)

    • upper right

    • upper left

    • lower left

    • lower right

    • right

    • center left

    • center right

    • lower center

    • upper center

    • center

  • nomule – bool, optional; if set to True, no mule will be printed

Returns:

the figure as well as all axis created

Example:

An NNLO K factor plot

>>> fig, (ax1, ax2, ax3) = kplot(
...   {
...     'lo':  lodata['thetae'],
...     'nlo': nlodata['thetae'],
...     'nnlo':nnlodata['thetae'],
...   },
...   labelx="$\theta_e\,/\,{\rm mrad}$",
...   labelsigma="$\D\sigma/\D\theta_e\ /\ {\rm\upmu b}$",
...   legend={
...     'lo': '$\sigma^{(0)}$',
...     'nlo': '$\sigma^{(1)}$',
...     'nnlo': '$\sigma^{(2)}$'
...   },
...   legendopts={'what': 'u', 'loc': 'lower right'}
... )
pymule.plot.setup_pgf()

setupf_pgf() ensures that Matplotlib exports PGF compatible plots.

pymule.plot.threepanel(labelx='', upleft=[], labupleft='', colupleft=['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'], middleleft=[], labmiddleleft='', colmiddleleft=['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'], downleft=[], labdownleft='', coldownleft=['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'])

creates three panel plot, accommodating at most three axes (upper, middle, lower). The x axis is naturally shared.

Parameters:
  • labelx – str, optional; label for the x axis

  • upleft – Nx3 numpy matrix or list thereof, optional; data plotted in the upper-left axes

  • colupleft – colour for upper-left data, defaults to colour scheme defined in colours

  • labupleft – str, optional; the label for the upper-left data

  • midleft – Nx3 numpy matrix or list thereof, optional; data plotted in the middle-left axes

  • colmidleft – colour for middle-left data, defaults to colour scheme defined in colours

  • labmidleft – str, optional; the label for the middle-left data

  • downleft – Nx3 numpy matrix or list thereof, optional; data plotted in the lower-left axes

  • coldownleft – colour for lower-left data, defaults to colour scheme defined in colours

  • labdownleft – str, optional; the label for the lower-left data

Returns:

the figure and a list of all axes created

pymule.plot.twopanel(labelx='', upleft=[], labupleft='', colupleft=['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'], downleft=[], labdownleft='', coldownleft=['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'], upright=[], labupright='', colupright=['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'], downright=[], labdownright='', coldownright=['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'], upalign=[], downalign=[])

creates two panel plot, accommodating at most four axes (upper left, upper right, lower left, and lower right). The x axis is naturally shared.

Parameters:
  • labelx – str, optional; label for the x axis

  • upleft – Nx3 numpy matrix or list thereof, optional; data plotted in the upper-left axes

  • colupleft – colour for upper-left data, defaults to colour scheme defined in colours

  • labupleft – str, optional; the label for the upper-left data

  • upright – Nx3 numpy matrix or list thereof, optional; data plotted in the upper-right axes

  • colupright – colour for upper-right data, defaults to colour scheme defined in colours

  • labupright – str, optional; the label for the upper-right data

  • downleft – Nx3 numpy matrix or list thereof, optional; data plotted in the lower-left axes

  • coldownleft – colour for lower-left data, defaults to colour scheme defined in colours

  • labdownleft – str, optional; the label for the lower-left data

  • downright – Nx3 numpy matrix or list thereof, optional; data plotted in the lower-right axes

  • coldownright – colour for lower-right data, defaults to colour scheme defined in colours

  • labdownright – str, optional; the label for the lower-right data

  • upalign – list of two values, optional; align the first and second values of the left and right y axes in the upper panel

  • downalign – list of two values, optional; align the first and second values of the left and right y axes in the lower panel

Returns:

the figure and a list of all axes created

Example:

make a comparison plot between dat and dat_ref as a \(\mathrm{d}\sigma/\mathrm{d}\theta_e\)

>>> fig,(ax1,ax2)=twopanel(
...     r'$\theta_e\,/\,{\rm mrad}$',
...     upleft=[dat, dat_ref],
...     downleft=divideplots(dat, dat_ref),
...     labupleft=r"$\D\sigma/\D\theta_e\,/\,\upmu{\rm b}$",
...     labdownleft=r'$\rm rel. difference$'
... )
pymule.plot.watermark(fig, txt='PRELIMINARY', fontsize=60, rotation=20)

watermarks a figure

Parameters:
  • fig – the figure to watermark

  • txt – str, optional; the watermark text to use

  • fontsize – int, optional; the fontsize of the watermark

  • rotation – int, optional; the angle of the watermark in deg

Example:

Watermark a figure as preliminary

>>> fig = figure()
>>> ...
>>> watermark(fig)

Watermark a figure as incomplete

>>> fig = figure()
>>> ...
>>> watermark(fig, "INCOMPLETE")
pymule.colours.alpha_composite(bg, fg, alpha)

calculates the result of alpha-compositing two colours

Parameters:
  • bf – colour specifier for the background

  • fg – colour specifier for the foreground

  • alpha – float; alpha value

Result:

the resulting colour

pymule.mule.mulify(fig, delx=0, dely=0, col='lightgray', realpha=True)

adds the McMule logo to a figure

Parameters:
  • fig – figure to add the logo

  • delx – float, optional; shift the logo in x direction

  • dely – float, optional; shift the logo in x direction

  • col – colour specifier, optional; colour to use for the logo

  • realpha – bool, optional; whether to re-run the alpha channel

pymule.mpl_axes_aligner.yaxes(ax1, ax2, y1=1, y2=None)

yaxes(ax1, ax2, y=1) changes the limits of ax1 and ax2 to align the values of y on both axis.

yaxes(ax1, y1, ax2, y2) changes the limits of the axis ax1 and ax2 such that the value for y1 on ax1 is aligned to the value of y2 on ax2.

Useful other functions

pymule.compress.uncompress(b)

uncompress(“string”) recovers an expression from a compressed string representation generated by Mathematica’s Compress. Only lists, numbers, and strings are supported. Lists can be nested.

pymule.maths.Li2(x)

Li2(x) returns PolyLog[2, x] for x as a number, a list, or an np.ndarray.

pymule.maths.Li3(x)

Li3(x) returns PolyLog[3, x] for x as a number, a list, or an np.ndarray.