import numpy, scipy, scipy.optimize, scipy.interpolate
import h5py
import os, os.path, time, copy
from PnSC_ui import *

#def ndiv(x, nptsoneside=20):
#    nptsoneside=max(nptsoneside, 2.)
#    gapptsoneside=min(gapptsoneside, nptsoneside-2.)
#    for gap in range(gapptsoneside+1):
#        starti=numpy.uint32([max(i-(nptsoneside-gap), 0) for i in range(len(arr))])
#        stopi=numpy.uint32([min(i+(nptsoneside-gap)+1, len(arr)) for i in range(len(arr))])
#        #print [numpy.append(arr[i0:i], arr[i+1:i1]) for i, i0, i1 in zip(range(len(arr)), starti, stopi)][8]
#        #print [(((numpy.append(arr[i0:i], arr[i+1:i1]).mean()-arr[i]))**2, (numpy.append(arr[i0:i], arr[i+1:i1]).std()*nsig)**2) for i, i0, i1 in zip(range(len(arr)), starti, stopi)][8]
#        arr=numpy.array([(((numpy.append(arr[i0:i], arr[i+1:i1]).mean()-arr[i]))**2<(numpy.append(arr[i0:i], arr[i+1:i1]).std()*nsig)**2 and (arr[i],) or (numpy.append(arr[i0:i], arr[i+1:i1]).mean(),))[0] for i, i0, i1 in zip(range(len(arr)), starti, stopi)], dtype=arr.dtype)
#    return arr

def concat_extrap_ends(x, npts, polyorder=1, lowside=True, highside=True):
    i=numpy.arange(npts, dtype='float64')
    if lowside:
        ans=scipy.polyfit(-1*(i+1.), x[:npts], polyorder)
        x=numpy.concatenate([scipy.polyval(list(ans), i[::-1]), x])
    if highside:
        ans=scipy.polyfit(-1*(i[::-1]-1.), x[-1*npts:], polyorder)
        x=numpy.concatenate([x, scipy.polyval(list(ans), i)])
    return x    
    
def lininterpbetweenregularpoints(existy, interval):
    existy=numpy.array(existy)
    x=numpy.arange(interval,dtype='float32')/interval
    diff=existy[1:]-existy[:-1]
    o=numpy.outer(diff,x)
    return numpy.concatenate([arr+start for arr,start in zip(o,existy[:-1])]+[existy[-1:]])
    
def interpwithinarr(existind, existy, order=3, interpplotax=None, interpcols=['k', 'r']):
    if order==1:
        existind=numpy.array(existind)
        diff=existind[1:]-existind[:-1]
        if numpy.all(diff==diff[0]):
            return lininterpbetweenregularpoints(existy, diff[0])
    interind=sorted(list(set(numpy.arange(max(existind)+1))-set(existind)))