3232Functions for resampling a spectrum from one band discretization to another.
3333'''
3434
35- # The following function is taken from:
36- # http://www.cs.princeton.edu/introcs/21function/ErrorFunction.java.html
37- # Implements the Gauss error function.
38- # erf(z) = 2 / sqrt(pi) * integral(exp(-t*t), t = 0..z)
39- #
40- # fractional error in math formula less than 1.2 * 10 ^ -7.
41- # although subject to catastrophic cancellation when z in very close to 0
42- # from Chebyshev fitting formula for erf(z) from Numerical Recipes, 6.2
43-
44-
4535from __future__ import division , print_function , unicode_literals
4636
47- def erf (z ):
48- '''The error function (used to calculate the gaussian integral).'''
49- import math
50- t = 1.0 / (1.0 + 0.5 * abs (z ))
51- # use Horner's method
52- ans = 1 - t * math .exp (- z * z - 1.26551223 +
53- t * (1.00002368 +
54- t * (0.37409196 +
55- t * (0.09678418 +
56- t * (- 0.18628806 +
57- t * (0.27886807 +
58- t * (- 1.13520398 +
59- t * (1.48851587 +
60- t * (- 0.82215223 +
61- t * (0.17087277 ))))))))))
62- if z >= 0.0 :
63- return ans
64- else :
65- return - ans
66-
37+ try :
38+ from math import erf
39+ except :
40+ from scipy .special import erf
6741
6842def erfc (z ):
6943 '''Complement of the error function.'''
7044 return 1.0 - erf (z )
7145
72-
7346def normal_cdf (x ):
7447 '''CDF of the normal distribution.'''
7548 sqrt2 = 1.4142135623730951
7649 return 0.5 * erfc (- x / sqrt2 )
7750
78-
7951def normal_integral (a , b ):
8052 '''Integral of the normal distribution from a to b.'''
8153 return normal_cdf (b ) - normal_cdf (a )
8254
83-
8455def ranges_overlap (R1 , R2 ):
8556 '''Returns True if there is overlap between ranges of pairs R1 and R2.'''
8657 if (R1 [0 ] < R2 [0 ] and R1 [1 ] < R2 [0 ]) or \
8758 (R1 [0 ] > R2 [1 ] and R1 [1 ] > R2 [1 ]):
8859 return False
8960 return True
9061
91-
9262def overlap (R1 , R2 ):
9363 '''Returns (min, max) of overlap between the ranges of pairs R1 and R2.'''
9464 return (max (R1 [0 ], R2 [0 ]), min (R1 [1 ], R2 [1 ]))
9565
96-
9766def normal (mean , stdev , x ):
9867 from math import exp , pi
9968 sqrt_2pi = 2.5066282746310002
10069 return exp (- ((x - mean ) / stdev )** 2 / 2.0 ) / (sqrt_2pi * stdev )
10170
102-
10371def build_fwhm (centers ):
10472 '''Returns FWHM list, assuming FWHM is midway between adjacent bands.
10573 '''
@@ -110,7 +78,6 @@ def build_fwhm(centers):
11078 fwhm [i ] = (centers [i + 1 ] - centers [i - 1 ]) / 2.0
11179 return fwhm
11280
113-
11481def create_resampling_matrix (centers1 , fwhm1 , centers2 , fwhm2 ):
11582 '''
11683 Returns a resampling matrix to convert spectra from one band discretization
@@ -182,7 +149,6 @@ def create_resampling_matrix(centers1, fwhm1, centers2, fwhm2):
182149 M [i , matches [k ]] = contribs [k ]
183150 return M
184151
185-
186152class BandResampler :
187153 '''A callable object for resampling spectra between band discretizations.
188154
0 commit comments