def ocilator_gen(functype, cycles, period, phase, resolution): """ Generates an oscillating function for MED experiments Parameters ---------- functype: str String which determines type of ocilator to use cycles: int Number of cycles for the total run period: float Period between peaks in seconds phase: float Additional phase to add in pi, i.e. 1 resolution: float Maximum time resolution of the data in data points per second """ t = np.linspace(0, cycles * period, cycles * period * resolution) phase = phase * np.pi internal = 2 * np.pi / period * t + phase if functype in ['sin', 'Sin']: ocil = np.sin(internal) elif functype in ['Triangle', 'tri']: ocil = 2 * abs(signal.sawtooth(internal)) - 1 elif functype in ['saw']: ocil = signal.sawtooth(internal) elif functype in ['square']: ocil = signal.square(internal) plt.plot(t, ocil, 'o') plt.ylim(-1.5, 1.5) plt.show() return ocil
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 somewaves(pen, waves, subwaves, wavperiod=[], wavtype=[], wavesize=[], waveshape=[]): global noise global plotter global g plotter.select_pen(pen) for idx, wav in enumerate(wavperiod): # print wav, idx, wavesize[idx] # plotter.select_pen(random.randint(1,3)) for i in range(0, rez): # print(wav, wavtype[idx], wavesize[idx], waveshape[idx]) if waveshape[idx] == "cross": atom = shapes.cross(size, np.cos(wav[i]) * size) if waveshape[idx] == "rect": atom = shapes.rectangle(size, np.sin(wav[i]) * size) if waveshape[idx] == "circle": atom = shapes.circle(signal.sawtooth(wav[i]) * size) transforms.perpendicular_noise(atom, noise) if waveshape[idx] == "spiral": atom = spiral_archimedean(size * 20, num_turns=22, wrapping_constant=1, direction="cw", segments=30) if wavtype[idx] == "sin": transforms.offset(atom, (i * interval, np.sin(wav[i]) * wavesize[idx])) if wavtype[idx] == "cos": transforms.offset(atom, (i * interval, np.cos(wav[i]) * wavesize[idx])) if wavtype[idx] == "saw": transforms.offset(atom, (i * interval, signal.sawtooth(wav[i]) * wavesize[idx])) if waves: g.append(atom) # plotter.write(g) # plotter.select_pen(2) # tr = shapes.rectangle(size,np.cos(wav1[i])*size) # transforms.offset(tr, (i*interval, np.cos(wav1[i])*3500 )) # if waves: # g.append(tr) # plotter.select_pen(3) # tr = shapes.circle(np.cos(wav2[i])*size) # transforms.offset(tr, (i*interval, np.cos(wav1[i])*2500 )) # if waves: # g.append(tr) if subwaves: p1 = getrandompoint(wav, wavtype[idx], wavesize[idx]) p2 = getrandompoint(wav, wavtype[len(wavtype) - 1], wavesize[len(wavtype) - 1]) # print p1 while randpointer < rez - 1: print randpointer # for i in range(int(randwavesize)): for w in range(len(wavtype)): l = shapes.line(p1, p2) transforms.noise(l, noise) g.append(l) p1 = p2 p2 = getrandompoint(wav, wavtype[w], wavesize[w]) plotter.write(g) g = shapes.group([])
def buddy_dynamic_thread(): general_settings = bt.ctrl_general_t() timing_settings = bt.ctrl_timing_t() runtime_settings = bt.ctrl_runtime_t() general_settings.function = bt.GENERAL_CTRL_DAC_ENABLE general_settings.mode = \ bt.MODE_CTRL_STREAM if streaming else bt.MODE_CTRL_IMMEDIATE #general_settings.channel_mask = bt.BUDDY_CHAN_ALL_MASK general_settings.channel_mask = bt.BUDDY_CHAN_0_MASK general_settings.resolution = bt.RESOLUTION_CTRL_HIGH timing_settings.period = bt.FREQUENCY_TO_NSEC(sample_rate) runtime_settings.dac_power = bt.RUNTIME_DAC_POWER_ON runtime_settings.dac_ref = bt.RUNTIME_DAC_REF_EXT if (bt.buddy_configure(handle, general_settings, runtime_settings, timing_settings) != bt.BUDDY_ERROR_CODE_OK): print 'test_waveform_dac: could not configure Buddy device' return -1 time.sleep(0.1) packet = bt.general_packet_t() test_seq_dac_count = 0 #y_mag = 255 y_mag = 4095 t = np.linspace(0, WAVEFORM_TIME, sample_rate * WAVEFORM_TIME, endpoint=False) if wave_type == 'square': y = ((scisig.square(np.pi * 2 * WAVEFORM_FREQUENCY * t) + 1) / 2) * y_mag elif wave_type == 'sine': y = ((np.sin(np.pi * 2 * WAVEFORM_FREQUENCY * t) + 1) / 2) * y_mag elif wave_type == 'sawtooth': y = ((scisig.sawtooth(np.pi * 2 * WAVEFORM_FREQUENCY * t) + 1) / 2) * y_mag else: return -1 for k in y: for i in range(bt.BUDDY_CHAN_0, bt.BUDDY_CHAN_7): bt.uint32_t_ptr_setitem(packet.channels, i, int(k)) print 'test_waveform_dac: sending %d packet with value %d' % (test_seq_dac_count, k) test_seq_dac_count += 1 if (bt.buddy_send_dac(handle, packet, streaming) != bt.BUDDY_ERROR_CODE_OK): print 'test_waveform_dac: could not send DAC packet' return -1 if not streaming: time.sleep(1.0 / sample_rate) bt.buddy_flush(handle) time.sleep(0.1)
def sound_sawtooth(f, t, a, d): """ Funkcja tworząca falę trójkątną (piła). Argumenty: * f - częstotliwość dźwięku * t - czas trwania dźwięku * a - czas trwania attack * d - czas trwania decay """ # tworzymy falę f_s = 44100 t0 = np.linspace(0, t, t * f_s) wave = scs.sawtooth(2 * np.pi * f * t0) # tworzymy attack A = np.floor(a * t * f_s) attack = np.linspace(0, 1, A) # tworzymy decay D = np.floor(d * t * f_s) decay = np.linspace(1, 0, D) # tworzymy sustain sustain = np.ones(t * f_s - A - D) # złączamy dzwięki sound = np.hstack((attack, sustain, decay)) * wave return sound
def wave_pattern(self): pNow = 0 if mainToggle == 1: if self.state == 1: if self.function == 'const.': pNow = self.pressure elif self.function == 'sine': tNow = time.time()-startTime pNow = self.pressure + self.amplitude*np.sin(tNow/self.period*2*np.pi-self.phase*np.pi/180.0) elif self.function == 'triangle': tNow = time.time()-startTime pNow = self.pressure + self.amplitude*spsg.sawtooth(tNow/self.period*2*np.pi-(self.phase + 270.0)*np.pi/180.0, 0.5) elif self.function == 'square': tNow = time.time()-startTime pNow = self.pressure + self.amplitude*spsg.square(tNow/self.period*2*np.pi-self.phase*np.pi/180.0, 0.5) elif self.function == 'calculate': tNow = time.time()-startTime pNow = self.calculated_pattern() else: pass else: pass else: pass return pNow
def zebra_cm(a=4, m=0.5, n=256): """ Zebra palette colormap with NBANDS broad bands and NENTRIES rows in the color map. The default is 4 broad bands cmap = zebra(nbands, nentries) References ---------- [1] Hooker, S. B. et al, Detecting Dipole Ring Separatrices with Zebra Palettes, IEEE Transactions on Geosciences and Remote Sensing, vol. 33, 1306-1312, 1995 Notes ----- Saturation and value go from m to 1 don't use m = 0. a = 4 -> there are this many large bands in the palette. """ x = np.arange(0, n) hue = np.exp(-3. * x / n) sat = m + (1. - m) * (0.5 * (1. + sawtooth(2. * np.pi * x / (n / a)))) val = m + (1. - m) * 0.5 * (1. + np.cos(2. * np.pi * x / (n / a / 2.))) return np.array([hsv_to_rgb(h, s, v) for h, s, v in zip(hue, sat, val)])
def Triangle(self, time_array, amplitude, width=0.5): """ Returns t sized array of equally spaced points from triangle wave with peak at t/2. See details in underlying scipy.signal.sawtooth """ t_length = time_array.shape[0] wave = signal.sawtooth(2 * np.pi * np.linspace(0, 1, t_length), 0.5) return -amplitude * 0.5 * (wave + 1)
def triangle(triangle_frequency=440, length=0): sample_freq = 44100 if length: end = length else: end = 6./triangle_frequency t = pl.arange(0., end, 1./sample_freq) msg = np.abs(2*signal.sawtooth(t*2*np.pi*triangle_frequency-np.pi/2)) - 1 msg = Message(sample_freq, t, msg) return msg
def saw_gen(self): x1 = self.x*chunk x2 = (self.x+1)*chunk sample = numpy.arange(x1, x2, dtype=numpy.float32) self.x = int(self.x + 1) sample *= numpy.pi * 2 / samplespeed sample *= self.frequency sample = sig.sawtooth(sample).astype(numpy.float32) return sample
def GenerateSawtoothData(freq, length, sampling_freq): """ Simple sawtooth signal synthesis """ end_time_s = float(length) / sampling_freq sampled_time = numpy.arange(0, end_time_s, 1.0 / sampling_freq) return signal.sawtooth(sampled_time * 2 * numpy.pi * freq)
def saw_wave(self): self.t = np.arange(0., self.L, self.T_s) #Time array self.y_t = signal.sawtooth(2.*np.pi*self.Hz*self.t) if self.scale == True: #Scaled up wave amplitude to audible level self.y_t = np.int16(self.y_t/np.max(np.abs(self.y_t))*self.s) return self.y_t #Wave no scaling self.H = self.y_t return self.y_t
def wavegen(freq, shape=None): # use sine if no shape is given if shape is None: shape='sine' # create array of time points t = 2.0 * np.pi * float(freq) * np.arange(0, np.floor(FS/freq)) / float(FS) # draw waveform if shape=='sine': wave = MAX_INT * np.sin(t) elif shape=='sawtooth': wave = MAX_INT * signal.sawtooth(t + np.pi) elif shape=='triangle': wave = MAX_INT * signal.sawtooth(t + np.pi/2, 0.5) elif shape=='square': wave = MAX_INT * signal.square(t) return np.array(wave, dtype=np.int16)
def triangle_wave(): nb = np.random.randint(1, 100, size=1)[0] shift = np.random.randint(0, 91, size=1)[0] x = np.arange(-nb * np.pi, nb * np.pi, step=(2 * nb * np.pi / nb_timesteps)) y = sawtooth(x + (shift / 180.), width=0.5) noise = np.random.uniform(-0.1, 0.1, size=len(x)) y += noise return y
def wave_fun(t, fun): """ Funkcja wave_fun(t, fun) definiuje funkcje, jaka ma wykonac na zmiennej t. Argument fun moze przyjmowac 3 wartosci - sin, saw i rec, wowczas generuje fale sinusoidalna, trojkatna lub prostokatna, odpowiednio. """ if fun == 'sin': return np.sin(t) elif fun == 'saw': return sp.sawtooth(t) elif fun == 'rec': return np.sign(np.sin(t))
def test_complex_cepstrum(): """The period of a periodic harmonic will show up as a peak in a complex cepstrum. """ duration = 5.0 fs = 8000.0 samples = int(fs*duration) t = np.arange(samples) / fs fundamental = 100.0 signal = sawtooth(2.*np.pi*fundamental*t) ceps, _ = complex_cepstrum(signal) assert(fundamental == 1.0/t[ceps.argmax()])
def generate(self, step, dumpworld): world = np.zeros([3, 10, 10, 10]) position = int( round((sawtooth(0.1 * step * self.speed, 0.5) + 1) * 4.51)) if self.dir == 0: world[:, position, :, :] = 1.0 elif self.dir == 1: world[:, :, position, :] = 1.0 else: world[:, :, :, position] = 1.0 return world
def osc_gen(_type, freq, length, rate): length *= .001 t = np.linspace(0, length, length * rate) if _type == u'square': return signal.square(2 * np.pi * freq * t) if _type == u'saw': return signal.sawtooth(2 * np.pi * freq * t) if _type == u'sine': return np.sin(2 * np.pi * freq * t) if _type == u'white_noise': return np.random.random(length * rate) * 2 - 1 raise osexception(u'Invalid oscillator: %s' % _type)
def sawtooth_wave(time_points, frequency, phase, amplitude, offset): ''' Generates a sawtooth wave Arguments: time_points: Time points to evaluate the function frequency: Frequencies of the inputs amplitude: Amplitude of the wave phase: Phase offset of wave offset: Offset of the input ''' rads = 2 * np.pi * frequency * time_points + phase wave = signal.sawtooth(rads + np.pi / 2, width=0.5) return amplitude * wave + np.outer(offset, np.ones(len(time_points)))
def segnal_triangular(amplitud, simetria, t, fs=1): """Señal triangular Args: amplitud (int): Amplitud de la señal simetria (float): simetria de la señal t (list): Lista de valores que definen el tiempo. fs (int, optional): Frecuencia de la señal. Defaults to 1. Returns: list: Lista de valores de la señal """ return amplitud * (signal.sawtooth(2 * np.pi * fs * t, simetria))
def voiced_fricative(phoneme, freq, length, width=0.2): laryngeal_tone = Larynx.get_base_tone(freq, length) noise_tone = Noise.get_noise(length) filtered_noise = Mouth.get_slice( Mouth.apply_formants(noise_tone, voiced_fricative_formant_dict[phoneme][1], width), 0.97) filtered_noise *= signal.sawtooth( 2 * np.pi * np.linspace(0, length, int(len(filtered_noise))) * freq) return Mouth.get_slice(Mouth.apply_formants(laryngeal_tone, voiced_fricative_formant_dict[phoneme][0], width) + laryngeal_tone * 0.02, 0.97) \ + filtered_noise
def osc_gen(_type, freq, length, rate): length *= .001 t = np.linspace(0, length, length*rate) if _type == u'square': return signal.square(2*np.pi*freq*t) if _type == u'saw': return signal.sawtooth(2*np.pi*freq*t) if _type == u'sine': return np.sin(2*np.pi*freq*t) if _type == u'white_noise': return np.random.random(length*rate)*2 - 1 raise osexception(u'Invalid oscillator: %s' % _type)
def sawtooth_freq(t, fm=1, B=1, fd=0, width=0.5): ''' Simulated frequencies of sawtooth modulation. t: Time array. fm: Modulation frequency. fd: Doppler frequency shift. B: Bandwidth. ''' f = B * 0.5 * (signal.sawtooth(2 * np.pi * fm * t, width=width) + 1) f += fd return f
def calc_msd(self): """ Calculates the mean square deviations and returns them as a numpy array """ # stretch if self.wgt_val_str.sum() > 0: delt = (self.pd.ric.get_val_stretches() - self.ref_val_str) * self.fact_str wdelt = delt * self.wgt_val_str self.msd_str = (wdelt * wdelt).sum() / self.wgt_val_str.sum() self.max_str = wdelt.max() self.amsd_str = delt * delt else: self.msd_str = 0.0 self.amsd_str = 0.0 # bend if self.wgt_val_ibe.sum() > 0: delt = (self.pd.ric.get_val_in_bends() - self.ref_val_ibe) * self.fact_ibe wdelt = delt * self.wgt_val_ibe self.msd_ibe = (wdelt * wdelt).sum() / self.wgt_val_ibe.sum() self.max_ibe = wdelt.max() self.amsd_ibe = delt * delt else: self.msd_ibe = 0.0 self.amsd_ibe = 0.0 # torsion ... to be fully implemented ### DO NOT REMOVE COMMENTS if self.wgt_val_tor.sum() > 0: delt = (self.pd.ric.get_val_torsions() - self.ref_val_tor) * self.fact_tor delt = 90 * (signal.sawtooth(delt / rad2deg, 0.5) + 1 ) ###only multiplicity 1 wdelt = delt * self.wgt_val_tor self.msd_tor = (wdelt * wdelt).sum() / self.wgt_val_tor.sum() self.max_tor = wdelt.max() self.amsd_tor = delt * delt else: self.msd_tor = 0.0 self.amsd_tor = 0.0 # wag ... not compared # hessian (currently all hessian elements are compared if self.absolute: delt = (self.pd.ric.get_ric_hessian() - self.ref_hes) * self.fact_hes else: delt = abs(1 - (self.pd.ric.get_ric_hessian() / self.ref_hes)) wdelt = delt * self.wgt_hes self.msd_hes = (wdelt * wdelt).sum() / self.wgt_hes.sum() self.max_hes = wdelt.max() self.amsd_hes = delt * delt return
def test(self): ############################################################################### # Generate sample data np.random.seed(0) n_samples = 2000 time = np.linspace(0, 8, n_samples) s1 = np.sin(2 * time) # Signal 1 : sinusoidal signal s2 = np.sign(np.sin(3 * time)) # Signal 2 : square signal s3 = signal.sawtooth(2 * np.pi * time) # Signal 3: saw tooth signal S = np.c_[s1, s2, s3] S += 0.2 * np.random.normal(size=S.shape) # Add noise S /= S.std(axis=0) # Standardize 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) # Generate observations # Compute ICA ica = FastICA(n_components=3) S_ = ica.fit_transform(X) # Reconstruct signals A_ = ica.mixing_ # Get estimated mixing matrix # We can `prove` that the ICA model applies by reverting the unmixing. assert np.allclose(X, np.dot(S_, A_.T) + ica.mean_) # For comparison, compute PCA pca = PCA(n_components=3) H = pca.fit_transform(X) # Reconstruct signals based on orthogonal components ############################################################################### # Plot results plt.figure() models = [X, S, S_, H] names = ['Observations (mixed signal)', 'True Sources', 'ICA recovered signals', 'PCA recovered signals'] colors = ['red', 'steelblue', 'orange'] for ii, (model, name) in enumerate(zip(models, names), 1): plt.subplot(4, 1, ii) plt.title(name) for sig, color in zip(model.T, colors): plt.plot(sig, color=color) plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.46) plt.show()
def wave ( tt, lo=0, hi=1, freq=0.1, phi=0, kind='saw', **kwargs ): # periodic signal functions have defined period 2 * pi, so we # scale the time points accordingly sct = tt * freq * 2 * np.pi + phi if kind == 'saw': if kwargs is not None and 'width' in kwargs: ss = sig.sawtooth ( sct, width=kwargs['width'] ) else: ss = sig.sawtooth ( sct ) elif kind == 'square': if kwargs is not None and 'duty' in kwargs: ss = sig.square ( sct, duty=kwargs['duty'] ) else: ss = sig.square ( sct ) elif kind == 'sine': ss = np.sin ( sct ) elif kind == 'uniform': ss = rng.rand(len(tt)) elif kind == 'gaussian': ss = rng.randn(len(tt)) if kwargs is not None: ss = ss * kwargs.get('sd', 1) + kwargs.get('mean', 0) elif kind == 'walk': ss = rng.randn(len(tt)) if kwargs is not None: ss = ss * kwargs.get('sd', 1) + kwargs.get('mean', 0) ss = np.cumsum(ss) # potentially other kinds here # default to a constant 0 output else: return tt * 0 return rescale(ss, lo, hi)
def generate_triangle(freq, t, amplitude, fs, phase=np.zeros(7)): ''' Generates a triangle wave form that can be used for the input data. freq: Frequencies of the inputs in an one-dimensional array t: The datapoint(s) index where to generate a sine value (1D array when multiple datapoints are used) amplitude: Amplitude of the sine wave (Vmax in this case) fs: Sample frequency of the device phase: (Optional) phase offset at t=0 ''' # There is an additional + np.pi/2 to make sure that if phase = 0. the inputs start at 0V return signal.sawtooth( (2 * np.pi * freq[:, np.newaxis] * t) / fs + phase[:, np.newaxis] + np.pi / 2, 0.5) * amplitude[:, np.newaxis]
def update_data(self): if self.waveform_list.list[0].isChecked(): self.waveform_index = 0 self.data = self.mod_amp * np.cos( 2 * np.pi * self.freq / self.n * np.arange(self.n)) elif self.waveform_list.list[1].isChecked(): self.waveform_index = 1 self.data = self.mod_amp * signal.sawtooth( 2 * np.pi * self.freq / self.n * np.arange(self.n), width=0.5) elif self.waveform_list.list[2].isChecked(): self.waveform_index = 2 self.data = self.mod_amp * signal.square( 2 * np.pi * self.freq / self.n * np.arange(self.n), duty=0.5) self.data_updated_signal.emit(self.index)
def main(args): t = np.linspace(0, 1, 10100) fs = 4 * 44.1E3 startTime = 0 endTime = 0.05 f = 40. t = np.linspace(startTime, endTime, (endTime - startTime) * fs) print t tri = (sig.sawtooth((t * 2 * pi * 1000.E3), width=0.5) + 1) * 0.5 sine = ((sin(2 * pi * t * f)) + 1) * 0.5 cmprtr = np.zeros(len(t)) cmprtr2 = np.zeros(len(t)) for i in range(len(t)): if sine[i] > tri[i]: cmprtr[i] = 1 sq = (sig.square((t * 2 * pi * 10.E3)) + 1) * 0.5 for i in range(len(t)): if sine[i] > sq[i]: cmprtr2[i] = 1 fc = 15.E3 data1 = butter_lowpass_filter(cmprtr, fc, fs) data2 = butter_lowpass_filter(cmprtr2, fc, fs) plt.figure() plt.subplot(411) plt.plot(t, sine) plt.subplot(412) plt.plot(t, tri) plt.subplot(413) plt.plot(t, cmprtr) plt.subplot(414) plt.plot(t, data1) plt.figure() plt.subplot(411) plt.plot(t, sine) plt.subplot(412) plt.plot(t, sq) plt.subplot(413) plt.plot(t, cmprtr2) plt.subplot(414) plt.plot(t, data2) plt.show() return 0
def osc_saw(self, freq, length, rate): """ desc: A saw-wave oscillator. visible: False """ length *= .001 t = np.linspace(0, length, length*rate) a = signal.sawtooth(2*np.pi*freq*t) return a
def create_dummy_data_array(width: float, processing: str, sawteeth_count: int, channel_index: int = 1, trace_number: int = 1) -> DataArray: identifier = 'ScopeTrace_{:03d}'.format(trace_number) label = 'Channel_{}'.format(channel_index) scope_data = sawtooth(2 * np.pi * (sawteeth_count * time / period), width) offset = {'left': 1 - width, 'center': (1 - width / 2), 'right': 0} scope_data = np.roll(scope_data, int(offset[processing] * len(scope_data))) return DataArray(identifier, label, preset_data=scope_data, set_arrays=[set_array])
def plot_ica(self): # Generate sample data np.random.seed(0) n_samples = 2000 time = np.linspace(0, 8, n_samples) s1 = np.sin(2 * time) # Signal 1 : sinusoidal signal s2 = np.sign(np.sin(3 * time)) # Signal 2 : square signal s3 = signal.sawtooth(2 * np.pi * time) # Signal 3: saw tooth signal S = np.c_[s1, s2, s3] # 縦に連結 S += 0.2 * np.random.normal(size=S.shape) # Add noise S /= S.std(axis=0) # Standardize 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) # Generate observations(観察データということにする) # Compute ICA ica = decomposition.FastICA(n_components=3) S_ = ica.fit_transform(X) # Reconstruct signals A_ = ica.mixing_ # Get estimated mixing matrix # We can `prove` that the ICA model applies by reverting the unmixing. assert np.allclose(X, np.dot(S_, A_.T) + ica.mean_) # For comparison, compute PCA pca = decomposition.PCA(n_components=3) H = pca.fit_transform(X) # Reconstruct signals based on orthogonal components ############################################################################### # Plot results plt.figure() models = [X, S, S_, H] names = ['Observations (mixed signal)', 'True Sources', 'ICA recovered signals', 'PCA recovered signals'] colors = ['red', 'steelblue', 'orange'] for ii, (model, name) in enumerate(zip(models, names), 1): plt.subplot(4, 1, ii) plt.title(name) for sig, color in zip(model.T, colors): plt.plot(sig, color=color) plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.46) plt.savefig("ica.jpg")
def generate2(): try: s2 = entFrequency2.get() t=float(s2) t = np.linspace(0, 1, 500) plot.plot(t, signal.sawtooth(2 * np.pi * 5 * t)) plot.xlabel('time') plot.ylabel('amplitude') plot.show() messagebox.showinfo("Results","Sawtooth wave generated") except ValueError: messagebox.showerror("Issue","Incorrect Input") entFrequency2.delete(0,END) entFrequency2.focus()
def fxWaveFormUpdater(self, value): self.convolutionSlider.setValue(-10) if value == 'Sine': self.fx = self.fxAmp * np.sin(2 * np.pi * self.fxFreq * self.x) elif value == 'Square': self.fx = self.fxAmp * signal.square( 2 * np.pi * self.fxFreq * self.x, 0.5) elif value == 'Triangle': self.fx = self.fxAmp * signal.sawtooth( 2 * np.pi * self.fxFreq * self.x, 0.5) elif value == 'Sawtooth': self.fx = self.fxAmp * signal.sawtooth( 2 * np.pi * self.fxFreq * self.x, 1) # change our plots self.canvas.convolutionPlot.clear() self.plot_refs['fx'][0].set_ydata(self.fx) self.canvas.convolutionPlot.plot(self.t_fx, self.fx, 'b') self.canvas.convolutionPlot.plot(self.t_gx, np.flip(self.gx, 0), 'g') self.canvas.convolutionPlot.set_xlim(-2, 2) # Trigger the canvas to update and redraw. self.canvas.draw() # Update colvolution with new signal self.update_convol()
def init_soundwaves(): volume = 0.3 # duration = 0.15 # in seconds, may be float decay = -0.000001 for i in range(22, 122): note_mapper = (2.0**((i - 69) / 12.0)) * 440.0 gain = np.exp(decay * np.arange(fs * duration)) #kernel=np.sign(np.sin(2*np.pi*np.arange(fs*duration)*note_mapper/fs)) #kernel=np.sign(np.sin(2*np.pi*np.arange(fs*duration)*note_mapper/fs)) kernel = signal.sawtooth(2 * np.pi * np.arange(fs * duration) * note_mapper / fs) samples = (volume * kernel).astype(np.float32) waves[i] = samples waves[0] = 0.0 * waves[23]
def cyclical(self, epoch, mode='sin', mean=1.0, amp=1.0, period=20, phase=0.0): if mode == 'sin': return amp / 2 * np.sin(2 * np.pi * epoch / period + phase) + mean elif mode == 'cos': return amp / 2 * np.cos(2 * np.pi * epoch / period + phase) + mean elif mode == 'triangular': return amp / 2 * signal.sawtooth(2 * np.pi * epoch / period + phase) + mean
def getrandompoint(wave, table, Vsize): global randpointer # global randpointerjump randpointer = randpointer + int(randpointerjump * randpointerbackrange - random.randint(0, randpointerjump)) if randpointer < 0: randpointer = 0 if randpointer >= rez: randpointer = rez - 1 # print randpointer if table == "sin": return (randpointer * interval, np.sin(wave[randpointer]) * Vsize) if table == "cos": return (randpointer * interval, np.cos(wave[randpointer]) * Vsize) if table == "saw": return (randpointer * interval, signal.sawtooth(wave[randpointer]) * Vsize)
def make_triangle_LFO(n_samps, rate, amplitude): """ Generate a triangle wave Inputs: n_samps number of samples rate oscillation frequency, in units of 1/samples amplitude amplitude :return: """ return amplitude * signal.sawtooth(2 * np.pi * rate * np.arange(n_samps), width=0.5)
def __init__(self): #Définition du nombre de périodes nT = 2 #Fréquence Hz = 50 #Définition de l'abscisse x = np.linspace(start=0, stop=nT, num=50) plt.grid(True) plt.ylim(-2, 2) # Génération d'un carré plt.plot(x, sg.square(2 * np.pi * Hz * x), c='RED') #Génération d'un signal en dent de scie plt.plot(x, sg.sawtooth(2 * np.pi * Hz * x), c='ORANGE') #Génération d'un signal en triangle plt.plot(x, sg.sawtooth(2 * np.pi * Hz * x, width = 0.5), c='CYAN') #Dessin plt.show()
def __init__(self, frequency, duration, attenuate=None): # Set member elements of Saw class self.frequency = frequency self.duration = duration # Set the sample frequency to 44.1 kHz self.sample_freq = 44100 # Create time and wave vector for sawtooth wave self.t = np.arange(0, duration, 1/self.sample_freq) # Period = 1/Frequency self.x = signal.sawtooth(2 * np.pi * self.frequency * self.t) # 2*pi*f to convert to angular frequency omega # If user wants to attenuate the signal, attenuate by that value (must be less than 1) if((attenuate != None) & (attenuate < 1)): self.x = self.x * attenuate
def _generate_wave(self, base): if base is None: return None if self.waveform == self.WAVE_SINE: wave = np.sin(base) elif self.waveform == self.WAVE_SAWTOOTH: wave = signal.sawtooth(base) elif self.waveform == self.WAVE_SQUARE: wave = signal.square(base) else: # unknown waveform or NONE l = 1 if base is None else len(base) wave = np.array([0] * l, dtype='float64') return wave
def create_sawtooth(start_time, params, sampling_rate, duration): min_value = params['amplitude'][0] max_value = params['amplitude'][1] num_of_cycles = params['num_of_cycles'] num_samples = int(duration * sampling_rate) sampling_interval = 1 / sampling_rate sampling_interval = timedelta(seconds=sampling_interval) x = np.arange(num_samples) t = [start_time + i * sampling_interval for i in x] x = np.linspace(0, 1, num_samples) y = sawtooth(2 * np.pi * num_of_cycles * x) y = scale_amp(y, min_value, max_value) return to_df(t, y)
def _saveGDparams(self, GDparams): self.lambda_L2 = GDparams['lambda_L2'] self.batch_size = GDparams['batch_size'] self.n_cycles = GDparams['n_cycles'] self.n_s = GDparams['n_s'] self.eta_min = GDparams['eta_min'] self.eta_max = GDparams['eta_max'] self.verbose = GDparams['verbose'] # Prepare schedule of the learning rate t = np.arange(self.n_s * 2) freq = 1 / (2 * self.n_s) self.scheduled_eta = (signal.sawtooth(2 * np.pi * t * freq, 0.5) + 1) / 2 * (self.eta_max - self.eta_min) + self.eta_min
def plotSawtooth(self, amp, freq): self.Fs: int = 44100 self.x = arange(0, 1, 1 / self.Fs) self.y = (amp / 10) * sawtooth(2 * pi * freq * self.x) self.plot = self.PlotView.plotItem self.vBox = self.plot.vb self.vBox.setLimits(xMin=-0, yMin=-2, xMax=1.3, yMax=2) self.vBox.setBackgroundColor("w") self.plot.addLegend() self.plot.showGrid(x=True, y=True) self.plot.plot(self.x, self.y, pen=mkPen('b', width=1), name=str(amp) + "Sawtooth(2π" + str(freq))
def __generateToneData(self): if self.toneType == 'sine': self.samples = ( self.volume * np.sin(2 * np.pi * np.arange(self.fs * self.duration) * self.f / self.fs)).astype(np.float32).tobytes() elif self.toneType == 'square': self.samples = ( self.volume * signal.square(2 * np.pi * np.arange(self.fs * self.duration) * self.f / self.fs)).astype(np.float32).tobytes() else: self.samples = (self.volume * signal.sawtooth( 2 * np.pi * np.arange(self.fs * self.duration) * self.f / self.fs)).astype(np.float32).tobytes()
def calculate_signal(self, **kwargs): try: sampling = kwargs['sampling_rate'] except: sampling = self.sampling waveIndex = self.wavelistbox.get_selection() st = float(self.start_time.get()) et = float(self.end_time.get()) a = float(self.amplitude.get()) f = float(self.frequency.get()) delay = float(self.delay.get()) displacement = float(self.displacement.get()) x = numpy.arange(st, et+1.0/sampling, 1.0/sampling) if (self.list[waveIndex] == 'Sine'): y = displacement + a*numpy.sin(2*numpy.pi*f*x - delay*f*numpy.pi) if (self.list[waveIndex] == 'Square'): y = displacement + a*sgl.square(2*numpy.pi *f*(x-delay)) if (self.list[waveIndex] == 'Sawtooth'): y = displacement + a*sgl.sawtooth(2*numpy.pi *f*(x-delay)) if (self.list[waveIndex] == 'Triangle'): y = displacement + a*sgl.sawtooth(2*numpy.pi *f*(x-delay), width=0.5) if (self.list[waveIndex] == 'User Function'): try: exec(self.userSignal.get()) except: pass return [x,y]
def playrec_sawtooth(frecuencia, duracion, amplitud=0.1, fs=192000): """ Emite y graba una funcion rampa. """ sd.default.samplerate = fs #frecuencia de muestreo sd.default.channels = 1, 2 #por las dos salidas de audio cantidad_de_periodos = duracion * frecuencia puntos_por_periodo = int(fs / frecuencia) puntos_totales = puntos_por_periodo * cantidad_de_periodos tiempo = np.linspace(0, duracion, puntos_totales) data = amplitud * signal.sawtooth(2 * np.pi * frecuencia * tiempo) grabacion = sd.playrec(data, blocking=True) return tiempo, data, grabacion
class MultiProfileTriangle(MultiProfileTestMixin, TestCase): x_values = np.linspace(0, 8*np.pi, num=200) values = sps.sawtooth(x_values, width=0.5) valley_max_idxs = (50, 100, 150) peak_max_idxs = (25, 75, 125, 175) peak_fwxm_idxs = (25, 75, 125, 175) def test_ground_profile(self): """Test that the profile is properly grounded to 0.""" p = MultiProfile(self.values) # the minimum shouldn't be zero to start with self.assertFalse(p.values.min() == 0) # but it should be after grounding p.ground() self.assertTrue(p.values.min() == 0)
def _reset_reference(self): # get absolute values of amplitude, frequency and offset self._amplitude = self._get_current_value(self._amplitude_range) self._frequency = self._get_current_value(self._frequency_range) offset_range = np.clip( self._offset_range, -self._limit_margin[1] + self._amplitude, self._limit_margin[1] - self._amplitude ) self._offset = self._get_current_value(offset_range) t = np.linspace(0, (self._current_episode_length - 1) * self._physical_system.tau, self._current_episode_length) phase = np.random.rand() * 2 * np.pi # note: in the scipy implementation of sawtooth() 1 time-period # corresponds to a phase of 2pi ref_width = np.random.rand() # a random value between 0,1 that creates asymmetry in the triangular reference # wave ref_width=1 creates a sawtooth waveform self._reference = self._amplitude * sg.sawtooth(2*np.pi * self._frequency * t + phase, ref_width) + self._offset self._reference = np.clip(self._reference, self._limit_margin[0], self._limit_margin[1])
def __init__(self, freq, numPoints=6000, sampleSpacing=1 / 800, amplitude=2.5): """ :freq: frequency of the input signal :amplitude: peak amplitude of input signal """ super(triangle, self).__init__(numPoints=numPoints, sampleSpacing=sampleSpacing, name='Triangle Modeled Waveform') # here, we override the relationship between time and frequency self.voltageFunction = amplitude * signal.sawtooth( 2 * np.pi * 5 * self.time, width=.5)
def make_signals(): # fix a random state seed rng = np.random.RandomState(42) n_samples = 2000 time = np.linspace(0, 8, n_samples) # create three signals s1 = np.sin(2 * time) # Signal 1 : sinusoidal signal s2 = np.sign(np.sin(3 * time)) # Signal 2 : square signal s3 = signal.sawtooth(2 * np.pi * time) # Signal 3: saw tooth signal # concatenate the signals, add noise S = np.c_[s1, s2, s3] S += 0.2 * rng.normal(size=S.shape) S /= S.std(axis=0) # Standardize data S -= S.min() return S
def update_data(self): # Compute waveform if self.waveform_list.list[0].isChecked(): # Sine self.waveform_index = 0 self.data = self.offset + self.mod_amp * np.sin(2 * np.pi * self.freq / self.n * np.arange(self.n)) elif self.waveform_list.list[1].isChecked(): # Triangle self.waveform_index = 1 self.data = self.offset + self.mod_amp * signal.sawtooth(2 * np.pi * self.freq / self.n * np.arange(self.n), width=0.5) elif self.waveform_list.list[2].isChecked(): # Square self.waveform_index = 2 self.data = self.offset + self.mod_amp * signal.square(2 * np.pi * self.freq / self.n * np.arange(self.n), duty=0.5) # Prevent overflow self.data[self.data >= +0.999] = +0.999 self.data[self.data <= -0.999] = -0.999 self.data_updated_signal.emit(self.index)
def main(): sin_functions = { 'sine': np.sin, 'sawtooth': lambda x: sawtooth(x, width=0.5), } parser = argparse.ArgumentParser() parser.add_argument('infile') parser.add_argument('outpath') parser.add_argument('--overwrite', '-O', action='store_true', help="Don't complain if outpath already exists") parser.add_argument('--fit-function', '-f', help='Choose a function to fit the waveforms', choices=sin_functions.keys(), default='sine') parser.add_argument( '--strains-from', '-s', choices=['fit', 'data'], default='fit', help=("Choose whether strains will be computed from the peaks of the " "fit function (fit; default) or from the average of the observed " "strains at the extended position determined from the fits (data).")) parser.add_argument('--fps', type=float, default=30.) args = parser.parse_args() try: os.makedirs(args.outpath) # do this first so we aren't surprised later except OSError: if not args.overwrite: print >> sys.stderr, "Output path exists. Use --overwrite to run anyway." sys.exit(1) f = open(args.infile, 'rU') frames = parse_mtrack2(f) f.close() centered_frames, jitter = recenter(frames) fit_parameters = sinefit(frames, dt=1./args.fps, sin=sin_functions[args.fit_function]) if args.strains_from == 'fit': (_center_x, _center_y, resting_x, resting_y, extended_x, extended_y) = \ process_coordinates(fit_parameters) elif args.strains_from == 'data': (_center_x, _center_y, resting_x, resting_y, extended_x, extended_y) = \ process_coordinates_from_data(fit_parameters, frames, 1./args.fps) else: raise ValueError peak_strain = calculate_peak_strain(fit_parameters, resting_x, resting_y, extended_x, extended_y) write_plots(frames, fit_parameters, jitter, args.outpath, peak_strain, dt=1./args.fps, min_strain=-0.05, max_strain=0.25)
def generate_target_force_trajectory(TrajectoryType,Time,Amplitude,AmplitudeModulation,FrequencyModulation): if TrajectoryType == 'triangle': delay = (1/FrequencyModulation)/4 triangle = 2*sawtooth(2*np.pi*(Time-Delay),0.5)-1 TargetForceTrajectory = AmplitudeModulation*triangle+Amplitude elif TrajectoryType == 'sinewave': TargetForceTrajectory = AmplitudeModulation*np.sin(2*np.pi*FrequencyModulation*Time)+Amplitude elif TrajectoryType == 'constant': SamplingFrequency = 10000 TargetForceTrajectory = np.concatenate((np.zeros(SamplingFrequency), (Amplitude)*(1/2)*Time[:2*SamplingFrequency], Amplitude*np.ones(len(Time)-3*SamplingFrequency), Amplitude*np.ones(5000))) TargetForceTrajectory = smooth(TargetForceTrajectory,500) TargetForceTrajectory = TargetForceTrajectory[:-5000] #TargetForceTrajectory = [Amplitude*np.ones(1,len(Time))] """ elif strcmp(type,'trapezoid') SamplingFrequency = 10000 offset = 0.01 % in %MVC slope = Amplitude/5 % %MVC/s %Amplitude = 30 % in %MVC holdtime = 0 interval = 5 % in seconds ramp_up = offset/interval*(Time(1:interval*SamplingFrequency)) delay_rise_start = SamplingFrequency*interval delay_rise_end = SamplingFrequency*(Amplitude/slope)+delay_rise_start delay_decay_start = delay_rise_end + SamplingFrequency*holdtime delay_decay_end = delay_rise_end + SamplingFrequency*holdtime + SamplingFrequency*(Amplitude/slope) y1 = slope*(Time(delay_rise_start:delay_rise_end)-interval) y2 = -slope*(Time(delay_decay_start:delay_decay_end)-delay_decay_end/SamplingFrequency) %zeros(1,interval*SamplingFrequency) Trapezoidal_Pulse = [zeros(1,interval*SamplingFrequency) y1 ... Amplitude*ones(1,holdtime*SamplingFrequency) y2 zeros(1,interval*SamplingFrequency)]+offset N = floor(Time(end)/(len(Trapezoidal_Pulse)/SamplingFrequency)) TargetForceTrajectory = repmat(Trapezoidal_Pulse,1,N) TargetForceTrajectory = [TargetForceTrajectory zeros(1,len(Time)-len(TargetForceTrajectory))+offset] TargetForceTrajectory(1:interval*SamplingFrequency) = ramp_up # 6%MVC => 0.0667 # 3%MVC => 0.05 # 1.5%MVC => 0.033 # 3%MVC + 5s hold => 0.04 # 3%MVC + 10s hold => """ return(TargetForceTrajectory)
def example_model(): # example model data from # http://scikit-learn.org/stable/auto_examples/decomposition/plot_ica_blind_source_separation.html np.random.seed(0) n_samples = 2000 time = np.linspace(0, 8, n_samples) s1 = np.sin(2 * time) # Signal 1 : sinusoidal signal s2 = np.sign(np.sin(3 * time)) # Signal 2 : square signal s3 = signal.sawtooth(2 * np.pi * time) # Signal 3: saw tooth signal S = np.c_[s1, s2, s3] S += 0.2 * np.random.normal(size=S.shape) # Add noise S /= S.std(axis=0) # Standardize 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) # Generate observations return S, A, X
def saw_custom(f,T,a=0,b=0): """ Funkcja zwraca macierz reprezentujaca dzwiek stworzony za pomoca fali typu sawtooth. Argumenty wejsciowe: f - czestotliwosc w Hz T - czas w sekundach a - wzgledny czas narastania liniowego dzwieku, 0<=a<=1 b - wzgledny czas wygaszania liniowego dzwieku, 0<=b<=1 """ fs=44100 t=np.linspace(0,T,T*fs) A=np.floor(a*fs*T) D=np.floor(b*fs*T) S1=np.linspace(0,1,A) S2=np.ones(T*fs-A-D) S3=np.linspace(1,0,D) S0=signal.sawtooth(2 * np.pi * f * t) return(np.hstack((S1,S2,S3))*S0)
def getData(self, tstamp): if (None == self.data): t = np.linspace(0, 1, self.sample_freq) self.data = signal.sawtooth(2 * np.pi * self.control_params.frequency * t) self.data = self.data * self.control_params.amplitude if (None == self.lastTime): self.lastTime = bulkio.timestamp.now() t_then = self.lastTime.twsec + self.lastTime.tfsec t_now = tstamp.twsec + tstamp.tfsec vec = None if (t_now - t_then >= self.window / self.sample_freq): vec = list(self.data[0:self.window]) self.data = np.roll(self.data, -self.window) self.lastTime = tstamp return vec
""" import neurolab as nl import numpy as np from scipy import signal def func1(x): if x < 0: return 10*np.exp(-.03*x*40 - 0.3)*np.sin((0.6*x*40-0.1))+40*x+.5 if x >= 0: return 10*np.exp(-.03*x*40 - 0.3)*np.sin((0.3*x*40-0.1))+40*x+.5 # Create train samples x = np.linspace(-0., 0.5, 100) o = signal.sawtooth(2 * np.pi * 5 * x) size = len(x) #print(size) y = o + (np.random.random(size)-0.5)*0.1 inp = x.reshape(size,1) tar = y.reshape(size,1) n = nl.net.newff([[np.min(inp), np.max(inp)]], [35, 1]) n.trainf = nl.train.train_bfgs n.trainf = nl.train.train_gd #import pdb; pdb.set_trace() error = n.train(inp, tar, epochs=30, goal=0.0, show=1, adapt=True) y3 = np.array(error) out = n.sim(inp) print(error[-1])
data_list.append(x1) ch_dict = { "label": "ramp", "dimension": "uV", "sample_rate": 200, "physical_max": 100, "physical_min": -100, "digital_max": 32767, "digital_min": -32768, "transducer": "", "prefilter": "", } channel_info.append(ch_dict) time = np.linspace(0, file_duration, file_duration * 200) x2 = signal.sawtooth(2 * np.pi * 1 * time) data_list.append(x2) ch_dict = { "label": "pulse 1", "dimension": "uV", "sample_rate": 200, "physical_max": 100, "physical_min": -100, "digital_max": 32767, "digital_min": -32768, "transducer": "", "prefilter": "", } channel_info.append(ch_dict) time = np.linspace(0, file_duration, file_duration * 200)