'''
Created on 14.09.2012

@author: Jakob

module to interpolate cell values.


'''

import numpy as np


def interpolate(vm, gm):
    '''
    arguments:
    vm ...    value matrix. a (usually 3D) numpy array containing the values to be interpolated
    gm ...    good value matrix. boolean numpy array (same size as vm) containing False if value is not good.
    
     
    how it works (or will probably work):
    interpolation will be linear between its next valid horizontal neighbors. actual cell position (xyz coords) 
    wont be considered. (distance between cells should be equal..)    
     
    '''
    
    
#    iv = np.zeros(shape=vm.shape, dtype=np.bool)
    counter = 0
    (rows, cols, dims) = vm.shape
    
    for d in range(dims):
        for r in range(rows):
            lgn = -1    # index of last good neighbor
            ngn = -1    # index of next good neighbor

            
            for c in range(cols):
                if not gm[r,c,d] and c != 0:
                    # found a not good cell
                    
                    if True in gm[r,c:,d]:
                        ngn = c + gm[r,c:,d].tolist().index(True) + 1    # return position next good neighbor
                        
                        # ready for interpolation
                        vm[r,c,d] = np.interp(c, [lgn, ngn], [vm[r, lgn, d], vm[r, ngn, d]])
                        
                    counter += 1
                
                else:
                    # found a good cell
                    lgn = c
            
    return vm














if __name__ == '__main__':
    import pickle, time
#    from quickviz import subplot_matrix
    (cm, vm, vgm, rdm, olm) = pickle.load(open('../testfiles/outliers.pickle','rb'))

    '''
    cm    ...    cell matrix
    vm    ...    value matrix
    vgm ...    good value matrix
    rdm ...    relative deviation (see http://mathworld.wolfram.com/RelativeDeviation.html)
    olm    ...    outlier matrix (1=outlier, 0=no outlier)
    '''
    
    # to get a matrix, where only "good (no outliers, no bad/value)" are True, we do the following:
    # goodvalues = olm * vgm 
    #FIXME>
    goodvalues  = abs(olm -1)
    
    
    t1 = time.time()
    iv = interpolate(vm, goodvalues)
#    print olm.shape, olm.shape[0]*olm.shape[1]*olm.shape[2], olm.sum(), iv
    
    print(time.time() - t1)
    
#    subplot_matrix(olm)
#    subplot_matrix(iv)