示例#1
0
 def test_gaussian(self):
     """
     Check that the weight of each sub-beam is close to the expected weight
     """
     # make a dict of bunches of xboa.Hits separated by event (spill) number
     bunch = Bunch.new_dict_from_read_builtin('maus_json_primary', \
                       BIN_SIM, 'pid')[-13]
     for key, value in {'energy':226.0, 'z':3.0, 'x':0., 'y':0., \
                        'px':0., 'py':0.}.iteritems():
         sigma = 5.*bunch.moment([key, key])**0.5\
             /float(bunch.bunch_weight())**0.5
         self.assertLess(abs(bunch.mean([key])[key]-value), sigma+1.)
     covs = bunch.covariance_matrix(['x', 'px', 'y', 'py'])
     test = numpy.array(\
     [[1.05668599e+03, -6.33950201e+02,  0.00000000e+00,  6.34327423e+02],
      [-6.33950201e+02, 1.14145263e+03, -6.34327423e+02,  0.00000000e+00],
      [0.00000000e+00, -6.34327423e+02,  1.05668599e+03, -6.33950201e+02],
      [6.34327423e+02,  0.00000000e+00, -6.33950201e+02,  1.14145263e+03]]
     )
     msg_ = "Determinants:"+str(numpy.linalg.det(test))+ \
                           str(numpy.linalg.det(covs))
     self.assertLess(\
           2.*abs(numpy.linalg.det(test) - numpy.linalg.det(covs))/ \
                 (numpy.linalg.det(test) + numpy.linalg.det(covs)), 0.2,
           msg=msg_)
     self.__cmp_matrix(test, covs)
示例#2
0
 def test_no_nan(self):
     """
     Check that no nans appear
     """
     bunch = Bunch.new_from_read_builtin('maus_json_primary', NAN_SIM)
     self.assertAlmostEqual(bunch.bunch_weight(), 1000.)
     for hit in bunch:
         self.assertFalse(math.isnan(hit['energy']))
     canvas, hist = bunch.root_histogram('kinetic_energy', 'MeV', xmin=0.,
                                                       xmax=150.)
     cmp_hist = ROOT.TH1D("test", "test", hist.GetNbinsX(), 0., 150.) # pylint: disable = E1101, C0301
     for h_bin in range(1, hist.GetNbinsX()+1):
         sigma = 25.
         norm = 2.*bunch.bunch_weight()/sigma/(2.*math.pi)**0.5
         norm *= 150./hist.GetNbinsX()
         my_x = hist.GetBinCenter(h_bin)
         my_y = math.exp(-my_x**2./2./sigma**2.)*norm
         cmp_hist.Fill(my_x, my_y)
     cmp_hist.SetLineStyle(2)
     cmp_hist.Draw("SAME")
     ks_value = cmp_hist.KolmogorovTest(hist)
     print "nan energy ks_value", ks_value
     canvas.Update()
     canvas.Print(PLOT_DIR+"/nan_energy_distribution_test.png")
     self.assertGreater(ks_value, 1e-3)
示例#3
0
    def test_binomial(self):
        """
        Check that we can generate a binomial distribution for event number
        """
        # make a dict of bunches of xboa.Hits separated by event (spill) number
        bunch_dict = Bunch.new_dict_from_read_builtin('maus_json_primary', \
                          BIN_SIM, 'spill')
        bunch_weights = []
        for bunch in bunch_dict.values():
            bunch_weights.append(bunch.bunch_weight())
        canvas = common.make_root_canvas("")
        hist = common.make_root_histogram("generated distribution", \
             bunch_weights, "bunch weights", BIN_N+1, xmin=-0.5, xmax=BIN_N+0.5)
        hist.Fill(0, 1000-hist.GetSumOfWeights()) # xboa ignores empty spills
        hist.Draw()

        test_hist = ROOT.TH1D("test_hist", "reference distribution", BIN_N+1, -0.5, BIN_N+0.5)  # pylint: disable = E1101, C0301
        for i in range(BIN_N+1):
            test_hist.SetBinContent(i, \
                    (ROOT.TMath.BinomialI(BIN_P, BIN_N, i-1)- ROOT.TMath.BinomialI(BIN_P, BIN_N, i))*N_SPILLS) # pylint: disable = E1101, C0301
            print i, test_hist.GetBinContent(i), hist.GetBinContent(i)
        test_hist.SetLineStyle(2)
        test_hist.Draw("SAME")
        ks_value = test_hist.KolmogorovTest(hist)
        canvas.Update()
        canvas.Print(PLOT_DIR+"/binomial_distribution_test.png")
        print "binomial ks_value", ks_value
        self.assertGreater(ks_value, 1e-3)
示例#4
0
 def test_defaults(self):
     """
     Check that the default beam parameters run and produce some number of
     primary hits > 0
     """
     bunch = Bunch.new_from_read_builtin('maus_json_primary', DEF_SIM)
     self.assertTrue(len(bunch) > 0)
 def analysis(self):
     print "Loading data"
     bunch_list = Bunch.new_list_from_read_builtin('maus_root_virtual_hit', 'maus_output.100.root')
     bunch_list = [bunch for bunch in bunch_list if bunch.bunch_weight() > 10 and bunch[0]['z'] < 3472.001]
     print len(bunch_list)
     delaunay = DelaunayWrapper(bunch_list[0], ['x', 'px', 'y', 'py', 't', 'energy'])
     areas_0 = delaunay.get_areas(bunch_list[0])
     areas_1 = delaunay.get_areas(bunch_list[1])
     self.plot_areas(areas_0, areas_1)
示例#6
0
文件: plotter.py 项目: ajdobbs/maus
 def _get_emittance(self, ref, ellipse):
     """Get the beam emittance for given reference hit and ellipse"""
     axis_list = self.axis_dict[self.first_var]
     el_list = self.el_dict[self.first_var]
     bunch = Bunch.new_from_hits([ref])
     cov_matrix = [None]*len(el_list)
     for cov_i, ell_i in enumerate(el_list):
         cov_matrix[cov_i] = [None]*len(el_list)
         for cov_j, ell_j in enumerate(el_list):
             cov_matrix[cov_i][cov_j] = ellipse.get_element(ell_i, ell_j)
     cov_matrix = numpy.array(cov_matrix)
     emittance = bunch.get_emittance(axis_list, cov_matrix)
     return emittance
 def track_bunch(self, bunch):
     primary_list = bunch.hits()
     hit_list_of_lists = self.maus.track_many(primary_list)
     # hit_list_of_lists is sliced by primary; we want to slice by station
     n_events = len(primary_list)
     # we take the min here to stop 
     n_stations = min([len(hit_list) for hit_list in hit_list_of_lists])
     i_list = range(n_events)
     j_list = range(n_stations)
     hit_lost_if_losts = [[hit_list_of_lists[i][j] for i in i_list] for j in j_list]
     # convert to a bunch
     bunch_list = [Bunch.new_from_hits(hit_list) for hit_list in hit_lost_if_losts]
     self.bunch_list = bunch_list
     return bunch_list
 def track(self, centre_hit, delta):
     primary_list = [centre_hit]
     for key, value in delta.iteritems():
         hit = centre_hit.deepcopy()
         hit[key] += value
         hit.mass_shell_condition('pz')
         primary_list.append(hit)
     # qhull needs 8 particles for some reason - so make an extra one
     hit = centre_hit.deepcopy()
     for key, value in delta.iteritems():
         hit[key] += value
     hit.mass_shell_condition('pz')
     primary_list.append(hit)
     bunch = Bunch.new_from_hits(primary_list)
     return self.track_bunch(bunch)
示例#9
0
 def test_weighting(self):
     """
     Check that the weight of each sub-beam is close to the expected weight
     """
     # make a dict of bunches of xboa.Hits separated by event (spill) number
     bunch_dict = Bunch.new_dict_from_read_builtin('maus_json_primary', \
                       BIN_SIM, 'pid')
     test_weights = {}
     sum_weights = 0
     for pid, bunch in bunch_dict.iteritems():
         test_weights[pid] = bunch.bunch_weight()
         sum_weights += test_weights[pid]
     for pid, weight in test_weights.iteritems():
         print pid, weight, WEIGHTS_TO_PID[pid]*sum_weights, sum_weights**0.5
         self.assertLess(abs(weight - WEIGHTS_TO_PID[pid]*sum_weights), \
                         sum_weights**0.5 )
示例#10
0
 def test_sawtooth_time(self):
     """
     Check that beam maker generates sawtooth t distribution correctly
     """
     bunch = Bunch.new_dict_from_read_builtin('maus_json_primary', \
                       BIN_SIM, 'pid')[-13]
     canvas, hist = bunch.root_histogram('t', 'ns', xmin=-1e6, xmax=1e6)
     cmp_hist = ROOT.TH1D("test", "test", hist.GetNbinsX(), -1e6, 1e6) # pylint: disable = E1101, C0301
     for h_bin in range(1, hist.GetNbinsX()+1):
         my_x = hist.GetBinCenter(h_bin)
         my_y = 2.*hist.GetSumOfWeights()*h_bin/hist.GetNbinsX()**2
         cmp_hist.Fill(my_x, my_y)
     cmp_hist.SetLineStyle(2)
     cmp_hist.Draw("SAME")
     ks_value = cmp_hist.KolmogorovTest(hist)
     print "sawtooth t ks_value", ks_value
     canvas.Update()
     canvas.Print(PLOT_DIR+"/sawtooth_time_distribution_test.png")
     self.assertGreater(ks_value, 1e-3)
示例#11
0
print("In this example, I will do some basic file i/o and data manipulation")
#input data
#by default this is installed at file_location
filename = sys.prefix+'/share/xboa/data/for009.dat'
filetype = "icool_for009" #some other options are "maus_root_virtual_hit", (requires libMausCpp.so in python path), "icool_for003", "g4blTrackFile", ...

#try to load an input file
#this will load the for009 file, and make a list of "bunches", one for each region
#a list is a python version of an array
print("Data can be loaded using new_list_from_read_builtin(filetype, filename) for builtin types")
print('List of builtin types:')
print(Hit.file_types())
print('For non-builtin types, you would use new_from_read_user(format_list, format_units_dict, filehandle, number_of_skip_lines)')
print('I\'ll try to load some example data that came with your installation...')
try:
  bunch_list = Bunch.new_list_from_read_builtin(filetype, filename)
except IOError:
  'Oh dear, I couldn\'t load the example data - I wonder if it was installed in the default place ('+filename+')?\nTry inputting a new location:'
  filename = input()
  bunch_list = Bunch.new_list_from_read_builtin(filetype, filename)
  print("Loaded")

print('\n====== HIT ======')
print('A hit is the intersection of a particle trajectory with a detector or output plane')
my_hit = bunch_list[0][10]
print('Normally you would access hit data using my_hit[get_variable], for example')
print('my_hit[\'x\']: ',my_hit['x'])
print('my_hit[\'px\'] (x component of momentum vector):',my_hit['px'])
print('my_hit[\'l_kin\'] (kinetic angular momentum):',my_hit['l_kin'])
print('Possible get_variables are:')
print(my_hit.get_variables())
示例#12
0
#

import xboa.hit
from xboa.hit import Hit
import xboa.bunch
from xboa.bunch import Bunch

import operator
import sys

print('========= XBOA example 3 =========')

#load data file
print("This example shows how to make cuts")
print("Loading file... ")
bunch_list = Bunch.new_list_from_read_builtin('icool_for009', sys.prefix+'/share/xboa/data/for009.dat')
print("Loaded")

#make px histogram
bunch_list[0].root_histogram('px', 'MeV/c')
#throw away particles with px > 30 MeV/c OR < -30 MeV/c
#here, operator.ge is a function that returns TRUE if x1 >= x2
#so throw away particles with operator.ge(value, test) is TRUE
bunch_list[0].cut({'px':30.},  operator.ge)
#now use operator.le, which is a function that returns TRUE if x1 <= x2 
bunch_list[0].cut({'px':-30.}, operator.le)
#make px histogram again; note that axis range is modified to fit values of the data
bunch_list[0].root_histogram('px','MeV/c')

#reset all weights to one
#note that if you loaded a file with some weights in, these will be cleared