"""
   This is a simple python script that simulates various aspects of radioactive decay.
   It is meant to be used as an educational resource, not for quantitative computations.
   No effort was made to optimize computational effort.

   author: Bob Wimmer, CAU Kiel, Germany
   email:  wimmer@physik.uni-kiel.de
   date:   April 17, 2015
   
 Copyright (C) 2015  Bob Wimmer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You can find a copy of the GNU General Public License
    at <http://www.gnu.org/licenses/>.
"""
import sys
from numpy import *
from numpy.random import exponential as expo
import time

Ntot = 100
freq = 2500
dur = 500

if  __name__ == '__main__':
    print 'usage: decay.py half_life (in seconds)'
    print 'or:    decay.py half_life unit [s, m, h, d, y, My]'
    half_life = float(sys.argv[1])
    if len(sys.argv) == 3: 
        unit = sys.argv[2]
        units = {'s':1., 'm': 60., 'h': 3600., 'y': 3.15576e7, 'My': 3.15576e13}
        un = units[unit]
        #print unit, un
    else:
        unit = 's'
        un = 1.
        fac = 1.
    if unit != 's':
        #print unit
        fac = units[unit]
        #print fac
        print "\n\n\nOops, this would last awfully long. I'll speed things up by a factor {0}.".format(fac)
    print "I'll simulate {0} decays".format(Ntot)
    raw_input("Hit return to continue")
    tau = half_life/log(2.)*fac #half life in seconds
    decay_data = expo(size=Ntot,scale=tau)
    t0 = time.time()
    decay_times = []
    i = 0
    while i < Ntot:
        print 'decay No. {0}, waiting time {1} {2} \a'.format(i,decay_data[i]/fac/(Ntot-i),unit)
        decay_times.append(decay_data[i]/fac/(Ntot-i))
        time.sleep(decay_data[i]/fac/(Ntot-i))
        if i == Ntot/2-1: t50 = time.time()
        i += 1
    t1 = time.time()
    print 'It would have taken {0} {1} for 100 decays.'.format((t1-t0),unit)
    print 'It would have taken {0} {1} for half the decays.'.format((t50-t0),unit) 
    print 'The mean interval between two decays was {0} {1}.'.format(mean(decay_times),unit) 

#    print decay_times
