Ejemplo n.º 1
0
def healpix_interp_along_axis(indata, theta_phi=None, inloc_axis=None,
                              outloc_axis=None, axis=-1, kind='linear',
                              bounds_error=True, fill_value=NP.nan,
                              assume_sorted=False, nest=False):

    """
    -----------------------------------------------------------------------------
    Interpolate healpix data to specified angular locations (HEALPIX 
    interpolation) and along one other specified axis (usually frequency axis, 
    for instance) via SciPy interpolation. Wraps HEALPIX and SciPy interpolations
    into one routine.

    Inputs:

    indata      [numpy array] input data to be interpolated. Must be of shape 
                (nhpy x nax1 x nax2 x ...). Currently works only for 
                (nhpy x nax1). nhpy is a HEALPIX compatible npix

    theta_phi   [numpy array] spherical angle locations (in radians) at which
                the healpix data is to be interpolated to at each of the other 
                given axes. It must be of size nang x 2 where nang is the number 
                of spherical angle locations, 2 denotes theta and phi. If set to
                None (default), no healpix interpolation is performed

    inloc_axis  [numpy array] locations along the axis specified in axis (to be 
                interpolated with SciPy) in which indata is specified. It 
                should be of size nax1, nax2, ... or naxm. Currently it works 
                only if set to nax1

    outloc_axis [numpy array] locations along the axis specified in axis to be 
                interpolated to with SciPy. The axis over which this 
                interpolation is to be done is specified in axis. It must be of
                size nout. If this is set exactly equal to inloc_axis, no 
                interpolation along this axis is performed

    axis        [integer] axis along which SciPy interpolation is to be done. 
                If set to -1 (default), the interpolation happens over the last
                axis. Since the first axis of indata is reserved for the healpix
                pixels, axis must be set to 1 or above (upto indata.ndim-1).

    kind        [str or int] Specifies the kind of interpolation as a 
                string ('linear', 'nearest', 'zero', 'slinear', 'quadratic', 
                'cubic' where 'slinear', 'quadratic' and 'cubic' refer to a 
                spline interpolation of first, second or third order) or as an 
                integer specifying the order of the spline interpolator to use. 
                Default is 'linear'.

    bounds_error 
                [bool, optional] If True, a ValueError is raised any time 
                interpolation is attempted on a value outside of the range of x 
                (where extrapolation is necessary). If False, out of bounds 
                values are assigned fill_value. By default, an error is raised.

    fill_value  [float] If provided, then this value will be used to fill in 
                for requested points outside of the data range. If not provided, 
                then the default is NaN.

    assume_sorted 
                [bool] If False, values of inloc_axis can be in any order and 
                they are sorted first. If True, inloc_axis has to be an array 
                of monotonically increasing values.
    
    nest        [bool] if True, the is assumed to be in NESTED ordering.

    Outputs:

    HEALPIX interpolated and SciPy interpolated output. Will be of size
    nang x ... x nout x ... x naxm. Currently returns an array of shape 
    nang x nout
    -----------------------------------------------------------------------------
    """

    try:
        indata
    except NameError:
        raise NameError('input data not specified')

    if not isinstance(indata, NP.ndarray):
        raise TypeError('input data must be a numpy array')

    if theta_phi is not None:
        if not isinstance(theta_phi, NP.ndarray):
            raise TypeError('output locations must be a numpy array')

        if theta_phi.ndim != 2:
            raise ValueError('Output locations must be a 2D array')

    if axis == -1:
        axis = indata.ndim - 1

    if (axis < 1) or (axis >= indata.ndim):
        raise ValueError('input axis out of range')

    if theta_phi is not None:
        intermediate_data_shape = list(indata.shape)
        intermediate_data_shape[0] = theta_phi.shape[0]
        intermediate_data_shape = tuple(intermediate_data_shape)
        
        intermediate_data = NP.zeros(intermediate_data_shape, dtype=NP.float64)
        for ax in range(1,indata.ndim):
            for i in xrange(indata.shape[ax]):
                intermediate_data[:,i] = HP.get_interp_val(indata[:,i], theta_phi[:,0], theta_phi[:,1], nest=nest)
    else:
        intermediate_data = NP.copy(indata)

    if outloc_axis is not None:
        if inloc_axis is not None:
            outloc_axis = outloc_axis.flatten()
            inloc_axis = inloc_axis.flatten()
            eps = 1e-8
            if (outloc_axis.size == inloc_axis.size) and (NP.abs(inloc_axis-outloc_axis).max() <= eps):
                outdata = intermediate_data
            else:
                if kind == 'fft':
                    df_inp = NP.mean(NP.diff(inloc_axis))
                    df_out = NP.mean(NP.diff(outloc_axis))
                    ntau = df_inp / df_out * inloc_axis.size
                    ntau = NP.round(ntau).astype(int)
                    tau_inp = DSP.spectral_axis(inloc_axis.size, delx=df_inp, shift=True)
                    fftinp = NP.fft.fft(intermediate_data, axis=axis)
                    fftinp_shifted = NP.fft.fftshift(fftinp, axes=axis)
                    if fftinp.size % 2 == 0:
                        fftinp_shifted[:,0] = 0.0 # Blank out the N/2 element (0 element when FFT-shifted) for conjugate symmetry
                    npad = ntau - inloc_axis.size
                    if npad % 2 == 0:
                        npad_before = npad/2
                        npad_after = npad/2
                    else:
                        npad_before = npad/2 + 1
                        npad_after = npad/2

                    fftinp_shifted_padded = NP.pad(fftinp_shifted, [(0,0), (npad_before, npad_after)], mode='constant')
                    fftinp_padded = NP.fft.ifftshift(fftinp_shifted_padded, axes=axis)
                    ifftout = NP.fft.ifft(fftinp_padded, axis=axis) * (1.0 * ntau / inloc_axis.size)
                    eps_imag = 1e-10
                    if NP.any(NP.abs(ifftout.imag) > eps_imag):
                        raise ValueError('Significant imaginary component has been introduced unintentionally during the FFT based interpolation. Debug the code.')
                    else:
                        ifftout = ifftout.real
                    fout = DSP.spectral_axis(ntau, delx=tau_inp[1]-tau_inp[0], shift=True)
                    fout -= fout.min()
                    fout += inloc_axis.min() 
                    ind_outloc, ind_fout, dfreq = LKP.find_1NN(fout.reshape(-1,1), outloc_axis.reshape(-1,1), distance_ULIM=0.5*(fout[1]-fout[0]), remove_oob=True)
                    outdata = ifftout[:,ind_fout]
                    
                    # npad = 2 * (outloc_axis.size - inloc_axis.size)
                    # dt_inp = DSP.spectral_axis(2*inloc_axis.size, delx=inloc_axis[1]-inloc_axis[0], shift=True)
                    # dt_out = DSP.spectral_axis(2*outloc_axis.size, delx=outloc_axis[1]-outloc_axis[0], shift=True)
                    # fftinp = NP.fft.fft(NP.pad(intermediate_data, [(0,0), (0,inloc_axis.size)], mode='constant'), axis=axis) * (1.0 * outloc_axis.size / inloc_axis.size)
                    # fftinp = NP.fft.fftshift(fftinp, axes=axis)
                    # fftinp[0,0] = 0.0  # Blank out the N/2 element for conjugate symmetry
                    # fftout = NP.pad(fftinp, [(0,0), (npad/2, npad/2)], mode='constant')
                    # fftout = NP.fft.ifftshift(fftout, axes=axis)
                    # outdata = NP.fft.ifft(fftout, axis=axis)
                    # outdata = outdata[0,:outloc_axis.size]
                else:
                    interp_func = interpolate.interp1d(inloc_axis, intermediate_data, axis=axis, kind=kind, bounds_error=bounds_error, fill_value=fill_value, assume_sorted=assume_sorted)
                    outdata = interp_func(outloc_axis)
        else:
            raise ValueError('input inloc_axis not specified')
    else:
        outdata = intermediate_data

    return outdata
Ejemplo n.º 2
0
def rms(inp, axis=None, filter_dict=None, mask=None, verbose=True):

    """
    -----------------------------------------------------------------------------
    Estimate the rms of multi-dimensional (complex) input data along an axis (if
    specified). Optionally, fourier frequency filtering and masks can be used to
    refine the data before estimating rms.

    Inputs:

    inp         [Numpy array] input data for which RMS has to be estimated.

    Keyword Inputs:

    axis        [scalar integer] Axis over which FFT is performed. Default = None
                (last axis). Any negative value or values exceeding the number of
                axes in the input data will be reset to use the last axis.

    filter_dict [dictionary] Filter parameters in the Fourier (frequency) domain.
                Default is None (no filtering to be applied). If set, the
                filtering will be applied along the specified axis. If axis is
                not specified, no frequency domain filtering will be applied. 
                This is a dictionary consisting of the following keys and info:
                'freqwts'    [Numpy array] frequency window of weights. Should 
                             either have same shape as inp or have number of
                             elements equal to the number of elements in input
                             data along specified axis. Default = None.
                             If not set, then it will be set to a rectangular
                             window of width specified by key 'width' (see below) 
                             and will be applied as a filter identically to the
                             entire data along the specified axis.
                'width'      [scalar] Width of the frequency window as a fraction 
                             of the bandwidth. Has to be positive. Default is
                             None. If width is None, wts should be set. One and
                             only one among wts and width should be set.  
                'passband'   [string scalar] String specifying the passband
                             ('low' or 'high') to be used. Default = 'low'.

    mask        [Numpy array] Numpy array with same dimensions as the input 
                data. The values can be Boolean or can be integers which in turn
                will be converted to Boolean values. Mask values with True will 
                be masked and ignored in the rms estimates while mask values with
                False will only be considered in obtaining the rms estimates. 
                Default = None (no masking to be applied)

    verbose     [boolean] If set to True (default), print messages indicating
                progress

    Output:
    
    RMS estimate of the input data. If the input data is complex, the output 
    consists of rms estimate of the real and imaginary parts of the data after
    applying the specified filtering and/or masking.
    -----------------------------------------------------------------------------
    """

    try:
        inp
    except NameError:
        raise NameError('No input data specified.')

    if isinstance(inp, list):
        inp = NP.asarray(inp)
    elif not isinstance(inp, NP.ndarray):
        raise TypeError('inp must be a list or numpy array')

    if axis is not None:
        if not isinstance(axis, int):
            raise TypeError('axis must be an integer')
        else:
            if (axis < 0) or (axis >= len(inp.shape)):
                axis = len(inp.shape) - 1        
                if verbose:
                    print '\tSetting axis to be the last dimension of data'
    
        tempinp = NP.copy(inp)
        if filter_dict is not None:
            if not isinstance(filter_dict, dict):
                raise TypeError('filter_dict must be a dictionary')
            else:
                freqwts = None
                if 'freqwts' in filter_dict:
                    freqwts = filter_dict['freqwts']
            
                width = None
                if 'width' in filter_dict:
                    width = filter_dict['width']

                passband = 'low'
                if 'passband' in filter_dict:
                    passband = filter_dict['passband']

                if verbose:
                    print '\tInvoking fft_filter() in the DSP module...'

                tempinp = DSP.fft_filter(inp, axis=axis, wts=freqwts, width=width, passband=passband, verbose=verbose)

        if mask is not None:
            # Check for broadcastability
            if mask.shape != tempinp.shape:
                if mask.size != tempinp.shape[axis]:
                    raise ValueError('mask and inp cannot be broadcast as numpy arrays')

            try:
                msk = NP.ones_like(inp) * mask.astype(NP.bool)
            except ValueError:
                raise ValueError('mask and inp cannot be broadcast as compatible numpy arrays in order to create the mask')

            tempinp = NP.ma.masked_array(tempinp, mask=msk) # create a masked array

        if NP.iscomplexobj(inp):
            rms = NP.std(tempinp.real, axis=axis, keepdims=True) + 1j * NP.std(tempinp.imag, axis=axis, keepdims=True)
        else:
            rms = NP.std(tempinp.real, axis=axis, keepdims=True)

        if len(rms.shape) < len(tempinp.shape):
            rms = NP.expand_dims(rms, axis)
        
    else:
        tempinp = NP.copy(inp)
        if mask is not None:
            if mask.shape != inp.shape:
                raise ValueError('mask and inp cannot be broadcasted as numpy arrays')

            try:
                msk = NP.ones_like(inp) * mask.astype(NP.bool)
            except ValueError:
                raise ValueError('mask and inp cannot be broadcast as compatible numpy arrays in order to create the mask')

            tempinp = NP.ma.masked_array(tempinp, mask=msk)

        if NP.iscomplexobj(inp):
            rms = NP.std(tempinp.real) + 1j * NP.std(tempinp.imag)
        else:
            rms = NP.std(tempinp.real)

    return rms