Esempio n. 1
0
def kde(samples, filled=False):
    try:
        # samples = np.asarray(samples, dtype=np.float64).flatten()
        samples = samples.flatten()
        if ~np.isfinite(samples).all():
            samples = get_finite_samples(samples)
        kde = gaussian_kde(samples)
        bw = kde.scotts_factor() * samples.std(ddof=1)
        #x = _kde_support(bw, bin_range=(samples.min(),samples.max()), clip=(samples.min(),samples.max()))
        x = kde_support(bw, bin_range=(samples.min(), samples.max()))
        y = kde(x)
        if filled:
            x = np.append(x, x[-1])
            x = np.insert(x, 0, x[0], axis=0)
            y = np.append(y, 0.0)
            y = np.insert(y, 0, 0.0, axis=0)
        return dict(x=x, y=y)
    except ValueError:
        print(
            "KDE cannot be estimated because %s samples were provided to kde" %
            str(len(samples)))
        return dict(x=np.array([]), y=np.array([]))
    except LinAlgError as err:
        if 'singular matrix' in str(err):
            print("KDE: singular matrix")
            y = unit_impulse(100, 'mid')
            x = np.arange(-50, 50)
            if filled:
                x = np.append(x, x[-1])
                x = np.insert(x, 0, x[0], axis=0)
                y = np.append(y, 0.0)
                y = np.insert(y, 0, 0.0, axis=0)
            return dict(x=x, y=y)
        else:
            raise
Esempio n. 2
0
    def setUp(self):  #this will be run before the test functions
        # Create a telescope and observation
        self.dishes = np.array([[0, 0], [0, 55], [30, 30], [0, 60], [2, 55],
                                [134, 65], [139, 163]])
        self.acorner = np.array([[120, 270], [122, 280], [120, 280],
                                 [122, 270]])

        self.HERA = HERA_hack.telescope(self.dishes,
                                        latitude=-30,
                                        channel_width=1.,
                                        Tsys=300,
                                        beam_width=3,
                                        beam='gaussian')
        self.obs = HERA_hack.observation(self.HERA,
                                         100.,
                                         100.,
                                         0.01,
                                         self.acorner,
                                         1,
                                         0.3,
                                         norm=True,
                                         pbeam=False)

        n_pix = self.obs.observable_coordinates().shape[0]
        imp = signal.unit_impulse(n_pix, 'mid')

        self.obs.convolve_map(
            imp
        )  # you have to run this in the setup so that all of the NONE variables get written!
        self.obs.generate_map_noise()
Esempio n. 3
0
    def playback(self, fs, duration, amplitude, frequency, phase, waveform,
                 loop):
        # loop: boolean; waveform: SIN/SQR/RAMP/PULSE.
        self.fs = fs
        self.duration = duration
        self.amplitude = amplitude
        self.frequency = frequency
        self.phase = phase
        self.waveform = waveform
        self.loop = loop

        # Set the input numpy.array to reproduce.
        time = np.linspace(start=0, stop=duration, num=duration * fs)
        sound = None

        if waveform == 'SIN':
            sound = amplitude * np.sin(2 * np.pi * frequency * time + phase)
        elif waveform == 'SQR':
            sound = amplitude * sg.square(2 * np.pi * frequency * time + phase,
                                          0.5)
        elif waveform == 'RAMP':
            sound = amplitude * sg.sawtooth(
                2 * np.pi * frequency * time + phase, 0.5)
        elif waveform == 'PULSE':
            sound = amplitude * sg.unit_impulse(shape=np.size(time), idx='mid')

        sd.play(data=sound, samplerate=fs, blocking=False, loop=loop)

        return time, sound
Esempio n. 4
0
def main():
    """Meant to emulate how pyfda will pass parameters to filters"""

    # fs = 1000.
    # f1 = 45.
    # f2 = 95.
    # b = signal.firwin(3,[f1/fs*2,f2/fs*2])    #3 taps
    #b, a = signal.iirfilter(3, [0.4, 0.7], rs=60, btype='band', ftype='cheby2')
    # print(len(b))
    # print(len(a))
    # print(b)
    # print(a)

    #print(max([max(b),max(a)]))
    #convert floating point to fixed point

    sos = signal.ellip(3, 0.009, 80, 0.05, output='sos')
    x = signal.unit_impulse(10)
    y_sos = signal.sosfilt(sos, x)
    print(sos)

    #print(y_sos)

    B1 = 12  # Number of bits
    L1 = 2**(B1 - 1)  # Round towards zero to avoid overflow

    sos_sc = sos * (2**(B1 - 1))
    sos_sc_int = sos_sc.astype(int)

    print(sos_sc_int)

    y1 = fixp_sine(sos_sc_int, B1, L1)
    # #print(y1/2**B1)
    y2 = floatp_sine(sos, B1, L1)
def fixp_sine(bsc_int, asc_int, B1, L1):
    # N=20
    # sig = [np.sin(0.1*np.pi*i) for i in np.arange(0,N,1)]

    sig = signal.unit_impulse(20)

    B2 = 12  # Number of bits
    L2 = math.floor(math.log((2 ** (B2 - 1) - 1) / max(sig), 2))  # Round towards zero to avoid overflow

    sig = np.multiply(sig, 2 ** L2)
    sig = sig.round()
    sig = sig.astype(int)
    print(sig)

    hdlfilter = FilterIIR()
    hdlfilter.set_coefficients(coeff_b=bsc_int, coeff_a=asc_int)
    hdlfilter.set_word_format((B1, B1 - 1, 0), (B2, B2 - 1, 0), (1000, 39, 0))
    hdlfilter.set_stimulus(sig)
    hdlfilter.run_sim()
    y = hdlfilter.get_response()

    yout = np.divide(y, 2 ** B1)
    print(yout)
    # hdlfilter.convert(hdl = 'verilog')
    # TODO: plotting should not be included in the tests,
    #       create simple scripts in filter-blocks/scripts
    #       for plotting ...
    # plt.plot(yout, 'b')
    # plt.show()

    return yout
Esempio n. 6
0
    def playback_record(self, fs, duration, amplitude, frequency, phase,
                        waveform, loop):

        self.fs = fs
        self.duration = duration
        self.amplitude = amplitude
        self.frequency = frequency
        self.phase = phase
        self.waveform = waveform
        self.loop = loop

        # Set the input numpy.array to reproduce
        time = np.linspace(start=0, stop=duration, num=duration * fs)
        sound = None

        if waveform == 'SIN':
            sound = amplitude * np.sin(2 * np.pi * frequency * time + phase)
        elif waveform == 'SQR':
            sound = amplitude * sg.square(2 * np.pi * frequency * time + phase,
                                          0.5)
        elif waveform == 'RAMP':
            sound = amplitude * sg.sawtooth(
                2 * np.pi * frequency * time + phase, 0.5)
        elif waveform == 'PULSE':
            sound = amplitude * sg.unit_impulse(shape=np.size(time), idx='mid')

        recording = sd.playrec(
            data=sound, samplerate=fs, blocking=False
        )  # If False, return immediately (but continue playrec in the background).

        return time, sound, recording
Esempio n. 7
0
def make_some_noise(gaus=1.,
                    impuls=1., num_impuls=20,
                    radio_impuls=1., num_radio=10,
                    amp_freq=[(1., 10e-10)],
                    amp=1):
    noize = np.zeros(32000)
    if amp == 0:
        return noize
    if gaus > 0:
        noize += np.random.normal(scale=gaus / 3, size=noize.shape)
    for amp_sinus, freq_sinus in amp_freq:
        if amp_sinus > 0:
            noize += np.fromfunction(lambda i: amp_sinus * np.sin((2 / 32000) * np.pi * freq_sinus * i), (32000,),
                                     dtype='float')
    if impuls > 0:
        freq = 32000 // num_impuls
        for i in range(num_impuls):
            j = random.randrange(i * freq, (i + 1) * freq)
            width = int(np.random.normal(loc=25, scale=10) % 20)
            try:
                noize[j:j + width] += np.random.normal(loc=impuls, scale=0.2 * impuls, size=width)
            except ValueError:
                pass
    if radio_impuls > 0 and num_radio > 0:
        freq = 32000 // num_radio
        b, a = signal.butter(4, 0.2)
        imp = signal.unit_impulse(25)
        for i in range(num_radio):
            j = random.randrange(i * freq, (i + 1) * freq)
            try:
                noize[j:j + 25] += 5 * radio_impuls * signal.lfilter(b, a, imp)
            except ValueError:
                pass
    noize *= amp
    return noize
Esempio n. 8
0
def fixp_sine(sos_asc_int, B1, L1):

    sig = signal.unit_impulse(10)

    B2 = 12  # Number of bits
    L2 = math.floor(math.log((2**(B2 - 1) - 1) / max(sig),
                             2))  # Round towards zero to avoid overflow

    sig = np.multiply(sig, 2**L2)
    sig = sig.round()
    sig = sig.astype(int)
    print(sig)

    hdlfilter = FilterIIR()
    hdlfilter.set_coefficients(sos=sos_asc_int)
    hdlfilter.set_cascade(3)
    hdlfilter.set_word_format((B1, B1 - 1, 0), (B2, B2 - 1, 0), (1000, 39, 0))
    hdlfilter.set_stimulus(sig)
    hdlfilter.run_sim()
    y = hdlfilter.get_response()

    #yout = np.divide(y, 2 ** B1)
    print(y)

    return y
Esempio n. 9
0
File: glm.py Progetto: mwaskom/lyman
    def transform(self, input):
        """Generate a prediction basis set for the input as Toeplitz matrix.

        Parameters
        ----------
        input : array or series
            Input data; should be one-dimensional

        Returns
        -------
        output : 2D array or DataFrame
            Output data; has same type of input but will have multiple columns.

        """
        row = signal.unit_impulse(self.n, 0)
        full_input = np.concatenate([input, np.zeros(self.offset)])
        basis = linalg.toeplitz(full_input, row)[self.offset:]

        if isinstance(input, pd.Series):
            pad = int(np.floor(np.log10(self.n))) + 1
            cols = [
                f"{input.name}{self.suffix}{i:0{pad}d}" for i in range(self.n)
            ]
            basis = pd.DataFrame(basis, index=input.index, columns=cols)

        return basis
Esempio n. 10
0
def generate_impulse(sample_length):

    print("Generating random impulse response...")
    rand_idx = randint(0, sample_length - 1)
    impulse = signal.unit_impulse(sample_length, rand_idx)

    return impulse
Esempio n. 11
0
    def transform(self, x):
        """Generate a prediction basis set for the input as Toeplitz matrix.

        Parameters
        ----------
        input : array or series
            Input data; should be one-dimensional

        Returns
        -------
        output : 2D array or DataFrame
            Output data; has same type of input but will have multiple columns.

        """
        row = signal.unit_impulse(self.n, 0)
        x_full = np.concatenate([x, np.zeros(self.offset)])
        basis = linalg.toeplitz(x_full, row)[self.offset:]

        if isinstance(x, pd.Series):
            pad = int(np.floor(np.log10(self.n))) + 1
            cols = [
                f"{x.name}{self.suffix}{i:0{pad}d}" for i in range(self.n)
            ]
            basis = pd.DataFrame(basis, index=x.index, columns=cols)

        return basis
Esempio n. 12
0
def impulse_response(a0, a1, a2, b0, b1, b2, n=250):
    raise NotImplemented(
        'biquad.impulse_response is not correctly implemented!')
    ir = signal.unit_impulse(n)
    for _a0, _a1, _a2, _b0, _b1, _b2 in zip(a0, a1, a2, b0, b1, b2):
        ir = signal.lfilter(np.concatenate([_b0, _b1, _b2]),
                            np.concatenate([_a0, _a1, _a2]), ir)
    ir = np.concatenate(([0.0], ir))
    return ir
Esempio n. 13
0
 def func(i):
     x = np.linspace(0, 2, 1000)
     g = 1
     v0 = -30
     y0 = 500
     pos = int(0.5 * g * i**2 + v0 * i + y0)
     y = signal.unit_impulse(1000, pos)
     line.set_data(x, y)
     return line,
Esempio n. 14
0
 def __create_pulse(self, c, f):
     from scipy.signal import unit_impulse
     from model.signal import SingleChannelSignalData, Signal
     signal = Signal(f"pulse_{c}",
                     unit_impulse(4 * HTP1_FS, 'mid'),
                     self.__preferences,
                     fs=HTP1_FS)
     return SingleChannelSignalData(name=f"pulse_{c}",
                                    filter=f,
                                    signal=signal)
Esempio n. 15
0
def update():
    y = 0
    for i in range(0, len(band)):
        h = signal.unit_impulse(sig_len)
        z0 = signal.sosfilt(band[i].low, h) * band[i].gain
        z1 = signal.sosfilt(band[i].high, h) * band[i].gain
        y += z0
        y += z1

    return y
Esempio n. 16
0
def unit_impulse(A, t1, d, fs, filename):
    ns = int(GUI.values['_ns_'])
    t2 = t1 + d
    N = int(d * fs)
    n = np.linspace(t1, t2, N)
    impuls = A * sig.unit_impulse(N, ns)
    x = calc.calc_signal(A, 0, t1, d, fs, 0, impuls)
    params = np.array([t1, fs, A, 0, d, 0])
    np.savez(filename, params, impuls)

    return params, impuls
Esempio n. 17
0
def full_sim(alpha_q=10, D_q=.1, gamma_q=20,
             alpha_a=100, D_a=1, gamma_a=20,
             q_thresh=80, a_thresh=700,
             D_rho=.05, dt=.05, K=10, rgrow=10, rkill=.5,
             rho_initial='none',nsteps=1):
       for n in range(nsteps):
           print(" ")
           print("Simulation running step %d out of %d"%(n+1,nsteps))
           if(rho_initial=='none'):
               cell_initial_pos = tuple([tuple(np.random.randint(0,100,2)) for i in range(300)])
               rho_initial = np.stack([signal.unit_impulse((100,100),i) for i in cell_initial_pos])
               rho_initial = np.sum(rho_initial,axis=0)
           rho_fig = plt.figure()
           plt.imshow(rho_initial,cmap=plt.cm.gray,vmin=0,vmax=10)
           path = "C:\\Users\\dyanni3\\Desktop\\santola_sims\\RHO\\prhofig%d.png"%(n-1)
           rho_fig.savefig(path)
           qtot = np.zeros((100,100))
           print("Configuring QS concentrations")
           for i in range(100):
               for j in range(100):
                   progressBar((100*i)+j,10000)
                   this_q = q(xx-x[j],yy-y[i],alpha_q,D_q,gamma_q)
                   this_q[i,j]=q(.01,.01,alpha_q,D_q,gamma_q)
                   qtot += rho_initial[i,j]*this_q
           qs_fig = plt.figure()
           plt.imshow(qtot)
           path = "C:\\Users\\dyanni3\\Desktop\\santola_sims\\QS\\pqsfig%d.png"%n
           qs_fig.savefig(path)
           atot = np.zeros((100,100))
           rho_a = rho_initial*(qtot>q_thresh)
           print(" ")
           print("Configuring Antibiotic concentrations")
           for i in range(100):
               for j in range(100):
                   progressBar((100*i)+j,10000)
                   this_a = q(xx-x[j],yy-y[i],alpha_a,D_a,gamma_a)
                   this_a[i,j] = q(.01,.01,alpha_a,D_a,gamma_a)
                   atot += rho_a[i,j]*this_a
           a_fig = plt.figure()
           plt.imshow(atot,cmap=plt.cm.jet)
           path = "C:\\Users\\dyanni3\\Desktop\\santola_sims\\AB\\pabfig%d.png"%n
           a_fig.savefig(path)
           rho_safe = rho_initial*(atot>a_thresh)
           plt.imshow(rho_safe)
           rho_die = rho_initial*(atot<=a_thresh)
           D_kernel = np.array([[0,1,0],[1,-4,1],[0,1,0]])
           rho_initial = rho_initial + dt*D_rho*signal.convolve2d(rho_initial,D_kernel,mode='same')
           rho_initial = rho_initial + dt*rho_safe*rgrow*(K-rho_initial)/K
           rho_initial = rho_initial - dt*rkill*rho_die
           rho_fig = plt.figure()
           plt.imshow(rho_initial,cmap=plt.cm.gray,vmin=0,vmax=10)
           path = "C:\\Users\\dyanni3\\Desktop\\santola_sims\\RHO\\prhofig%d.png"%n
           rho_fig.savefig(path)
       return(rho_initial)
Esempio n. 18
0
    def generate(self, amplitude: float, start_time: float, duration: float,
                 sampling_frequency: float) -> Signal:
        x = self.get_arguments(start_time, duration, sampling_frequency)
        if start_time <= 0 and abs(round(start_time)) <= duration:
            index_of_jump = round(abs(start_time) / duration * (len(x) - 1))
            y = amplitude * signal.unit_impulse(len(x), index_of_jump)
        else:
            y = x * 0.0

        return Signal(start_time, 0.0, sampling_frequency, list(y),
                      SignalType.REAL, SignalPeriodic.NO)
Esempio n. 19
0
def accuracy(Y, t, size):
    error = np.zeros(10)
    for i in range(size):
        j = np.argmax(Y[:, i])
        label = signal.unit_impulse(10, j)
        if np.dot(label, t[i, :]) != 1:
            j = np.argmax(t[i, :])
            error[j] = error[j] + 1

    accuracy = np.average(1 - error / size)
    return accuracy
Esempio n. 20
0
def phiFence():
    fence = np.zeros(xx.shape)
    for i in range(3):
        fence += 100. * (unit_impulse(xx.swapaxes(0, i).shape, (0,)) + unit_impulse(xx.swapaxes(0, i).shape, (-1,))).swapaxes(0, i)
        fence += 060. * (unit_impulse(xx.swapaxes(0, i).shape, (1,)) + unit_impulse(xx.swapaxes(0, i).shape, (-2,))).swapaxes(0, i)
        fence += 010. * (unit_impulse(xx.swapaxes(0, i).shape, (2,)) + unit_impulse(xx.swapaxes(0, i).shape, (-3,))).swapaxes(0, i)
    return fence
Esempio n. 21
0
def generate_impulse(duration, baseline, sample_size, amplitude=127):
    impulse = sig.unit_impulse(duration + 1)
    multiple = math.ceil(float(sample_size) / float(duration))

    i = np.array(list(impulse) * multiple)
    i = i[:sample_size]
    y = np.arange(len(i))
    i = i * amplitude
    # plt.plot(y, i)
    # plt.xlabel('Time [Samples]')
    # plt.ylabel('Amplitude')
    # plt.show()
    return y, i
def f_of_q(q, model_number):
    '''
    volume-limited binary mass ratio distribution.
    '''

    if model_number in [1,5]:
        f_q = signal.unit_impulse(len(q), -1)

    elif model_number in [2,3,4,6,7]:
        f_q = q**β

    norm_q = trapz(f_q, q)
    f_q /= norm_q
    return f_q, norm_q
Esempio n. 23
0
def flux_n_tr(k):
    """
	Calculate the transmitted flux of resonant cyclotron scattering, see M.Lyutikov & F.P.Gavriil(2006)
	Input parameter: relation omega/omega_0
	"""
    omega_0 = 8
    omega = k * omega_0

    # another way to find omega_0 independly
    #omega = 0.1
    #omega_0 = omega/k

    dif = omega - omega_0
    if k == 1:
        n_transm = (
            exp(-tau_0 / 2) *
            (10 * signal.unit_impulse(2)[0] + tau_0 /
             (8 * beta_T * omega_0) * sqrt(
                 (omega_0 * (1 + 4 * beta_T) - omega) / (dif + 0.1)) *
             special.i1(
                 (tau_0 /
                  (4 * beta_T * omega_0) * sqrt(dif *
                                                (omega_0 *
                                                 (1 + 4 * beta_T) - omega))))))
    elif 1 < k <= 1.4:
        n_transm = (
            exp(-tau_0 / 2) *
            (signal.unit_impulse(2)[1] + tau_0 / (8 * beta_T * omega_0) * sqrt(
                (omega_0 * (1 + 4 * beta_T) - omega) / dif) *
             special.i1(
                 (tau_0 /
                  (4 * beta_T * omega_0) * sqrt(dif *
                                                (omega_0 *
                                                 (1 + 4 * beta_T) - omega))))))
    else:
        n_transm = 0
    return n_transm
def main():

    times = np.linspace(0, 256e-9, 256)
    b, a = signal.butter(9, 0.6)

    noise_1 = np.random.normal(0, 11 * 1e-6, 256)
    noise_2 = np.random.normal(0, 11 * 1e-6, 256)

    imp_1 = signal.unit_impulse(256, 100)
    imp_2 = signal.unit_impulse(256, 150)

    response_1 = signal.lfilter(b, a, imp_1)
    response_2 = signal.lfilter(b, a, imp_2)

    noisy_signal_1 = (response_1 * 4 * 1e-6) + noise_1
    noisy_signal_2 = (response_2 * 4 * 1e-6) + noise_2

    fig = plt.figure(figsize=(11, 8.5))  #make a figure object
    ax = fig.add_subplot(2, 1, 1)  #make a subplot for the limit
    ax.plot(times, noisy_signal_1)
    ax = fig.add_subplot(2, 1, 2)  #make a subplot for the limit
    ax.plot(times, noisy_signal_2)
    fig.savefig("test.png", edgecolor='none',
                bbox_inches="tight")  #save the figure
def computeGradient(x,currentCost,twistMode):
    newCosts = np.zeros(7)

    if twistMode == 'flat':
        coordinates = 4
        delta = np.array([0,0,0,0,1,1,1])
        twistCost,_,_ = cost(x+np.multiply(epsilon,delta))
        newCosts[4]=newCosts[5]=newCosts[6]=twistCost

    for i in range(coordinates):
        newCosts[i],_,_ = cost(x+np.multiply(epsilon,signal.unit_impulse(7,i)))

    gradient = np.divide(newCosts-currentCost,epsilon)

    return gradient
Esempio n. 26
0
 def psf_pc(self,radius,F,W,R):        
     Lambda = 0.5
     xx,yy = np.meshgrid(np.linspace(-radius,radius,2*radius+1), np.linspace(-radius,radius,2*radius+1))
     scale2 = 10
     xx = xx/scale2
     yy = yy/scale2
     rr = np.sqrt(xx**2 + yy**2)
     x = rr*(2*np.pi)*(1/F)*(1/Lambda)
     #ker = o_airy(rr_dl,R,W)
     ker = R*jv(1,2*3.1416*R*x)/x - (R-W)*jv(1,2*3.1416*(R-W)*x)/x
     ker[radius,radius] = np.nanmax(ker)
     ker = ker/np.linalg.norm(ker)
     ker -= unit_impulse(xx.shape,(radius,radius))    
     ker = gaussian(ker,1)        
     #ker = self.normalize2max(ker)
     ker = ker/np.sum(ker)
     return ker
Esempio n. 27
0
def floatp_sine(b, a, B1, L1):
    # sig = [np.sin(0.1*np.pi*i) for i in np.arange(0,x,1)]
    sig = signal.unit_impulse(10)
    # print(sig)

    B2 = 12  # Number of bits
    L2 = math.floor(math.log((2 ** (B2 - 1) - 1) / max(sig), 2))  # Round towards zero to avoid overflow
    # print(L)
    sig = np.multiply(sig, 2 ** L2)
    sig = sig.round()
    sig = sig.astype(int)

    y_tf = signal.lfilter(b, a, sig)

    print(y_tf)

    return y_tf
    def test_freq_resp(self):
        # Test that frequency response meets tolerance from ITU-R BS.468-4
        N = 12000
        fs = 300000
        impulse = signal.unit_impulse(N)
        out = ITU_R_468_weight(impulse, fs)
        freq = np.fft.rfftfreq(N, 1/fs)
        levels = 20 * np.log10(abs(np.fft.rfft(out)))

        if mpl:
            plt.figure('468')
            plt.semilogx(freq, levels, alpha=0.7, label='fft')
            plt.legend()
            plt.axis([20, 45000, -50, +15])

        # Interpolate FFT points to measure response at spec's frequencies
        func = interp1d(freq, levels)
        levels = func(frequencies)
        assert all(np.less_equal(levels, responses + upper_limits))
        assert all(np.greater_equal(levels, responses + lower_limits))
Esempio n. 29
0
    def test_freq_resp(self):
        # Test that frequency response meets tolerance from ANSI S1.4-1983
        N = 40000
        fs = 300000
        impulse = signal.unit_impulse(N)
        out = A_weight(impulse, fs)
        freq = np.fft.rfftfreq(N, 1 / fs)
        levels = 20 * np.log10(abs(np.fft.rfft(out)))

        if mpl:
            plt.figure('A')
            plt.semilogx(freq, levels, alpha=0.7, label='fft')
            plt.legend()
            plt.ylim(-80, +5)

        # Interpolate FFT points to measure response at spec's frequencies
        func = interp1d(freq, levels)
        levels = func(frequencies)
        assert all(np.less_equal(levels, responses['A'] + upper_limits))
        assert all(np.greater_equal(levels, responses['A'] + lower_limits))
    def test_freq_resp(self):
        # Test that frequency response meets tolerance from ITU-R BS.468-4
        N = 12000
        fs = 300000
        impulse = signal.unit_impulse(N)
        out = ITU_R_468_weight(impulse, fs)
        freq = np.fft.rfftfreq(N, 1 / fs)
        levels = 20 * np.log10(abs(np.fft.rfft(out)))

        if mpl:
            plt.figure('468')
            plt.semilogx(freq, levels, alpha=0.7, label='fft')
            plt.legend()
            plt.axis([20, 45000, -50, +15])

        # Interpolate FFT points to measure response at spec's frequencies
        func = interp1d(freq, levels)
        levels = func(frequencies)
        assert all(np.less_equal(levels, responses + upper_limits))
        assert all(np.greater_equal(levels, responses + lower_limits))
Esempio n. 31
0
def gaussian_smoothing_test(plot_flag=PLOT_FLAG):
    kernel = signal.gaussian(50000, 10000)

    # Dirac delta function, 500 pts, @ center of these points
    dirac = signal.unit_impulse(50000, 'mid')

    convolved = signal.fftconvolve(dirac, kernel, 'same')
    #convolved = fftshift(convolved)
    xs = np.linspace(0., 1000, 50000)
    if plot_flag:
        fig, ax = plt.subplots(sharex=True)
        ax.plot(xs[1:], convolved[1:], 'r-', label='Convolution')
        ax.plot(xs[1:], kernel[1:], 'b--', label='Original Gaussian')
        ax.plot(xs[1:], dirac[1:], 'g', label='Dirac Delta')
        leg = ax.legend()
        fig.suptitle("Gaussian Smoothing Test")
        ax.set(xlabel='unit...time? idk, you choose',
               ylabel='the dependent variable')
        ax.label_outer
        plt.show()
    return convolved
Esempio n. 32
0
def metronome(bpm, fs,timsig,bar,s=[]):
    while True:
        if (60*fs%bpm != 0):
           fs+=1
        else:
           break

    samplehop= int((60/bpm)*fs)
    x = np.zeros(int(fs*((60/bpm)*bar*timsig)))
    barc=0
    countsig=timsig
    si=0
    for counter in range(len(x)):
        if (counter%samplehop==0):
             imp = signal.unit_impulse((int(fs*((60/bpm)*bar*timsig))), [counter])
             if (s[si]==1):
                if(countsig==timsig):
                    x = x+imp
                
                else:
                    x = x+ (0.316*imp)
             elif (s[si]==0):
                  x = x
            
                 
            
                
             counter+=1
             countsig-=1
             si+=1
             if(countsig==0):
                countsig = timsig
                barc+=1
                si=0
                if(barc==bar):
                    break
    
    onset_gen = np.where(x>0)                
    return x, onset_gen[0],fs
Esempio n. 33
0
# Read the info from the sample dataset. This defines the location of the
# sensors and such.
info = mne.io.read_info(raw_fname)
info.update(sfreq=sfreq, bads=[])

# Only use gradiometers
picks = mne.pick_types(info, meg='grad', stim=True, exclude=())
mne.pick_info(info, picks, copy=False)

# Define a covariance matrix for the simulated noise. In this tutorial, we use
# a simple diagonal matrix.
cov = mne.cov.make_ad_hoc_cov(info)
cov['data'] *= (20. / snr) ** 2  # Scale the noise to achieve the desired SNR

# Simulate the raw data, with a lowpass filter on the noise
stcs = [(stc_signal, unit_impulse(n_samp, dtype=int) * 1),
        (stc_noise, unit_impulse(n_samp, dtype=int) * 2)]  # stacked in time
duration = (len(stc_signal.times) * 2) / sfreq
raw = simulate_raw(info, stcs, forward=fwd)
add_noise(raw, cov, iir_filter=[4, -4, 0.8], random_state=rand)


###############################################################################
# We create an :class:`mne.Epochs` object containing two trials: one with
# both noise and signal and one with just noise

events = mne.find_events(raw, initial_event=True)
tmax = (len(stc_signal.times) - 1) / sfreq
epochs = mne.Epochs(raw, events, event_id=dict(signal=1, noise=2),
                    tmin=0, tmax=tmax, baseline=None, preload=True)
assert len(epochs) == 2  # ensure that we got the two expected events
Esempio n. 34
0
"""Create some examples of time-domain NFC-HOA."""

import numpy as np
import matplotlib.pyplot as plt
import sfs
from scipy.signal import unit_impulse

# Parameters
fs = 44100  # sampling frequency
grid = sfs.util.xyz_grid([-2, 2], [-2, 2], 0, spacing=0.005)
N = 60  # number of secondary sources
R = 1.5  # radius of circular array
array = sfs.array.circular(N, R)

# Excitation signal
signal = unit_impulse(512), fs, 0

# Plane wave
max_order = None
npw = [0, -1, 0]  # propagating direction
t = 0  # observation time
delay, weight, sos, phaseshift, selection, secondary_source = \
    sfs.td.nfchoa.plane_25d(array.x, R, npw, fs, max_order)
d = sfs.td.nfchoa.driving_signals_25d(
        delay, weight, sos, phaseshift, signal)
p = sfs.td.synthesize(d, selection, array, secondary_source,
                      observation_time=t, grid=grid)

plt.figure()
sfs.plot2d.level(p, grid)
sfs.plot2d.loudspeakers(array.x, array.n)