Module Contents

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

pymadx - Royal Holloway utility to manipulate MADX data and models.

Authors:

  • Laurie Nevay

  • Andrey Abramov

  • Stewart Boogert

  • William Shields

  • Jochem Snuverink

  • Stuart Walker

Copyright Royal Holloway, University of London 2023.

pymadx.Beam module

Class to create a MADX beam definition.

class pymadx.Beam.Beam(particletype='e-', energy=1.0, distrtype='reference', *args, **kwargs)

Bases: dict

A class that extends a dictionary for the specific parameters in a MADX beam definition. This class can return a string representation of itself that is valid MADX syntax.

Setter methods are dynamically added based on the distribution selected.

GetItemStr(key)
ReturnBeamString()
ReturnPtcString()
ReturnPtcTwissString(basefilename='output')
ReturnTwissString(basefilename='output')
SetDistributionType(distrtype='reference')
SetEnergy(energy=1.0, unitsstring='GeV')
SetParticleType(particletype='e-')
SetT0(t0=0.0, unitsstring='s')
SetX0(x0=0.0)
SetXP0(xp0=0.0)
SetY0(y0=0.0)
SetYP0(yp0=0.0)
WriteToFile(filename)

pymadx.Builder module

Builder

Classes for programmatically constructing and writing out a MADX lattice. You can create a lattice using one of the predefined simple lattices or by instantiating the Machine class and adding many elements to it using its various Add methods. This instance may be written out to a MADX input text file using the WriteMachine method.

Classes:

Element - beam line element that always has name and type Line - a list of elements Machine - a sequence of elements and associated options and beam etc.

class pymadx.Builder.Element(name, category, **kwargs)

Bases: dict

Element - a beam element class - inherits dict

Element(name,type,**kwargs)

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.

Numbers are converted to a python Decimal type to provide higher accuracy in the representation of numbers - 15 decimal places are used.

keysextra()
class pymadx.Builder.Line(name, *args)

Bases: list

DefineConstituentElements()
class pymadx.Builder.Machine(verbose=False)

Bases: object

AddBeam(beam=None)
AddDecapole(name='dd', length=0.1, k4=0.0, **kwargs)
AddDipole(category='sbend')

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

AddDrift(name='dr', length=0.1, **kwargs)
AddHKicker(name='hk', hkick=0, length=0, **kwargs)
AddMarker(name='mk', **kwargs)
AddMultipole(name='mp', knl=0, ksl=0, **kwargs)
AddOctupole(name='oc', length=0.1, k3=0.0, **kwargs)
AddOptions(*args, **kwargs)
AddPTCTrackAperture(aperture=[])

Add a PTC 6D max aperture for ptc_track command.

AddQuadrupole(name='qd', length=0.1, k1=0.0, **kwargs)
AddSampler(*elementnames)
AddSextupole(name='sd', length=0.1, k2=0.0, **kwargs)
AddSolenoid(name='sl', length=0.1, ks=0.0, **kwargs)
AddTKicker(name='tk', vkick=0, hkick=0, length=0, **kwargs)
AddVKicker(name='vk', vkick=0, length=0, **kwargs)
Append(object)
Write(filename, verbose=False)

Write the machine to a series of gmad files.

next()
class pymadx.Builder.Sampler(name)

Bases: object

Class that can return the appropriate sampler syntax if required.

pymadx.Builder.WriteMachine(machine(machine), filename(string), verbose(bool))

Write a lattice to disk. This writes several files to make the machine, namely:

  • filename_components.madx - component files (max 10k per file)

  • filename_sequence.madx - lattice definition

  • filename_samplers.madx - sampler definitions (max 10k per file)

  • filename.gmad - suitable main file with all sub

    files in correct order

These are prefixed with the specified filename / path.

pymadx.Data module

Classes to load and manipulate data from MADX.

class pymadx.Data.Aperture(filename=None, verbose=False)

Bases: Tfs

Inherits Tfs, with added functionality specific to apertures: changing aperture types, getting the aperture at a specific S, etc.

Keyword Arguments: filename – TFS file to be loaded (default None) verbose – (default False) beamLossPattern – Whether to apply beamLossPattern’s interpretation of APER numbers to infer APERTYPE (default False)

CheckKnownApertureTypes()
GetApertureAtS(sposition)

Return a dictionary of the aperture information specified at the closest S position to that requested - may be before or after that point.

GetEntriesBelow(value=8, keys='all')
GetExtent(name)

Get the x and y maximum +ve extent (assumed symmetric) for a given entry by name.

GetExtentAll()

Get the x and y maximum +ve extent (assumed symmetric) for the full aperture instance.

returns x,y where x and y are 1D numpy arrays

GetExtentAtS(sposition)

Get the x and y maximum +ve extent (assumed symmetric) for a given s position.

GetNonZeroItems()

Return a copy of this class with all non-zero items removed.

Plot(machine=None, outputfilename=None, plot='xy', plotapertype=True)

This plots the aperture extent in x and y.

This replaces the base class Tfs Plot method.

Inputs:

title (str) - The title of the resultant plot (default: None) outputfilename (str) - Name without extension of the output file if desired (default: None) machine (str or pymadx.Data.Tfs) - TFS file or TFS istance to plot a machine lattice from (default: None) plot (str) - Indicates whcih aperture to plot - ‘x’ for X, ‘y’ for Y and ‘xy’ for both (default: ‘xy’) plotapertype (bool) - If enabled plots the aperture type at every definted aperture point as a color-coded dot (default: False)

PlotN1(machine=None, outputfilename=None)

Plot the N1 aperture value from MADX.

Requires N1 and S column.

Optional “machine” argument is string to or pymadx.Data.Tfs instance for twiss description to provide a machine diagram on top.

RemoveAboveValue(limits=8, keys='all')
RemoveBelowValue(limits, keys='all')

Return a copy of the aperture instance with all entries where any of the aperture values are below value. The default is the tolerance as defined by SetZeroTolerance().

RemoveDuplicateSPositions()

Takes the first aperture value for entries with degenerate S positions and removes the others.

RemoveNoApertureTypeEntries()

Return a copy of this instance with any null aperture types removed.

Aperture type of “” and “NONE” will be removed.

ReplaceType(existingType, replacementType)
SetZeroTolerance(tolerance)

Set the value below which aperture values are considered 0.

pymadx.Data.CheckItsTfs(tfsfile)

Ensure the provided file is a Tfs instance. If it’s a string, ie path to a tfs file, open it and return the Tfs instance.

tfsfile can be either a tfs instance or a string.

pymadx.Data.CheckItsTfsAperture(tfsfile)

Ensure the provided file is an Aperture instance. If it’s a string, ie path to a tfs file, open it and return the Tfs instance.

tfsfile can be either a tfs instance or a string.

pymadx.Data.GetApertureExtent(aper1, aper2, aper3, aper4, aper_type)

Get the maximum +ve half extent in x and y for a given aperture model and (up to) four aperture parameters.

returns x,y

pymadx.Data.PrintMADXApertureTypes()
class pymadx.Data.Tfs(filename=None, verbose=False)

Bases: object

MADX Tfs file reader

>>> a = Tfs()
>>> a.Load('myfile.tfs')
>>> a.Load('myfile.tar.gz') -> extracts from tar file

or

>>> a = Tfs("myfile.tfs")
>>> b = Tfs("myfile.tar.gz")
a has data members:
header - dictionary of header items
columns - list of column names
formats - list of format strings for each column
data - dictionary of entries in tfs file by name string
sequence - list of names in the order they appear in the file
nitems - number of items in sequence

NOTE: if no column “NAME” is found, integer indices are used instead

See the various methods inside a to get different bits of information:

>>> a.ReportPopulations?

Examples:

>>> a['IP.1']  # returns dict for element named "IP.1"
>>> a[:30]     # returns list of dicts for elements up to number 30
>>> a[345]     # returns dict for element number 345 in sequence
Clear()

Empties all data structures in this instance.

ColumnIndex(columnstring)

Return the index to the column matching the name

REMEMBER: excludes the first column NAME 0 counting

ComponentPerturbs(indexInSequence)

Returns names of variables which would perturb a particle. Some components written out in TFS are redundant, so it’s useful to know which components perturb a particle’s motion. This is likely not an exhaustive check so refer to source if unsure.

Checks integrated stengths (but not if L=0), HKICK and VKICK

indexInSequence - index of component to be checked. terse - print out the parameters which perturb if False

ConcatenateMachine(*tfs)

This is used to concatenate machines.

EditComponent(index, variable, value)

Edits variable of component at index and sets it to value. Can only take indices as every single element in the sequence has a unique definition, and components which may appear degenerate/reused are in fact not in this data model.

ElementPerturbs(component)

Search an invidivual dictionary representing a row in the TFS file for as to whether it perturbs.

GetCollimators()

Returns a Tfs instance containing any type of collimator (including COLLLIMATOR, RCOLLIMATOR and ECOLLIMATOR).

GetColumn(columnstring)

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

GetColumnDict(columnstring)

return all data from one column in a dictionary

note not in order

GetElementNamesOfType(typename)

Returns a list of the names of elements of a certain type. Typename can be a single string or a tuple or list of strings.

Examples:

>>> GetElementsOfType('SBEND')
>>> GetElementsOfType(['SBEND','RBEND'])
>>> GetElementsOfType(('SBEND','RBEND','QUADRUPOLE'))
GetElementsOfType(typename)

Returns a Tfs instance containing only the elements of a certain type. Typename can be a sintlge string or a tuple or list of strings.

This returns a Tfs instance with all the same capabilities as this one.

GetElementsWithTextInName(text)

Returns a Tfs instance containing only the elements with the string in text in the their name.

This returns a Tfs instance with all the same capabilities as this one.

GetRow(elementname)

Return all data from one row as a list

GetRowDict(elementname)

Return a dictionary of all parameters for a specifc element given by element name.

note not in order

GetSegment(segmentnumber)
IndexFromGmadName(gmadname, verbose=False)

Returns the indices of elements which match the supplied gmad name. Useful because tfs2gmad strips punctuation from the component names, and irritating otherwise to work back. When multiple elements of the name match, returns the indices of all the components in a list. Arguments: gmadname : The gmad name of a component to search for. verbose : prints out matching name indices and S locations. . Useful for discriminating between identical names.

IndexFromName(namestring)

Return the index of the element named namestring. Raises ValueError if not found.

IndexFromNearestS(S)

return the index of the beamline element which CONTAINS the position S.

Note: For small values beyond smax, the index returned will be -1 (i.e. the last element).

InterrogateItem(itemname)

Print out all the parameters and their names for a particlular element in the sequence identified by name.

Load(filename, verbose=False)
>>> a = Tfs()
>>> a.Load('filename.tfs')

Read the tfs file and prepare data structures. If ‘tar’ or ‘gz are in the filename, the file will be opened still compressed.

NameFromIndex(integerindex)

return the name of the beamline element at index

NameFromNearestS(S)

return the name of the beamline element clostest to S

Plot(title='', outputfilename=None, machine=True, dispersion=False, squareroot=True)

Plot the Beta amplitude functions from the file if they exist.

squareroot -> whether to square root the beta functions or not (default = True)

PlotCentroids(title='', outputfilename=None, machine=True)

Plot the centroid in the horizontal and vertical from the file if they exist.

PlotSigma(title='', outputfilename=None, machine=True, dispersion=False)

Plot the beam size.

PrintBasicBeamProperties(elementname)

Print centroid, transverse momentum, beta, alpha and sigma in x and y.

Will fail if these are not available.

RenameElement(index, new)

Rename indexed element.

ReportPopulations()

Print out all the population of each type of element in the beam line (sequence)

SplitElement(SSplit)

Splits the element found at SSplit given, performs the necessary operations on the lattice to leave the model functionally identical and returns the indices of the first and second component. Element new name will be the same as the original except appended with a number corresponding to its location in the list of previously identically defined components used in the sequence and either “split_1” or “split_2” depending on which side of the split it is located. It is necessary to append both of these numbers to ensure robust name mangling.

WARNING: DO NOT SPLIT THE ELEMENT WHICH MARKS THE BEGINNING OF YOUR LATTICE. YOUR OPTICS WILL BE WRONG!

Write(outputfilename, columns=None, removePymadxColumns=True)

Write this instance to file in MADX TFS format.

Specify column names with columns=[‘S’, ‘L’] for example.

next()

pymadx.Plot module

Various plots for madx TFS files using the pymadx Tfs class

pymadx.Plot.AddMachineLatticeToFigure(figure, tfsfile, tightLayout=True, reverse=False, offset=None)

Add a diagram above the current graph in the figure that represents the accelerator based on a madx twiss file in tfs format.

Note you can use matplotlib’s gcf() ‘get current figure’ as an argument.

>>> pymadx.Plot.AddMachineLatticeToFigure(gcf(), 'afile.tfs')

A pymadx.Tfs class instance or a string specifying a tfs file can be supplied as the second argument interchangeably.

If the reverse flag is used, the lattice is plotted in reverse only. The tfs instance doesn’t change.

Offset can optionally be the name of an object in the lattice (exact name match).

If both offset and reverse are used, reverse happens first. The right click searching works with the reverse and offset similarly.

pymadx.Plot.Aperture(aperture, machine=None, outputfilename=None, plot='xy', plotapertype=True)

Plots the aperture extents vs. S from a pymadx.Data.Aperture instance.

Inputs:

aperture (pymadx.Data.Aperture) - the aperture model to plot from machine (str or pymadx.Data.Tfs) - TFS file or TFS istance to plot a machine lattice from (default: None) outputfilename (str) - Name without extension of the output file if desired (default: None) plot (str) - Indicates whcih aperture to plot - ‘x’ for X, ‘y’ for Y and ‘xy’ for both (default: ‘xy’) plotapertype (bool) - If enabled plots the aperture type at every definted aperture point as a color-coded dot (default: False)

pymadx.Plot.ApertureN1(aperture, machine=None, outputfilename=None)

Plot the N1 aperture value from MADX.

Requires N1 and S column.

Optional “machine” argument is string to or pymadx.Data.Tfs instance for twiss description to provide a machine diagram on top.

pymadx.Plot.Beta(tfsfile, title='', outputfilename=None, machine=True, dispersion=False, squareroot=True, dispersionY=False, legendLoc='best')

Plot sqrt(beta x,y) as a function of S. By default, a machine diagram is shown at the top of the plot.

Optionally set dispersion=True to plot x dispersion as second axis. Optionally turn off machine overlay at top with machine=False Specify outputfilename (without extension) to save the plot as both pdf and png.

pymadx.Plot.Centroids(tfsfile, title='', outputfilename=None, machine=True)

Plot the centroid (mean) x and y from the a Tfs file or pymadx.Tfs instance.

tfsfile - can be either a string or a pymadx.Tfs instance. title - optional title for plot outputfilename - optional name to save file to (extension determines format) machine - if True (default) add machine diagram to top of plot

pymadx.Plot.MachineDiagram(tfsfile, title=None, reverse=False)

Plot just a machine diagram on its own. The S axis is shown.

Parameters:
  • tfsfile (pymadx.Data.TFS, str) – TFS instance or file name of lattice to plot.

  • title (None, str) – Title for plot.

  • reverse (bool) – Whether to reverse the direction of the machine.

pymadx.Plot.RMatrixOptics(tfsfile, dx=1.0, dpx=1.0, dP=1.0, dy=1.0, dpy=1.0, title=None, outputfilename=None, machine=True)

Plot the propagation of 3 rays with dx, dy, dpx, dpy, and dE independently. :param dx: displacement in x in mm that is propagated :type dx: float :param dpx: displacement in px (component of unit vector) in 1e-3 (e.g. mrad in small angle). :type dpx: float :param dP: displacement in momentum as a percentage :type dP: float :param dy: displacement in x in mm that is propagated :type dy: float :param dyx: displacement in px (component of unit vector) in 1e-3 (e.g. mrad in small angle). :type dyx: float

pymadx.Plot.Sigma(tfsfile, title='', outputfilename=None, machine=True, dispersion=False)

Plot sqrt(beta x,y) as a function of S. By default, a machine diagram is shown at the top of the plot.

Optionally set dispersion=True to plot x dispersion as second axis. Optionally turn off machine overlay at top with machine=False Specify outputfilename (without extension) to save the plot as both pdf and png.

pymadx.Plot.Survey(tfsfile, title='', outputfilename=None)

Plot the x and z coordinates from a tfs file.

pymadx.Plot.TwoMachineDiagrams(tfsTop, tfsBottom, labelTop=None, labelBottom=None, title=None, reverse=False)

Plot just a machine diagram on its own. The S axis is shown.

Parameters:
  • tfsfile (pymadx.Data.TFS, str) – TFS instance or file name of lattice to plot.

  • title (None, str) – Title for plot.

  • reverse (bool) – Whether to reverse the direction of the machine.

pymadx.Ptc module

Classes to handle PTC runs and data.

class pymadx.Ptc.FlatGenerator(mux=0.0, widthx=0.001, mupx=0.0, widthpx=0.001, muy=0.0, widthy=0.001, mupy=0.0, widthpy=0.001)

Bases: object

Simple ptc inray file generator - even distribution

Generate(nToGenerate=100, fileName='inrays.madx')

returns an Inrays structure

class pymadx.Ptc.GaussGenerator(gemx=1e-10, betax=0.1, alfx=0.0, gemy=1e-10, betay=0.1, alfy=0.0, sigmat=1e-12, sigmapt=1e-12)

Bases: object

Simple ptx inray file generator

Generate(nToGenerate=1000, fileName='inrays.madx')

returns an Inrays structure

class pymadx.Ptc.Inray(x=0.0, px=0.0, y=0.0, py=0.0, t=0.0, pt=0.0)

Bases: object

Class for a madx ptc input ray x : horizontal position [m] px : horizontal canonical momentum p_x/p_0 y : vertical position [m] py : vertical canonical momentum p_y/p_0 t : c*(t-t0) [m] pt : (delta-E)/(pc)

use str(Inray) to get the representation for file writing

class pymadx.Ptc.Inrays

Bases: list

Class based on python list for Inray class

AddParticle(x=0.0, px=0.0, y=0.0, py=0.0, t=0.0, pt=0.0)
Clear()
Plot()
Statistics()
Write(filename)
pymadx.Ptc.LoadInrays(fileName)

Load input rays from file fileName : inrays.madx return : Inrays instance

pymadx.Ptc.PlotInrays(i)

Plot Inrays instance, if input is a sting the instance is created from the file

pymadx.Ptc.WriteInrays(fileName, inrays)

pymadx.PtcAnalysis module

Analysis utilities for PTC data.

class pymadx.PtcAnalysis.PtcAnalysis(ptcInput=None, ptcOutput=None)

Bases: object

Deprecated.

Optical function calculation for PTC tracking data.

This has be reimplemented and replaced by C++ implementation in rebdsim.

CalculateOpticalFunctions(output)

Calulates optical functions from a PTC output file

output - the name of the output file

SamplerLoop()