API Reference

zgoubi.core

This contains the main PyZgoubi classes: Line and Results

zgoubi.core.Line

class zgoubi.core.Line(name)

The Line object holds a series of elements, to represent an accelerator lattice.

add(*elements)
Add an elements to the line. Can also be used to add one line into another.
add_input_files(file_paths=None, pattern=None)

Add some extra input files to the directory where zgoubi is run. This is useful for field map files. file_paths can be a string:

l.add_input_files('map')

an iterable, for example a list:

l.add_input_files(['map1', 'map2', 'map3'])

To add many files use a pattern eg:

l.add_input_files(pattern="maps/*")

Will use symlinks when avaliable (Linux/UNIX), falls back to copying otherwise.

clean()
clean up temp directories
dat()
return zgoubi.dat as a string. (It is better to use the equivalent method on the results object)
dat_fh()
return zgoubi.dat file handle. (It is better to use the equivalent method on the results object)
elements()
Iterator for elements in line, including sub lines.
fai()
return zgoubi.fai as a string. (It is better to use the equivalent method on the results object)
fai_fh()
return zgoubi.fai file handle. (It is better to use the equivalent method on the results object)
find_elements(element)
Returns all the positions of element in line
full_tracking(enable=True)
Enable full tracking on magnetic elements. This works by setting IL=2 for any element with an IL parameter. use line.full_tracking(False) to disable tracking
insert(index, *elements)
Insert elements into the line before position given by index
output()
Generate the zgoubi.dat file, and return it as a string
plt()
return zgoubi.plt as a string. (It is better to use the equivalent method on the results object)
plt_fh()
return zgoubi.plt file handle. (It is better to use the equivalent method on the results object)
remove(index)
Remove element at index
remove_looping()
removes any REBELOTE elements from the line
replace(elementold, elementnew, select_index=0)
Replace an element in the line. setting select_index to n will replace the nth occurence of that item. If select index is not set, the first occurence is replaced
res()
return zgoubi.res as a string. (It is better to use the equivalent method on the results object)
res_fh()
return zgoubi.res file handle. (It is better to use the equivalent method on the results object)
run(xterm=False, tmp_prefix='/tmp/', silence=False)
Run zgoubi on line. If break is true, stop after running zgoubi, and open an xterm for the user in the tmp dir. From here zpop can be run.
save_dat(path)
save zgoubi.dat to path. (It is better to use the equivalent method on the results object)
save_fai(path)
save zgoubi.fai to path. (It is better to use the equivalent method on the results object)
save_plt(path)
save zgoubi.plt to path. (It is better to use the equivalent method on the results object)
save_res(path)
save zgoubi.res to path. (It is better to use the equivalent method on the results object)
save_spn(path)
save zgoubi.spn to path. (It is better to use the equivalent method on the results object)
spn()
return zgoubi.spn as a string. (It is better to use the equivalent method on the results object)
spn_fh()
return zgoubi.spn file handle. (It is better to use the equivalent method on the results object)
track_bunch(bunch, **kwargs)
Track a bunch through a Line, and return the bunch. This function will uses the OBJET_bunch object, and so need needs a Line that does not already have a OBJET
track_bunch_mt(bunch, n_threads=4, max_particles=None, **kwargs)
This function should be used identically to the track_bunch function, apart from the addition of the n_threads argument. This will split the bunch into several slices and run them simultaneously. Set n_threads to the number of CPU cores that you have. max_particle can be set to limit how many particles are sent at a time.

zgoubi.core.Results

class zgoubi.core.Results(line=None, rundir=None, element_types=None)

This class lets you analyse the results after running a line.

b_fai()
return binary fai file as string
b_fai_fh()
return file handle for binary fai file
b_plt()
return binary plt file as string
b_plt_fh()
return file handle for binary plt file
check_bounds(file, min_bounds, max_bounds, coord='Y', part_ids=None, assume_in_order=False)
read whole file. for each chunk, check if it is an element with bounds, if yes check if it is inside record crashes, by particle id min_bounds and max_bounds should be of the form {‘label’: bound, ‘label’: bound} returns numpy arrays note: lost particles dont crash
clean()
clean up temp directory
dat()
return dat file as string
dat_fh()
return file handle for dat file
fai()
return fai file as string
fai_fh()
return file handle for fai file
get_all(file='plt', id=None)
Read all the data out of the file. Set file to plt or fai if using the new headered data formats will return a numpy array with named columns, otherwise returns a list of dicts. each dict has the particle coordinates at a point
get_bunch(file, end_label=None, old_bunch=None)
“Get back a bunch object from the fai file. It is recommended that you put a MARKER before the last FAISCNL, and pass its label as end_label, so that only the bunch at the final position will be returned. All but the final lap is ignored automatically. Optionally the an old_bunch can be passed to the function, its mass and charge will be copyed to the new bunch.
get_extremes(file, element_label=None, coord='Y', id=None)
Get the max and min positions of a certain coordinate, in a certain element
get_track(file, coord_list, multi_list=None)

returns a list of coordinates specified, and multiply them by the multiplier if not none eg get_trac(‘plt’, [‘X’,’Y’,’element_label’],[0.01,0.01,None])

If all the columns requested are numerical, and new headered data formats are being used then this function will return a numpy array

get_tune()
Returns a tuple (NU_Y, NU_Z) of the tunes. Needs a beam line is an OBJET type 5, and a MATRIX element.
get_twiss_parameters()
Returns a tuple (beta_y, alpha_y, gamma_y, beta_z, alpha_z, gamma_z) from the twiss parameter matrix. Needs a beam line is an OBJET type 5, and a MATRIX element.
in_bounds(file, element_label, min_bound, max_bound, coord='Y', verbose=False, id=None)
check if particle exceeded bounds in this element. pass bounds in zgoubi’s default unit for that coordinate
plt()
return plt file as string
plt_fh()
return file handle for plt file
res()
return res file as string
res_fh()
return file handle for res file
run_success()
Checks that zgoubi completed
save_b_fai(path)
save binary fai file to path
save_b_plt(path)
save binary plt file to path
save_dat(path)
save dat file to path
save_fai(path)
save fai file to path
save_plt(path)
save plt file to path
save_res(path)
save res file to path
save_spn(path)
save spn file to path
show_particle_info()
show the particle info, a good check of energies, mass etc
spn()
return spn file as string
spn_fh()
return file handle for spn file
test_rebelote()
Return true if end of REBELOTE procedure reported Needs a REBELOTE element.

zgoubi.bunch

A bunch object to hold the coordinates for many particles

Note that all values are in SI units, m, rad, eV, s

class zgoubi.bunch.Bunch(nparticles=0, ke=None, rigidity=0, mass=0, charge=1, particles=None)

Object to store a bunch of particles efficiently using numpy. All values are in SI units, m, rad, eV, s Can be use to create a bunch of particles with all there coordinates set to zero (appart from the D coordinate which is set to 1):

my_bunch = Bunch(nparticles=100, ke=1e6, mass=PROTON_MASS, charge=1)

It can also be used to create a bunch from some existing coordinates stored in a numpy array:

my_bunch = Bunch(ke=1e6, mass=PROTON_MASS, charge=1, particles=existing_coords)
static gen_gauss_x_xp_y_yp(npart, emit_y, emit_z, beta_y, beta_z, alpha_y, alpha_z, seed=None, ke=None, rigidity=0, mass=0, charge=1)

Generate a Gaussian bunch in x-xp (Y-T) and in y-yp (Z-P). S and D are set to 0 and 1 respectively. example:

my_bunch = Bunch.gen_kv_x_xp_y_yp(1000, 1e-3, 1e-3, 4, 5, 1e-3, 2e-2, ke=50e6, mass=PROTON_MASS, charge=1)

creates a Gaussian bunch called my_bunch with 1000 particles of the given parameters.

static gen_gauss_x_xp_y_yp_s_dp(npart, emit_y, emit_z, beta_y, beta_z, alpha_y, alpha_z, mom_spread=0, bunch_length=0, disp=0, disp_prime=0, seed=None, ke=None, rigidity=0, mass=0, charge=1)
Generate a Gaussian bunch in transverse and longitudinal phase space emit_y, emit_z : horizontal and vertical plane geometric emittance (1 sigma) beta_y, beta_z : horizontal and vertical betatron function alpha_y, alpha_z : horizontal and vertical alpha mom_spead : sigma of momentum spread (percentage) bunch_length : sigma of bunch length (metres) disp, disp_prime : dispersion and dispersion prime (D’) in horizontal plane
static gen_halo_x_xp_y_yp(npart, emit_y, emit_z, beta_y, beta_z, alpha_y, alpha_z, seed=None, ke=None, rigidity=0, mass=0, charge=1)

Generate a halo bunch, i.e. an elipse outline in x-xp (Y-T) and in y-yp (Z-P). S and D are set to 0 and 1 respectively. example:

my_bunch = Bunch.gen_halo_x_xp_y_yp(1000, 1e-3, 1e-3, 4, 5, 1e-3, 2e-2, ke=50e6, mass=PROTON_MASS, charge=1)

creates a halo bunch called my_bunch with 1000 particles of the given parameters.

static gen_kv_x_xp_y_yp(npart, emit_y, emit_z, beta_y, beta_z, alpha_y, alpha_z, seed=None, ke=None, rigidity=0, mass=0, charge=1)

Generate a uniform (KV) bunch, i.e. a filled elipse in x-xp (Y-T) and in y-yp (Z-P). S and D are set to 0 and 1 respectively. example:

my_bunch = Bunch.gen_kv_x_xp_y_yp(1000, 1e-3, 1e-3, 4, 5, 1e-3, 2e-2, ke=50e6, mass=PROTON_MASS, charge=1)

creates a KV bunch called my_bunch with 1000 particles of the given parameters.

get_bunch_ke()
Get bunch kinetic energy
get_bunch_rigidity()
Get bunch rigidity
get_centers()
Returns the center of the bunch in each dimension Y,T,Z,P,S,D
get_emmitance()
return emittance h and v in m rad. Uses the bunch full width, so should only be used for a hard edge distribution
get_min_BORO()
Returns the minimum rigidity of the bunch
get_twiss(emittance)
Returns the twiss valuse Beta_h, Alpha_h, Beta_v, Alpha_v, calculated from bunch width extent
get_widths()
Returns the width of the bunch in each dimension Y,T,Z,P,S,D (D not calculated yet)
particles()
Returns the numpy array that holds the coordinates
plot(fname=None, lims=None, add_bunch=None)
Plot a bunch, if no file name give plot is displayed on screen. lims can be used to force axis limits eg [lY,lT,lZ,lP,lX,lD] would plot limit plot from -lY to +lY in Y, etc. Additional bunches can be passed, as add_bunch, to overlay onto the same plot.
static read_YTZPSD(fname, ke=None, rigidity=0, mass=0, charge=1)
Read in a bunch from a file. assumes columns are Y, T, Z, P, X, D, separated by white space:: my_bunch = Bunch.read_YTZPSD(“mybunch.dat”, ke=1e9, mass=ELECTRON_MASS, charge=-1)
set_bunch_ke(ke)
Set bunch kinetic energy
set_bunch_rigidity(rigidity)
Set bunch rigidity
split_bunch(max_particles, n_slices)
Split a bunch into n_slices smaller bunches, or more if they would have too many particles in.
write_YTZPSD(fname, binary=False)
Output a bunch, compatible with read_YTZPSD

zgoubi.constants

Some physical constants.

zgoubi.ellipse

Algorithm by J. Scott Berg to find the smallest circle that enclose a set of ellipses that lie on the midplane.

class zgoubi.ellipse.BestCircle

Class to allow one to find a circle enclosing a set of ellipses. append((a, b, c)) adds an ellipse to the set of ellipses, where a is the half width, b is the half height, and c is the horizontal center.

radius(z) returns the radius of a circle with horizontal center at z which encloses all the ellipses.

get_circle() returns a sequence (z, r) giving the horizontal center z and radius r of the smallest circle enclosing all of the ellipses

append(e)
Add an ellipse e to the set of ellipses
get_circle()
Return (z,r), where z is the center and r is the radius of the circle with the smallest radius that encloses all the ellipses
radius(z)
Get the radius of a circle, centered at z, enclosing all of the ellipses
zgoubi.ellipse.ivl_add(l, ivl)
Add the interval ivl=(min, max) to the interval list l

zgoubi.execptions

Exceptions raised by pyzgoubi

exception zgoubi.exceptions.BadLineError
Line on sufficient for this function
exception zgoubi.exceptions.NoTrackError
No particle track
exception zgoubi.exceptions.OldFormatError
Old file format passed to function that expects new format

zgoubi.io

Module to handle reading and writing of Zgoubi files

zgoubi.io.define_file(fname, allow_lookup=True)
Read header from a file and determine formating. Returns a dict that describes the file
zgoubi.io.listreplace(l, old, new)
Replace all occurrences of ‘old’ with ‘new’ in ‘l’
zgoubi.io.open_file_or_name(forn, mode='r')
Pass either a filename or file handle like object. Returns a file like object
zgoubi.io.read_file(fname)
Read a zgoubi output file. Return a numpy array with named column headers. The format is automatically worked out from the header information.
zgoubi.io.read_fortran_record(fh)
Read 1 record from a fortran file
zgoubi.io.store_def_all()
Run define file on set of files, and output a code block that can be put into the to of this file to save rerunning define_file at program runtime
zgoubi.io.write_fortran_record(fh, record)
Write a record, adds record length to start and end

zgoubi.rel_conv

All values in energy eV, momentum eV/c, mass ev/c**2, speed c, charge elementry charge

zgoubi.rel_conv.beta_to_gamma(beta)
Convert speed to lorentz factor
zgoubi.rel_conv.beta_to_ke(mass, beta)
Convert speed to kinetic energy
zgoubi.rel_conv.gamma_to_beta(gamma)
Convert lorentz factor to speed
zgoubi.rel_conv.gamma_to_ke(mass, gamma)
Convert lorentz factor to kinetic energy
zgoubi.rel_conv.ke_to_beta(mass, ke)
Convert kinetic energy to speed
zgoubi.rel_conv.ke_to_gamma(mass, ke)
Convert kinetic energy to lorentz factor
zgoubi.rel_conv.ke_to_mom(mass, ke)
Convert kinetic energy to momentum
zgoubi.rel_conv.ke_to_rigidity(mass, ke, charge)
Convert kinetic energy to magnetic rigitity
zgoubi.rel_conv.ke_to_te(mass, ke)
Convert kinetic energy to total energy
zgoubi.rel_conv.mom_to_ke(mass, mom)
Convert momentum to kinetic energy
zgoubi.rel_conv.mom_to_rigidity(mom, charge)
Convert momentum to magnetic rigitity
zgoubi.rel_conv.mom_to_te(mass, mom)
Convert momentum to total energy
zgoubi.rel_conv.rigidity_to_ke(mass, rigidity, charge)
Convert magnetic rigitity to kinetic energy
zgoubi.rel_conv.rigidity_to_mom(rigidity, charge)
Convert magnetic rigitity to momentum
zgoubi.rel_conv.te_to_ke(mass, te)
Convert total energy to kinetic energy
zgoubi.rel_conv.te_to_mom(mass, te)
Convert total energy to momentum

zgoubi.utils

Various useful functions and utilities

zgoubi.utils.calc_area_simple(ellipse, centre=(0, 0))
can’t handle noise. finds closest and furthest point from centre, assumes they are a and b
zgoubi.utils.coords_grid(min_c=None, max_c=None, step=None, dtype=<type 'float'>)

make a list of coordinate aranged in a grid in a generalised space eg:

coords_grid(min_c=[0,0],max_c=[1,1],step=[10,10])

will give you 100 points in 2 dimensions between 0 and 1

zgoubi.utils.emittance_to_coords(emit_horizontal, emit_vertical, gammayz, betayz, beta_gamma_input=1, ncoords=1)

Given some emittance in horizonal and vertical space

If ncoords <= 1 return points where phase space ellipse crosses the y,y’ and z,z’ axis.

If ncoords > 1, will instead give a distribution of points (y,t) around the phase space ellipse uniform in angle theta where::
y = a*cos(theta)*cos(phi) - b*sin(theta)*sin(phi) t = a*cos(theta)*sin(phi) + b*sin(theta)*cos(phi)

where (a,b) are major and minor radii and phi is the tilt of the major radius w.r.t horizontal axis. A (z,p) distribution is similarly calculated.

Can use these points, returned in coords_YTZP to start tracking at the desired emittance (assuming that the optical functions don’t change with amplitude).

Emittances in both the horizontal and vertical planes may be supplied. Twiss parameters beta and gamma in both places may be determined calling get_twiss_parameters beforehand i.e.:

twissparam = r.get_twiss_parameters()
betayz = [twissparam[0],twissparam[3]]
gammayz = [twissparam[2],twissparam[5]]
zgoubi.utils.find_centre(ellipse)
find centre by using mean of coords, this assumes that point are evenly distributed around ellipse
zgoubi.utils.find_closed_orbit(line, init_YTZP=None, max_iterations=100, fai_label=None, tol=9.9999999999999995e-07, D=1)

Find a closed orbit for the line. can optionally give a list of initial coordinates, init_YTZP, eg: find_closed_orbit(line, init_YTZP=[1.2,2.1,0,0]) otherwise [0,0,0,0] are used.

The line is expected to have a OBJET2 and either a FAISCNL at the end or, using FAISTORE, a MARKER at the end of the cell identified by fai_label. The latter option allows the zgoubi.fai file to contain coordinates throughout the lattice while using just those points with fai_label in this function.

It is recommend to have a REBELOTE, with several laps. The area of the phase space ellipse is approximated from the coordinates from the FAISCNL (or MARKER with fai_label), and the center is used for the new coordinates. Once the relative variation between iterations is less that the tolerance, the function returns the closed orbit coordinates. If a coordinate is close to zero (less than the tolerance) then it is compared absolutely instead of relatively.

zgoubi.utils.find_closed_orbit_range(line, init_YTZP=None, max_iterations=100, fai_label=None, tol=9.9999999999999995e-07, D=1, range_YTZP=None, count_YTZP=None)

Same as find_closed_orbit, but if init_YTZP is unstable, will generate a bunch or particles, with a spread of range_YTZP, and if any of those are stable will do a closed orbit search with that particle:

init_YTZP=[5,0,0,0], range_YTZP=[10,0,0,0], count_YTZP[50,0,0,0]

will vary the Y coordinate from -5 to 15 cm in 50 steps:

range_YTZP=[10,5,0,0], count_YTZP=[10,10,0,0]

would create 100 particles in a grid.

zgoubi.utils.find_indices(a_list, list_element)
Find all occurences of list_element in list. Return the indices.
zgoubi.utils.flatten(x)

flatten(sequence) -> list

Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables).

http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks

Examples: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)]) [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]

zgoubi.utils.fourier_tune(line, initial_YTZP, D_in, nfourierturns, plot_fourier=False, coords=None)

Calculate tune using FFT. nfourierturns determines the number of passes through the lattice. Can supply set of horizontal and vertical coordinates in coords = [ycoords,zcoords], otherwise

routine will calculate coordinates

Set plot_fourier= True to show Fourier spectrum. Default is False

zgoubi.utils.gaussian_cutoff(npoints, mean, sigma, sigma_cutoff, seed=None)

Generate Gaussian distribution about mean with standard deviation sigma npoints - number of points in distribution required sigma_cutoff - the cutoff factor i.e. points outside sigma*sigma_cutoff eliminated

Seed - Optional parameter to set random seed

zgoubi.utils.get_cmd_param(key, default=None)
get things formated like key=value from the commandline. returns the requested value
zgoubi.utils.get_cmd_param_bool(key, default=None)
get things formated like key=value from the commandline. returns true for: yes, on, true, 1 returns false for: no, off, false, 0 case insensitve
zgoubi.utils.get_enclosing_circle(ellipse_data)

Find smallest circle that encloses a set of ellipses centred on the midplane. The ellipses are defined by their horizontal and vertical radii and by their centre along the horizontal axis (a,b,c). The algorithm optimised both the centre of the enclosing circle and its radius.

Ellipse algorithm by J. Scott Berg (BNL)

Reference - J. Scott Berg. ‘Finding the Circular Magnet Aperture which Encloses and Arbitrary number of midplace-centered Beam Ellipses’, Proc. EPAC04, 5-9 July, Lucerne Congress Centre, Lucerne, Switzerland

zgoubi.utils.get_twiss_profiles(line, file_result, input_twiss_parameters=None)

Calculates the twiss parameters at all points written to zgoubi.plt. 11 particle trajectories are used to calculate the transfer matrix, just as is done in zgoubi. The code mirrors that found in mat1.f, mksa.f. The twiss parameters are first calculated at the end of the cell using either input_twiss_parameters (format [beta_y, alpha_y, gamma_y, beta_z, alpha_z, gamma_z]) or, if this is not supplied, it assumes the cell is periodic and uses get_twiss_parameters to find the boundary condition.

The twiss parameters are then mapped to all points in the magnets using the transfer matrix calculated at each point. The results are stored in list twiss_profiles where each row represents a point in the zgoubi.plt file and has format

[s_coord, label, mu_y, beta_y, alpha_y, gamma_y, mu_z, beta_z, alpha_z, gamma_z]

Requires an OBJET type 5, and a MATRIX element.

Note - This calculation uses trajectories as measured in the local coordinate system of the magnet.

zgoubi.utils.ke_to_relativistic_beta_gamma(ke, mass)
ke in eV, mass in eV/c^2
zgoubi.utils.ke_to_rigidity(ke, mass)
ke in eV, mass in eV/c^2 gives result in kGauss cm, which is handy for OBJET
zgoubi.utils.misalign_element(line, element_indices, mean, sigma, sigma_cutoff, misalign_dist=None, seed=None)

Misalign the set of elements identified by element_indices. The misalignment is Gaussian with sigma, sigma_cutoff and mean among the input parameters. If sigma = 0.0, the misalignment is constant and given by mean

Alternatively, misalignments specified by list misalign_dist

Returns the misailgnment distribution (misalign_dist), unit meters

element_indices can be determined using line.find_elements(element_name)

mean and sigma should be input in meters

zgoubi.utils.mom_to_ke(mom, mass)
mom in eV/c gives results in eV
zgoubi.utils.mom_to_rigidity(mom)
mom in eV/c gives result in kGauss cm, which is handy for OBJET
zgoubi.utils.plot_data_xy_multi(data_x_list, data_y_list, filename, labels=None, style='', legend=' ', legend_location='best', xlim=None, ylim=None)

Plots multiple sets of data where the X and Y coordinates are each specified in a list of lists. Should also work if a single set of X, Y data is specified or if one X is supplied with multiple Y data points (as long the dimensions of Y equals that of X in all cases).

Required input - data_x_list - Set of X data. May be a single list or a list of lists each with the same dimension. data_y_list - Set of Y data. May be a single list or a list of lists each with the same dimension. Can have a single list of X data and multiple lists of data_y_list. filename - Plot saved to filename.png

Optional parameters - labels = [“Plot Title”,”X axis label”,”Y axis label”] style - The plot style can be supplied as a list or as a single value. If no style is specified, will cycle over a predefined style list. legend - Legends can be supplied as a list of strings or as a single string. legend_location - Default of location of legend box is ‘best’, otherwise can select ‘upper right’ or numerical code for position. See matplotlib documentation. xlim = [lower_value, upper_value] - Limit horizontal axis ylim = [lower_value, upper_value] - Limit vertical axis

zgoubi.utils.readArray(filename, skipchar='#', dtype=<type 'float'>)

# PURPOSE: read an array from a file. Skip empty lines or lines # starting with the comment delimiter (defaulted to ‘#’). # # OUTPUT: a float numpy array # # EXAMPLE: >>> data = readArray(“/home/albert/einstein.dat”) # >>> x = data[:,0] # first column # >>> y = data[:,1] # second column from http://www.scipy.org/Cookbook/InputOutput

Note: please switch to using numpy functions: numpy.savetxt(), numpy.loadtxt() or numpy.genfromtxt()

zgoubi.utils.scaling_to_dipole(k, r0, b0_in, d_r0=0, scale_factor=1.0, terms=4)

A scaling FFAG has field given by B/B0 = (r/r0)^k where k is the scaling factor. The Taylor expansion about r0 yields

B(r)/B0 = (k!/(n!(k-n)!)) * (r-r0)^n/r0^n for each multipole n

In DIPOLES the magnetic field (ignoring fringe field factor) is given by

B(r)/B0 = bcoef[n] (r-r0)^n/r0^n for each multipole n

It follows that setting bcoef[n] = (k!/(n!(k-n)!)) will create a DIPOLE magnet whose field approximates the scaling law. Routine returns bcoef up to number of terms specified.

If r0 is scaled by scale_factor, the coefficients are scaled accordingly. If r0 is shifted by d_r0, the routine will update B0 (b0_in) according to the scaling law

zgoubi.utils.scaling_to_poly(b0, k, r0, rmin, rmax, step, order=5)

In a scaling FFAG, the magnetic field follows the scaling law given by B=B0*(r/r0)^k where r is the radial coordinate, B0 is the field at r=r0 and k is the scaling factor. This def fits a polynomial of a given order to the scaling field at points in the region rmin < r < rmax, where the number of points is determined by the increment step. The coefficients of polynomial are returned.

Required input - b0 - the field at r0 r0 - the reference radius rmin,rmax - region of fit step - step size in (rmin,rmax) at which scaling field is evaluated

Optional input- order - Order of polynomial fit (default 5)

Author - S. Sheehy

zgoubi.utils.scan_dynamic_aperture(line, emit_list, closedorb_YTZP, npass, D_mom, beta_gamma_input=1, ellipse_coords=1, twiss_parameters=[], plot_data=False)

Check a list of emittances (emit_list, units Pi m rad) to see if tracking succeeds. Can be used to establish the dynamic aperture. If the elements in emit_list are increasing then will stop tracking once it finds the lowest emittance where a particle is lost. On the other hand, if the elements in emit_list are decreasing then will stop tracking once it reaches the first point where tracking succeeds without loss.

Required input:

emit_list - List of emittances to check

closedorb_YTZP - Closed orbit coordinates as returned by find_closed_orbit

npass - Number of passes through lattice

D_mom - Momentum factor p/pref

Optional input

beta_gamma_input - If this is supplied then the emittances supplied in emit_list are assumed to be normalised and a conversion t o geometrical emittance is made. Otherwise the emittances are assumed to be geometrical.

ellipse_coords - If greater than 1 will test uniformly distributed set of coordinates around around phase space ellipse. Otherwise will take single point where phase space cuts y (or z) axis. Can also specify ellipse coords = [n,m] – distribute n points around ellipse but only test point m of these.

twiss_parameters - Can supply twiss parameters in format [[alpha_y,beta_y,gamma_y],[alpha_z,beta_z,gamma_z]], i.e the output of r.get_twiss_parameters(). If not supplied an attempt will be made to calculate the twiss parameters in this function.

plot_data - If True, creates phase space plots at all emittances scanned in both transverse planes.

If a particle is lost, returns index_lost in emit_list where the loss occurs. Otherwise index_lost remains 0.

zgoubi.utils.show_file(file_path, mode)
shows a file. mode can be: cat - dumps to screen less - scrollable view win - scollable new win (less in an xterm)
zgoubi.utils.tune_diagram(tune_list, order=3, xlim=None, ylim=None)

Plot a list of tunes on a tune diagram with resonance line up to a given order.

Required input
tune_list - format [[list of horizontal tunes],[list of vertical tunes]]
Optional
order - Integer denoting order up to which resonance lines are drawn. Default value 3 (third order). xlim = [lower_value, upper_value] - Limit horizontal axis ylim = [lower_value, upper_value] - Limit vertical axis

At the moment, since the tune diagram covers the range [0,1] just fractional tunes can be shown. The default value of order is 3. Written by Y. Giboudet