def get_source(group, time, num_samples): S = None first = max(2, int(num_samples / 4000)) second = max(3, int(num_samples / 3000)) third = max(2, first / 10) if group == 1: s1 = np.sin(first * time) s2 = np.sign(np.sin(second * time)) s3 = signal.sawtooth(first * np.pi * time) S = np.c_[s1, s2, s3] elif group == 2: s1 = np.sin(first * time) s2 = np.sign(np.sin(second * time)) s3 = signal.sawtooth(first * np.pi * time) s4 = signal.sweep_poly(third * time, [1, 2]) S = np.c_[s1, s2, s3, s4] elif group == 3: s1 = np.cos(second * time) # Signal 1: cosineusoidal signal s2 = np.sign(np.sin(second * time)) # Signal 2: square signal s3 = signal.sawtooth(first * np.pi * time) # Signal 3: saw tooth signal s4 = signal.sweep_poly(third * time, [1, 2]) # Signal 4: sweeping polynomial signal s5 = np.sin(first * time) # Signal 5: sinusoidal signal S = np.c_[s1, s2, s3, s4, s5] elif group == 4: s1 = np.sin(first * time) s2 = signal.sawtooth(float(first / 2.55) * np.pi * time) s3 = np.sign(np.sin(second * time)) s4 = signal.sawtooth(first * np.pi * time) s5 = signal.sweep_poly(third * time, [1, 2]) S = np.c_[s1, s2, s3, s4, s5] S += 0.2 * np.random.normal(size=S.shape) S /= S.std(axis=0) return S.T
def get_source(group, time, num_samples): S = None first = max(2, int(num_samples/4000)) second = max(3, int(num_samples/3000)) third = max(2, first/10) if group == 1: s1 = np.sin(first * time) s2 = np.sign(np.sin(second * time)) s3 = signal.sawtooth(first * np.pi * time) S = np.c_[s1, s2, s3] elif group == 2: s1 = np.sin(first * time) s2 = np.sign(np.sin(second * time)) s3 = signal.sawtooth(first * np.pi * time) s4 = signal.sweep_poly(third * time, [1,2]) S = np.c_[s1, s2, s3, s4] elif group == 3: s1 = np.cos(second * time) # Signal 1: cosineusoidal signal s2 = np.sign(np.sin(second * time)) # Signal 2: square signal s3 = signal.sawtooth(first * np.pi * time) # Signal 3: saw tooth signal s4 = signal.sweep_poly(third * time, [1,2]) # Signal 4: sweeping polynomial signal s5 = np.sin(first * time) # Signal 5: sinusoidal signal S = np.c_[s1, s2, s3, s4, s5] elif group == 4: s1 = np.sin(first * time) s2 = signal.sawtooth(float(first/2.55) * np.pi * time) s3 = np.sign(np.sin(second * time)) s4 = signal.sawtooth(first * np.pi * time) s5 = signal.sweep_poly(third * time, [1,2]) S = np.c_[s1, s2, s3, s4, s5] S += 0.2 * np.random.normal(size=S.shape) S /= S.std(axis=0) return S.T
def save_non_linguistic_control_stimuli(missing_f0=False, add_noise=None, stretch_factor=0): pitches, _ = get_continuous_pitch_and_intensity() stim_prefixes = ['female_st1', 'female_st2', 'female_st3', 'female_st4', 'male_st1', 'male_st2', 'male_st3', 'male_st4'] polydeg = 16 fs = 44100 t = np.arange(np.int(1.1*fs))/fs t_extra = np.arange(np.int(1.1*fs))/fs amplitude_ratio = [5000, 5000, 5000] #original [24000, 6000, 1500] if add_noise is not None: amplitude_ratio = np.array(amplitude_ratio)/1 info = "" if not missing_f0 else "_missing_f0" if add_noise is not None: info = info + "_noise" if add_noise == 'first': info = info + "_first" pitches = np.array([stretch(p, stretch_factor) for p in pitches]) info = info + "_stretch_" + str(stretch_factor) for i in range(8): pitch1 = pitches[i, 0:110] pitch2 = pitches[i, 110:] ys_all = [] for harmonic in np.arange(0,6): z1 = np.polyfit(np.arange(110)/100, (harmonic+1)*pitch1, polydeg) z2 = np.polyfit(np.arange(110)/100, (harmonic+1)*pitch2, polydeg) phase = _sweep_poly_phase(t_extra, z1) y = np.concatenate([sweep_poly(t, z1), sweep_poly(t, z2, np.rad2deg(phase[-1]))]) ys_all.append(y) ys = [ys_all[0], ys_all[1], ys_all[2]] if not missing_f0 else [ys_all[3], ys_all[4], ys_all[5]] if i > 3: if add_noise is not None: amplitude_ratio = [6500, 6500, 6500] else: amplitude_ratio = [6500, 6500, 6500] s= ys[0]*amplitude_ratio[0] + ys[1]*amplitude_ratio[1] + ys[2]*amplitude_ratio[2] if add_noise == 'first': s = add_sec_to_beg(s) s = s + (2000*noise_longer_filtered[:len(s)]).astype(np.int16) elif add_noise == 'together': s = s + (2000*noise_filtered).astype(np.int16) s= np.asarray(apply_cos_squared_ramp(s), dtype=np.int16) wavfile.write('missing_f0/purr' + info + "_" + stim_prefixes[i] + '.wav', fs, s)
def poly_cubic(self, N=None, **tkw): """Cubic polynomial frequency variation + pure tone (non-configurable; adjusts with N to keep bands approx unmoved in time-frequency plane). """ N = N or self.N t = np.linspace(0, 10, N, endpoint=True) p1 = np.poly1d([0.025, -0.36, 1.25, 2.0]) * (N / 256) p3 = np.poly1d([0.01, -0.25, 1.5, 4.0]) * (N / 256) x1 = sig.sweep_poly(t, p1) x3 = sig.sweep_poly(t, p3) x2 = np.sin(2 * np.pi * (.5 * N / 256) * t) x = x1 + x2 + x3 return x, t
def create_grating(grating_length=0.150, points_per_period=9, grating_flag=0, g_0=300000.0, g_1=0.0, g_2=0.0, g_3=0.0): lines_per_m = g_0 period = 1. / lines_per_m number_of_periods = grating_length / period print("Number of periods: ", number_of_periods) print("Period: %f um" % (1e6 * period)) x = numpy.linspace(-grating_length / 2, grating_length / 2, int(points_per_period * number_of_periods)) if grating_flag == 0: # sin y = (numpy.sin(2 * numpy.pi * x / period) + 1) / 2 elif grating_flag == 1: # cos y = (numpy.cos(2 * numpy.pi * x / period) + 1) / 2 elif grating_flag == 2: # square from scipy.signal import square y = (square(2 * numpy.pi * x / period, duty=0.5) + 1) / 2 elif grating_flag == 3: # vls from scipy.signal import sweep_poly p = numpy.poly1d([g_3, g_2, g_1, g_0]) y = numpy.ceil(sweep_poly(x, p)) return x, y
def poly_sweep(x_values, y_values, duration): """ Given x_values (time), y_values (frequency) and total duration of the stroke, generate a polynomial sweep """ poly = lagrange(x_values,y_values) t = np.linspace(0, duration, (SAMPLE_RATE * duration) + 1) w = 25000 * sg.sweep_poly(t, poly) return w
def sweep(self, p1, p2, p3, p4, p5): p = np.poly1d([p1, p2, p3, p4, p5]) sweep = sweep_poly(self.t, p) plt.plot(self.t, sweep) plt.title('Sweep Poly') plt.xlabel('t[s]') plt.ylabel('Amplituda') plt.grid(True) plt.show()
def test_poly(): """Cubic polynomial frequency variation + pure tone.""" N, f = 257, 0.5 padtype = 'wrap' penalty = 2.0 t = np.linspace(0, 10, N, endpoint=True) p1 = np.poly1d([0.025, -0.36, 1.25, 2.0]) x1 = sig.sweep_poly(t, p1) x2 = np.sin(2*np.pi * f * t) x = x1 + x2 tf_transforms(x, t, padtype=padtype, stft_bw=4, penalty=penalty)
def create_grating(lines_per_m=300000.0, grating_length=0.150, points_per_period=9, form_code=0, vls=[300000.0, 269816.234363, 87748.010405, 27876.983114]): """ Create a grating profile :param lines_per_m: :param grating_length: :param points_per_period: :param form_code: =0sin, 1=cos, 2=square :return: (x,y) the arrays with abscissas and normalized ordinates (ampliture=1) """ period = 1. / lines_per_m number_of_periods = grating_length / period print("Number of periods: ", number_of_periods) print("Period: %f um" % (1e6 * period)) x = numpy.linspace(-grating_length / 2, grating_length / 2, int(points_per_period * number_of_periods)) if form_code == 0: # sin y = (numpy.sin(2 * numpy.pi * x / period) + 1) / 2 elif form_code == 1: # cos y = (numpy.cos(2 * numpy.pi * x / period) + 1) / 2 elif form_code == 2: # square from scipy.signal import square y = (square(2 * numpy.pi * x / period, duty=0.5) + 1) / 2 elif form_code == 3: # vls from scipy.signal import sweep_poly p = numpy.poly1d([vls[3], vls[2], vls[1], vls[0]]) y = numpy.ceil(sweep_poly(x, p)) return x, y
def make_one_CFcall(call_durn, fm_durn, cf_freq, fs, call_shape, **kwargs): '''A test function used to check how well the segmenting+measurement functions in the module work. Parameters ---------- call_durn : float fm_durn : float cf_freq : float fs : float call_shape : str One of either 'staplepin' OR 'rightangle' fm_bandwidth : float, optional FM bandwidth in Hz. Returns -------- cfcall : np.array The synthesised call. Raises ------- ValueError If a call_shape that is not 'staplepin' OR 'rightangle' is given Notes ------ This is not really the besssst kind of CF call to test the functions on, but it works okay. The CF call is made by using the poly spline function and this leads to weird jumps in frequency especially around the CF-FM junctions. Longish calls with decently long FM parts look fine, but calls with very short FM parts lead to rippling of the frequency. ''' # choose an Fm start/end fr equency : FM_bandwidth = np.arange(2, 20) fm_bw = kwargs.get('fm_bandwidth', np.random.choice(FM_bandwidth, 1) * 10.0**3) start_f = cf_freq - fm_bw # polynomial_num = 25 t = np.linspace(0, call_durn, int(call_durn * fs)) # define the transition points in the staplepin freqs = np.tile(cf_freq, t.size) numfm_samples = int(fs * fm_durn) if call_shape == 'staplepin': freqs[:numfm_samples] = np.linspace(start_f, cf_freq, numfm_samples, endpoint=True) freqs[-numfm_samples:] = np.linspace(cf_freq, start_f, numfm_samples, endpoint=True) p = np.polyfit(t, freqs, polynomial_num) elif call_shape == 'rightangle': # alternate between rising and falling right angle shapes rightangle_type = np.random.choice(['rising', 'falling'], 1) if rightangle_type == 'rising': freqs[:numfm_samples] = np.linspace(cf_freq, start_f, numfm_samples, endpoint=True) elif rightangle_type == 'falling': freqs[-numfm_samples:] = np.linspace(cf_freq, start_f, numfm_samples, endpoint=True) p = np.polyfit(t, freqs, polynomial_num) else: raise ValueError('Wrong input given') cfcall = signal.sweep_poly(t, p) #windowing = np.random.choice(['hann', 'nuttall', 'bartlett','boxcar'], 1)[0] windowing = 'boxcar' cfcall *= signal.get_window(windowing, cfcall.size) cfcall *= signal.tukey(cfcall.size, 0.01) return cfcall
# In[21]: import numpy as np import matplotlib.pyplot as plt from scipy.signal import sweep_poly, chirp, spectrogram from sklearn.decomposition import FastICA, PCA # Generate the data np.random.seed(1) n = 1000 t = np.linspace(0, 10, n) p = np.poly1d([0.025, -0.36, 1.25, 2.0]) s1 = np.cos(2 * t) # Signal 1 s2 = sweep_poly(t, p) # Signal 2 s3 = chirp(t, f0=6, f1=1, t1=10, method='linear') # Signal 3 S = np.c_[s1, s2, s3] S += 0.2 * np.random.normal(size=S.shape) # Add noise S /= S.std(axis=0) # Standardized data # Mix data A = np.array([[1, 1, 1], [0.5, 2, 1.0], [1.5, 1.0, 2.0]]) # Mixing matrix X = np.dot(S, A.T) # Observations # ICA ica = FastICA(n_components=3) S_ = ica.fit_transform(X) A_ = ica.mixing_ # estimated mixing matrix
def Sweep_poly(poly, width, sRate=1e2, phi=0): '''参考scipy.signal.sweep_poly 多项式频率''' timeFunc = lambda t: sweep_poly(t, poly, phi=0) domain = (0, width) return Wavedata.init(timeFunc, domain, sRate)
def __init__(self, nb_batches, batch_size, N, file, sr, content='Rand', complex=True): self.nb_batches = nb_batches self.batch_size = batch_size if ((content == 'Audio') & (complex == False)): if (file == None): f = f = os.path.join('/Users/elinemer/cnn_gamatone_fb/Music/', 'orchestra01.wav') else: f = os.path.join('/Users/elinemer/cnn_gamatone_fb/Music/', file) #audio, sr = librosa.load(f) audio, sr = utils.wav_to_array(f) len = audio.size if ((batch_size * nb_batches * N) > len): print( f'Audio file not long enough. len = {len}, product = {batch_size * nb_batches * N}' ) exit() else: fr_len = N nb_frames = len // fr_len nb_bat = nb_frames // batch_size self.samples = np.resize(audio, [nb_bat, batch_size, fr_len]) if ((content == 'Audio') & (complex == True)): print(f' Cannot generate complex audio') exit() if ((content == 'Rand') & (complex == True)): self.samples = np.random.randn( nb_batches, batch_size, N) + 1j * np.random.randn(nb_batches, batch_size, N) if ((content == 'Rand') & (complex == False)): self.samples = np.zeros((nb_batches, batch_size, N), dtype=float) # Loop over the batches for b in range(nb_batches): # generate random noise len = batch_size * N # noise_sig = np.random.randn(len) noise_sig = generator.white(len) # generate a chirp signal for the entire batch len_time = len / sr # duration in seconds t = np.linspace(0, len_time, num=len, dtype=float) t1 = len_time / 2 f0 = np.random.uniform(10, sr // 4, 1) f1 = np.random.uniform(sr // 4, sr // 2, 1) phi = np.random.uniform(0, 360, 1) #print(f' len = {len}, len time = {len_time}, size of t = {t.shape}, f0 = {f0}, f1 = {f1}, phi = {phi}') A = chirp(t, f0, len_time, f1, method='linear', phi=np.round(phi)) #plt.plot(t, A) #plt.title("Linear Chirp, f(0)=6, f(10)=1") #plt.xlabel('t (sec)') # generate a generalized sweep a0 = np.random.uniform(0, 0.125, 1) a1 = np.random.uniform(-0.5, 0.5, 1) a2 = np.random.uniform(0.75, 1.5, 1) a3 = np.random.uniform(1.5, 2.5, 1) #print(f' aaa {a0}, {a1}, {a2}, {a3}') p = np.poly1d([a0[0], a1[0], a2[0], a3[0]]) w = sweep_poly(t, p) # generate Amplitude-moduled signal AM = self.amplitude_modulation(t, sr) #plt.plot(t, AM) #plt.title("AM") #plt.xlabel('t (sec)') PN = generator.pink(len) #plt.plot(PN) #plt.title("Pink") #plt.xlabel('t (sec)') BN = generator.blue(len) VN = generator.violet(len) alpha = np.random.uniform(0.25, 0.45, 1) beta = np.random.uniform(0, 0.1, 1) delta = np.random.uniform(0, 0.1, 1) if ((b % 6) == 0): Combo_sig = (alpha[0] * noise_sig) + ((1.0 - alpha[0]) * A) if ((b % 6) == 1): Combo_sig = (alpha[0] * noise_sig) + (delta[0] * w) if ((b % 6) == 2): Combo_sig = (alpha[0] * noise_sig) + ( (1.0 - alpha[0]) * A) + (delta[0] * AM) #Combo_sig = (alpha[0] * noise_sig) + (beta[0] * A) + (delta[0] * AM) if ((b % 6) == 3): #Combo_sig = (alpha[0] * noise_sig) + ((1.0-alpha[0]) * A) + (delta[0] * w) Combo_sig = (alpha[0] * noise_sig) + (beta[0] * A) + (delta[0] * w) if ((b % 6) == 4): Combo_sig = (alpha[0] * noise_sig) + (delta[0] * AM) if ((b % 6) == 5): Combo_sig = (alpha[0] * noise_sig) + (delta[0] * AM) + (delta[0] * w) #Combo_sig = (alpha[0] * noise_sig) + (delta[0] * A) + (delta[0] * w) + (delta[0] * AM) + (delta[0] * PN) #Combo_sig = (alpha[0] * noise_sig) + (delta[0] * A) + (delta[0] * w) + (beta[0] * AM) + (beta[0] * PN) Combo_sig = (noise_sig) #Combo_sig = AM self.samples[b, :, :] = np.resize(Combo_sig, [batch_size, N]) #plt.plot(t, Combo_sig) #plt.title("Combo_sig") #plt.xlabel('t (sec)') #plt.show() #self.samples = np.random.uniform(-1, 1, (nb_batches, batch_size, N)) #plt.show() print(f'size of samples = {(self.samples).shape}')
def get_pattrn_rec_IO(task_ref='T2', n_input_nodes=10, gain=3, n_patterns=10, n_repeats=100, time_len=50, **kwargs): if task_ref == 'T1': #spike trains "Generates random patterns of single spikes" # create original patterns and labels time_lens = time_len * np.ones(n_patterns, dtype=np.int16) sections = [ np.sum(time_lens[:idx]) for idx in range(1, len(time_lens)) ] patterns = np.split(np.random.randint(0, n_input_nodes, (np.sum(time_lens))), sections, axis=0) labels = list(range(n_patterns)) # add noise to original patterns def add_noisy_samples(patterns, labels, n_input_nodes, n_repeats, n_jitters=None, **kwargs): noisy_patt = [*patterns] new_labels = [*labels] for _ in range(n_repeats - 1): new_repeat = [] for patt in patterns: tmp_pattern = patt.copy() if n_jitters is None: n_jitters = int(0.1 * len(patt)) rnd_idx = np.random.choice(len(patt), n_jitters, replace=False) tmp_pattern[rnd_idx] = np.random.randint( 0, n_input_nodes, n_jitters) new_repeat.append(tmp_pattern) noisy_patt.extend(new_repeat) new_labels.extend(labels) return noisy_patt, new_labels samples, targets = add_noisy_samples(patterns=patterns, labels=labels, n_input_nodes=n_input_nodes, n_repeats=n_repeats, **kwargs) # create inputs and outputs inputs = [] outputs = [] for sample, target in zip(samples, targets): out_seq = -1 * np.ones((len(sample), n_patterns), dtype=np.int16) out_seq[:, target] = 1 in_seq = np.zeros((len(sample), n_input_nodes)) #, dtype=np.int16) for idx_time, val in enumerate(sample): # idx_input_node = input_nodes[val] in_seq[idx_time, val] = gain inputs.append(in_seq) outputs.append(out_seq) # split training/test sets train_frac = 0.5 n_train_samples = int(round(n_repeats * train_frac)) * n_patterns x_train = np.vstack(inputs[:n_train_samples]) x_test = np.vstack(inputs[n_train_samples:]) y_train = np.vstack(outputs[:n_train_samples]) y_test = np.vstack(outputs[n_train_samples:]) if task_ref == 'T2': "Generates noisy, random sinusoidal patterns with variable frequency" coeffs = [np.random.uniform(-2, 2, size=4) for _ in range(n_patterns)] t = np.linspace(0, 10, time_len) patterns = [] labels = [] for _ in range(n_repeats): for label in range(n_patterns): coeff = coeffs[label] poly = np.poly1d([coeff[0], coeff[1], coeff[2], coeff[3]]) w = gain * sweep_poly(t, poly) w += np.random.normal(0, 0.1, len(w)) labels.append(label) patterns.append(w) data = list(zip(patterns, labels)) # split training/test sets train_frac = 0.5 n_train_samples = int(train_frac * n_repeats) * n_patterns train_data = data[:n_train_samples] test_data = data[n_train_samples:] # shuffle data random.shuffle(train_data) random.shuffle(test_data) train_patterns, train_labels = zip(*train_data) test_patterns, test_labels = zip(*test_data) x_train = [] y_train = [] for pattern, label in zip(train_patterns, train_labels): new_label = -1 * np.ones( (len(pattern), n_patterns), dtype=np.int16) new_label[:, label] = 1 x_train.append(pattern[:, np.newaxis]) y_train.append(new_label) x_test = [] y_test = [] for pattern, label in zip(test_patterns, test_labels): new_label = -1 * np.ones( (len(pattern), n_patterns), dtype=np.int16) new_label[:, label] = 1 x_test.append(pattern[:, np.newaxis]) y_test.append(new_label) # concatenate data x_train = np.vstack(x_train) y_train = np.vstack(y_train) x_test = np.vstack(x_test) y_test = np.vstack(y_test) return (x_train, x_test), (y_train, y_test)
# # <codecell> t = np.linspace(0, 10, 5001) w = chirp(t, f0=12.5, f1=2.5, t1=10, method='hyperbolic') # <markdowncell> # <![](files/FrequencySweptDemo_attachments/chirp_hyperbolic.png> )# # Sweep Poly # ========== # # Sample code: # # <codecell> p = poly1d([0.05, -0.75, 2.5, 5.0]) t = np.linspace(0, 10, 5001) w = sweep_poly(t, p) # <markdowncell> # <![](files/FrequencySweptDemo_attachments/sweep_poly.png> )# # The script that generated the plots is here: # # <![](files/FrequencySweptDemo_attachments/chirp_plot.py> )#
t = np.linspace(0, 20, N, endpoint=True) x1 = sig.chirp(t, f0=2, f1=8, t1=20, method='linear') x2 = sig.chirp(t, f0=.4, f1=4, t1=20, method='quadratic') x = x1 + x2 tf_transforms(x, t, padtype=padtype, stft_bw=4, penalty=penalty) #%%# Cubic polynomial frequency variation + pure tone ######################## N, f = 257, 0.5 padtype = 'wrap' penalty = 20 t = np.linspace(0, 10, N, endpoint=True) p1 = np.poly1d([0.025, -0.36, 1.25, 2.0]) p3 = np.poly1d([0.01, -0.25, 1.5, 4.0]) x1 = sig.sweep_poly(t, p1) x3 = sig.sweep_poly(t, p3) x2 = np.sin(2 * np.pi * f * t) x = x1 + x2 + x3 # x += np.sqrt(1) * np.random.randn(len(x)) tf_transforms(x, t, n_ridges=3, padtype=padtype, stft_bw=4, ssq_stft_bw=4, penalty=penalty) #%%# Reflect-added linear chirps ############################################# N = 512
doublet321_2 = lambda dt: np.hstack([ np.zeros(int(1 / dt)), np.ones(int(2 / dt)), -np.ones(int(1.5 / dt)), np.ones(int(0.5 / dt)), -np.ones(int(0.5 / dt)), np.zeros(int(1 / dt)) ]) doublet321_3 = lambda dt: np.hstack([ np.zeros(int(1 / dt)), np.ones(int(3 / dt)), -np.ones(int(2 / dt)), np.ones(int(1 / dt)), -np.ones(int(1 / dt)), np.zeros(int(1 / dt)) ]) doublet2_zeros = lambda dt: np.zeros_like(doublet2(dt)) excitation = lambda dt: np.vstack([ -1.0 * signal.sweep_poly(np.arange(0, 20, dt), 0.075 * np.poly1d( [10], True)), -2.5 * np.sin(1 / 2.5 * np.pi * np.arange(0, 20, dt)), 0. * signal.chirp(np.arange(0, 20, dt), 0.25, 20, 1, phi=90) ]) # Test maneuvers omega_r1 = np.pi / 60 # Rate 1 turn omega_r2 = np.pi / 30 # Rate 2 turn omega_r3 = np.pi / 15 # Rate 3 turn zeros = lambda T, dt: np.zeros(int(T / dt)) ones = lambda T, dt: np.ones(int(T / dt)) bank_angle = lambda V, ROT: np.clip( np.arccos(1 / np.sqrt( (V**2 / (9.81 * (V / ROT)))**2 + 1)), -np.deg2rad(25), np.deg2rad(25) ) # Calculate bank angle [rad] with desired rate of turn (ROT) [rad/s]