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:
dictA 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:
dictElement - 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.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:
objectClass 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:
TfsInherits 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.RotoTranslation2D(rotationAngle=0, translation=(0, 0), rotationOrigin=None)
Bases:
objectA class to hold a 2D rotation about an offset point.
- Inverse()
- class pymadx.Data.Tfs(filename=None, verbose=False)
Bases:
objectMADX Tfs file reader
- Parameters:
filename (str, pathlib.Path) – filename of Tfs file
>>> 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 itemscolumns - list of column namesformats - list of format strings for each columndata - dictionary of entries in tfs file by name stringsequence - list of names in the order they appear in the filenitems - number of items in sequenceNOTE: 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 individual 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). :return pymadx.Data.Tfs:
- GetColumn(column_string)
Return a numpy array of the values in column_string in order as they appear in the beamline
- GetColumnDict(column_string)
return all data from one column in a dictionary
note not in order
- GetElementNamesOfType(typename)
- Parameters:
typename (str, list(str)) – name of type to return or list of them
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.
- Returns:
list(str)
Examples:
>>> GetElementsOfType('SBEND') >>> GetElementsOfType(['SBEND','RBEND']) >>> GetElementsOfType(('SBEND','RBEND','QUADRUPOLE'))
- GetElementsOfType(typename)
- Parameters:
typename (str, list(str)) – string of MADX type to match or list of strings
Returns a Tfs instance containing only the elements of a certain type. Typename can be a single string or a tuple or list of strings. :return: pymadx.Data.Tfs
- GetElementsWithTextInName(text)
- Parameters:
text (str, list(str)) – string or list of strings to match a subset of for each component
Returns a Tfs instance containing only the elements with the string in text in their name.
- Returns:
pymadx.Data.Tfs
- GetRotoTranslationFromElementZX(elementName)
If this is a survey TFS file and has the columns Z, X and THETA, this will give the rototranslation to apply to get an object from 0,0 to the frame of this element in the survey (at its end usually).
>>> offset = np.array([0, 0.3]) # want to place this offset relative to end of 'MCA1' >>> a = pymadx.Data.Tfs("mysurvey.tfs") >>> r = a.GetRotoTranslationFromElementZX("MCA1") >>> offsetMCA1 = r * offset
- GetRotoTranslationFromElementZY(elementName)
If this is a survey TFS file and has the columns Z, Y and PHI, this will give the rototranslation to apply to get an object from 0,0 to the frame of this element in the survey (at its end usually).
>>> offset = np.array([0, 0.3]) # want to place this offset relative to end of 'MCA1' >>> a = pymadx.Data.Tfs("mysurvey.tfs") >>> r = a.GetRotoTranslationFromElementZY("MCA1") >>> offsetMCA1 = r * offset
- GetRow(element_name)
Return all data from one row as a list
- GetRowDict(element_name)
Return a dictionary of all parameters for a specifc element given by element name.
note not in order
- GetSegment(segment_number)
- 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(name)
- Parameters:
name (str) – name of element in the sequence
- Returns:
int
Return the index of the element named name. Raises ValueError if not found.
- IndexFromNearestS(S)
- Parameters:
S (float) – curvilinear cumulative distance along the machine
- Returns:
int
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)
- Parameters:
itemname (str) – the element in the sequence to print out
Print out all the parameters and their names for a particular 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.
- LoadFromCpymadTable(twissTable, verbose=False)
- NameFromIndex(index)
- Parameters:
index (int) – index of element
- Returns:
str
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=True, squareroot=False, dispersionY=False)
Plot the Beta amplitude functions from the file if they exist.
See
pymadx.Plot.Beta().
- 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, ax=None, figsize=(9, 5))
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()
- to_dataframe(only_original_columns=True)
This will only work if pandas is available at run time. It is not a formal dependency of this package.
pymadx.Diagrams module
Various plots for madx TFS files using the pymadx Tfs class
- pymadx.Diagrams.Polygon(edges, colour, alpha)
Return a polygon patch from a list of points as a numpy array.
- Parameters:
edges (numpy.array([x1,y1], [x2,y2],...)) – numpy array of [x,y] edges
colour (str) – colour of the polygon
alpha (float) – transparency of the polygon
- pymadx.Diagrams.Rotate(points, angle, origin=None)
Apply a rotation to an array of [x,y] pairs about (0,0) or an optional origin point.
- Parameters:
points (numpy.array([x1,y1], [x2,y2],...])) – numpy array of [x,y] points (any length)
angle (float, int) – angle to rotate by in radians. Positive is anti-clockwise in the x-y plane.
origin (np.array([x,y])) – optional [x,y] to rotate the data about - default [0,0]
- pymadx.Diagrams.RotateTranslate(points, angle, translation, rotationOrigin=None)
Apply a rotation and then add a translation to all points. See Rotate()
- Parameters:
translation (np.array([x,y])) – [x,y] to add to all points after rotation
- pymadx.Diagrams.Survey2DZX(survey_tfsfile, ax=None, greyOut=False, offsetRotoTranslation=None, title='', outputfilename=None, zOffset=0, defaultWidth=0.5, elementDict=None, typeDict=None, funcDict=None, maskNames=None, ignoreNames=None, resolution=0.1, defaultCoilLength=0.15, pipeRadius=None, pipeMaskRanges=None, invisibleAxes=False, arrowsDy=0, arrowsDx=0, defaultAlpha=None, drawXLabel=True)
Draw a schematic of a beamline in the Z-X plane. Allow styling of different elements by type or by name.
- Parameters:
survey_tfsfile (str, pymadx.Data.Tfs) – list of tfs files as strings or already loaded pymadx.Data.Tfs objects.
ax (matplotlib.axes.Axes, None) – matplotlib axes object
greyOut (bool) – whether to plot the whole line in greyscale
offsetRotoTranslation (None, str, pymadx.Data.RotoTranslation2D) – Optional roto-translation to apply before plotting to offset the whole diagram. Can be the name of the element in the survey file also.
title (str) – title of the plot
outputfilename (str) – output filename to save the plot to
zOffset (int) – z-offset when drawing in matplotlib. Higher is more to the front. Use in single integer steps.
defaultWidth (float) – default width of each magnet in metres.
elementDict (dict(str, dict(str, str|float|int))) – dictionary of element_name to dict of parameters
typeDict (dict(str, dict(str, str|float|int))) – dictionary of element_name to dict of parameters for a given type, e.g. QUADRUPOLE
funcDict (dict(str, function)) – dictionary of element_name to function to draw it
maskNames (list(str)) – list of elements to grey out as grey with alpha = 0.1
ignoreNames (list(str)) – list of elements to ignore and not draw at all
resolution (float) – sampling distance along curved arcs in metres
defaultCoilLength (float) – default coil length along S in metres
pipeRadius (None, float) – pipe radius (i.e. half-width) in metres
pipeMaskRanges (None, list(tuple(float, float))) – list of tuples of (start, end) to hide the beam pipe
invisibleAxes (bool) – whether to hide the bounding box of the matplotlib axes
arrowsDy (float) – fraction of figure height to move the orientation arrows (positive is up in the plot)
arrowsDx (float) – fraction of figure width to move the orientation arrows (positive is down in the plot)
defaultAlpha (None, float) – default alpha value to use for the whole beamline if not otherwise specified per element
drawXLabel (bool) – whether to draw the x-axis label on the axis
Order of precedence is: funcDict, elementDict, typeDict. i.e. funcDict replaces any information given in the other two. An elementDict always overrides any typeDict information.
- pymadx.Diagrams.Survey2DZY(survey_tfsfile, ax=None, greyOut=False, offsetRotoTranslation=None, title='', outputfilename=None, zOffset=0, defaultWidth=0.5, elementDict=None, typeDict=None, funcDict=None, maskNames=None, ignoreNames=None, resolution=0.1, defaultCoilLength=0.15, pipeRadius=None, pipeMaskRanges=None, invisibleAxes=False, arrowsDy=0, arrowsDx=0, defaultAlpha=None, drawXLabel=True)
Draw a schematic of a beamline in the Z-Y plane. Allow styling of different elements by type or by name.
- Parameters:
survey_tfsfile (str, pymadx.Data.Tfs) – list of tfs files as strings or already loaded pymadx.Data.Tfs objects.
ax (matplotlib.axes.Axes, None) – matplotlib axes object
greyOut (bool) – whether to plot the whole line in greyscale
offsetRotoTranslation (None, str, pymadx.Data.RotoTranslation2D) – Optional roto-translation to apply before plotting to offset the whole diagram. Can be the name of the element in the survey file also.
title (str) – title of the plot
outputfilename (str) – output filename to save the plot to
zOffset (int) – z-offset when drawing in matplotlib. Higher is more to the front. Use in single integer steps.
defaultWidth (float) – default width of each magnet in metres.
elementDict (dict(str, dict(str, str|float|int))) – dictionary of element_name to dict of parameters
typeDict (dict(str, dict(str, str|float|int))) – dictionary of element_name to dict of parameters for a given type, e.g. QUADRUPOLE
funcDict (dict(str, function)) – dictionary of element_name to function to draw it
maskNames (list(str)) – list of elements to grey out as grey with alpha = 0.1
ignoreNames (list(str)) – list of elements to ignore and not draw at all
resolution (float) – sampling distance along curved arcs in metres
defaultCoilLength (float) – default coil length along S in metres
pipeRadius (None, float) – pipe radius (i.e. half-width) in metres
pipeMaskRanges (None, list(tuple(float, float))) – list of tuples of (start, end) to hide the beam pipe
invisibleAxes (bool) – whether to hide the bounding box of the matplotlib axes
arrowsDy (float) – fraction of figure height to move the orientation arrows (positive is up in the plot)
arrowsDx (float) – fraction of figure width to move the orientation arrows (positive is down in the plot)
defaultAlpha (None, float) – default alpha value to use for the whole beamline if not otherwise specified per element
drawXLabel (bool) – whether to draw the x-axis label on the axis
Order of precedence is: funcDict, elementDict, typeDict. i.e. funcDict replaces any information given in the other two. An elementDict always overrides any typeDict information.
pymadx.Plot module
Various plots for madx TFS files using the pymadx Tfs class
- pymadx.Plot.AddMachineLatticeToFigure(figure, tfsfile, reverse=False, offset=None, s_offset=0.0)
Add a diagram above the current graph in the figure that represents the accelerator based on a madx twiss file in tfs format.
- Parameters:
figure (matplotlib.figure.Figure) – matplot figure
tfsfile (str, pymadx.Data.Tfs) – path to madx file
reverse (bool) – whether to reverse the order of the diagram
offset (None, str) – name of element in sequence to cycle the machine diagram about
s_offset (float, int) – apply this S offset to the diagram
>>> pymadx.Plot.AddMachineLatticeToFigure(gcf(), 'afile.tfs')
If the reverse flag is used, the lattice is plotted in reverse only. The tfs instance doesn’t change. 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 instance to plot a machine lattice from (default: None) outputfilename (str) - Name without extension of the output file if desired (default: None) plot (str) - Indicates which 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 defined 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.ApertureSeparate(aperture, machine=None, outputfilename=None, ymax=None, figsize=(12, 5))
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 instance to plot a machine lattice from (default: None) outputfilename (str) - Name without extension of the output file if desired (default: None) plot (str) - Indicates which 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 defined aperture point as a color-coded dot (default: False)
- pymadx.Plot.Beta(tfsfile, title='', outputfilename=None, machine=True, dispersion=True, squareroot=False, dispersionY=True, legendLoc='best', ax=None, figsize=(9, 5))
Plot Twiss Beta x,y as a function of S. By default, a machine diagram is shown at the top of the plot. Horizontal dispersion is included by default on a separate y-axis.
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.BetaMultiple(tfsfiles, labels=None, s_offsets=None, title='', outputfilename=None, machine=True, dispersion=True, squareroot=False, dispersionY=False, legendLoc='best')
Plot Twiss Beta x,y as a function of S. By default, a machine diagram is shown at the top of the plot. Horizontal dispersion is included by default on a separate y-axis.
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=None, outputfilename=None, machine=True, units=1000.0, grid=True, xtickmultiple=None)
Plot the centroid (mean) x and y from the Tfs file or
pymadx.Data.Tfs()instance.- Parameters:
tfsfile (str) – Tfs file (twiss output).
title (None, str) – Optional title of the plot
outputfilename (str) – Optional name to save file to (extension determines format).
machine (bool) – Whether to draw a machine diagram at the top.
units (float) – Optional factor to multiply by - default 1e3 for MADX m -> mm.
grid (bool) – Whether to draw a grid or not.
- Returns:
figure instance
- pymadx.Plot.CentroidsAngle(tfsfile, title='', outputfilename=None, machine=True)
Plot the centroid (mean) x and y from the Tfs file or
pymadx.Data.Tfs()instance.tfsfile - can be either a string or a
pymadx.Data.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.DrawMachineLattice(axesinstance, pymadxtfsobject, reverse=False, offset=None, useQuadStrength=True, maskNames=None, flipQuads=False, s_offset=0.0)
- pymadx.Plot.Envelopes(tfsfile, title='', outputfilename=None, machine=True, factors=(1, 3, 7), axX=None, axY=None, figsize=(9, 5))
Plot 1, 3, 7 sigma with the centroid added on.
- Parameters:
tfsfile (pymadx.Data.Tfs, str) – TFS file object or filename
title (str) – title of the figure
outputfilename (None, str) – output filename
machine (bool) – whether machine diagram is shown
factors (tuple(float, ....), list(float, ...)) – numbers of sigmas to plot of envelopes
axX (matplotlib.axes.Axes) – axes to draw the horizontal envelopes into
axY (matplotlib.axes.Axes) – axes to draw the vertical envelopes into
figsize (tuple(float, float)) – figure size
- pymadx.Plot.GetHorizontalVerticalMaskNames(tfs, collimatorHRegex=None, collimatorVRegex=None)
- pymadx.Plot.MachineDiagram(tfsfile, title=None, reverse=False, figsize=(10, 3))
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.PhaseAdvance(tfsfile, title='', outputfilename=None, machine=True, ax=None, figsize=(9, 5))
Plot mu x,y as a function of S. By default, a machine diagram is shown at the top of the plot.
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.PrintRMatrixTable(tfs)
- pymadx.Plot.RMatrixOptics(tfsfile, dx=1.0, dpx=1.0, dP=1.0, dy=1.0, dpy=1.0, outputfilename=None, collimatorHRegex=None, collimatorVRegex=None, figsize=(12, 8), grid=True, s_offset=None, machineFile=None, diagnosticS=None, aperture=None, apertureMinimum=0.001)
Plot the propagation of 3 rays with dx, dy, dpx, dpy, and dE independently. Two plots are given for horizontal and vertical planes in the same figure. The bends in the wrong plane are greyed out. The optional collimator regex patterns can be used to do the same for the collimators.
- Parameters:
dx (float) – displacement in x in mm
dpx (float) – displacement in px (component of unit vector) in 1e-3 (e.g. mrad in small angle).
dP (float) – displacement in momentum as a percentage
dy (float) – displacement in x in mm
dpy (float) – displacement in py (component of unit vector) in 1e-3 (e.g. mrad in small angle).
outputfilename (None, str) – Optional name to save file to - will save to both pdf and png.
collimatorHRegex (None, str) – Optional regular expression to match the collimator names in the horizontal.
collimatorVRegex (None, str) – Optional regular expression to match the collimator names in the vertical plane.
s_offset (None, float) – S to add to coordinates and machine diagram
machineFile (None, str) – Optional machine diagram file to override with, e.g. for tertiary optics.
diagnosticS (None, list(float)) – List of S locations to plot a purple dotted line over as a diagnostics highlight.
- pymadx.Plot.RMatrixOpticsSeparate(tfsfile, dx=1.0, dpx=1.0, dP=1.0, dy=1.0, dpy=1.0, title=None, outputfilename=None, machine=True, s_offset=None)
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.RMatrixTableString(tfs, tablefmt='grid')
- Parameters:
tfs (pymadx.Data.Tfs) – TFS object to inspect.
tablefmt (str) – tabulate table format
Get the most common rmatrix terms out of the TFS file and prepare a string of them in a nice big table. Returns a string.
- pymadx.Plot.RMatrixTableToPdf(tfs, outputfilename)
Save an rmatrix table to a pdf on multiple pages.
- Parameters:
tfs (pymadx.Data.Tfs) – TFS instance to get the data from.
outputfilename (str) – file name to save the pdf as
- pymadx.Plot.Sigma(tfsfile, title='', outputfilename=None, machine=True, dispersion=False, ax=None, figsize=(9, 5))
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.
- Parameters:
tfsfiles – list of tfs files as strings or already loaded pymadx.Data.Tfs objects.
title (str) – optional title for plot
outputfilename (str) – optional output file name including extension to plt.savefig
- pymadx.Plot.SurveyMultiple(tfsfiles, labels=None, title='', outputfilename=None)
Plot the X vs. Z and Y vs. Z coordinates from multiple tfs files on top of each other
- Parameters:
tfsfiles ([str,..], or [pymadx.Data.Tfs,...]) – list of tfs files as strings or already loaded pymadx.Data.Tfs objects.
labels ([str,...]) – optional list of labels that should match the length of tfsfiles
title (str) – optional title for plot
outputfilename (str) – optional output file name including extension to plt.savefig
- pymadx.Plot.SurveyMultipleHorizontal(tfsfiles, labels=None, title='', outputfilename=None)
Plot X vs. Z coordinates from multiple tfs files on top of each other
- Parameters:
tfsfiles ([str,..], or [pymadx.Data.Tfs,...]) – list of tfs files as strings or already loaded pymadx.Data.Tfs objects.
labels ([str,...]) – optional list of labels that should match the length of tfsfiles
title (str) – optional title for plot
outputfilename (str) – optional output file name including extension to plt.savefig
- pymadx.Plot.SurveyMultipleVertical(tfsfiles, labels=None, title='', outputfilename=None)
Plot Y vs. Z coordinates from multiple tfs files on top of each other
- Parameters:
tfsfiles ([str,..], or [pymadx.Data.Tfs,...]) – list of tfs files as strings or already loaded pymadx.Data.Tfs objects.
labels ([str,...]) – optional list of labels that should match the length of tfsfiles
title (str) – optional title for plot
outputfilename (str) – optional output file name including extension to plt.savefig
- pymadx.Plot.SurveyPlusRMatrix(twisstfs, surveytfs, verticalRMatrixScale=0.05, horizontalRMatrixScale=0.05, dx=5.0, dpx=0.5, dP=1.0, dy=5.0, dpy=0.5, title=None, outputfilename=None, machine=True, collimatorHRegex=None, collimatorVRegex=None, figsize=(12, 8), grid=True, s_offset=None, machineFile=None)
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 :param s_offset: S to add to coordinates and machine diagram :type s_offset: None, float
- pymadx.Plot.TwoMachineDiagrams(tfsTop, tfsBottom, labelTop=None, labelBottom=None, title=None, reverse=False, figsize=(10, 3))
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:
objectSimple 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:
objectSimple 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:
objectClass 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:
listClass 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:
objectDeprecated.
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()