
# path_length.py
# ----------------------------------------------------------------------
# A program which determines typical path lengths for particles in our
# RPC

# IMPORT CLASSES

# See seperate file ParticleModelClasses.py for classes imported in the
# following statement
from ParticleModelClasses import *

# MODEL VARIABLES

# Set number of event want to model for the histogram
num_events = 5000

# Set bin increments for histogram (mm)
bin_inc = 0.02

# RPC dimensions x, y, z (mm)
rpc_dims = [180,200,2]

# Reolution of model in mm
resolution = 0.02

# MAIN ROUTINE

# Create RPC
rpc = Detector(rpc_dims, [0,0,0])

# Extend model boundary so it encloses RPC by least 1 mm on all
# sides. This is because CosmicRay traceback mathod places particle up to
# 1mm inside of model
Detector.model_limits = Box([x+2 for x in rpc.dims], rpc.pos)

for id in range(num_events):
	# Create particle
	muon = CosmicRay(Detector.model_limits)
	# Create a place to store path length from this particle in RPC
	rpc.hits[id] = 0
	# Trace particle path through model until it leaves
	while Detector.model_limits.inside(muon.pos):
		# Check to see if particle is inside RPC
		if rpc.inside(muon.pos):
			# If is inside add 'resolution' mm to path length in RPC
			rpc.hits[id] = rpc.hits[id] + resolution
		# Update particle posistion for next iteration
		muon.pos = muon.pos + resolution * muon.vel

# PROCESS DATA

# Compiles frequency data for a histogram for use in Excel

# Get lower and upper limits for the histogram
min_val = min(rpc.hits.values())
max_val = max(rpc.hits.values())

# Initialise array to store frequency data
bins = {}
# Not necessary, but makes program easier to read
curr_bin_boundary = min_val
# Iterates over all bins in histogram
while curr_bin_boundary < max_val:
	# Gets a list of values which lie between 'divider' and 'divider +
	# bin_inc', then stores the length of this in list
	bins[divider] = len([x for x in rpc.hits.values() if x >= curr_bin_boundary and x < curr_bin_boundary + bin_inc])
	# Move the bin boundary to the next histogram bin
	curr_bin_boundary = curr_bin_boundary + bin_inc

# OUTPUT

# Outputs a tab seperated list of pair values for use in Excel. Use UNIX
# redirect (i.e. 'path_length.py > file.dat') to output to a file.

# Have to use this cludgey code for sorting a dictionary
bin_vals = bins.keys()
bin_vals.sort()
for bin_val in bin_vals:
	print bin_val, '\t', bins[bin_val]

