xboa.Common
index
/home/cr67/MAUS/maus_merge/third_party/install/lib/python2.7/site-packages/xboa/Common.py

Common module contains a number of useful interfaces, defaults, data and ancillary functions that support the rest of the XBOA package.
Maths functions:
  min_max
  multisort
  nd_newton_raphson1
  nd_newton_raphson2
Interfaces to ROOT plotting library:
  has_root
  make_root_graph
  make_root_histogram
  make_root_multigraph
  clear_root
  wait_for_root
  make_root_canvas
Interfaces to matplotlib plotting library:
  has_matplot
  make_matplot_graph
  make_matplot_histogram
  make_matplot_multigraph
  make_matplot_scatter
  wait_for_matplot
  matplot_show_and_continue
Physics data:
  constants
  pdg_pid_to_icool
  pdg_pid_to_mars
  pdg_pid_to_mass
  pdg_pid_to_name
  pdg_pid_to_charge
  icool_pid_to_pdg
  mars_pid_to_pdg
  units
Defaults for e.g. root canvases, etc:
  canvas_fill_color
  canvas_highlight_color
  default_margin
  float_tolerance
  graph_margin
  histo_margin
  python_version
  xboa_version
  kill_subprocesses_at_exit
Some other useful functions:
  get_bin_edges
  histogram
  substitute
  has_numpy
  build_installation
  make_grid
  make_shell
  normalise_vector
  kolmogorov_smirnov_test
  kill_all_subprocesses
  has_multiprocessing
  has_json

 
Modules
       
ROOT
atexit
bisect
copy
ctypes
json
libMausCpp
numpy.linalg
math
matplotlib
multiprocessing
numpy
operator
os
pydoc
pylab
matplotlib.pyplot
signal
string
sys
time

 
Classes
       
rg

 
class rg
    Container to hold some details of root global style information
 
  Data and other attributes defined here:
canvas_border_mode = 0
canvas_fill_color = 10
canvas_highlight_color = 2
fill_color = 0
graph_fill_color = 10
graph_margin = 0.1
hist_fill_color = 10
histo_margin = 0.0
line_color = 1
line_style = 1
line_width = 2
stats = False

 
Functions
       
clear_root()
Close root plots (and free memory)
common_overview_doc(verbose=False)
Creates some summary documentation for the Common module. If verbose is True then will also print any functions or data not included in summary
get_bin_edges(list_of_variables, number_of_bins, xmin=None, xmax=None)
Get a sorted list of equally spaced bin edges from a list of floats
 
- list_of_variables = list of floats to be binned
- number_of_bins    = number of bins to make; note that there will be number_of_bins+1 edges
- xmin              = lower edge of all the bins (set to None to auto-detect)
- xmax              = upper edge of all the bins (set to None to auto-detect)
has_json()
Raise an exception if json data libraries have not been imported properly
has_matplot()
Raise an exception if NumPy numerical algebra libraries have not been imported properly
has_maus()
Raise an exception if MAUS tracking library has not been imported properly
has_multiprocessing()
Raise an exception if multiprocessing libraries have not been imported properly
has_numpy()
Raise an exception if NumPy numerical algebra libraries have not been imported properly
has_root()
Raise an exception if ROOT graphics libraries have not been imported properly
histogram(x_values, x_bins, y_values=None, y_bins=None, weights=None)
Get a 1d or 2d list of bin weights from a set of data, weights and bin edges
 
- x_values = list of x values to be binned
- x_bins   = list of x bin edges
- y_values = list of y values to be binned. Set to None to make a 1d binning
- y_bins   = list of y bin edges of same length as x_values
- weights  = list of statistical weights of same length as x_values. Set to None to make all weights default to 1.
 
Return value is a tuple of (bin_weights, x_bins, y_bins)
kill_all_subprocesses()
Kill all subprocesses generated by Common.subprocess call; automatically called at exit unless kill_subprocesses_at_exit is set to False
Note that this makes a call to the os, which may take a bit of time to respond.
kolmogorov_smirnov_test(list_1, list_2)
Convenience wrapper for ROOT kolmogorov-smirnov test.
- list_1 = list of floats that are sampled from some parent probability distribution
- list_2 = list of floats that are sampled from other some parent distribution
Returns double between 0. and 1. giving probability that list_1 and list_2 have the same parent distribution.
make_dist_preliminaries(source_folder='/home/cr67', target_folder='/home/cr67', test=True)
Preliminaries to making a distribution:
- run test scripts
- generate documentation
make_doc(source_folder='/home/cr67', target_folder='/home/cr67', test=True)
make_grid(n_dimensions, n_per_dimension)
Make a rectangular n_dimensional grid of points evenly spaced between [-1,1] in each 
dimension
 
- n_dimensions     = number of dimensions
- n_per_dimension  = number of points in each dimension; total number of points will be
                     n_per_dimension^n_dimensions
 
Return value is a list of numpy.matrices with shape (n_dimensions, 1)
make_matplot_graph(x_float_list, x_axis_string, y_float_list, y_axis_string, sort=True)
Make a matplot graph with data taken from float lists and axes naemd after the axis strings. Return value is a tuple of (hist, graph)
matplot can format using tex expressions - use '$some math expression$' to include math text in your labels
 
- x_float_list  = list of x-data
- x_axis_string = string used to label the x-axis
- y_float_list  = list of y-data
- y_axis_string = string used to label the y-axis
- sort          = boolean - set to true to automatically sort input data
 
After building the graph, use matplotlib.pyplot.show() to show something on the screen
make_matplot_histogram(x_float_list, x_axis_string, n_x_bins, y_float_list=[], y_axis_string='', n_y_bins=0, weight_list=[])
Make a matplot graph with data taken from float lists and axes naemd after the axis strings. Return value is a tuple of (hist, graph)
matplot can format using tex expressions - use '$some math expression$' to include math text in your labels
 
- x_float_list  = list of x-data
- x_axis_string = string used to label the x-axis
- y_float_list  = list of y-data
- y_axis_string = string used to label the y-axis
 
After building the graph, use matplotlib.pyplot.show() to show something on the screen
make_matplot_multigraph(x_float_list_of_lists, x_axis_string, y_float_list_of_lists, y_axis_string)
Print several different graphs on the same axes. Some default colour scheme is applied, but it may not be the best...
 
- x_float_list_of_lists = list of lists. Each list will be used as the x-axis for a graph
- x_axis_string         = string that will be used to label the x_axis
- y_float_list_of_lists = list of lists. Each list will be used as the y-axis for a graph
- y_axis_string         = string that will be used to label the y_axis
 
E.g. Common.make_matplot_multigraph('example', [[1.,2.,3.,4.], [1.,4.,9.,16.]], 'x', [[1.,2.,3.,4.],[1.,2.,3.,4.]], 'f(x)') will make a graph of f = x and  f = x^0.5
make_matplot_scatter(x_float_list, x_axis_string, y_float_list, y_axis_string)
Make a matplot scatter graph with data taken from float lists and axes naemd after the axis strings.
matplot can format using tex expressions - use '$some math expression$' to include math text in your labels
 
- x_float_list  = list of x-data
- x_axis_string = string used to label the x-axis
- y_float_list  = list of y-data
- y_axis_string = string used to label the y-axis
 
After building the graph, use matplotlib.pyplot.show() to show something on the screen
make_root_canvas(name_string, title_string=None, bg_color=10, highlight_color=2, border_mode=0, frame_fill_color=10)
Make a root canvas with name canvas_name_string-<index> where <index> is a unique integer starting from 0
 
- name_string      = Name of the canvas. Due to a ROOT bug, xboa adds a unique identifier to the name_string to ensure the canvas is drawn.
- title_string     = Title of the canvas (as displayed in canvas window title bar); if set to None will use the name_string.
- bg_color         = Fill color of the canvas.
- highlight_color  = When a canvas is selected, ROOT draws a border with a particular color to indicate that the canvas is selected.
- border_mode      = When a canvas is selected, ROOT draws a border if border mode is not set to 0.
- frame_fill_color = Fill color of frames drawn on the canvas (e.g. histograms).
make_root_graph(name_string, x_float_list, x_axis_string, y_float_list, y_axis_string, sort=True, xmin=None, xmax=None, ymin=None, ymax=None, line_color=1, line_style=1, line_width=2, fill_color=10, hist_title_string='')
Make a root graph with data taken from float lists and axes named after the axis strings. Return value is a tuple of (hist, graph)
 
- name_string   = name given to the histogram
- x_float_list  = list of x-data
- x_axis_string = string used to label the x-axis
- y_float_list  = list of y-data
- y_axis_string = string used to label the y-axis
- sort          = boolean - set to true to automatically sort input data
- xmin          = float that overrides auto-detection of minimum x-axis value
- xmax          = float that overrides auto-detection of maximum x-axis value
- ymin          = float that overrides auto-detection of minimum y-axis value
- ymax          = float that overrides auto-detection of maximum y-axis value
- line_color    = int that sets the line colour of the graph
- line_style    = int that sets the line style of the graph
- line_width    = int that sets the line width of the graph
- fill_color    = graphs dont usually get a fill, but sometimes the fill colour turns up in e.g. legend drawing
- hist_title_string    = specify the string that will appear as a title
 
Return value is a tuple of (histogram, graph)
make_root_histogram(name_string, x_float_list, x_axis_string, n_x_bins, y_float_list=[], y_axis_string='', n_y_bins=0, weight_list=[], xmin=None, xmax=None, ymin=None, ymax=None, line_color=1, line_style=1, line_width=2, fill_color=0, stats=False, hist_title_string='')
Make a root histogram with data taken from float lists and axes named after the axis strings.
 
- name_string   = name given to the histogram
- x_float_list  = list of x-data
- x_axis_string = string used to label the x-axis
- n_x_bins      = number of bins in x direction
- y_float_list  = list of y-data. If number of items in y list not equal to number in x list, will build 1d histogram
- y_axis_string = string used to label the y-axis
- n_y_bins      = number of y bins
- weight_list   = if present, each item will be filled with weight taken from this list
- xmin          = float that overrides auto-detection of minimum x-axis value
- xmax          = float that overrides auto-detection of maximum x-axis value
- ymin          = float that overrides auto-detection of minimum y-axis value
- ymax          = float that overrides auto-detection of maximum y-axis value
- line_color    = int that sets the line colour of the histogram
- line_style    = int that sets the line style of the histogram
- line_width    = int that sets the line width of the histogram
- fill_color    = int that sets the fill color of the histogram
- stats         = set to True to plot a stats box on the histogram
- hist_title_string = specify the string that will appear as a title on the canvas
 
Return value is the histogram
make_root_legend(canvas, root_item_list)
Build a legend for the canvas
make_root_multigraph(name_string, x_float_list_of_lists, x_axis_string, y_float_list_of_lists, y_axis_string)
Print several different graphs on the same canvas. Some default colour scheme is applied, but it may not be the best...
 
- name_string  = name that will be given to the axes (histogram)
- x_float_list_of_lists = list of lists. Each list will be used as the x-axis for a graph
- x_axis_string         = string that will be used to label the x_axis
- y_float_list_of_lists = list of lists. Each list will be used as the y-axis for a graph
- y_axis_string         = string that will be used to label the y_axis
 
E.g. Common.make_root_multigraph('example', [[1.,2.,3.,4.], [1.,4.,9.,16.]], 'x', [[1.,2.,3.,4.],[1.,2.,3.,4.]], 'f(x)') will make a graph of f = x and  f = x^0.5
make_shell(n_per_dimension, ellipse)
Make a shell of points that sit on a hyper-ellipsoid defined by ellipse matrix
 
- n_per_dimension  = number of points in each dimension; total number of points will be
                     n_per_dimension^n_dimensions if n_per_dimension is even or
                     n_per_dimension^n_dimensions-1 if n_per_dimension is odd
- ellipse          = matrix that defines the ellipse on which vector sits; should be a
                     numpy.matrix with shape (vec_length, vec_length)
 
Points are defined on a (hyper-)cuboidal grid and then compressed so that lengths are 
all 1. Doesn't necessarily mean points are evenly spaced. Return value is a list of 
numpy.matrices with shape (n_dimensions, 1)
matplot_show_and_continue()
Show matplotlib plots and return to the script
min_max(x_float_list, weight_list=[], margin=0.1, xmin=None, xmax=None)
Return minimum and maximum of a list (i) discarding values with ~0 weight and (ii) adding a margin. For making histograms.
 
- x_float_list = return minimum and maximum of this list of floats
- weight_list  = ignore items in x_float_list if weight is 0. Ignored if weight_list is not same length as x_float_list
- margin = add a margin given by (x_max-x_min)*margin
- xmin = if set, will override the xmin value
- xmax = if set, will override the xmax value
 
e.g. Common.min_max([0.1,0.2,0.3,0.4], [0,1,1,1], 0.2) will return [0.16,0.44]
multisort(list_of_lists)
Sort a list of lists by the first list
n_bins(n_points, nx_bins=None, ny_bins=None, nz_bins=None, n_dimensions=1)
Dynamically decide a number of bins depending on the number of points in the histogram
 
- n_points     = number of data points in the histogram
- nx_bins      = set to an integer to override the automatic selection for number of x bins
- ny_bins      = set to an integer to override the automatic selection for number of y bins
- n_dimensions = set to number of dimensions in the histogram 
 
Return value is a tuple (nx_bins, ny_bins, nz_bins), setting 0 to values that are out of the dimension range
nd_newton_raphson1(y_function, y_tolerances_list, x_start_values_list, x_deltas_list, max_iteration=10, x_upper_limits=None, x_lower_limits=None, verbose=True)
Root finding in an arbitrary dimensional system. Returns x-value for y(x) = 0; caveat is dimension of y must equal dimension of x.
If you use this, you might find more and better root finding functions in SciPy module
 
- y_function is a reference to the function to be minimised i.e. y(x); it takes a list of x-values; and returns a list of y-values
- y_tolerances_list is a list of tolerances; the iteration will stop when abs(value) < value_tolerance
_ x_start_values_list is a list of the values I will try to start with
- x_deltas_list is a list of the initial estimates of the error on x
- max_iteration is the maximum number of iterations allowed
- x_upper_limits is for future development
- x_lower_limits is for future development
 
e.g. nd_newton_raphson(some_function, [0.1, 0.1], [0,0], [1,1]) will find root to y(x) < (0.1,0.1); starting at x=(0,0); initial error estimated to be [1,1]. 
some_function would be called like some_function([x_0, x_1]) and should return a list like [y_0,y_1]
nd_newton_raphson2(y_function, y_tolerances_list, x_start_values_list, x_deltas_list, max_iteration=10, x_upper_limits=None, x_lower_limits=None, verbose=True)
Alternative version of nd_newton_raphson1. Here y_function takes a list of lists of x_values, of length dimension+1 and returns a list of lists of y_values
Optimisation for when y_function can be made faster by running several jobs at once...
 
- y_function is a reference to the function to be minimised i.e. y(x); it takes a list of lists of x-values; and returns a list of lists y-values
- y_tolerances_list is a list of tolerances; the iteration will stop when abs(value) < value_tolerance
- x_start_values_list is a list of the values I will try to start with
- x_deltas_list is a list of the initial estimates of the error on x
- max_iteration is the maximum number of iterations allowed
- x_upper_limits is for future development
- x_lower_limits is for future development
 
e.g. nd_newton_raphson(some_function, [0.1, 0.1], [0,0], [1,1]) will find root to y(x) < (0.1,0.1); starting at x=(0,0); initial error estimated to be [1,1]. 
some_function would be called like some_function([[x_00, x_01] ,[x_10, x_11], [x_20, x_21]) and should return a list like [[y_00,y_01],[y_10,y_11],[y_20,y_21]]
normalise_vector(vector, matrix_inverse)
Normalise vector so that vector.T() * matrix.inverse * vector = 1
 
- vector         = the vector to normalise; should be a numpy.matrix with shape (vec_length,1)
- matrix_inverse = inverse of matrix that defines the ellipse on which vector sits; should be a
                   numpy.matrix with shape (vec_length, vec_length)
 
Return value is a list of numpy.matrices with shape (vec_length,1)
process_list(function_call, list_of_args, max_n_processes)
Run multiprocessing on a list of arguments
 
- function_call multiprocess this function call
- list_of_args list of tuples of arguments for function_call
- max_n_processes maximum number of concurrent processes to use
 
Returns list of return values, one for each function call. List is always
         sorted into same order as input.
 
e.g. process_list(time.sleep, [(3, ), (6, ), (2, )], 2) will multiprocess
the time.sleep function with inputs 3, 6 and 2 across 2 cores and return 
list like [None, None, None].
subprocess(function, args)
Make a function call in  a subprocess; return the subprocess pid
- This uses the multiprocessing libary in the first instance - if multiprocessing is not available
  the function tries to use os.fork(); however, os.fork is not compatible with ROOT. If
- multiprocessing is not available and ROOT is installed, this routine will throw an ImportError
substitute(file_name_in, file_name_out, switch_dict)
Read in file_name_in and write to file_name_out, replacing key with value in switch_dict. Must be a built in function somewhere to do same...
 
- file_name_in  = string name of the input file
- file_name_out = string name of the output file
- switch_dict   = dict of values to be swapped to the values they will be swapped for
 
e.g. Common.substitute('file.in', 'file.out', {'energy':'momentum'})
wait_for_matplot()
Show any plots made using matplotlib on the screen
wait_for_root()
Force python to halt processing until ROOT windows are closed

 
Data
        constants = {'c_light': 299.792458, 'echarge': 1, 'pi': 3.14159265}
float_tolerance = 1e-09
icool_pid_to_pdg = {-5: -2212, -4: -321, -3: -211, -2: 13, -1: 11, 0: 0, 1: -11, 2: -13, 3: 211, 4: 321, ...}
k = 40
kill_subprocesses_at_exit = True
mars_pid_to_pdg = {1: 2212, 2: 2112, 3: 211, 4: -211, 5: 321, 6: -321, 7: -13, 8: 13, 9: 22, 10: 11, ...}
muon1_pid_to_pdg = {'mu+': -13}
pdg_pid_to_charge = {-3122: 0, -2212: -1, -2112: 0, -321: -1, -211: -1, -14: 0, -13: 1, -12: 0, -11: 1, 0: 0, ...}
pdg_pid_to_icool = {-2212: -5, -321: -4, -211: -3, -13: 2, -11: 1, 0: 0, 11: -1, 13: -2, 211: 3, 321: 4, ...}
pdg_pid_to_mars = {-3122: 27, -2212: 12, -2112: 31, -321: 6, -311: 25, -211: 4, -14: 19, -13: 7, -12: 21, -11: 11, ...}
pdg_pid_to_mass = {0: 0, 11: 0.51099891, 12: 0.0, 13: 105.6583668, 14: 0.0, 22: 0.0, 111: 134.9766, 130: 497.614, 211: 139.57018, 310: 497.614, ...}
pdg_pid_to_muon1 = {-13: 'mu+'}
pdg_pid_to_name = {-3122: 'antilambda', -2212: 'antiproton', -2112: 'antineutron', -321: 'K-', -211: 'pi-', -14: 'muon antineutrino', -13: 'mu+', -12: 'electron antineutrino', -11: 'e+', 0: 'none', ...}
units = {'': 1.0, 'Coulomb': 6.24150974e+18, 'GHz': 1.0, 'GV': 1000.0, 'GV/m': 1.0, 'GV/mm': 1000.0, 'GW': 6241509740000.0, 'Gauss': 1e-07, 'GeV': 1000.0, 'GeV/c': 1000.0, ...}
v = 0
wrapped_y_function = None
xboa_version = '0.15.1'