Esempio n. 1
0
def test_xy():
    filename = "/home/terrasa/UROP/polar-measurement/data/19_Jan15/spv1840.pkl"
    pd = polarData.fromPkl(filename)

    pd.plotAngle(90)

    # position in mm
    mic = Microphone(pd, [-500, 2000])

    fs = 44.1e3
    length = 100000
    n = np.arange(length)

    f_targ = (fs / length) * 4000  # (2pi/ T)*k
    # f_targ_2 = 2300

    sin_wave_1 = np.sin(n * (2 * np.pi) * (f_targ / fs))
    # sin_wave_2 = np.sin(n*(2*np.pi)*(f_targ_2/fs))
    sin_wave = audioSample(sin_wave_1, type="t", Fs=fs)

    pad = 10000
    # sin_wave.hanning()
    sin_wave.zeroPadStart(pad)
    sin_wave.zeroPadEnd(pad)

    sin_wave.plot(both=True)

    for theta in range(0, 20, 15):
        sin_shifted = mic.apply_xy(sin_wave, theta)

        sin_shifted.plot(both=True)
Esempio n. 2
0
    def freqz(self, worN, fs):
        """

        Returns an audioSample of the frequency response corresponding to 
        the zpk filter. Inputs are the same as scipy.signal.freqz_zpk

        ---------------------------------------------------------------------
        INPUTS
        ---------------------------------------------------------------------
        worN			| (int) length of the frequency response (assumes
                        | single-sided)
        ---------------------------------------------------------------------
        fs  			| (int) sampling frequency
        ---------------------------------------------------------------------
        
        ---------------------------------------------------------------------
        OUTPUTS
        ---------------------------------------------------------------------
        (audioSample) containing the frequency response (frequency domain)
        of the filter
        ---------------------------------------------------------------------

        """

        if isinstance(worN, float):
            print(
                "Float given instead of integer for length of freqz. This will be converted to an integer"
            )
            worN = int(worN)

        w, h = sig.freqz_zpk(self.get_zs(), self.get_ps(answer_complex=True), \
            self.get_k(), worN=worN)

        return audioSample(h, type="f", Fs=fs)
Esempio n. 3
0
    def from2dArray(data, angles, fs, type):
        """
        Make a polar data object from a 2D Array such that the data[i,j] is 
        the magnitude of the jth value in the audio sample at the ith angle
        
        
        ---------------------------------------------------------------------
        INPUTS
        ---------------------------------------------------------------------
        data    		| (numpy.array-2d) data array of responses 
        ---------------------------------------------------------------------
        angles          | (numpy.array) of angles present 
        ---------------------------------------------------------------------
        fs      		| (float) sampling frequency (Hz)
        ---------------------------------------------------------------------
        
        
        ---------------------------------------------------------------------
        OUTPUTS
        ---------------------------------------------------------------------
        pd 				| (polarData) constructed from the inputs
        ---------------------------------------------------------------------
        
        """

        pd = polarData(angles=angles, fs=fs)

        # fill polarData
        for i, response in enumerate(data):
            theta = angles[i]
            pd[theta] = audioSample(response, type, fs, supress=True)

        return pd
Esempio n. 4
0
def simulate_polar_array():

    filename = "/home/terrasa/UROP/polar-measurement/data/19_Jan15/spv1840.pkl"
    pd = polarData.fromPkl(filename)

    fs = 44.1e3
    length = 100000
    n = np.arange(10000)
    f_options = np.int32(np.logspace(2, 4, 4)) * 2 * (fs / length)

    # pd.plotAngle(90)

    f_1 = f_options[0]
    f_2 = f_options[2]
    c = 343e3
    d_1 = c / (2 * f_1)
    d_2 = c / (2 * f_2)

    # position in mm
    mic_1 = Microphone(pd, [0, 0])
    mic_2 = Microphone(pd, [d_1, 0])
    mic_3 = Microphone(pd, [0, d_2])

    mic_array = MicrophoneArray([mic_1, mic_2])
    # mic_array = MicrophoneArray([mic_1, mic_2, mic_3])

    plt.figure(2)

    for f_test in f_options:

        sin_wave = np.sin(n * (2 * np.pi) * (f_test / fs))
        sin_wave = 2 / length * audioSample(sin_wave, type="t", Fs=fs)
        # sin_wave.hanning()

        thetas = np.array(list(range(0, 361, 2)))
        mags = []

        for theta in thetas:

            print(f_test, theta)

            result = mic_array.apply(sin_wave, theta)

            # sin_wave.plot(both=True)
            # result.plot(both=True)

            # get magnitude of the closest frequency of the result
            result.toDb()
            mags.append(result.getFreq([f_test])[0].real)

        plt.polar(thetas * np.pi / 180, mags)

    plt.legend(f_options, loc="upper left")
    mic_array.visualize()
Esempio n. 5
0
    def fromPkl(filename, pickleAsAudioSample=False):
        """
        loads in data from polarPlot
        Args: 
        filename (str): path to pickled file from polarPlot
        Instance variables:
        self.filename = the given file location at the creation of the object
        self.angles = list of all the angles for which data was collected
        self.audioData = dictionary mapping angle to the audioSample collected    
        self._fs_rm = frequencies that have been removed from all audioSamples
                      polarData level    
        """

        pd = polarData()

        pd.filename = filename

        with open(filename, "rb") as file_:
            loadedFile = pickle.load(file_, encoding="latin1")

        # use for original-style pickles as originally recorded
        # not that this will only work if called from the
        # pythonAudioMeasurements directory
        if pickleAsAudioSample:

            pd.angles = loadedFile[0]["angles"]

            # dictionary mapping int value of each angle to its appropriate audioSample
            pd.audioData = dict(zip(pd.angles, loadedFile[0]["measurements"]))

            pd.assertValidData()

        # recommended way of loading
        else:

            # angles
            pd.angles = loadedFile["angles"]

            # convert the tuples to audioSamples
            for i in range(len(loadedFile["measurements"])):
                asTuple = loadedFile["measurements"][i]
                loadedFile["measurements"][i] = audioSample(
                    dataArray=asTuple[0],
                    type=asTuple[1],
                    Fs=asTuple[2],
                    supress=True)

            # dictionary mapping int value of each angle to its appropriate audioSample
            pd.audioData = dict(zip(pd.angles, loadedFile["measurements"]))

        pd.removeDCOffset()

        return pd
Esempio n. 6
0
    def apply(self, signal, theta):

        original_type = signal.type

        signal.toTime()
        result = np.zeros(len(signal))

        for mic in self.microphones:
            this_result = mic.apply(signal, theta)
            this_result.toTime()
            result += this_result.data[:len(
                signal)]  # accounts for 1-off from even-lengthsed signals

        signal.setType(original_type)

        result /= len(self.microphones)

        return audioSample(result, type=signal.type, Fs=signal.fs)
Esempio n. 7
0
def simulate_polar_1mic():

    filename = "/home/terrasa/UROP/polar-measurement/data/19_Jan15/spv1840.pkl"
    pd = polarData.fromPkl(filename)

    pd.plotAngle(0, both=True)

    # position in mm
    mic = Microphone(pd, [-500, 2000])

    fs = 44.1e3
    length = 100000
    n = np.arange(10000)
    f_options = np.int32(np.logspace(2, 4, 6)) * 2 * (fs / length)

    plt.figure(1)

    for f_test in f_options:

        sin_wave = np.sin(n * (2 * np.pi) * (f_test / fs))
        sin_wave = audioSample(sin_wave, type="t", Fs=fs)
        # sin_wave.hanning()

        thetas = np.array(list(range(0, 361, 1)))
        mags = []

        for theta in thetas:

            print(f_test, theta)

            result = mic.apply(sin_wave, theta)

            # sin_wave.plot(both=True)
            # result.plot(both=True)

            # get magnitude of the closest frequency of the result
            result.toDb()
            mags.append(result.getFreq([f_test])[0].real)

        plt.polar(thetas * np.pi / 180, mags)

    plt.title("RESULT")
    plt.legend(np.int32(f_options), loc="upper left")
    pd.plotFreqs(f_options, fig=2)
Esempio n. 8
0
    def apply_xy(self, signal, theta):
        """

        Simulate running the given signal at an incedent angle of theta
        
        
        ---------------------------------------------------------------------
        INPUTS
        ---------------------------------------------------------------------
        signal			| (audioSample) input signal
        ---------------------------------------------------------------------
        theta			| (float, int) incedent angle
        ---------------------------------------------------------------------
        
        
        ---------------------------------------------------------------------
        OUTPUTS
        ---------------------------------------------------------------------
        (audioSample) result of simulating the signal 
        ---------------------------------------------------------------------

        """

        original_type = signal.type
        signal.toTime()
        result = np.zeros(len(signal))

        for mic in self.microphones:

            # apply this mic's transfer function to the signal
            this_result = mic.apply_xy(signal, theta)
            this_result.toTime()

            # add the result of each microphonw together
            result += this_result.data[:len(
                signal)]  # accounts for 1-off from even-lengthsed signals

        # return input signal to original type
        signal.setType(original_type)

        return audioSample(result, type=signal.type, Fs=signal.fs)
Esempio n. 9
0
    def apply_xy(self, signal, theta):
        """

        Applies the phase shift to a signal resluting from its (x,y)
        position, effectively collapses the microphone to the origin

        Leverages that in the freq domain e^(j*t_0*w)*X(w) shifts the 
        corresponding time domain signal by t_0

        ---------------------------------------------------------------------
        INPUTS
        ---------------------------------------------------------------------
        same as Microphone.apply(self, signal, theta)
        ---------------------------------------------------------------------

        ---------------------------------------------------------------------
        OUTPUTS
        ---------------------------------------------------------------------
        (audioSample) resulting from the described transformation
        ---------------------------------------------------------------------

        """

        # used to preserve input signal type without creating new audioSample
        original_type = signal.type

        # get the component frequencies
        signal.toFreq()

        freqs = signal.f()

        # time-domain shift and resulting phase shift (func of freq)
        delta_t = self.normal_origin_dist(theta) / self.c
        phase_shift = np.exp(-1j * 2 * np.pi * freqs * delta_t)

        result = audioSample(signal * phase_shift, type="f", Fs=signal.fs)

        # set input signal type back to original value
        signal.setType(original_type)

        return result
Esempio n. 10
0
    def apply_microphone(self, signal, theta, f_targ=None):
        """
        Applies the transform associated with the a signal entering a mic at
        a given angle

        ---------------------------------------------------------------------
        INPUTS
        ---------------------------------------------------------------------
        same as Microphone.apply(self, signal, theta)
        ---------------------------------------------------------------------

        ---------------------------------------------------------------------
        OUTPUTS
        ---------------------------------------------------------------------
        (audioSample) resulting from the described transformation
        ---------------------------------------------------------------------
        """

        # get the frequency response of the microphone at the given theta
        mic_response = self.polar.getData(theta)
        mic_response.removeDCOffset()

        # must have signal of same fs as mic response
        assert mic_response.fs == signal.fs, "your input signal must have the same " + \
        "sampling frequency. the microphone has fs: %d, and your signal as %d"%(mic_response.fs, signal.fs)

        # to preserve the original type of the input signal
        original_type = signal.type

        # apply filter with time-domain convolution
        signal.toTime()
        mic_response.toTime()
        result = convolve(signal, mic_response, "same")

        # set signal back to original type
        signal.setType(original_type)

        return audioSample(result, Fs=signal.fs)
Esempio n. 11
0
    def get_k(self):
        """
        the gain of a filter
        """
        return self.g.numpy()[0]

    def get_train_vars(self):
        return self.train_vars


if __name__ == "__main__":

    zpk_filter = ZPKOptimizableFilter()

    a = audioSample(np.arange(10000))
    freqs = a.f()

    tf_freqs = tf.constant(freqs, dtype=tf.float64)

    print("frequencies", tf_freqs)

    h = zpk_filter.get_magnitudes_tf(tf_freqs)

    mags = tf.abs(h)  # this is now a float64
    phases = tf.math.angle(h)  # also float64

    print("h_mags equals:", mags)
    print("h_phase equals:", phases)

    # freq_response = zpk_filter.freqz(512, 44e3)
Esempio n. 12
0
    print(full_path)
    print(full_mod_path)

    # ensure that this is a pickle object that can be loaded
    if extension != "pkl":
        print("not a pickle, moving on")
        continue

    # some sessions of collecting data had a baseline for the
    # microphone and the room collected. These were stored
    # pickles as just one audioSample and had to be converted
    # differently
    if filename[:4] == "meas":
        with open(full_path, "rb") as file_:
            loadedFile = pickle.load(file_, encoding="latin1")
        m = audioSample(loadedFile).toStorageTuple()
        with open(full_mod_path, "wb") as f_:
            pickle.dump(loadedFile, f_)

        continue

    with open(full_path, "rb") as file_:
        # dictionary with "measurements" -> [list of audioSamples]
        loadedFile = pickle.load(file_, encoding="latin1")[0]

    # change the value stored for the key "measurements" to a list
    # of "storagee tuples" as specified in audioSample
    m = loadedFile["measurements"]
    new_measurements = []

    for i in range(len(m)):
import pickle
from pythonAudioMeasurements.audioSample import audioSample
from pythonAudioMeasurements.polarData import polarData

filename = "/home/terrasa/UROP/polar-measurement/data/19_Jan15_fixedpkls/spv1840.pkl"
filename_2 = "/home/terrasa/UROP/polar-measurement/data/19_Jan15/spv1840.pkl"


with open(filename, "rb") as this_file:
    # should be a dictionary
    raw_load = pickle.load(this_file)

test_samp = raw_load["measurements"][5]
print(test_samp)
as_asamp = audioSample(test_samp[0], test_samp[1], test_samp[2])
print(as_asamp)


as_asamp.plot(both=True)


pd = polarData.fromPkl(filename)
pd_2 = polarData.fromPkl(filename_2, pickleAsAudioSample=True)

pd.plotFreqs([400, 1000])
pd_2.plotFreqs([400, 1000])