'''
Created on 19.09.2012

@author: Jakob
'''
#from sys import warnoptions
import sys
import numpy as np

def get_moving_average(vmat, vgoodmat, cfg):
    '''
    return a velocity matrix with horizontally averaged velocity components
    
    cfg vars:
    order ...    order of averaging. must be an uneven integer
    
    '''
    
    if not cfg['order'] % 2:
        print(('get_moving_average(): cfg variable "order" must not be even.'.format()))
    
    radius = int(cfg['order']/2)
    (rows, columns, dims) = vmat.shape
    avg = np.zeros(shape=(rows, columns, dims), dtype=np.float) # matrix with averaged 
    
    for r in range(rows):
        lbc = -1    # last bad column
        for c in range(columns):
            if vgoodmat[r,c] == True:
                # do the averaging job
                if False in vgoodmat[r,c+1:]:
                    nbc = c + vgoodmat[r,c+1:].tolist().index(False) + 1    # position of next bad neighbor
                    temp1 = False
                else:
                    nbc = columns-1
                    temp1 = True
                

                # averaging submatrix
                x = vmat[r, max(lbc, max(0, c - radius)):min(nbc, min(columns-1, c + radius + 1)),:]
                if x.shape[0] == 0:
                    print(('OOPS {}x{:3} bn: {:3} {:3} {}'.format(r, c, lbc, nbc, temp1)))
#                print x.shape, x.mean(axis=0)
                avg[r,c] =  x.mean(axis=0)
                
            else:
                lbc = c
        
    return avg

def get_averaged_profile(p, cfg):
    ''' return an averager profile 
    cfg vars:
    order ...    order of averaging. must be an uneven integer
    '''
    from copy import deepcopy
    p = deepcopy(p)
    
    import outliers
    cm = outliers.get_cell_matrix(p)
    
    velocity_matrix, velocity_matrix_mask = outliers.get_valuematrix_from_cellmatrix(cm, '.velocity.v')
    vma = get_moving_average(velocity_matrix, velocity_matrix_mask, cfg)
    p.update_velocities(vma, velocity_matrix_mask)
    
    return p

def thin_out(p, cfg):
    ''' make only every n'th element stay in ensemble and profile 
    cfg vars:
    keep_ensemble
    keep_cell
    '''
    from copy import deepcopy
    p = deepcopy(p)
    
    # thin out ensembles
    p.ensembles = p.ensembles[::cfg['keep_ensemble'] if 'keep_ensemble' in cfg else 1]
    
    for e in p.ensembles:
        if not e.void:
            e.cells = e.cells[::cfg['keep_cell'] if 'keep_cell' in cfg else 1]
    
    return p
    
            
if __name__ == '__main__':
    import pickle, time
#    from quickviz import subplot_matrix
    profile = pickle.load(open('../testfiles/demodata.pickle','rb'))
    (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)
    '''
    get_moving_average(vm, vgm, dict(order=3))
    get_moving_average(vm, vgm, dict(order=5))
    vma = get_moving_average(vm, vgm, dict(order=9))
    
    
    