snoplusuk / echidna

MIT License
4 stars 12 forks source link

Add float checking/conversion to Spectra.scale #80

Closed ashleyrback closed 9 years ago

ashleyrback commented 9 years ago

I noticed when running some verification tests on #76, that if you call the scale method on a spectrum with a number of events that is not a float, there is a chance all _data can be set to zero e.g.:

    Xe136_0n2b_n1 = store.load("data/pr_76/Xe136_0n2b_n1_smeared.hdf5")
    print Xe136_0n2b_n1.sum()
    Xe136_0n2b_n1.scale(1000)
    print Xe136_0n2b_n1.sum()

yields:

47577.0
0.0

Debugging the code, within the scale method:

(Pdb) print numpy.multiply(self._data, num_decays / self._num_decays)
[[ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]
 ..., 
 [ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]]

as you can see all become zero as python is doing integer division, where num_decays is much less than self._num_decays. But if I cast num_decays as a float, all goes as expected:

(Pdb) print numpy.multiply(self._data, float(num_decays) / self._num_decays)
[[  2.49716652e-06   2.49716662e-06   2.49716671e-06 ...,   2.49713646e-06
    2.49713631e-06   2.49713615e-06]
 [  6.01030304e-06   6.01030326e-06   6.01030348e-06 ...,   6.01022526e-06
    6.01022488e-06   6.01022450e-06]
 [  6.11828942e-06   6.11828962e-06   6.11828982e-06 ...,   6.11818621e-06
    6.11818580e-06   6.11818539e-06]
 ..., 
 [  0.00000000e+00   0.00000000e+00   0.00000000e+00 ...,   0.00000000e+00
    0.00000000e+00   0.00000000e+00]
 [  0.00000000e+00   0.00000000e+00   0.00000000e+00 ...,   0.00000000e+00
    0.00000000e+00   0.00000000e+00]
 [  0.00000000e+00   0.00000000e+00   0.00000000e+00 ...,   0.00000000e+00
    0.00000000e+00   0.00000000e+00]]

The solution should be quite simple, either we cast num_decays as a float (as above) or raise a TypeError if you supply a value for num_decays that is not of float type.