import numpy as np
import scipy as sp
import scipy.ndimage
from skimage import data, img_as_float
import matplotlib.pyplot as plt

import echolect as el

camimg = img_as_float(data.camera())

b13 = np.asarray([1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1]).astype(np.float_)
b13amb = np.abs(el.autocorr(b13, 32))

K = np.fft.fftshift(b13amb, axes=0).T/np.max(b13amb)
def kernel(x):
    return np.sum(x*K)

blurredimg = sp.ndimage.convolve(camimg, K, mode='constant', cval=0.0)

plt.imsave('blurred_image_example_orig.png', camimg, 
           cmap=plt.cm.gray, dpi=camimg.shape[1]/1.3)

plt.imsave('blurred_image_example_kernel.png', K, 
           cmap=plt.cm.gray, dpi=K.shape[1]/1.3)

plt.imsave('blurred_image_example_blurred.png', blurredimg, 
           cmap=plt.cm.gray, dpi=blurredimg.shape[1]/1.3)
def make_lfm(n, ts, bandwidth_hz):
    t = np.arange(n)*ts
    slope = bandwidth_hz/(n*ts)
    return np.exp(2*np.pi*1j*(0.5*slope*t - bandwidth_hz/2.)*t)

barker13 = np.array([1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1]).astype(np.float_)
uncoded = np.ones(13)
msl = np.array([-1, -1, -1, 1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, 1, -1, -1, -1, 1, 1, -1, -1, 1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, 1, 1]).astype(np.float_)
lfm = make_lfm(51, 1e-6, 1e6)

d13 = np.fft.fftshift(np.fft.fftfreq(2*13 - 1)*(2*13 - 1))
d51 = np.fft.fftshift(np.fft.fftfreq(2*51 - 1)*(2*51 - 1))
f = np.fft.fftshift(np.fft.fftfreq(512, 1))

b13amb = np.abs(el.autocorr(barker13, 512))
uncamb = np.abs(el.autocorr(uncoded, 512))
mslamb = np.abs(el.autocorr(msl, 512))
lfmamb = np.abs(el.autocorr(lfm, 512))

dpi = 425
savedpi = dpi*1 # should be a multiple of dpi

def plotter(z, x, y, pixelaspect, **kwargs):
    xinches = len(x)/float(dpi)
    yinches = len(y)/float(dpi)*pixelaspect
    figsize = (xinches + 1.5, yinches + 1)
    fig = plt.figure(figsize=figsize)
    ax = plt.subplot(111)
    el.make_axes_fixed(ax, xinches, yinches)
    img = el.implot(z, x, y, ax=ax, csize=0.0625, cpad=0.05, **kwargs)