
# noise_coincidence.py
# ----------------------------------------------------------------------
# A program  for determining how many noise blips are needed to get a
# specified coincidence ratio with a signal of a specified amount.

from random import *
from math import *

# SET VARIABLES

# Signal blip length (S)
sig_dur = 60E-9

# Noise blip duration (S)
noise_dur = 10E-9

# Approx number of signals per second
sig_freq = 1.5

# Coincidence ratio (ratio between signals:coincidences)
coinc_ratio = input("Enter coincidence ratio: ")

# START MAIN ROUTINE

# We calculate the cumulative probabilities, so we can say 'if we are
# getting 50% coincidences, this could be due to a noise level of N
# blips per second' The maths is as follows,

# P1(cumul) = P1
# P2(cumul) = !P1*P2 + P1
# P3(cumul) = !P1*!P2*P3 + !p1*P2 + P1
# P4(cumul) = !P1*!P2*!P3*P4 + !P1*!P2*P3 + !P1*P2 + P1
# etc.

# Where Pn is the probability of the nth blip coinciding, !Pn is the
# probability of the nth blip NOT coinciding.

# We can use an iterative method (if you look Pn is P(n-1) with an extra
# term) and stop when Pn(cumul) is more than the coincidence ratio.

# ALGORITHM

# Initialise with probability of one blip coinciding 
n = 1
Pcumul = (noise_dur+sig_dur)*sig_freq

# We see that the new term in each iteration is comprised of all the !Pn
# from the previous iteration with the extra !P(n-1)*Pn factor. We
# therefore store the series up to !P(n-2) in an array to avoid
# recalculating. This is initialised as 1
Pnot_series = 1

# Keep iterating until we break past the ratio. n will then be set to
# the number we want
while Pcumul < coinc_ratio:
	# Bump up the amount of noise blips 1 at a time
	n = n + 1
	# Calculate !P(n-1)
	Pprev_not = 1 - ((n-1)*noise_dur+sig_dur)*sig_freq
	# Calculate prob of nth particle coinciding
	Pn = (n*noise_dur+sig_dur)*sig_freq
	# Extend array
	Pnot_series = Pnot_series * Pprev_not
	# Calculate current cumulative probability
	Pcumul = Pnot_series * Pn + Pcumul

# OUTPUT

print "Signal blip size: \t", sig_dur
print "Signal frequency: \t", sig_freq
print "Noise blip size:  \t", noise_dur
print "Coincidence ratio:\t", coinc_ratio
print "Number of noise blips/sec:\t", n
