Module Contents

This documentation is automatically generated by scanning all the source code. Parts may be incomplete.

pybdsim - python tool for BDSIM.

Copyright Royal Holloway, University of London 2023.

Module

Description

Builder

Create generic accelerators for BDSIM.

Compare

Comparison of optics between different codes.

Constants

Constants.

Convert

Convert other formats into gmad.

Data

Read the bdsim output formats.

DataUproot

Data loading with uproot instead of pyroot. (optional)

Field

Read and write BDSIM field format files.

Geant4

Dictionary that contains process and subprocess IDs

Gmad

Create bdsim input files - lattices & options.

ModelProcessing

Tools to process existing BDSIM models and generate other versions of them.

Optics

Optical calculation in development. (optional)

Options

Methods to generate bdsim options.

Plot

Some nice plots for data.

Run

Run BDSIM programatically.

Visualisation

Help locate objects in the BDSIM visualisation, requires a BDSIM survey file.

Writer

Write various objects from Builder.

Class

Description

Beam

A beam options dictionary with methods.

XSecBias

A cross-section biasing object.

pybdsim.Beam module

Module containing a similarly named Beam class for creating a BDSIM beam distribution programmatically.

class pybdsim.Beam.Beam(particleType='e-', energy=1.0, distrType='reference', *args, **kwargs)

Bases: dict

ReturnBeamString()
SetDistributionType(distrType='reference')
SetE0(e0=1, unitsstring='GeV')
SetEnergy(energy=1.0, unitsstring='GeV')
SetParticleType(particleType='e-')
SetS0(s0=0, unitsstring='m')
SetT0(t0=0.0, unitsstring='s')
SetX0(x0=0.0, unitsstring='m')
SetXP0(xp0=0.0)
SetY0(y0=0.0, unitsstring='m')
SetYP0(yp0=0.0)
SetZ0(z0=0.0, unitsstring='m')
SetZP0(zp0=0.0)
WriteToFile(filename)

pybdsim.Builder module

Builder

Build generic machines for bdsim. You can create a lattice using one of the predefined simple lattices or by adding many pieces together of your own design. Finally, output the gmad files required.

Classes: Element - beam line element that always has name,type and length Machine - a list of elements

class pybdsim.Builder.Aperture(name, **kwargs)

Bases: GmadObject

A crystal definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.ApertureModel(apertureType='circular', aper1=0.1, aper2=0, aper3=0, aper4=0, warningName='')

Bases: dict

A class that produces the aperture representation of an element. Only non-zero values are written for the aperture parameters. Includes parameter checking.

class pybdsim.Builder.Atom(name, **kwargs)

Bases: GmadObject

A atom definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.BLM(name, **kwargs)

Bases: GmadObject

A blmplacement definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.CavityModel(name, **kwargs)

Bases: GmadObject

A cavitymodel definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

pybdsim.Builder.CreateDipoleDriftRing(filename, ncells=60, circumference=100.0, driftfraction=0.1, samplers='first')

Create a ring composed of dipoles and drifts filename ncells - number of cells, each containing 1 dipole and a drift circumference - in metres driftfraction - the fraction of drift in each cell (0.0 < driftfraction < 1.0) samplers - ‘first’, ‘last’ or ‘all’

pybdsim.Builder.CreateDipoleFodoRing(filename, ncells=60, circumference=200.0, ncellsToMake=None, samplers='first')

Create a ring composed of fodo cells with 2 dipoles per fodo cell.

filename ncells - number of fodo+dipole cells to create circumference - circumference of machine in metres ncellsToMake - number of cells to actually build for part of the machine (None = all) samplers - ‘first’,’last’ or ‘all’

Hard coded to produce the following cell fractions: 50% dipoles 20% quadrupoles 30% beam pipe / drift

pybdsim.Builder.CreateDipoleRing(filename, ndipoles=60, circumference=100.0, samplers='first')

Create a ring composed of only dipoles filename ncells - number of cells, each containing 1 dipole and a drift circumference - in metres samplers - ‘first’, ‘last’ or ‘all’

pybdsim.Builder.CreateFodoLine(filename, ncells=10, driftlength=4.0, magnetlength=1.0, samplers='all', **kwargs)

Create a FODO lattice with ncells.

ncells - number of fodo cells driftlength - length of drift segment in between magnets magnetlength - length of quadrupoles samplers - ‘all’,’first’ or ‘last’ kwargs - kwargs to supply to quadrupole constructor

class pybdsim.Builder.Crystal(name, **kwargs)

Bases: GmadObject

A crystal definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.CrystalCol(name, l, xsize, material, **kwargs)

Bases: Element

class pybdsim.Builder.Decapole(name, l, k4, **kwargs)

Bases: Element

class pybdsim.Builder.Degrader(name, l, nWedges, wedgeLength, degHeight, materialThickness=None, degraderOffset=None, **kwargs)

Bases: Element

class pybdsim.Builder.Drift(name, l, **kwargs)

Bases: Element

class pybdsim.Builder.Dump(name, l, **kwargs)

Bases: Element

class pybdsim.Builder.ECol(name, l, xsize, ysize, **kwargs)

Bases: _Col

class pybdsim.Builder.Element(name, category, isMultipole=False, **kwargs)

Bases: ElementBase

Element - an element / item in an accelerator beamline. Very similar to a python dict(ionary) and has the advantage that built in printing or string conversion provides BDSIM syntax.

Element(name,type,**kwargs)

>>> a = Element("d1", "drift", l=1.3)
>>> b = Element("qx1f", "quadrupole", l=(0.4,'m'), k1=0.2, aper1=(0.223,'m'))
>>> print(b)
qx1f: quadrupole, k1=0.2, l=0.4*m, aper1=0.223*m;
>>> str(c)
qx1f: quadrupole, k1=0.2, l=0.4*m, aper1=0.223*m\n;

A beam line element must ALWAYs have a name, and type. The keyword arguments are specific to the type and are up to the user to specify - these should match BDSIM GMAD syntax.

The value can be either a single string or number or a python tuple where the second entry must be a string (shown in second example). Without specified units, the parser assumes S.I. units.

An element may also be multiplied or divided. This will scale the length and angle appropriately.

>>> c = Element('sb1', 'sbend', l=(0.4,'m'), angle=0.2)
>>> d = c/2
>>> print(d)
sb1: sbend, l=0.2*m, angle=0.1;

This inherits and extends ElementBase that provides the basic dictionary capabilities. It adds the requirement of type / category (because ‘type’ is a protected keyword in python) as well as checking for valid BDSIM types.

classmethod from_element(parent_element_name: str, isMultipole=False, **kwargs)
split(points)

Split this element into len(points)+1 elements, with the correct lengths. This does not affect magnetic strengths, etc, which is left to derived classes where appropriate.

class pybdsim.Builder.ElementBase(name, isMultipole=False, **kwargs)

Bases: MutableMapping

A class that represents an element / item in an accelerator beamline. Printing or string conversion produces the BDSIM syntax.

This class provides the basic dict(ionary) inheritance and functionality and the representation that allows modification of existing parameters of an already declared item.

keysextra()
class pybdsim.Builder.ElementModifier(name, isMultipole=False, **kwargs)

Bases: ElementBase

A class to MODIFY an already defined element in a gmad file by appending an updated definition. Using this alone in BDSIM will result in an undefined type error. This class is particularly useful for creating a strength file.

# define an element >>> a = Element(‘qf1’, ‘quadrupole’, l=0.3, k1=0.00345) >>> b = ElementModifier(‘qf1’,k1=0.0245) >>> f = open(‘mylattice.gmad’, ‘w’) >>> f.write(str(a)) >>> f.write(str(b)) >>> f.close()

cat mylattice.gmad qf1: quadrupole, l=0.3, k1=0.00345; qf1: k1=0.0245;

This results in the quadrupole strength k1 in this example being changed to 0.0245.

class pybdsim.Builder.ExternalGeometry(name, l, geometryFile, **kwargs)

Bases: Element

class pybdsim.Builder.Field(name, **kwargs)

Bases: GmadObject

A field definition. Any kwargs will be written as parameter=value. parameteter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.Gap(name, l, **kwargs)

Bases: Element

pybdsim.Builder.GenerateSamplersFromBDSIMSurvey(surveyfile, outputfilename, excludesamplers=True)

Create a gmad file with samplers for all the elements in a beamline as described by the survey outline from bdsim

bdsim –file=mylattice.gmad –outline=survey.dat –outline_type=survey

excludesamplers - bool - exclude any existing samplers

class pybdsim.Builder.GmadObject(objecttype, name, **kwargs)

Bases: MutableMapping

A gmad object does not have a length unlike every Element hence it needs its own class to produce its representation.

keysextra()
class pybdsim.Builder.HKicker(name, hkick, **kwargs)

Bases: Element

split(points)

Split this element into len(points)+1 elements, with the correct lengths. This does not affect magnetic strengths, etc, which is left to derived classes where appropriate.

class pybdsim.Builder.JCol(name, l, xsize, ysize, **kwargs)

Bases: _Col

class pybdsim.Builder.Kicker(name, hkick, vkick, **kwargs)

Bases: Element

split(points)

Split this element into len(points)+1 elements, with the correct lengths. This does not affect magnetic strengths, etc, which is left to derived classes where appropriate.

class pybdsim.Builder.Laser(name, l, x, y, z, waveLength, **kwargs)

Bases: Element

class pybdsim.Builder.Line(name, *args)

Bases: list

A class that represents a list of Elements

Provides ability to print out the sequence or define all the components.

Example:

>>> d1 = Element("drift1", "drift", l=1.3)
>>> q1 = Element("q1", "quadrupole", l=0.4, k1=4.5)
>>> a = Line([d1,q1])
DefineConstituentElements()

Return a string that contains the lines required to define each element in the Line.

Example using predefined Elements name ‘d1’ and ‘q1’:

>>> l = Line([d1,q1])
>>> f = open("file.txt", "w")
>>> f.write(l.DefineConsituentElements())
>>> f.close()
class pybdsim.Builder.Machine(verbose=False, sr=False, energy0=0.0, charge=-1.0)

Bases: object

A class represents an accelerator lattice as a sequence of components. Member functions allow various lattice components to be append to the sequence of the machine. This class allows the user to programatically create a lattice and write the BDSIM gmad representation of it.

Example:

>>> a = Machine()
>>> a.AddDrift('mydrift', l=1.3)
>>> a.Write("lattice.gmad")

Example with Sychrotron rescaling:

>>> a = Machine(sr=True, energy0=250,charge=-1)
>>> a.AddDipole('sb1','sbend',length=1.0,angle=1e-5)
>>> a.AddDrift('dr1',length=1)
>>> a.AddDipole('sb2','sbend',length=1.0,angle=1e-5)
>>> a.AddDrift("dr2",length=1)

Caution: adding an element of the same name twice will result the element being added only to the sequence again and not being redefined - irrespective of if the parameters are different. If verbose is used (True), then a warning will be issued.

AddBLM(name, **kwargs)
AddBeam(beam=None)

Assign a beam instance to this machine. If no Beam instance is provided, a reference distribution is used.

AddBias(biases)

Add a Builder.XSecBias instance or iterable of instances to this machine.

AddCT(name='ctscan', length=1.0, dicomDataFile='', dicomDataPath='', **kwargs)
AddCrystal(name, **kwargs)
AddCrystalCol(name='cc', length=0.01, xsize=0.001, **kwargs)
AddDecapole(name='dc', length=0.1, k4=0.0, **kwargs)
AddDegrader(length=0.1, name='deg', nWedges=1, wedgeLength=0.1, degHeight=0.1, materialThickness=None, degraderOffset=None, **kwargs)
AddDipole(category='sbend')

category - ‘sbend’ or ‘rbend’ - sector or rectangular bend

AddDrift(name='dr', length=0.1, **kwargs)

Add a drift to the beam line

AddDump(name='du', length=0.1, **kwargs)
AddECol(name='ec', length=0.1, xsize=0.1, ysize=0.1, **kwargs)
AddElement(name='el', length=0.1, geometryFile='geometry.gdml', **kwargs)
AddFodoCell(basename, magnetlength, driftlength, kabs, **kwargs)

basename - the basename for the fodo cell beam line elements magnetlength - length of magnets in metres driftlength - length of drift segment in metres kabs - the absolute value of the quadrupole strength - alternates between magnets

kwargs are other parameters for bdsim - ie material=’Fe’

AddFodoCellMultiple(basename='fodo', magnetlength=1.0, driftlength=4.0, kabs=0.2, ncells=2, **kwargs)
AddFodoCellSplitDrift(basename, magnetlength, driftlength, kabs, nsplits, **kwargs)

basename - the basename for the fodo cell beam line elements magnetlength - length of magnets in metres driftlength - length of drift segment in metres kabs - the absolute value of the quadrupole strength - alternates between magnets nsplits - number of segments drift length is split into

Will add qf quadrupole of strength +kabs, then drift of l=driftlength split into nsplit segments followed by a qd quadrupole of strength -kabs and the same pattern of drift segments.

nsplits will be cast to an even integer for symmetry purposes.

kwargs are other parameters for bdsim - ie aper=0.2

AddFodoCellSplitDriftMultiple(basename='fodo', magnetlength=1.0, driftlength=4.0, kabs=0.2, nsplits=10, ncells=2, **kwargs)
AddGap(name='gp', length=1.0, **kwargs)
AddHKicker(name='hk', hkick=0.0, **kwargs)
AddIncludePost(include)

Add the name of a file (str) that should be included in the main file after others.

AddIncludePre(include)

Add the name of a file (str) that should be included in the main file before others.

AddJCol(name='jc', length=0.1, xsize=0.1, ysize=0.1, **kwargs)
AddKicker(name='kk', hkick=0.0, vkick=0.0, **kwargs)
AddLaser(length=0.1, name='lsr', x=1, y=0, z=0, waveLength=5.32e-07, **kwargs)
AddMarker(name='mk')
AddMaterial(materials)

Add a Builder.Material instance or iterable of instances to this machine.

AddMuSpoiler(name='mu', length=0.1, b=0.0, **kwargs)
AddMultipole(name='mp', length=0.1, knl=(0, 0), ksl=(0, 0), **kwargs)
AddObject(obj)

Add an object or definition to be written to the model. An ‘object’ is a definition that isn’t part of a sequence such as a Field, Crystal, or Placement. Anything that has a string representation can be added to the list.

For an iterable object, tuple, list, and dict are accepted. For a dict, the value (not the key) is added to the internal list without the key.

Objects: Aperture, Atom, BLM, CavityModel, Crystal, Field, Laser, Material, NewColour Placement, Query, Region, SamplerPlacement, Scorer, ScorerMesh, XSecBias.

AddOctupole(name='oc', length=0.1, k3=0.0, **kwargs)
AddOptions(options=None)

Assign an options instance to this machine.

AddPlacement(name, **kwargs)
AddQuadrupole(name='qd', length=0.1, k1=0.0, **kwargs)
AddRBend(name='rb', length=0.1, angle=None, b=None, **kwargs)
AddRCol(name='rc', length=0.1, xsize=0.1, ysize=0.1, **kwargs)
AddRFCavity(name='arreff', length=0.1, gradient=10, **kwargs)
AddRmat(name='rmat', length=0.1, r11=1.0, r12=0, r13=0, r14=0, r21=0, r22=1.0, r23=0, r24=0, r31=0, r32=0, r33=1.0, r34=0, r41=0, r42=0, r43=0, r44=1.0, **kwargs)
AddSBend(name='sb', length=0.1, angle=None, b=None, **kwargs)
AddSampler(names)
AddScorerMesh(name, **kwargs)
AddSextupole(name='sx', length=0.1, k2=0.0, **kwargs)
AddShield(name='sh', length=0.1, **kwargs)
AddSolenoid(name='sl', length=0.1, ks=0.0, **kwargs)
AddTKicker(name='tk', hkick=0.0, vkick=0.0, **kwargs)
AddTarget(name='trg', length=0.1, material='Cu', **kwargs)
AddThinMultipole(name='mp', knl=(0, 0), ksl=(0, 0), **kwargs)
AddThinRmat(name='rmatthin', r11=1.0, r12=0, r13=0, r14=0, r21=0, r22=1.0, r23=0, r24=0, r31=0, r32=0, r33=1.0, r34=0, r41=0, r42=0, r43=0, r44=1.0, **kwargs)
AddTransform3D(name='t3d', **kwargs)
AddUndulator(name='un', length=1.0, b=0, undulatorPeriod=0.1, **kwargs)
AddVKicker(name='vk', vkick=0.0, **kwargs)
AddWireScanner(name='ws', length=0.1, wireDiameter=0.001, wireLength=0.1, **kwargs)
Append(item, addToSequence=True)

Add an element or sequence to the main sequence.

Parameters:
GetIntegratedAngle()

Get the cumulative angle of all the bends in the machine. This is therefore the difference in angle between the entrance and exit vectors. All angles are assumed to be in the horizontal plane so this will not be correct for rotated dipoles.

GetIntegratedLength()

Get the integrated length of all the components.

GetNamesOfType(category)

Returns a list of names of elements that are of the specified category.

InsertAndReplace(newElement, sLocation)

New element will be placed at the central s location.

RegenerateLenInt()
ReplaceElementCategory(category, newcategory)

Change category of all elements of a given category. All parameters of the element being changed will be preserved, please update with the UpdateCategoryParameter function.

ReplaceWithElement(name, newelement, warnAboutLengthDifference=True)

Replace an element in the machine with a new element object (one of the individual element pybdsim.Builder classes that inherit the Element class).

SynchrotronRadiationRescale()

Rescale all component strengths for SR

UpdateCategoryParameter(category, parameter, value)

Update parameter for all elements of a given category.

UpdateElement(name, parameter, value)

Update a parameter for a specified element name. Modifying element length will produce a warning. If a value for that parameter already exists, the value will be overwritten.

UpdateElements(names, parameter, value, namelocation='all')

Update multiple elements. Supplied names can be a sequence type object containing a list of element names or a string where all elements with names containing that string will be updated. namelocation specifies if names string can be at the ‘beginning’, ‘end’, or anywhere (‘all’) in an elements name.

UpdateGlobalParameter(parameter, value)

Update parameter for all elements of a given category.

Write(filename, verbose=False, overwrite=True)

Write the machine to a series of gmad files.

kwargs: overwrite : Do not append an integer to the basefilename if already exists, instead overwrite existing files.

next()
class pybdsim.Builder.Marker(name)

Bases: Element

class pybdsim.Builder.Material(name, **kwargs)

Bases: GmadObject

A material definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.MuSpoiler(name, l, B, **kwargs)

Bases: Element

class pybdsim.Builder.Multipole(name, l, knl, ksl, **kwargs)

Bases: Element

split(points)

Split this element into len(points)+1 elements, with the correct lengths. This does not affect magnetic strengths, etc, which is left to derived classes where appropriate.

class pybdsim.Builder.NewColour(name, **kwargs)

Bases: GmadObject

A newcolour definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.Octupole(name, l, k3, **kwargs)

Bases: Element

class pybdsim.Builder.Placement(name, **kwargs)

Bases: GmadObject

A placement definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

pybdsim.Builder.PrepareApertureModel(rowDictionary, default='circular', warningName='')
class pybdsim.Builder.Quadrupole(name, l, k1, **kwargs)

Bases: Element

class pybdsim.Builder.Query(name, **kwargs)

Bases: GmadObject

A query definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.RBend(name, l, angle=None, B=None, **kwargs)

Bases: _Dipole

class pybdsim.Builder.RCol(name, l, xsize, ysize, **kwargs)

Bases: _Col

class pybdsim.Builder.RFCavity(name, l, gradient, **kwargs)

Bases: Element

class pybdsim.Builder.Region(name, **kwargs)

Bases: GmadObject

A region definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.Rmat(name, l, r11, r12, r13, r14, r21, r22, r23, r24, r31, r32, r33, r34, r41, r42, r43, r44, **kwargs)

Bases: Element

class pybdsim.Builder.SBend(name, l, angle=None, B=None, **kwargs)

Bases: _Dipole

class pybdsim.Builder.Sampler(name)

Bases: object

A sampler is unique in that it does not have a length unlike every Element hence it needs its own class to produce its representation.

class pybdsim.Builder.SamplerPlacement(name, **kwargs)

Bases: GmadObject

A samplerplacement definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.Scorer(name, **kwargs)

Bases: GmadObject

A scorer definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.ScorerMesh(name, **kwargs)

Bases: GmadObject

A scorermesh definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.Sextupole(name, l, k2, **kwargs)

Bases: Element

class pybdsim.Builder.Shield(name, l, **kwargs)

Bases: Element

class pybdsim.Builder.Solenoid(name, l, ks, **kwargs)

Bases: Element

pybdsim.Builder.SuggestFodoK(magnetlength, driftlength)

returns k1 (float) value for matching into next quad in a FODO cell. f = 1/(k1 * magnetlength) = driftlength -> solve for k1

Note the convention in pybdsim.Builder is that the quadrupoles in the fodo cell are split in two. So this is in fact half the integrated k you need. This matches with the other functions in Builder.

class pybdsim.Builder.TKicker(name, hkick, vkick, **kwargs)

Bases: Element

split(points)

Split this element into len(points)+1 elements, with the correct lengths. This does not affect magnetic strengths, etc, which is left to derived classes where appropriate.

class pybdsim.Builder.ThinMultipole(name, knl=(0, 0), ksl=(0, 0), **kwargs)

Bases: Element

class pybdsim.Builder.Transform3D(name, **kwargs)

Bases: Element

class pybdsim.Builder.Tunnel(name, **kwargs)

Bases: GmadObject

A tunnel definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

class pybdsim.Builder.Undulator(name, l, b, undulatorPeriod, **kwargs)

Bases: Element

class pybdsim.Builder.VKicker(name, vkick, **kwargs)

Bases: Element

split(points)

Split this element into len(points)+1 elements, with the correct lengths. This does not affect magnetic strengths, etc, which is left to derived classes where appropriate.

class pybdsim.Builder.WireScanner(name, l, wireDiameter, wireLength, material, **kwargs)

Bases: Element

class pybdsim.Builder.XSecBias(name, **kwargs)

Bases: GmadObject

A xsecbias definition. Any kwargs will be written as parameter=value. parameter=(value,unit) -> parameter=value*unit

pybdsim.Compare

pybdsim.Compare.MadxVsBDSIM(tfs, bdsim, survey=None, functions=None, postfunctions=None, figsize=(10, 5), saveAll=True, outputFileName=None)

Compares MadX and BDSIM optics variables. User must provide a tfsoptIn file or Tfsinstance and a BDSAscii file or instance.

Parameters

Description

tfs

Tfs file or pymadx.Data.Tfs instance.

bdsim

Optics root file (from rebdsimOptics or rebdsim).

survey

BDSIM model survey.

functions

Hook for users to add their functions that are called immediately prior to the addition of the plot. Use a lambda function to add functions with arguments. Can be a function or a list of functions.

figsize

Figure size for all figures - default is (12,5)

pybdsim.Compare.MadxVsBDSIMOrbit(tfs, bds, survey=None, functions=None, postfunctions=None, figsize=(12, 5))

Plot both the BDSIM orbit and MADX orbit (mean x,y).

tfs - either file name or pymadx.Data.Tfs instance bds - filename or BDSAsciiData instance - rebdsimOrbit, rebdsimOptics output files

pybdsim.Compare.BDSIMVsBDSIM(first, second, first_name=None, second_name=None, survey=None, saveAll=True, outputFileName=None, **kwargs)

Display all the optical function plots for the two input optics files.

pybdsim.Compare.TransportVsBDSIM(first, second, first_name=None, second_name=None, survey=None, saveAll=True, outputFileName=None, **kwargs)

Display all the optical function plots for the two input optics files.

pybdsim.Constants module

pybdsim.Constants.GetPDGInd(particlename)
pybdsim.Constants.GetPDGName(particleid)

pybdsim.Convert

Module for various conversions.

pybdsim.Convert.BdsimPrimaries2Mad8(inputfile, outfile, start=0, ninrays=-1)

Takes .root file generated from a BDSIM run an an input and creates a MAD8 inrays file from the primary particle tree.

Parameters:
  • inputfile (str) – root format output from BDSIM run

  • outfile (str) – filename for the inrays file

  • start (int) – starting primary particle index

  • ninrays (int) – total number of inrays to generate

pybdsim.Convert.BdsimPrimaries2Madx(inputfile, outfile, start=0, ninrays=-1)

Takes .root file generated from a BDSIM run an an input and creates a MADX inrays file from the primary particle tree.

Parameters:
  • inputfile (str) – root format output from BDSIM run

  • outfile (str) – filename for the inrays file

  • start (int) – starting primary particle index

  • ninrays (int) – total number of inrays to generate, default is all available

pybdsim.Convert.BdsimPrimaries2Ptc(inputfile, outfile=None, start=0, ninrays=-1)

Takes .root file generated from a BDSIM run an an input and creates a PTC inrays file from the primary particle tree. If no output file name is given, it will be <inputfile>.madx (stripping off the .root).

Parameters:
  • inputfile (str) – root format output from BDSIM run

  • outfile (str) – filename for the inrays file

  • start (int) – starting primary particle index

  • ninrays (int) – total number of inrays to generate (-1 means all)

pybdsim.Convert.MadxTfs2Gmad(tfs, outputfilename, startname=None, stopname=None, stepsize=1, ignorezerolengthitems=True, samplers='all', aperturedict={}, aperlocalpositions={}, collimatordict={}, userdict={}, partnamedict={}, verbose=False, beam=True, flipmagnets=None, usemadxaperture=False, defaultAperture='circular', biases=None, allelementdict={}, optionsdict={}, beamparamsdict={}, linear=False, overwrite=True, write=True, allNamesUnique=False, namePrepend='')

MadxTfs2Gmad convert a madx twiss output file (.tfs) into a gmad tfs file for bdsim

Example:

>>> a,b = pybdsim.Convert.MadxTfs2Gmad('twiss.tfs', 'mymachine')

returns Machine, [omittedItems]

Returns two pybdsim.Builder.Machine instances. The first desired full conversion. The second is the raw conversion that’s not split by aperture. Thirdly, a list of the names of the omitted items is returned.

tfs

path to the input tfs file or pymadx.Data.Tfs instance

outputfilename

requested output file

startname

the name (exact string match) of the lattice element to start the machine at this can also be an integer index of the element sequence number in madx tfs. This item is included in the lattice

stopname

the name (exact string match) of the lattice element to stop the machine at this can also be an integer index of the element sequence number in madx tfs. This item is not included

stepsize

the slice step size. Default is 1, but -1 also useful for reversed line.

ignorezerolengthitems

nothing can be zero length in bdsim as real objects of course have some finite size. Markers, etc are acceptable but for large lattices this can slow things down. True allows to ignore these altogether, which doesn’t affect the length of the machine.

samplers

can specify where to set samplers - options are None, ‘all’, or a list of names of elements (normal python list of strings). Note default ‘all’ will generate separate outputfilename_samplers.gmad with all the samplers which will be included in the main .gmad file - you can comment out the include to therefore exclude all samplers and retain the samplers file.

aperturedict

Aperture information. Can either be a dictionary of dictionaries with the the first key the exact name of the element and the daughter dictionary containing the relevant bdsim parameters as keys (must be valid bdsim syntax). Alternatively, this can be a pymadx.Aperture instance that will be queried.

aperlocalpositions

Dictionary of element indices to local aperture definitions of the form {1: [(0.0, {“APERTYPE”: “CIRCULAR”, “APER1”: 0.4}),

(0.5, {“APERTYPE”: “ELLIPSE”, “APER1”: 0.3, “APER2”: 0.4}), …],

2: […],

} This defines apertures in the element at index 1 starting with a CIRCULAR aper from 0.0m (i.e. the start) before changing to ELLIPSE 0.5m into the element, with possible further changes not displayed above. As the aperture definition in GMAD is tied inseparable from its aperture definition, and vice versa, this conversion function will automatically split the element at the provided local aperture points whilst retaining optical correctness. This kwarg is mutually exclusive with ‘aperturedict’.

collimatordict

A dictionary of dictionaries with collimator information keys should be exact string match of element name in tfs file value should be dictionary with the following keys: ‘bdsim_material’ - the material ‘angle’ - rotation angle of collimator in radians ‘xsize’ - x full width in metres ‘ysize’ - y full width in metres

userdict

A python dictionary the user can supply with any additional information for that particular element. The dictionary should have keys matching the exact element name in the Tfs file and contain a dictionary itself with key, value pairs of parameters and values to be added to that particular element.

partnamedict

A python dictionary of dictionaries. The key is a substring of that should be matched. ie add the parameter ‘vhRatio’ : 1 to all elements with ‘MBVA’ in their name.

verbose

Print out lots of information when building the model.

beam

True | False - generate an input gauss Twiss beam based on the values of the twiss parameters at the beginning of the lattice (startname) NOTE - we thoroughly recommend checking these parameters and this functionality is only for partial convenience to have a model that works straight away.

flipmagnets

True | False - flip the sign of all k values for magnets - MADX currently tracks particles agnostic of the particle charge - BDSIM however, follows the definition strictly - positive k -> horizontal focussing for positive particles therefore, positive k -> vertical focussing for negative particles. Use this flag to flip the sign of all magnets.

usemadxaperture

True | False - use the aperture information in the TFS file if APER_1 and APER_2 columns exist. Will only set if they’re non-zero. Supercedes kwargs aperturedict and aperlocalpositions.

defaultAperture

The default aperture model to assume if none is specified.

biases

Optional list of bias objects to be defined in own _bias.gmad file. These can then be attached either with allelementdict for all components or userdict for individual ones.

allelementdict

Dictionary of parameter/value pairs to be written to all components.

optionsdict

Optional dictionary of general options to be written to the bdsim model options.

beamparamsdict

Optional dictionary of parameters to be passed to the beam.

linear

Only linear optical components

overwrite

Do not append an integer to the base file name if it already exists. Instead overwrite the files.

allNamesUnique

Treat every row in the TFS file/instance as a unique element. This makes it easier to edit individual components as they are guaranteed to appear only once in the entire resulting GMAD lattice.

write

Whether to write the converted machine to file or not.

namePrepend

Optional string prepended to the name of every component.

pybdsim.Convert.MadxTfs2GmadStrength(input, outputfilename, existingmachine=None, verbose=False, flipmagnets=False, linear=False, allNamesUnique=False, ignoreZeroLengthItems=True)

Use a MADX Tfs file containing full twiss information to generate a strength (only) BDSIM GMAD file to be used with an existing lattice.

existingmachine

either a list or dictionary with names of elements to prepare.

flipmagnet

similar behaviour to MAdxTfs2Gmad whether to flip k values for negatively charged particles.

linear

only use linear strengths, k2 and higher set to 0.

pybdsim.Convert._MadxTfs2Gmad.MadxTfs2Gmad(tfs, outputfilename, startname=None, stopname=None, stepsize=1, ignorezerolengthitems=True, samplers='all', aperturedict={}, aperlocalpositions={}, collimatordict={}, userdict={}, partnamedict={}, verbose=False, beam=True, flipmagnets=None, usemadxaperture=False, defaultAperture='circular', biases=None, allelementdict={}, optionsdict={}, beamparamsdict={}, linear=False, overwrite=True, write=True, allNamesUnique=False, namePrepend='')

MadxTfs2Gmad convert a madx twiss output file (.tfs) into a gmad tfs file for bdsim

Example:

>>> a,b = pybdsim.Convert.MadxTfs2Gmad('twiss.tfs', 'mymachine')

returns Machine, [omittedItems]

Returns two pybdsim.Builder.Machine instances. The first desired full conversion. The second is the raw conversion that’s not split by aperture. Thirdly, a list of the names of the omitted items is returned.

tfs

path to the input tfs file or pymadx.Data.Tfs instance

outputfilename

requested output file

startname

the name (exact string match) of the lattice element to start the machine at this can also be an integer index of the element sequence number in madx tfs. This item is included in the lattice

stopname

the name (exact string match) of the lattice element to stop the machine at this can also be an integer index of the element sequence number in madx tfs. This item is not included

stepsize

the slice step size. Default is 1, but -1 also useful for reversed line.

ignorezerolengthitems

nothing can be zero length in bdsim as real objects of course have some finite size. Markers, etc are acceptable but for large lattices this can slow things down. True allows to ignore these altogether, which doesn’t affect the length of the machine.

samplers

can specify where to set samplers - options are None, ‘all’, or a list of names of elements (normal python list of strings). Note default ‘all’ will generate separate outputfilename_samplers.gmad with all the samplers which will be included in the main .gmad file - you can comment out the include to therefore exclude all samplers and retain the samplers file.

aperturedict

Aperture information. Can either be a dictionary of dictionaries with the the first key the exact name of the element and the daughter dictionary containing the relevant bdsim parameters as keys (must be valid bdsim syntax). Alternatively, this can be a pymadx.Aperture instance that will be queried.

aperlocalpositions

Dictionary of element indices to local aperture definitions of the form {1: [(0.0, {“APERTYPE”: “CIRCULAR”, “APER1”: 0.4}),

(0.5, {“APERTYPE”: “ELLIPSE”, “APER1”: 0.3, “APER2”: 0.4}), …],

2: […],

} This defines apertures in the element at index 1 starting with a CIRCULAR aper from 0.0m (i.e. the start) before changing to ELLIPSE 0.5m into the element, with possible further changes not displayed above. As the aperture definition in GMAD is tied inseparable from its aperture definition, and vice versa, this conversion function will automatically split the element at the provided local aperture points whilst retaining optical correctness. This kwarg is mutually exclusive with ‘aperturedict’.

collimatordict

A dictionary of dictionaries with collimator information keys should be exact string match of element name in tfs file value should be dictionary with the following keys: ‘bdsim_material’ - the material ‘angle’ - rotation angle of collimator in radians ‘xsize’ - x full width in metres ‘ysize’ - y full width in metres

userdict

A python dictionary the user can supply with any additional information for that particular element. The dictionary should have keys matching the exact element name in the Tfs file and contain a dictionary itself with key, value pairs of parameters and values to be added to that particular element.

partnamedict

A python dictionary of dictionaries. The key is a substring of that should be matched. ie add the parameter ‘vhRatio’ : 1 to all elements with ‘MBVA’ in their name.

verbose

Print out lots of information when building the model.

beam

True | False - generate an input gauss Twiss beam based on the values of the twiss parameters at the beginning of the lattice (startname) NOTE - we thoroughly recommend checking these parameters and this functionality is only for partial convenience to have a model that works straight away.

flipmagnets

True | False - flip the sign of all k values for magnets - MADX currently tracks particles agnostic of the particle charge - BDSIM however, follows the definition strictly - positive k -> horizontal focussing for positive particles therefore, positive k -> vertical focussing for negative particles. Use this flag to flip the sign of all magnets.

usemadxaperture

True | False - use the aperture information in the TFS file if APER_1 and APER_2 columns exist. Will only set if they’re non-zero. Supercedes kwargs aperturedict and aperlocalpositions.

defaultAperture

The default aperture model to assume if none is specified.

biases

Optional list of bias objects to be defined in own _bias.gmad file. These can then be attached either with allelementdict for all components or userdict for individual ones.

allelementdict

Dictionary of parameter/value pairs to be written to all components.

optionsdict

Optional dictionary of general options to be written to the bdsim model options.

beamparamsdict

Optional dictionary of parameters to be passed to the beam.

linear

Only linear optical components

overwrite

Do not append an integer to the base file name if it already exists. Instead overwrite the files.

allNamesUnique

Treat every row in the TFS file/instance as a unique element. This makes it easier to edit individual components as they are guaranteed to appear only once in the entire resulting GMAD lattice.

write

Whether to write the converted machine to file or not.

namePrepend

Optional string prepended to the name of every component.

pybdsim.Convert._MadxTfs2Gmad.MadxTfs2GmadBeam(tfs, startname=None, verbose=False, extraParamsDict={})

Takes a pymadx.Data.Tfs instance and extracts information from first line to create a BDSIM beam definition in a pybdsim.Beam object. Note that if kwarg startname is used, the optics are retrieved at the start of the element, i.e. you do not need to get the optics of the previous element, this function does that automatically.

Works for e+, e- and proton. Default emittance is 1e-9mrad if 1 in tfs file.

pybdsim.Convert._MadxTfs2Gmad.ZeroMissingRequiredColumns(tfsinstance)

Sets any missing required columns to zero. Warns user when doing so.

pybdsim.Data module

Output loading

Read bdsim output

Classes: Data - read various output files

class pybdsim.Data.ApertureInfo(apertureType, aper1, aper2=0, aper3=0, aper4=0, offsetX=0, offsetY=0)

Bases: object

Simple class to hold aperture parameters and extents.

class pybdsim.Data.BDSAsciiData(*args, **kwargs)

Bases: list

General class representing simple 2 column data.

Inherits python list. It’s a list of tuples with extra columns of ‘name’ and ‘units’.

ConcatenateMachine(*args)

Add 1 or more data instances to this one - suitable only for things that could be loaded by this class. Argument can be one or iterable. Either of str type or this class.

Filter(booleanarray)

Filter the data with a booleanarray. Where true, will return that event in the data.

Return type is BDSAsciiData

GetColumn(columnstring, ignoreCase=False)

Return a numpy array of the values in columnstring in order as they appear in the beamline

GetItemTuple(index)

Get a specific entry in the data as a tuple of values rather than a dictionary.

IndexFromNearestS(S)

return the index of the beamline element clostest to S

Only works if “SStart” column exists in data

MatchValue(parametername, matchvalue, tolerance)

This is used to filter the instance of the class based on matching a parameter withing a certain tolerance.

>>> a = pybdsim.Data.Load("myfile.txt")
>>> a.MatchValue("S",0.3,0.0004)

this will match the “S” variable in instance “a” to the value of 0.3 within +- 0.0004.

You can therefore used to match any parameter.

Return type is BDSAsciiData

NameFromNearestS(S)
ToDF()

Get this BDSAsciiData instance as a pandas.DataFrame instance.

class pybdsim.Data.BDSBH4D(hist, extractData=True)

Bases: object

Wrapper for a BDSBH instance. Converts to numpy data.

ErrorsToErrorOnMean()

Errors are by default the error on the mean. However, if you used ErrorsToSTD, you can convert back to error on the mean with this function, which divides by sqrt(N).

ErrorsToSTD()

Errors are by default the error on the mean. Call this function to multiply by sqrt(N) to convert to the standard deviation. Will automatically only apply itself once even if repeatedly called.

class pybdsim.Data.BeamData(data)

Bases: object

classmethod FromROOTFile(path)
GetBeamEnergy()
class pybdsim.Data.CavityInfo(rootInstance=None)

Bases: object

Simple class to represent a cavity info instance. Construct from a root instance of the class.

pybdsim.Data.CheckBdsimDataHasSurveyModel(bfile)
pybdsim.Data.CheckItsBDSAsciiData(bfile, requireOptics=False)
class pybdsim.Data.CollimatorInfo(rootInstance=None)

Bases: object

Simple class to represent a collimator info instance. Construct from a root instance of the class.

pybdsim.Data.CombinePickledHistogram1DSets(globPattern='*.dat', nCPUs=1)
Parameters:
  • globPattern (str) – pattern of files to gather together to merge.

  • nCPUS (int) – number of cpus / processes to use for parallelising this - to be finished.

Gather a set of files. Assume they each contain 1x pickled (binary) Histogram1DSet instance and accumulate them all. Returns the total object.

pybdsim.Data.CreateEmptyRebdsimFile(outputFileName, nOriginalEvents=1)

Create an empty rebdsim format file with the layout of folders. Returns the ROOT.TFile object.

class pybdsim.Data.EventInfoData(data)

Bases: object

Extract data from the Info branch of the Event tree.

classmethod FromROOTFile(path)
class pybdsim.Data.EventSummaryData(data)

Bases: EventInfoData

Extract data from the Summary branch of the Event tree.

pybdsim.Data.GetApertureExtent(apertureType, aper1=0, aper2=0, aper3=0, aper4=0)
pybdsim.Data.GetFileName(ob)
pybdsim.Data.GetHistoryPDGTuple(trajectories, startingTrajectoryStorageIndex, reduceDuplicates=False)

Return a tuple of PDG IDs for the history of a particle given by trajectories in an event.

Parameters:
  • trajectories (event.Trajectory) – event.Trajectory instance from loaded ROOT data

  • startingTrajectoryStorageIndex (int) – storage index of which trajectory to start from

  • reduceDuplicates (bool) – whether to remove sequential duplicates from the history

>>> d = pybdsim.Data.Load("somdbdsimoutputfile.root")
>>> et = d.GetEventTree()
>>> for event in et:
        tid = event.sampler1.trackID[0]
        history = pybdsim.Data.GetHistoryPDGTuple(event.Trajectory, tid)
        print(history)

An example might be (13,211,211,2212) or with reducedDuplicates (31,211,2212)

Note, this will raise an IndexError if you haven’t stored the right trajectories. and must be used knowing that the connected trajectories for a given starting trackID are stored.

pybdsim.Data.GetModelForPlotting(rootFile, beamlineIndex=0)

Returns BDSAsciiData object with just the columns from the model for plotting.

pybdsim.Data.GetNEventsInBDSIMFile(filename)

Utility function to extract the number of events in a file quickly without fully loading it. Uses only ROOT to inspect the tree. Will raise an IOError exception if no Event tree is found. No check if it’s a BDSIM format file or not.

class pybdsim.Data.Header(**kwargs)

Bases: object

A simple Python version of a header in a (RE)BDSIM file for easy access to the data.

class pybdsim.Data.Histogram1DSet(name=None)

Bases: object

Basic histogram for a categorical axis with a dict / map as the storage.

This is completely agnostic of the type of the value used as the axis.

It is ultimately a python dict[key] = (value, sumWeightsSq) where ‘key’ is the ‘x’ used to file the histogram.

The bin errors can be accessed by calling Result() to return a dictionary of key : (value, error)

h = Histogram1DSet(“PDG_ID”) h.Fill(2212) h.Fill(-13)

Histograms can be merged with the += operator:

h2 = Histogram1DSet() h2.Fill(2212) h2.Fill(13)

h2 += h1

Fill(x, weight=1.0)
Flush()

Empy the bins and set the number of entries to 0.

Result()

return a dictionary of key : (value, error)

value is the bin value. error is calculated as sqrt(sum(weights^2)/n) for the sum of the weights squared in an individual bin.

ResultMean()

return a dictionary of key : (mean, error)

mean is the bin value / n error is calculated as sqrt(1/n * sum(weights^2)/n) for the sum of the weights squared in an individual bin.

SortByBin()
pybdsim.Data.IsSurvey(file)

Checks if input is a BDSIM generated survey

pybdsim.Data.Load(filepath)

Load the data with the appropriate loader.

ASCII file - returns BDSAsciiData instance. BDSIM file - uses ROOT, returns BDSIM DataLoader instance. REBDSIM file - uses ROOT, returns RebdsimFile instance.

pybdsim.Data.LoadPickledObject(filename)

Unpickle an object. If the name contains .pbz2 the bz2 library will be used as well to load the compressed pickled object.

pybdsim.Data.LoadROOTLibraries()

Load root libraries. Only works once to prevent errors.

pybdsim.Data.LoadSDDSColumnsToDict(filename)

Load columns from an SDDS file, e.g. twiss output.

filename - str - path to file

returns dict{columnname:1d numpy array}

class pybdsim.Data.ModelData(data)

Bases: object

A python versio of the data held in a Model tree in BDSIM output.

d = pybdsim.Data.Load(“output.root”) md = pybdsim.Data.ModelData(d)

Extracts this from a bdsim output file.

classmethod FromROOTFile(path)
GetApertureData(removeZeroLength=False, removeZeroApertures=True, lengthTolerance=1e-06)

return a list of aperture instances along with coordinates: l,s,x,y,apertures l - length of element s - curvilinear S coordinate at the end of the element x - horizontal extent y - vertical extent apertures = [ApertureInfo]

PrepareAxisAngleRotations()
class pybdsim.Data.OptionsData(data)

Bases: object

classmethod FromROOTFile(path)
pybdsim.Data.PadHistogram1D(hist, padValue=1e-20)

Pad a 1D histogram with padValue.

This adds an extra ‘bin’ to xwidths, xcentres, xlowedge, xhighedge, contents and errors with either pad value or a linearly interpolated step in the range (i.e. for xcentres).

returns a new pybdsim.Data.TH1 instance.

pybdsim.Data.ParseSpectraName(hname)
class pybdsim.Data.PhaseSpaceData(data, samplerIndexOrName=0)

Bases: _SamplerData

Pull phase space data from a loaded DataLoader instance of raw data for all events.

Extracts only: ‘x’,’xp’,’y’,’yp’,’z’,’zp’,’energy’,’T’

Can either supply the sampler name or index as the optional second argument. The index is 0 counting including the primaries (ie +1 on the index in data.GetSamplerNames()). Examples:

>>> f = pybdsim.Data.Load("file.root")
>>> primaries = pybdsim.Data.PhaseSpaceData(f)
>>> samplerfd45 = pybdsim.Data.PhaseSpaceData(f, "samplerfd45")
>>> thirdAfterPrimaries = pybdsim.Data.PhaseSpaceData(f, 3)
pybdsim.Data.PickleObject(ob, filename, compress=True)

Write an object to a pickled file using Python pickle.

If compress is True, the bz2 package will be imported and used to compress the file.

class pybdsim.Data.ROOTHist(hist)

Bases: object

Base class for histogram wrappers.

ErrorsToErrorOnMean()

Errors are by default the error on the mean. However, if you used ErrorsToSTD, you can convert back to error on the mean with this function, which divides by sqrt(N).

ErrorsToSTD()

Errors are by default the error on the mean. Call this function to multiply by sqrt(N) to convert to the standard deviation. Will automatically only apply itself once even if repeatedly called.

class pybdsim.Data.RebdsimFile(filename, convert=True, histogramsOnly=False)

Bases: object

Class to represent data in rebdsim output file.

Parameters:
  • filename (str) – File to load

  • convert (bool) – Whether to ROOT histograms to pybdsim ones as well

  • histogramsOnly (bool) – If true, then don’t load rebdsim libraries and only load histograms.

Contains histograms as root objects. Conversion function converts to pybdsim.Rebdsim.THX classes holding numpy data.

If optics data is present, this is loaded into self.Optics which is BDSAsciiData instance.

If convert=True (default), root histograms are automatically converted to classes provided here with numpy data.

If histogramsOnly is true, only the basic ROOT libraries are needed (i.e. import ROOT) and no Model data will be loaded - only ROOT histograms.

ConvertToPybdsimHistograms()

Convert all root histograms into numpy arrays.

GetModel()
GetModelTree()
ListOfDirectories()

List all directories inside the root file.

ListOfLeavesInTree(tree)

List all leaves in a tree.

ListOfTrees()

List all trees inside the root file.

pybdsim.Data.ReplaceZeroWithMinimum(hist, value=1e-20)

Replace zero values with given value. Useful for log plots.

For log plots we want a small but +ve number instead of 0 so the line is continuous on the plot. This is also required for padding to work for the edge of the lines.

Works for TH1, TH2, TH3.

returns a new instance of the pybdsim.Data.TH1, TH2 or TH3.

pybdsim.Data.SDDSBuildParameterDicts(sddsColumnDict)

Use first the LoadSDDSColumnsToDict on a parameters file. Then call this function to sort it into ElementName : {ParameterName:ParameterValue}. An extra key will be added that is KEYWORD for the ElementType in the inner dictionary.

class pybdsim.Data.SamplerData(data, samplerIndexOrName=0)

Bases: _SamplerData

Pull sampler data from a loaded DataLoader instance of raw data for all events.

Loads all data in a given sampler.

Can either supply the sampler name or index as the optional second argument. The index is 0 counting including the primaries (ie +1 on the index in data.GetSamplerNames()). Examples:

>>> f = pybdsim.Data.Load("file.root")
>>> primaries = pybdsim.Data.SamplerData(f)
>>> samplerfd45 = pybdsim.Data.SamplerData(f, "samplerfd45")
>>> thirdAfterPrimaries = pybdsim.Data.SamplerData(f, 3)
pybdsim.Data.SkimBDSIMFile(inputFileName, filterFunction, outputFileName=None)

Skim a raw BDSIM file with a custom filter function.

Parameters:
  • inputFileName (str) – raw input BDSIM file to skim.

  • filterFunction (function) – a function of form bool Function(event)

  • outputFileName (None, str) – optional specific output file name to write to.

If no outputFileName is given, then it will be inputFileName_skim.root.

The function must accept a single argument that will be the event. This variable will have the layout of the event exactly as you see it in a TBrowser (e.g. event.PrimaryLastHit.x[0] could be used. It should return a Boolean True or False whether that event should be included in the output skim file.

class pybdsim.Data.Spectra(nameIn=None)

Bases: object

append(pdgid, hist, path, nameIn=None, flag=None)
pop(pdgid, flag='n')

Remove a pdgid from the spectra - perhaps to filter before plotting.

class pybdsim.Data.TH1(hist, extractData=True)

Bases: ROOTHist

Wrapper for a ROOT TH1 instance. Converts to numpy data.

>>> h = file.Get("histogramName")
>>> hpy = TH1(h)
Integrate(xLow=None, xHigh=None)

Integrate the histogram based on coordinates (not bins). The default is to return the integral of the whole histogram.

returns the integral,error

IntegrateFromBins(startBin=None, endBin=None)

Calculate the integral from start bin index to end bin index in ROOT’s TH1D bin numbering scheme (usually 1 is the first bin and 0 is the underflow). If left empty, they will integrate the whole range.

returns the integral,error

Rebin(nBins)
class pybdsim.Data.TH2(hist, extractData=True)

Bases: TH1

Wrapper for a ROOT TH2 instance. Converts to numpy data.

>>> h = file.Get("histogramName")
>>> hpy = TH2(h)
IntegrateAlongX()

Integrate along the x axis returning a TH1 in y.

IntegrateAlongY()

Integrate along the y axis returning a TH1 in x.

Rebin(nBinsX, nBinsY=None)
SwapAxes()

Swap X and Y for all members. Returns a new copy of the histogram.

class pybdsim.Data.TH3(hist, extractData=True)

Bases: TH2

Wrapper for a ROOT TH3 instance. Converts to numpy data.

>>> h = file.Get("histogramName")
>>> hpy = TH3(h)
IntegateAlong1Dimension(dimension)

Integrate along a dimension returning a new 2D histogram.

Parameters:

dimension (str) – ‘x’, ‘y’ or ‘z’ dimension to integrate along

returns pybdsim.Data.TH2 instance.

If the projection is done in z, a 2D histogram of x,y is returned that is the sum of the bins along z. The errors are also calculated.

For ‘x’, the 2D histogram is z,y. For ‘y’, the 2D histogram is z,x. For ‘z’, the 2D hsitogram is x,y.

IntegateAlong2Dimensions(resultDimension)

Integrate along 2 dimensions returning a new 1D histogram along the result dimension

Parameters:

resultDimension (str) – ‘x’, ‘y’ or ‘z’ dimension to produce 1D histogram along.

returns pybdsim.Data.TH1 instance.

Slice2DXY(index)

Extract a single 2D histogram from an index along the Z dimension.

Parameters:

index (int) – index in z array of bins to extract, e.g. 0 -> nbinsz-1

Slice2DXZ(index)

Extract a single 2D histogram from an index along the Y dimension.

Parameters:

index (int) – index in y array of bins to extract, e.g. 0 -> nbinsy-1

Slice2DZY(index)

Extract a single 2D histogram from an index along the X dimension.

Parameters:

index (int) – index in x array of bins to extract, e.g. 0 -> nbinsx-1

WriteASCII(filename, scalingFactor=1.0, comments=None)

Write the contents to a text file. Optionally multiply contents by a numerical factor.

Adds the histogram name (self.name) to the filename, e.g. filename-name.dat. Returns name that was built up.

Parameters:
  • filename (str) – output name to write to - can optionally include .dat suffix.

  • scalingFactor (float) – numerical factor to multiply all contents by on writing out only.

  • comments (list(str)) – list of comments to be written at the top of the file.

pybdsim.Data.TRotationToAxisAngle(trot)

This will return a list of [Ax,Ay,Az,angle] from a ROOT.TRotation.

If not imported, it will return [0,0,0,0]

class pybdsim.Data.TrajectoryData(dataLoader, eventNumber=0)

Bases: object

Pull trajectory data from a loaded Dataloader instance of raw data

Loads all trajectory data in a event event

>>> f = pybdsim.Data.Load("file.root")
>>> trajectories = pybdsim.Data.TrajectoryData(f,0)
next()
pybdsim.Data.WriteROOTHistogramsToDirectory(tfile, directoryName, histograms)
Parameters:
  • tfile (ROOT.TFile.) – TFile object to write to.

  • directoryName (str (e.g. "Event/PerEntryHistograms" )) – Full path of directory you wish to write the histograms to.

  • histograms ([ROOT.TH1,..]) – List of ROOT histograms to write.

Write a list of histograms (ROOT.TH*) to a directory (str) in a ROOT.TFile instance.

pybdsim.Field module

Utilities to convert and prepare field maps.

Most of the plots assume magnetic fields for the labels, but they work equally well for electric fields.

class pybdsim.Field._Field.Field(array=array([], dtype=float64), columns=[], flip=False, doublePrecision=False)

Bases: object

Base class used for common writing procedures for BDSIM field format.

This does not support arbitrary loop ordering - only the originally intended xyzt.

AddComment(commentString)

Add a string that will be put on a comment line at the beginning of the file.

Write(fileName, writeLoopOrderReversed=False, overrideLoopOrder=None)
Parameters:
  • writeLoopOrderReversed (bool) – Write this field map with the other loop order.

  • overrideLoopOrder (str) – string to write irrespective of internal data as the loop order.

gzip - if the file ends with “.gz” the file will be compressed automatically.

For overrideLoopOrder it should be only ‘xyzt’ or ‘tzyx’. This option is provided in case a field is prepared in the other order somehow and you want to control the writing of this header variable independently.

WriteFLUKA2DFormat1(fileName)

Write one of the FLUKA formats (x,y,Bx,by) in cm,T with no header.

Very simple and only works for Field2D - can be improved.

WriteMGNDataCard(fileName, name='magnet', symmetry='0.0')
Parameters:
  • fileName (str) – Name of file to write the fieldmap to.

  • name (str) – Name of the magnetic field in the MGNCREAT card.

  • symmetry (str) – Symmetry that gets applied to the fieldmap inside FLUKA.

Write 2D field maps stored in Field2D to FLUKA format which can be loaded with MGN data cards. Therefore, we create a magnet which is purely based on a fieldmap (200.0) without offsetting it, as (0,0) in the fieldmap is, where the beam is (and it’s only used for analytical fields). The symmetry needs to be specified in accordance to Sx + Sy*10 + Sz*100, for example for a quadrupole it’s 12.0 and for a C-shaped bend it’s 10.0. 0.0 means no symmetry. In the final file, one can see three field points per MGNDATA card without specifying the location, as this is given by the grid definition. In the file, the points need to go from low x and y to high x and y, with looping first over y and then x.

class pybdsim.Field._Field.Field1D(data, doublePrecision=False, column='X')

Bases: Field

Utility class to write a 1D field map array to BDSIM field format.

The array supplied should be 2 dimensional. Dimensions are: (x,value) where value has 4 elements [x,fx,fy,fz]. So a 120 long array would have np.shape of (120,4).

This can be used for both electric and magnetic fields.

Example:

>>> a = Field1D(data)
>>> a.Write('outputFileName.dat')
class pybdsim.Field._Field.Field2D(data, flip=False, doublePrecision=False, firstColumn='X', secondColumn='Y')

Bases: Field

Utility class to write a 2D field map array to BDSIM field format.

The array supplied should be 3 dimensional. Dimensions are: (x,y,value) where value has 5 elements [x,y,fx,fy,fz]. So a 100x50 (x,y) grid would have np.shape of (100,50,5).

Example:

>>> a = Field2D(data) # data is a prepared array
>>> a.Write('outputFileName.dat')

The ‘flip’ boolean allows an array with (y,x,value) dimension order to be written as (x,y,value). Values must still be (x,y,fx,fy,fz).

The ‘doublePrecision’ boolean controls whether the field and spatial values are written to 16 s.f. (True) or 8 s.f. (False - default).

class pybdsim.Field._Field.Field3D(data, flip=False, doublePrecision=False, firstColumn='X', secondColumn='Y', thirdColumn='Z')

Bases: Field

Utility class to write a 3D field map array to BDSIM field format.

The array supplied should be 4 dimensional. Dimensions are: (x,y,z,value) where value has 6 elements [x,y,z,fx,fy,fz]. So a 100x50x30 (x,y,z) grid would have np.shape of (100,50,30,6).

Example:

>>> a = Field3D(data) # data is a prepared array
>>> a.Write('outputFileName.dat')

The ‘flip’ boolean allows an array with (z,y,x,value) dimension order to be written as (x,y,z,value). Values must still be (x,y,fx,fy,fz).

The ‘doublePrecision’ boolean controls whether the field and spatial values are written to 16 s.f. (True) or 8 s.f. (False - default).

class pybdsim.Field._Field.Field4D(data, flip=False, doublePrecision=False)

Bases: Field

Utility class to write a 4D field map array to BDSIM field format.

The array supplied should be 5 dimensional. Dimensions are: (t,y,z,x,value) where value has 7 elements [x,y,z,t,fx,fy,fz]. So a 100x50x30x10 (x,y,z,t) grid would have np.shape of (10,30,50,100,7).

Example:

>>> a = Field4D(data) # data is a prepared array
>>> a.Write('outputFileName.dat')

The ‘flip’ boolean allows an array with (t,z,y,x,value) dimension order to be written as (x,y,z,t,value). Values must still be (x,y,fx,fy,fz).

The ‘doublePrecision’ boolean controls whether the field and spatial values are written to 16 s.f. (True) or 8 s.f. (False - default).

pybdsim.Field._Field.Load(filename, debug=False)
Parameters:

filename (str) – name of file to load

Load a BDSIM field format file into a numpy array. Can either be a regular ascii text file or can be a compressed file ending in “.tar.gz”.

returns a numpy array with the corresponding number of dimensions and the dimension has the coordinates and fx,fy,fz.

pybdsim.Field._Field.MirrorDipoleQuadrant1(field2D)

2

1

3

4

Parameters:

field2D (pybdsim.Field._Field.Field2D instance) – field object

returns an instance of the same type.

For a 2D field (i.e. function of x,y but can include Bx,By,Bz), for the quadrant number 1, mirror it and generate a bigger field for all four quadrants.

  1. original data

  2. data mirrored in x, (x,Bx) *= -1

  3. data mirrored in x,y, (x,y,By) *= -1

  4. data mirrored in y, (y,Bx) *= -1

This is based on a dipole field.

pybdsim.Field._Field.SortUnorderedFieldMap2D(field)

Rearrange the data in a 2D field map to be in a linearly progressing loop of (x,y). In future this could be generalised to more dimensions and also any two dimensions, not just x,y.

Parameters:

field (pybdsim.Field.Field2D) – Incoming jumbled field map

Returns a new Field2D object

class pybdsim.Field.FieldPlotter.FourDData(filename, xind=0, yind=1, zind=2, tind=3)

Class purely to simplify plotting of fields. Not for general use.

class pybdsim.Field.FieldPlotter.OneDData(filename)

Class purely to simplify plotting of fields. Not for general use.

pybdsim.Field.FieldPlotter.Plot1DFxFyFz(filename)

Plot a bdsim 1D field map file.

Parameters:

filename (str, pybdsim.Field._Field.Field1D instance) – name of the field map file or object

pybdsim.Field.FieldPlotter.Plot2D(filename, scale=None, title=None, flipX=False, flipY=False, firstDimension='X', secondDimension='Y', aspect='equal')

Plot a bdsim field map file using any two planes. The corresponding field components are plotted (e.g. X:Z -> Fx:Fz).

Parameters:
  • filename (str, pybdsim.Field._Field.Field2D instance) – name of field map file or object

  • scale (float) – numerical scaling for quiver plot arrow lengths.

  • title (str) – title for plot

  • flipX (bool) – whether to plot x backwards to match the right hand coordinate system of Geant4.

  • firstDimension (str) – Name of first dimension, e.g. “X”

  • secondDimension (str) – Name of second dimension, e.g. “Z”

  • aspect (str) – Matplotlib axes aspect (e.g. ‘auto’ or ‘equal’)

pybdsim.Field.FieldPlotter.Plot2DXY(filename, scale=None, title=None, flipX=False, firstDimension='X', secondDimension='Y', aspect='equal', figsize=(6, 5))

Plot a bdsim field map file using the X,Y plane.

Parameters:
  • filename (str, pybdsim.Field._Field.Field2D instance) – name of field map file or object

  • scale (float) – numerical scaling for quiver plot arrow lengths.

  • title (str) – title for plot

  • flipX (bool) – whether to plot x backwards to match the right hand coordinate system of Geant4.

  • firstDimension (str) – Label of first dimension, e.g. “X”

  • secondDimension (str) – Label of second dimension, e.g. “Z”

  • aspect (str) – Matplotlib axes aspect (e.g. ‘auto’ or ‘equal’)

pybdsim.Field.FieldPlotter.Plot2DXYBx(filename, scale=None, title=None, flipX=False, aspect='equal')

Plot a bdsim field map file use the X,Y plane, but plotting By component.

Parameters:
  • filename (str, pybdsim.Field._Field.Field2D instance) – name of field map file or object

  • scale (float) – numerical scaling for quiver plot arrow lengths.

  • title (str) – title for plot

  • aspect (str) – Matplotlib axes aspect (e.g. ‘auto’ or ‘equal’)

pybdsim.Field.FieldPlotter.Plot2DXYBy(filename, scale=None, title=None, flipX=False, aspect='equal')

Plot a bdsim field map file use the X,Y plane, but plotting By component.

Parameters:
  • filename (str, pybdsim.Field._Field.Field2D instance) – name of field map file or object

  • scale (float) – numerical scaling for quiver plot arrow lengths.

  • title (str) – title for plot

  • aspect (str) – Matplotlib axes aspect (e.g. ‘auto’ or ‘equal’)

pybdsim.Field.FieldPlotter.Plot2DXYBz(filename, scale=None, title=None, flipX=False, aspect='equal')

Plot a bdsim field map file use the X,Y plane, but plotting By component.

Parameters:
  • filename (str, pybdsim.Field._Field.Field2D instance) – name of field map file or object

  • scale (float) – numerical scaling for quiver plot arrow lengths.

  • title (str) – title for plot

  • aspect (str) – Matplotlib axes aspect (e.g. ‘auto’ or ‘equal’)

pybdsim.Field.FieldPlotter.Plot2DXYComponent(filename, componentIndex=2, scale=None, title=None, flipX=False, aspect='equal')

Plot a bdsim field map file use the X,Y plane, but plotting By component.

Parameters:
  • filename (str, pybdsim.Field._Field.Field2D instance) – name of field map file or object

  • componentIndex (int) – index of field component (0,1,2) for Fx, Fy, Fz

  • scale (float) – numerical scaling for quiver plot arrow lengths.

  • title (str) – title for plot

  • aspect (str) – Matplotlib axes aspect (e.g. ‘auto’ or ‘equal’)

pybdsim.Field.FieldPlotter.Plot2DXYConnectionOrder(filename)

Plot a point in orange and a line in blue (default matplotlib colours) for each location in the field map. If the field map is constructed correctly, this should show a set of lines with diagonals between them. The other plots with the arrows are independent of order unlike when BDSIM loads the fields. So you might see an OK field map, but it could be wrong if handwritten.

pybdsim.Field.FieldPlotter.Plot2DXYFxFyFz(filename, title=None, aspect='auto', extent=None, **imshowKwargs)

Plot Fx,Fy,Fz components of a field separately as a function of X,Y.

Parameters:
  • filename (str, pybdsim.Field._Field.Field1D instance) – name of field map file or object

  • title (None, str) – optional title for plot

  • aspect (str) – aspect ratio for matplotlib imshow

  • extent (list,tuple) – list or tuple of (xmin,xmax,ymin,ymax) for each plot (optional)

pybdsim.Field.FieldPlotter.Plot2DXYMagnitude(filename, title=None, flipX=False, firstDimension='X', secondDimension='Y', aspect='equal', zlabel='|$B_{x,y}$| (T)', figsize=(6, 5))

Plot a the magnitude of a 2D bdsim field map file using any two planes.

Parameters:
  • filename (str, pybdsim.Field._Field.Field2D instance) – name of field map file or object

  • title (str, None) – title for plot

  • flipX (bool) – whether to plot x backwards to match the right hand coordinate system of Geant4.

  • firstDimension (str) – Name of first dimension, e.g. “X”

  • secondDimension (str) – Name of second dimension, e.g. “Z”

  • aspect (str) – Matplotlib axes aspect (e.g. ‘auto’ or ‘equal’)

  • zlabel (str) – Label for colour bar

pybdsim.Field.FieldPlotter.Plot2DXYStream(filename, density=1, zIndexIf3D=0, useColour=True, aspect='equal')

Plot a bdsim field map file using the X,Y plane as a stream plot and plotting Fx, Fy.

Parameters:
  • filename (str, pybdsim.Field._Field.Field2D or Field3D instance) – name of field map file or object

  • density (float) – arrow density (default=1) for matplotlib streamplot

  • zIndexIf3D (int) – index in Z if using 3D field map (default=0)

  • useColour (bool :param aspect: Matplotlib axes aspect (e.g. 'auto' or 'equal')) – use magnitude of field as colour.

Note, matplotlibs streamplot may raise an exception if the field is entriely 0 valued.

pybdsim.Field.FieldPlotter.Plot2DXZStream(filename, density=1, yIndexIf3D=0, useColour=True, aspect='equal')

Plot a bdsim field map file using the X,Z plane as a stream plot and plotting Fx, Fz.

Parameters:
  • filename (str, pybdsim.Field._Field.Field2D or Field3D instance) – name of field map file or object

  • density (float) – arrow density (default=1) for matplotlib streamplot

  • yIndexIf3D (int) – index in Z if using 3D field map (default=0)

  • useColour (bool) – use magnitude of field as colour.

  • aspect (str) – Matplotlib axes aspect (e.g. ‘auto’ or ‘equal’)

Note, matplotlibs streamplot may raise an exception if the field is entriely 0 valued.

pybdsim.Field.FieldPlotter.Plot3DXY(filename, scale=None)

Plots (B_x,B_y) as a function of x and y.

pybdsim.Field.FieldPlotter.Plot3DXZ(filename, scale=None)

Plots (B_x,B_z) as a function of x and z.

class pybdsim.Field.FieldPlotter.ThreeDData(filename)

Class purely to simplify plotting of fields. Not for general use.

class pybdsim.Field.FieldPlotter.TwoDData(filename)

Class purely to simplify plotting of fields. Not for general use.

pybdsim.Gmad module

Survey() - survey a gmad lattice, plot element coords
Loader() - load a gmad file using the compiled bdsim parser
GmadFile() - modify a text based gmad file
class pybdsim.Gmad.GmadFile(fileName)

Bases: object

Class to determine parameters and gmad include structure

class pybdsim.Gmad.GmadFileBeam(fileName)

Bases: object

Class to load a gmad options file to a buffer and modify the contents

class pybdsim.Gmad.GmadFileComponents(fileName)

Bases: object

Class to load a gmad components file to a buffer and modify the contents

Example : python> g = pybdsim.Gmad.GmadFileComponents(“./atf2_components.gmad”) python> g.change(“KEX1A”,”l”,”10”) python> g.write(“./atf2_components.gmad”)

change(element, parameter, value)

Edit element dictionary

elementNames()

Make a list of element names, stored in self.elementNameList

findElement(elementName)

Returns the start and end (inclusive location of the element lines as a tuble (start,end)

getParameter(element, parameter)

Edit element dictionary

getType(element)
parseElement(elementString)

Create element dictionary from element

write(fileName)
class pybdsim.Gmad.GmadFileOptions(fileName)

Bases: object

Class to load a gmad options file to a buffer and modify the contents

class pybdsim.Gmad.Lattice(filename=None)

Bases: object

BDSIM Gmad parser lattice.

Use this class to load a bdsim input file using the BDSIM parser (GMAD) and then interrogate it. You can use this to regenerate a lattice with less information for example

>>> a = Lattice("filename.gmad")

or

>>> a = Lattice()
>>> a.Load("filename.gmad")
>>> a  # this will tell you some basic details
>>> print(a) # this will print out the full lattice
GetAllNames()
GetAngle(index)
GetAper1(index)
GetAper2(index)
GetAper3(index)
GetAper4(index)
GetApertureExtents()
GetApertureType(index)
GetColumn(column)
GetElement(i)
GetIndexOfElementNamed(elementname)
GetKs(index)
GetLength(index)
GetName(index)
GetType(index)
IndexFromNearestS(S)

return the index of the beamline element clostest to S

Load(filename)

Load the BDSIM input file and parse it using the BDSIM parser (GMAD).

ParseLattice()

Put lattice data into python data structure

Print(includeheaderlines=True)
PrintZeroLength(includeheaderlines=True)

Print elements with zero length with s location

next()
class pybdsim.Gmad.Survey(filename=None)

Bases: object

Survey - load a gmad lattice and have a look

Example:

>>> a = Survey()
>>> a.Load('mylattice.gmad')
>>> a.Plot()
CompareMadX(fileName)
FinalDiff()
FindClosestElement(coord)
Load(filename)
Plot()
Step(angle, length)

pybdsim.ModelProcessing module

ModelProcessing

Tools to process existing BDSIM models and generate other versions of them.

pybdsim.ModelProcessing.GenerateFullListOfSamplers(inputfile, outputfile)

inputfile - path to main gmad input file

This will parse the input using the compiled BDSIM parser (GMAD), iterate over all the beamline elements and generate a sampler for every element. Ignores samplers, but may include already defined ones in your own input.

pybdsim.ModelProcessing.GetAxisAlignedBoundingBoxOfCollimator(modelData, collimatorName)

Inspect pybdsim.Data.ModelData assuming collimator info was stored to give an axis aligned bounding box set of ranges in global coordinates.

pybdsim.ModelProcessing.GetMaterialIDOfCollimator(modelData, collimatorName)

Inspect pybdsim.Data.ModelData assuming collimator info was stored to give an axis aligned bounding box set of ranges in global coordinates.

pybdsim.ModelProcessing.WrapLatticeAboutItem(maingmadfile, itemname, outputfilename)

pybdsim.Options module

See Options class inside this module.

pybdsim.Options.ElectronColliderOptions()
class pybdsim.Options.Options(*args, **kwargs)

Bases: dict

Inherits a dict. Converting to a string or using ReturnOptionsString() will give a suitable GMAD string to write out to a file.

o = pybdsim.Options.Options() o[“trajectoryConnect”] = 1 o[“aper1”] = (5, ‘m’) str(o) ‘option, trajectoryConnect=1,

aper1=5*m;’

There is no checking on the option if using []. A tuple of (value, unitsString) can be used too resulting in value*unitsString.

ReturnOptionsString()
SetBLMLength(length=50.0, unitsstring='cm')
SetBLMRadius(radius=5.0, unitsstring='cm')
SetBeamPipeRadius(beampiperadius=5.0, unitsstring='cm')
SetBeamPipeThickness(bpt, unitsstring='mm')
SetBeamlineS(beamlineS=0, unitsstring='m')
SetBuildTunnel(tunnel=False)
SetBuildTunnelFloor(tunnelfloor=False)
SetCherenkovOn(on=True)
SetChordStepMinimum(csm=1.0, unitsstring='nm')
SetDefaultBiasMaterial(biases='')
SetDefaultBiasVaccum(biases='')
SetDefaultRangeCut(drc=0.7, unitsstring='mm')
SetDeltaChord(dc=0.001, unitsstring='m')
SetDeltaIntersection(di=10.0, unitsstring='nm')
SetDeltaOneStep(dos=10.0, unitsstring='nm')
SetDontSplitSBends(dontsplitsbends=False)
SetELossHistBinWidth(width)
SetEMLeadParticleBiasing(on=True)
SetEPAnnihilation2HadronEnhancementFactor(ef=1.0)
SetEPAnnihilation2MuonEnhancementFactor(ef=1.0)
SetGamma2MuonEnahncementFactor(ef=1.0)
SetGeneralOption(option, value)
SetIncludeFringeFields(on=True)
SetIncludeIronMagField(iron=True)
SetIntegratorSet(integratorSet='"bdsim"')
SetLPBFraction(fraction=0.5)
SetLengthSafety(ls=10.0, unitsstring='um')
SetMagnetGeometryType(magnetGeometryType='"none"')
SetMaximumEpsilonStep(mes=1.0, unitsstring='m')
SetMaximumStepLength(msl=20.0, unitsstring='m')
SetMaximumTrackingTime(mtt=-1.0, unitsstring='s')
SetMinimumEpsilonStep(mes=10.0, unitsstring='nm')
SetNGenerate(nparticles=10)
SetNLinesIgnore(nlines=0)
SetNPerFile(nperfile=100)
SetOuterDiameter(outerdiameter=2.0, unitsstring='m')
SetPhysicsList(physicslist='')
SetPipeMaterial(bpm)
SetPrintModuloFraction(pmf=0.01)
SetProductionCutElectrons(pc=100.0, unitsstring='keV')
SetProductionCutPhotons(pc=100.0, unitsstring='keV')
SetProductionCutPositrons(pc=100.0, unitsstring='keV')
SetRandomSeed(rs=0)
SetSRLowX(lowx=True)
SetSRMultiplicity(srm=2.0)
SetSamplerDiameter(radius=10.0, unitsstring='m')
SetSensitiveBeamPipe(on=True)
SetSensitiveBeamlineComponents(on=True)
SetSenssitiveBLMs(on=True)
SetSoilMaterial(sm)
SetSoilThickness(st=4.0, unitsstring='m')
SetStopSecondaries(stop=True)
SetStoreTrajectory(on=True)
SetStoreTrajectoryParticle(particle='muon')
SetSynchRadiationOn(on=True)
SetThresholdCutCharged(tcc=100.0, unitsstring='MeV')
SetThresholdCutPhotons(tcp=1.0, unitsstring='MeV')
SetTrackSRPhotons(track=True)
SetTrajectoryCutGTZ(gtz=0.0, unitsstring='m')
SetTrajectoryCutLTR(ltr=10.0, unitsstring='m')
SetTunnelFloorOffset(offset=1.0, unitsstring='m')
SetTunnelMaterial(tm)
SetTunnelOffsetX(offset=0.0, unitsstring='m')
SetTunnelOffsetY(offset=0.0, unitsstring='m')
SetTunnelRadius(tunnelradius=2.0, unitsstring='m')
SetTunnelThickness(tt=1.0, unitsstring='m')
SetVacuumMaterial(vm)
SetVacuumPressure(vp)

Vacuum pressure in bar

SetWritePrimaries(on=True)
pybdsim.Options.ProtonColliderOptions()

pybdsim.Plot module

Useful plots for bdsim output

pybdsim.Plot.AddMachineLatticeFromSurveyToFigure(figure, surveyfile, tightLayout=True, sOffset=0.0, fraction=0.9)

Add a machine diagram to the top of the plot in a current figure.

Parameters:
  • figure (matplotlib.figure.Figure) – the matplotlib figure to add the plot to.

  • surveyfile (str, pybdsim.Data.RebdsimFile, pybdsim.Data.BDSAsciiData, cppyy.gbl.DataLoader) – BDSIM file or REBDSIM file (with Model tree filled) or BDSIM survey output or path to any of these.

  • tightLayout (bool) – whether to call matplotlib’s tight layout after adding the axes.

  • sOffset (float) – add this number to the S coordinate of all elements in the machine diagram.

  • fraction (float) – controls fraction of the figure for the plot, the remainder being used for the survey.

pybdsim.Plot.AddMachineLatticeFromSurveyToFigureMultiple(figure, machines, tightLayout=True)

Similar to AddMachineLatticeFromSurveyToFigure() but accepts multiple machines.

pybdsim.Plot.Aperture(rootFileName, filterThin=False, surveyFileName=None)
pybdsim.Plot.BDSIMAperture(data, machineDiagram=True, plot='xy', plotApertureType=True, removeZeroLength=False, removeZeroApertures=True)

Plot the aperture from a BDSIM DataLoader instance. By default it’s colour coded and excludes any 0 aperture elements. Zero length elements are included.

pybdsim.Plot.BDSIMApertureFromFile(filename, machineDiagram=True, plot='xy', plotApertureType=True, removeZeroLength=False, removeZeroApertures=True)

Plot the aperture from a BDSIM output file. By default it’s colour coded and excludes any 0s.

pybdsim.Plot.BDSIMOptics(rebdsimOpticsOutput, outputfilename=None, saveall=True, survey=None, **kwargs)

Display all the optical function plots for a rebdsim optics root file. By default, this saves all optical functions into a single (outputfilename) pdf, to save the optical functions separately, supply an outputfilename with saveall=false.

pybdsim.Plot.DrawMachineLattice(axesinstance, bdsasciidataobject, sOffset=0.0)

The low-level version of drawing a machine diagram. Draws into an axes instance given using loaded model data in the form of a pybdsim.Data.BDSAsciiData instance.

Parameters:
  • axesinstance (matplotlib.axes.Axes) – the plotting axis to draw the machine diagram into.

  • sOffset (float) – add this value to the S of all machine elements in the diagram.

Param:

bdsasciidataobject The model data.

The main interface is AddMachineLatticeFromSurveyToFigure, but this function may be useful for more granular plotting, e.g. with custom subfigures / axes.

pybdsim.Plot.EnergyDeposition(filename, outputfilename=None, tfssurvey=None, bdsimsurvey=None)

Plot the energy deposition from a REBDSIM output file - uses premade merged histograms.

Optional either Twiss table for MADX or BDSIM Survey to add machine diagram to plot. If both are provided, the machine diagram is plotted from the MADX survey.

pybdsim.Plot.EnergyDepositionCoded(filename, outputfilename=None, tfssurvey=None, bdsimsurvey=None, warmaperinfo=None, **kwargs)

Plot the energy deposition from a REBDSIM output file - uses premade merged histograms.

Optional either Twiss table for MADX or BDSIM Survey to add machine diagram to plot. If both are provided, the machine diagram is plotted from the MADX survey.

If a BDSIM survey is provided, collimator positions and dimensions can be taken and used to split losses into categories: collimator, warm and cold based on warm aperture infomation provided. To enable this, the “warmaperinfo” option must be set according to the prescription below.

The user can supply a list of upper and lower edges of warm regions or give the path to a coulmn-formated data file with this information via the “warmaperinfo” option. Set warmaperinfo=1 to treat all non-collimator losses as warm or set warmaperinfo=-1 to treat them as cold. Default is not perform the loss classification.

If no warm aperture information is provided, the plotting falls back to the standard simple plotting provided by a pybdsimm.Plot.Hisgogram1D interface.

Args:

filename (str): Path to the REBDSIM data file outputfilename (str, optional): Path where to save a pdf file with the plot. Default is None.

tfssurvey (str, optional): Path to MADX survey used to plot machine diagram on top of figure. Default is None.

tfssurvey (str, optional): Path to BDSIM survey used to classify losses into collimator/warm/cold and/or plot machine diagram on top of figure. Default is None.

warmaperinfo (int|list|str, optional): Information about warm aperture in the machine. Default is None. **kwargs: Arbitrary keyword arguments.

Kwargs:

skipMachineLattice (bool): If enabled, use the BDSIM survey to classify losses, but do not plot the lattice on top.

Returns:

matplotlib.pyplot.Figure object

pybdsim.Plot.Histogram1D(histogram, xlabel=None, ylabel=None, title=None, scalingFactor=1.0, xScalingFactor=1.0, figsize=(6.4, 4.8), log=False, ax=None, **errorbarKwargs)

Plot a pybdsim.Data.TH1 instance.

Parameters:
  • xlabel – x axis label

  • ylabel – y axis label

  • title – plot title

  • scalingFactor – multiplier for values

  • xScalingFactor – multiplier for x axis coordinates

  • log – whether to automatically plot on a vertical log scale

  • ax – Matplotlib.Axis instance to draw into. If None, a figure will be created.

return figure instance

pybdsim.Plot.Histogram1DMultiple(histograms, labels, log=False, xlog=False, xlabel=None, ylabel=None, title=None, scalingFactors=None, xScalingFactors=None, figsize=(10, 5), legendKwargs={}, ax=None, **errorbarKwargs)

Plot multiple 1D histograms on the same plot. Histograms and labels should be lists of the same length with pybdsim.Data.TH1 objects and strings.

return figure instance

xScalingFactors may be a single float, int and therefore equally applied to all histograms, or a list of floats that must match the length of the hsitograms for unique scalings of each one.

Example:

Histogram1DMultiple([h1,h2,h3], 
                    ['Photons', 'Electrons', 'Positrons'], 
                    xlabel=r'$\mu$m', 
                    ylabel='Fraction',
                    scalingFactors=[1,100,100],
                    xScalingFactors=1e6,
                    log=True)
Parameters:

ax – matplotlib axes to draw into - if none, a new figure will be created.

pybdsim.Plot.Histogram1DRatio(histogram1, histogram2, label1='', label2='', xLogScale=False, yLogScale=False, xlabel=None, ylabel=None, title=None, scalingFactor=1.0, xScalingFactor=1.0, figsize=(6.4, 4.8), ratio=3, histogram1Colour=None, histogram2Colour=None, ratioColour=None, ratioYAxisLimit=None, **errorbarKwargs)

Plot two histograms with their ratio (#1 / #2) in a subplot below.

Parameters:
  • histogram1 – a pybdsim.Data.TH1 instance

  • histogram2 – a pybdsim.Data.TH1 instance

  • label1 – legend label for histogram1 (str or “” or None)

  • label2 – legend label for histogram2

  • ratio – integer ratio of main plot height to ratio plot height (recommend 1 - 5)

  • ratioYAxisLimit (tuple(float, float)) – ylim upper for ratio subplot y axis

If the labels are “” then the histogram.title string will be used. If None, then no label will be added.

pybdsim.Plot.Histogram2D(histogram, logNorm=False, xLogScale=False, yLogScale=False, xlabel='', ylabel='', zlabel='', title='', aspect='auto', scalingFactor=1.0, xScalingFactor=1.0, yScalingFactor=1.0, figsize=(6, 5), vmin=None, autovmin=False, vmax=None, colourbar=True, ax=None, cax=None, **imshowKwargs)

Plot a pybdsim.Data.TH2 instance. logNorm - logarithmic colour scale xlogscale - x axis logarithmic scale ylogscale - y axis logarithmic scale zlabel - label for color bar scale aspect - “auto”, “equal”, “none” - see imshow? scalingFactor - multiplier for values xScalingFactor - multiplier for x coordinates yScalingFactor - multiplier for y coordinates autovmin - automatically determin the lower limit of the colourbar from the data vmin - explicitly control the vmin for the colour normalisation vmax - explicitly control the vmax for the colour normalisation ax - optional matplotlib axes to draw into cax - optional axes to draw coloubar into

return figure instance

pybdsim.Plot.Histogram2DErrors(histogram, logNorm=False, xLogScale=False, yLogScale=False, xlabel='', ylabel='', zlabel='', title='', aspect='auto', scalingFactor=1.0, xScalingFactor=1.0, yScalingFactor=1.0, figsize=(6, 5), vmin=None, autovmin=False, vmax=None, colourbar=True, ax=None, cax=None, **imshowKwargs)

Similar to Histogram2D() but plot the errors from the histogram instead of the contents. See pybdsim.Plot.Histogram2D for documentation of arguments.

pybdsim.Plot.Histogram3D(th3)

Plot a pybdsim.Data.TH3 instance - TBC

pybdsim.Plot.LossAndEnergyDeposition(filename, outputfilename=None, tfssurvey=None, bdsimsurvey=None, hitslegendloc='upper left', elosslegendloc='upper right', perelement=False, elossylim=None, phitsylim=None)

Load a REBDSIM output file and plot the merged histograms automatically generated by BDSIM.

Optional either Twiss table for MADX or BDSIM Survey to add machine diagram to plot.

pybdsim.Plot.LossMap(ax, xcentres, y, ylow=None, **kwargs)

Plot a loss map in such a way that works well for very large loss maps. xcentres, xwidth and y are all provided by TH1 python histograms (see pybdsim.Data.TH1).

Parameters:
  • ax – Matplotlib axes instance to draw to

  • xcentres – centres of bins

  • y – loss map signal data, same length as xcentres.

  • ylow – small non-zero value to fill between to ensure works with log scales.

kwargs: * passed to calls to plot and fill_between.

pybdsim.Plot.MadxTfsBeta(tfsfile, title='', outputfilename=None)

A forward to the pymadx.Plot.PlotTfsBeta function.

pybdsim.Plot.ModelBDSIMXZ(model, ax=None)

The ModelBDSIMXZ and ModelBDSIMYZ functions add the possibility to plot a survey done in BDSIM. The results can be found in the BDSIM output file in the Model tree. The functions can plot the start and end positions of each element in the sequence.

pybdsim.Plot.ModelBDSIMYZ(model, ax=None)

The ModelBDSIMXZ and ModelBDSIMYZ functions add the possibility to plot a survey done in BDSIM. The results can be found in the BDSIM output file in the Model tree. The functions can plot the start and end positions of each element in the sequence.

pybdsim.Plot.ModelElegantXZ(model, ax=None, transpose=False)

Plot a model madx from elegant. In development.

pybdsim.Plot.ModelElegantYZ(model, ax=None, transpose=False)

Plot a model madx from elegant. In development.

pybdsim.Plot.PhaseSpace(data, nbins=None, outputfilename=None, extension='.pdf')

Make two figures for coordinates and correlations.

Number of bins chosen depending on number of samples.

‘outputfilename’ should be without an extension - any extension will be stripped off.

Plots are saves automatically as pdf, the file extension can be changed with the ‘extension’ kwarg, e.g. extension=’.png’.

pybdsim.Plot.PhaseSpaceFromFile(filename, samplerIndexOrName=0, nbins=None, outputfilename=None, extension='.pdf')

Load a BDSIM output file and plot the phase space of a sampler (default the primaries). Only accepts raw BDSIM output.

Number of bins chosen depending on number of samples.

‘outputfilename’ should be without an extension - any extension will be stripped off. Plots are saves automatically as pdf, the file extension can be changed with the ‘extension’ kwarg, e.g. extension=’.png’.

pybdsim.Plot.PhaseSpaceSeparateAxes(filename, samplerIndexOrName=0, outputfilename=None, extension='.pdf', nbins=None, energy='total', offsetTime=True, includeSecondaries=False, coordsTitle=None, correlationTitle=None, scalefactors={}, labels={}, log1daxes=False, log2daxes=False, includeColorbar=True)

Plot the coordinates and correlations of both the transverse and longitudinal phase space in separate plots (four total) recorded in a sampler. Default sampler is the primary distribution.

‘outputfilename’ is name without extension, extension can be supplied as a string separately. Default = pdf.

The number of bins chosen depending on number of samples. Can be overridden with nbins.

Energy can be binned as either kinetic or total (default), supply either energy=’total’ or energy=’kinetic’.

offSetTime centers the time distribution about the nominal time for the specified sampler rather than the absolute time. Default = True.

Secondaries can be included in the distributions with includeSecondaries. Default = False.

Plot titles can be supplied as strings with coordsTitle and correlationTitle.

Parameter scale factors should be supplied in a dictionary in the format {parameter: scalefactor}, e.g scalefactors={‘x’: 1000, ‘y’:1000}. Acceptable parameters are ‘x’,’y’,’xp’,’yp’, ‘T’,’kinetic’, and ‘energy’ for total energy.

Axis labels for parameters should be supplied as a dictionary in the format {parameter: label}, e.g labels={‘x’: “X (mm)”, ‘energy’: “Energy (MeV)”}. Acceptable parameters are ‘x’,’y’,’xp’,’yp’, ‘T’,’kinetic’, and ‘energy’ for total energy.

log1daxes & log2daxes plots the 1D and 2D phase space on logarithmic scales respectively. Defaults = False.

includeColorbar adds a colorbar to the correlation plots. The colorbar is normalised for all plot subfigures. Default = True.

pybdsim.Plot.PlotAlpha(bds, outputfilename=None, survey=None, **kwargs)
pybdsim.Plot.PlotBeta(bds, outputfilename=None, survey=None, **kwargs)
pybdsim.Plot.PlotDisp(bds, outputfilename=None, survey=None, **kwargs)
pybdsim.Plot.PlotDispP(bds, outputfilename=None, survey=None, **kwargs)
pybdsim.Plot.PlotEmittance(bds, outputfilename=None, survey=None, **kwargs)
pybdsim.Plot.PlotMean(bds, outputfilename=None, survey=None, **kwargs)
pybdsim.Plot.PlotNPart(bds, outputfilename=None, survey=None, **kwargs)
pybdsim.Plot.PlotSigma(bds, outputfilename=None, survey=None, **kwargs)
pybdsim.Plot.PlotSigmaP(bds, outputfilename=None, survey=None, **kwargs)
pybdsim.Plot.PrimaryPhaseSpace(filename, outputfilename=None, extension='.pdf')

Load a BDSIM output file and plot primary phase space. Only accepts raw BDSIM output.

‘outputfilename’ should be without an extension - any extension will be stripped off. Plots are saves automatically as pdf, the file extension can be changed with the ‘extension’ kwarg, e.g. extension=’.png’.

pybdsim.Plot.PrimarySurvival(filename, outputfilename=None, tfssurvey=None, bdsimsurvey=None)
pybdsim.Plot.PrimaryTrajectoryAndProcess(rootData, eventNumber)
pybdsim.Plot.ProvideWrappedS(sArray, index)
pybdsim.Plot.Spectra(spectra, log=False, xlog=False, xlabel=None, ylabel=None, title=None, scalingFactor=1.0, xScalingFactor=1.0, figsize=(10, 5), legendKwargs={}, vmin=None, vmax=None, **errorbarKwargs)

Plot a Spectra object loaded from data that represents a set of histograms.

Parameters:
  • scalingFactor (float, int) – value to multiply all bin contents by (single number)

  • xScalingFactor (float, int) – value to multiply all bin centre coordinates by (single number)

returns a list of figure objects.

pybdsim.Plot.SpectraSelect(spectra, pdgids, log=False, xlog=False, xlabel=None, ylabel=None, title=None, scalingFactor=1.0, xScalingFactor=1.0, figsize=(10, 5), legendKwargs={}, vmin=None, vmax=None, **errorbarKwargs)
pybdsim.Plot.SubplotsWithDrawnMachineLattice(survey, nrows=2, machine_plot_gap=0.01, gridspec_kw=None, subplots_kw=None, **fig_kw)

Create a figure with a single column of axes, sharing the x-axis by default, with the machine drawn from the provided survey on the top row axes. nrows gives the number of axes, the first is always the machine lattice. by default 2 are drawn, the first for the machine, and the second for any data to be plotted to afterwards.

Parameters:

survey (str, pybdsim.Data.BDSAsciiData) – BDSIM survey which is used to draw the machine lattice on the top axes.

machine_plot_gap : vertical space between the top of the first axes and the bottom of the machine axes. By default this is small.

Returns (figure, machine_axes, (axes1, axes2, …))

figure : Figure instance. machine_axes : Axes instance with the machine drawn on it. Can be used to further edit axes : iterable of axes, in order from the first below the machine, downwards.

pybdsim.Plot.Trajectory3D(rootFileName, eventNumber=0, bottomLeft=None, topRight=None)

Plot e-, e+ and photons only as r,g,b respectively for a given event from a BDSIM output file.

bottomLeft and topRight are optional [xlow,xhigh] limits for plots.

pybdsim.Run module

Utilities for running BDSIM and other tools from Python.

pybdsim.Run.Bdsim(gmadpath, outfile, ngenerate=10000, batch=True, silent=False, errorSilent=False, options=None, bdsimExecutable=None)

Runs bdsim with gmadpath as inputfile and outfile as outfile. Runs in batch mode by default, with 10,000 particles. Any extra options should be provided as a string or iterable of strings of the form “–vis_debug” or “–vis_mac=vis.mac”, etc.

pybdsim.Run.Chunks(l, n)

Yield successive n-sized chunks from list l.

class pybdsim.Run.ExecOptions(*args, **kwargs)

Bases: dict

GetExecArgs()
GetExecFlags()
pybdsim.Run.GetOpticsFromGMAD(gmad, keep_optics=False)

Get the optical functions as a BDSAsciiData instance from this GMAD file. If keep_optics is false then all intermediate files are discarded, otherwise the final optics ROOT file is written to ./

class pybdsim.Run.GmadModifier(rootgmadfilename)

Bases: object

CheckExtensions()
DetermineIncludes(filename)
ReplaceTokens(tokenDict)
pybdsim.Run.Rebdsim(rootpath, inpath, outpath, silent=False, rebdsimExecutable=None)

Run rebdsim with rootpath as analysisConfig file, inpath as bdsim file, and outpath as output analysis file.

pybdsim.Run.RebdsimCombine(rootpath, outpath, silent=False, rebdsimHistoExecutable=None)

Run rebdsimCombine

pybdsim.Run.RebdsimHistoMerge(rootpath, outpath, silent=False, rebdsimHistoExecutable=None)

Run rebdsimHistoMerge

pybdsim.Run.RebdsimOptics(rootpath, outpath, silent=False)

Run rebdsimOptics

pybdsim.Run.RebdsimOrbit(rootpath, outpath, index='1', silent=False, rebdsimHistoExecutable=None)

Run rebdsimOrbit

pybdsim.Run.Reduce(globcommand, nPerChunk, outputprefix)

Apply bdsimCombine to the globcommand set of files combining nPerchunks into an output file.

ReduceRun(“datadir/*.root”, 10, “outputdir/”)

pybdsim.Run.ReduceParallel(globcommand, nPerChunk, outputprefix, nCPUs=4)

In parallel, apply bdsimCombine to the globcommand set of files combining nPerChunk into an output file.

chunkermp.ReduceRun(“testfiles/*.root”, 14, “testfiles-merge/”, nCPUs=7)

class pybdsim.Run.Study

Bases: object

A holder for multiple runs.

GetInfo(index=-1)

Get info about a particular run.

Run(inputfile='optics.gmad', output='rootevent', outfile='output', ngenerate=1, bdsimcommand='bdsim-devel', **kwargs)
RunExecOptions(execoptions, debug=False)

pybdsim.Visualisation module

Work in progress.

class pybdsim.Visualisation.Helper(surveyFileName)

Bases: object

To help locate objects in the BDSIM visualisation, requires a BDSIM survey file

draw()

Quick survey drawing for diagnostic reasons.

findComponentCoords(componentName)

Returns the XYZ coordinates of a component relative to the centre

getWorldCentre(type='linear')

Returns the center in world coordinates of the centre of the visualisation space

pybdsim.Writer module

Writer

Write files for a pybdsim.Builder.Machine instance. Each section of the written output (e.g. components, sequence, beam etc.) can be written in the main gmad file, written in its own separate file, or called from an external, pre-existing file.

Classes: File - A class that represents each section of the written output - contains booleans and strings. Writer - A class that writes the data to disk.

class pybdsim.Writer.FileSection(willContain='')

Bases: object

A class that represents a section of a gmad file. The sections that this class can represent are:

  • Components

  • Sequence

  • Samplers

  • Beam

  • Options

  • Bias

  • Material

The class contains booleans and strings relating to the location of that sections data. The section can set to be:

  • Written in its own separate file (default)

  • Written in the main gmad file

  • Called from an external file

These classes are instantiated in the writer class for each section. An optional string passed in upon class instantiation is purely for the representation of the object which will state where the data will be written/called. This string should be one of the section names listed above.

Example:

>>> beam = FileSection('beam')
>>> beam.CallExternalFile('../myBeam.gmad')
>>> beam
pybdsim.Writer.File instance
File data will be called from the external file:
../myBeam.gmad
CallExternalFile(filepath='')
WriteInMain()
WriteSeparately()
class pybdsim.Writer.Writer

Bases: object

A class for writing a pybdsim.Builder.Machine instance to file.

This class allows the user to write individual sections of a BDSIM input file (e.g. components, sequence, beam etc.) or write the machine as a whole.

There are 6 attributes in this class which are FileSection instances representing each section of the data. The location where these sections will be written/read is stored in these instances. See the FileSection class for further details.

The optional boolean ‘singlefile’ in the WriteMachine function for writing the sections to a single file overrides any sections locations set in their respective FileSection instances.

This class also has individual functions (e.g. WriteBeam) to write each file section and the main file (WriteMain) separately. These section functions must be called BEFORE the WriteMain function is called otherwise the main file will have no reference to these sections.

Examples:

Writing the Builder.Machine instance myMachine to separate files:

>>> a = Writer()
>>> a.WriteMachine(myMachine,'lattice.gmad')
Lattice written to:
lattice_components.gmad
lattice_sequence.gmad
lattice_beam.gmad
lattice.gmad
All included in main file:
lattice.gmad

Writing the Builder.Machine instance myMachine into a single file:

>>> a = Writer()
>>> a.WriteMachine(myMachine,'lattice.gmad',singlefile=True)
Lattice written to:
lattice.gmad
All included in main file:
lattice.gmad
WriteBeam(machine, filename='')

Write a machines beam to disk: filename.gmad

Machine can be either a pybdsim.Builder.Machine instance or a pybdsim.Beam.Beam instance.

WriteBias(machine, filename='')

Write the machines bias to disk: filename.gmad

WriteComponents(machine, filename='')

Write the machines components to disk: filename.gmad

WriteMachine(machine(machine), filename(string), singlefile(bool), verbose(bool))

Write a machine to disk. By default, the machine will be written into the following individual files:

filename_components.gmad

component files (max 10k per file)

filename_sequence.gmad

lattice definition

filename_samplers.gmad

sampler definitions (max 10k per file)

filename_options.gmad

options

filename_beam.gmad

beam definition

filename_bias.gmad

machine biases (if defined)

filename_material.gmad

machine materials (if defined)

filename.gmad

suitable main file with all sub files in correct order

These are prefixed with the specified filename / path

The optional bool singlefile = True will write all the above sections into a single file:

filename.gmad

kwargs: overwrite : Do not append an integer to the basefilename if already exists, instead overwrite existing files.

WriteMain(machine(machine), filename(string))

Write the main gmad file: filename.gmad

The functions for the other sections of the machine (components,sequence,beam,options,samplers,bias,material) must be written BEFORE this function is called.

WriteMaterial(machine, filename='')

Write the machines material to disk: filename.gmad

WriteObjects(machine, filename='')

Write the machines objects (e.g. crystals) to disk: filename.gmad

WriteOptions(machine, filename='')

Write a machines options to disk: filename.gmad

Machine can be either a pybdsim.Builder.Machine instance or a pybdsim.Options.Options instance.

WriteSamplers(machine, filename='')

Write the machines samplers to disk: filename.gmad

WriteSequence(machine, filename='')

Write the machines sequence to disk: filename.gmad

pybdsim.XSecBias module

class pybdsim.XSecBias.XSecBias(name, particle, processes, xsecfactors, flags)

Bases: object

A class for containing all information regarding cross section definitions.

CheckBiasedProcesses()
SetFlags(flags)

Set flags. flags should be a space-delimited string of integers, 1-3, in the same order as the processes,

SetName(name)

Set the bias name. Cannot be any upper/lowercase variant of reserved keyword “xsecBias”.

SetParticle(particle)

Set the particle for bias to be associated with.

SetProcesses(processes)

Set the list of processes to be biased. processes hould be a space-delimited string of processes.

SetXSecFactors(xsecs)

Set cross section factors. xsecs should be a space-delimited string of floats, e.g. “1.0 1e13 1234.9”