# Path: opensauce/helpers.py
# def wavread(fn):
#     """Read in a 16-bit integer PCM WAV file for processing
# 
#     Args:
#         fn - filename of WAV file [string]
# 
#     Returns:
#          y_float - Audio samples in float format [NumPy vector]
#          y_int - Audio samples in int format [NumPy vector]
#         Fs - Sampling frequency in Hz [integer]
# 
#     Emulate the parts of the Matlab wavread function that we need.
# 
#     Matlab's wavread is used by voicesauce to read in the wav files for
#     processing.  As a consequence, all the translated algorithms assume the
#     data from the wav file is in matlab form, which in this case means a double
#     precision float between -1 and 1.  The corresponding scipy function returns
#     the actual integer PCM values from the file, which range between -32768 and
#     32767.  (matlab's wavread *can* return the integers, but does not by
#     default and voicesauce uses the default).  Consequently, after reading the
#     data using scipy's io.wavfile, we convert to float by dividing each integer
#     by 32768.
# 
#     Also, save the 16-bit integer data in another NumPy vector.
# 
#     The input WAV file is assumed to be in 16-bit integer PCM format.
#     """
#     # For reference, I figured this out from:
#     # http://mirlab.org/jang/books/audiosignalprocessing/matlab4waveRead.asp?title=4-2%20Reading%20Wave%20Files
#     # XXX: if we need to handle 8 bit files we'll need to detect them and
#     # special case them here.
#     try:
#         Fs, y = wavfile.read(fn)
#     except ValueError:
#         raise
#     if y.dtype != 'int16':
#         raise IOError('Input WAV file must be in 16-bit integer PCM format')
# 
#     return y/np.float64(32768.0), y, Fs
# 
# def round_half_away_from_zero(x):
#     """Rounds a number according to round half away from zero method
# 
#     Args:
#         x - number [float]
# 
#     Returns:
#         q - rounded number [integer]
# 
#     For example:
#        round_half_away_from_zero(3.5) = 4
#        round_half_away_from_zero(3.2) = 3
#        round_half_away_from_zero(-2.7) = -3
#        round_half_away_from_zero(-4.3) = -4
# 
#     The reason for writing our own rounding function is that NumPy uses the
#     round-half-to-even method. There is a Python round() function, but it
#     doesn't work on NumPy vectors. So we wrote our own
#     round-half-away-from-zero method here.
#     """
#     q = np.int_(np.sign(x) * np.floor(np.abs(x) + 0.5))
# 
#     return q
# 
# Path: test/support.py
# def load_json(fn):
#     """Load the json file fn"""
#     with open(data_file_path(fn) + '.json') as f:
#         data = json.load(f)
#     # Convert lists of numbers to NumPy arrays
#     for k in data:
#         if isinstance(data[k], list):
#             data[k] = np.array(data[k])
# 
#     return data


import sys
import os
import glob
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import randint
from scipy.signal import resample
from opensauce.helpers import wavread, round_half_away_from_zero
from test.support import load_json
        # Do resample
        y_rs, t_rs = resample(y, ns_rs, t)
        y_h, t_h = resample(y, ns_rs, t, window='hamming')

        # Number of points to plot
        n = 1000
        # Start plotting from this data point
        # Choose random starting point
        s = randint(10000, 35015-n)

        fig = plt.figure()
        fig.suptitle(os.path.basename(wav_file))
        # Compare original data with resampled ata
        ax = plt.subplot(2,1,1)
        ax.plot(t, y, 'b-', markersize=1)
        ax.plot(t_rs, y_rs, 'ro', markersize=3)
        ax.set_xlim([s*period, (s+n)*period])
        ax.set_ylabel('Amplitude')
        ax.set_title('Normal resample')
        # Compare original data with resampling + Hamming window
        ax = plt.subplot(2,1,2)
        ax.plot(t, y, 'b-', markersize=1)
        ax.plot(t_h, y_h, 'ro', markersize=3)
        ax.set_xlim([s*period, (s+n)*period])
        ax.set_ylabel('Amplitude')
        ax.set_xlabel('Time (s)')
        ax.set_title('Hamming window')
        plt.savefig(os.path.splitext(os.path.basename(wav_file))[0] + '.pdf')

        fn = os.path.splitext(os.path.basename(wav_file))[0] + '-matlab-resample'

# Path: opensauce/helpers.py
# def wavread(fn):
#     """Read in a 16-bit integer PCM WAV file for processing
# 
#     Args:
#         fn - filename of WAV file [string]
# 
#     Returns:
#          y_float - Audio samples in float format [NumPy vector]
#          y_int - Audio samples in int format [NumPy vector]
#         Fs - Sampling frequency in Hz [integer]
# 
#     Emulate the parts of the Matlab wavread function that we need.
# 
#     Matlab's wavread is used by voicesauce to read in the wav files for
#     processing.  As a consequence, all the translated algorithms assume the
#     data from the wav file is in matlab form, which in this case means a double
#     precision float between -1 and 1.  The corresponding scipy function returns
#     the actual integer PCM values from the file, which range between -32768 and
#     32767.  (matlab's wavread *can* return the integers, but does not by
#     default and voicesauce uses the default).  Consequently, after reading the
#     data using scipy's io.wavfile, we convert to float by dividing each integer
#     by 32768.
# 
#     Also, save the 16-bit integer data in another NumPy vector.
# 
#     The input WAV file is assumed to be in 16-bit integer PCM format.
#     """
#     # For reference, I figured this out from:
#     # http://mirlab.org/jang/books/audiosignalprocessing/matlab4waveRead.asp?title=4-2%20Reading%20Wave%20Files
#     # XXX: if we need to handle 8 bit files we'll need to detect them and
#     # special case them here.
#     try:
#         Fs, y = wavfile.read(fn)
#     except ValueError:
#         raise
#     if y.dtype != 'int16':
#         raise IOError('Input WAV file must be in 16-bit integer PCM format')
# 
#     return y/np.float64(32768.0), y, Fs
# 
# def round_half_away_from_zero(x):
#     """Rounds a number according to round half away from zero method
# 
#     Args:
#         x - number [float]
# 
#     Returns:
#         q - rounded number [integer]
# 
#     For example:
#        round_half_away_from_zero(3.5) = 4
#        round_half_away_from_zero(3.2) = 3
#        round_half_away_from_zero(-2.7) = -3
#        round_half_away_from_zero(-4.3) = -4
# 
#     The reason for writing our own rounding function is that NumPy uses the
#     round-half-to-even method. There is a Python round() function, but it
#     doesn't work on NumPy vectors. So we wrote our own
#     round-half-away-from-zero method here.
#     """
#     q = np.int_(np.sign(x) * np.floor(np.abs(x) + 0.5))
# 
#     return q
# 
# Path: test/support.py
# def load_json(fn):
#     """Load the json file fn"""
#     with open(data_file_path(fn) + '.json') as f:
#         data = json.load(f)
#     # Convert lists of numbers to NumPy arrays
#     for k in data:
#         if isinstance(data[k], list):
#             data[k] = np.array(data[k])
# 
#     return data


# Path: tools/compare_resample.py
import sys
import os
import glob
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import randint
from scipy.signal import resample
from opensauce.helpers import wavread, round_half_away_from_zero
from test.support import load_json

        # Do resample
        y_rs, t_rs = resample(y, ns_rs, t)
        y_h, t_h = resample(y, ns_rs, t, window='hamming')

        # Number of points to plot
        n = 1000
        # Start plotting from this data point
        # Choose random starting point
        s = randint(10000, 35015-n)

        fig = plt.figure()
        fig.suptitle(os.path.basename(wav_file))
        # Compare original data with resampled ata
        ax = plt.subplot(2,1,1)
        ax.plot(t, y, 'b-', markersize=1)
        ax.plot(t_rs, y_rs, 'ro', markersize=3)
        ax.set_xlim([s*period, (s+n)*period])
        ax.set_ylabel('Amplitude')
        ax.set_title('Normal resample')
        # Compare original data with resampling + Hamming window
        ax = plt.subplot(2,1,2)
        ax.plot(t, y, 'b-', markersize=1)
        ax.plot(t_h, y_h, 'ro', markersize=3)
        ax.set_xlim([s*period, (s+n)*period])
        ax.set_ylabel('Amplitude')
        ax.set_xlabel('Time (s)')
        ax.set_title('Hamming window')
        plt.savefig(os.path.splitext(os.path.basename(wav_file))[0] + '.pdf')

        fn = os.path.splitext(os.path.basename(wav_file))[0] + '-matlab-resample'

        data = load_json(os.path.join('soundfile', fn))