def DeltaLogSFR_dutycycle(t0, tf, t_q=None, dutycycle_prop=None, indices=None): ''' log(SFR) contribution from the SF duty cycle fluctuation log(SFR)_sfdutyfluctuation = Delta log(SFR) * squarewave( freq * (t + phase) ) ''' if dutycycle_prop['name'] == 'notperiodic': if indices is None: return dutycycle_prop['delta_sfr'] else: return dutycycle_prop['delta_sfr'][indices] elif dutycycle_prop['name'] == 'squarewave': freq = dutycycle_prop['freq'] phase = dutycycle_prop['phase'] if t_q is None: t_cosmic = tf - t0 else: t_cosmic = t_q - t0 notqing = np.where(tf <= t_q) t_cosmic[notqing] = tf - t0 sfduty = dutycycle_prop['delta_sfr'] * signal.square(freq * t_cosmic - phase) if indicies is None: return sfduty else: return sfduty[indices] elif dutycycle_prop['name'] == 'newamp_squarewave': if indices is not None: freq = dutycycle_prop['freq'][indices] phase = dutycycle_prop['phase'][indices] amp = dutycycle_prop['amp'][indices] else: freq = dutycycle_prop['freq'] phase = dutycycle_prop['phase'] amp = dutycycle_prop['amp'] if t_q is None: t_cosmic = tf - t0 else: t_cosmic = t_q - t0 notqing = np.where(tf <= t_q) t_cosmic[notqing] = tf - t0 # individual n_cycle n_cycles = ((t_cosmic - phase) // (2.0 * np.pi / freq)).astype(int) #print amp.shape, np.max(n_cycles) n_cycles += np.arange(amp.shape[0]) * amp.shape[1] sfduty = amp.reshape(amp.shape[0] * amp.shape[1])[n_cycles] * \ signal.square(freq * t_cosmic - phase) return sfduty
def GetSqSq(N=1000, K=4): """GetSqSq: Get modulation and demodulation functions for square coding scheme. The shift between each demod function is 2*pi/k where k can be [3,4,5...]. Args: N (int): Number of discrete points in the scheme k (int): Number of mod/demod function pairs 0.5 Returns: np.array: modFs np.array: demodFs """ #### Allocate modulation and demodulation vectors modFs = np.zeros((N, K)) demodFs = np.zeros((N, K)) t = np.linspace(0, 2 * np.pi, N) dt = float(TauDefault) / float(N) #### Declare base sin function sqF = (0.5 * signal.square(t, duty=0.5)) + 0.5 #### Set each mod/demod pair to its base function and scale modulations for i in range(0, K): ## No need to apply phase shift to modF modFs[:, i] = sqF ## Scale modF so that area matches the total energy modFs[:, i] = Utils.ScaleAreaUnderCurve(modFs[:, i], dx=dt, desiredArea=TotalEnergyDefault) ## Apply phase shift to demodF demodFs[:, i] = sqF #### Apply phase shifts to demodF shifts = np.arange(0, K) * (float(N) / float(K)) demodFs = Utils.ApplyKPhaseShifts(demodFs, shifts) #### Return coding scheme return (modFs, demodFs)
def __init__(self, amplitude=10.0, frequency=5.0, sample=500, functions="enumerate(('ramp',\ 'sinus',\ 'cosinus',\ 'square',\ 'triangle'))", peak_to_peak=True): from scipy import signal import numpy as np if peak_to_peak: div = 0 else: div = 1 t = np.linspace(0, 1, sample) if functions == 'ramp': self.y = (amplitude / (div + 1)) * ( signal.sawtooth(2 * np.pi * frequency * t) + div) elif functions == 'triangle': self.y = (amplitude / (div + 1)) * ( signal.sawtooth(2 * np.pi * frequency * t, 0.5) + div) elif functions == 'square': self.y = (amplitude / (div + 1)) * (signal.square(2 * np.pi * frequency * t) + div) elif functions == "sinus": self.y = (amplitude / (div + 1)) * (np.sin(2 * np.pi * frequency * t) + div) elif functions == "cosinus": self.y = (amplitude / (div + 1)) * (np.cos(2 * np.pi * frequency * t) + div)
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 gxWaveFormUpdater(self, value): self.convolutionSlider.setValue(-10) if value == 'Sine': self.gx = self.gxAmp * np.sin(2 * np.pi * self.gxFreq * self.x) elif value == 'Square': self.gx = self.gxAmp * signal.square( 2 * np.pi * self.gxFreq * self.x, 0.5) elif value == 'Triangle': self.gx = self.gxAmp * signal.sawtooth( 2 * np.pi * self.gxFreq * self.x, 0.5) elif value == 'Sawtooth': self.gx = self.gxAmp * signal.sawtooth( 2 * np.pi * self.gxFreq * self.x, 1) # change our plots self.canvas.convolutionPlot.clear() self.plot_refs['gx'][0].set_ydata(self.gx) self.canvas.convolutionPlot.plot(self.t_gx, np.flip(self.gx, 0), 'g') self.canvas.convolutionPlot.plot(self.t_fx, self.fx, 'b') 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 oscillator(length: int, shape: str, ν: int, φ: int = 0) -> np.ndarray: assert 0 <= φ <= ν shape = shape.lower() x = np.linspace(0, length + ν - 1, length + ν) if shape == "triangle": y = sawtooth(τ * x / ν, width=0.5) elif shape == "saw": y = sawtooth(τ * x / ν, width=1.0) elif shape == "reversesaw": y = sawtooth(τ * x / ν, width=0.0) elif shape == "square": y = square(τ * x / ν) elif shape == "halfsin": _y = np.zeros(ν) _y[:ν // 2] = np.sin(τ * np.linspace(0, 1, ν // 2)) y = np.tile(_y, x.shape[0] // ν + 1) elif shape == "noise": y = np.random.rand(*x.shape) y *= 0.1 elif shape == "sin": y = np.sin(τ * x / ν) else: raise ValueError("Invalid shape given") y = y[φ:φ + length][None, ...] return y
def playNote(x, y, c): # quantize to scale m = interpolate.interp1d([0, 515], [1, 8]) f_i = int(m(x)) v = interpolate.interp1d([0, 390], [0, 1]) volume = v(y) # range [0.0, 1.0] fs = 44100 // 3 # sampling rate, Hz, must be integer duration = 1.0 # in seconds, may be float f = f_map[f_i] # sine frequency, Hz, may be float # generate samples, note conversion to float32 array if c == 0: samples = (np.sin(2 * np.pi * np.arange(fs * duration) * f / fs)).astype(np.float32) elif c == 1: samples = signal.sawtooth(2 * np.pi * np.arange(fs * duration) * f / fs).astype(np.float32) else: samples = signal.square(2 * np.pi * np.arange(fs * duration) * f / fs).astype(np.float32) # for paFloat32 sample values must be in range [-1.0, 1.0] stream = p.open(format=pyaudio.paFloat32, channels=1, rate=fs, output=True) # play. May repeat with different volume values (if done interactively) stream.write(volume * samples) stream.stop_stream() stream.close()
def data_generation(S0,example): if example==1: x = np.arange(-1,1,0.05) y = 0.5+0.25*np.sin(3*np.pi*x) x = np.atleast_2d(x) if example==2: x = np.arange(-1,1,0.05) y=signal.square(2*np.pi*x,0.5) x = np.atleast_2d(x) if example==3: axisx=np.arange(-2,2,0.1) axisy=np.arange(-2,2,0.1) x=np.zeros([S0,1]) i=0 while i<len(axisx): j=0 while j<len(axisy): x=np.concatenate((x,np.reshape([axisx[i],axisy[j]],(S0,1))),axis=1) j+=1 i+=1 X,Y=np.meshgrid(axisx,axisy) z = np.sinc(X)*np.sinc(Y) y = z.flatten() x = np.delete(x,0,1) if example==4: Q=400 #x=np.random.normal(0, 0.5, [S0,Q]) x=np.random.uniform(-1,1,(S0,Q)) y=np.zeros([Q,]) i=0 while i<Q: y[i]=np.sin(2*np.pi*x[0,i])*x[1,i]**2*x[2,i]**3*x[3,i]**4*np.exp(-x[0,i]-x[1,i]-x[2,i]-x[3,i]) i+=1 return x,y
def sfr_squarewave(mass, tcosmic, **sfr_param): ''' SFR determined by square function Parameters ---------- mass : stellar mass tcosmic : cosmic time sfr_param : SFR parameters (amplitude, phase, and frequency) Notes ----- * Arbitrary sfr_param will be fed to produce random SFRs * ''' sfr_A = sfr_param['amp'] sfr_d = sfr_param['phase'] sfr_w = sfr_param['freq'] if not isinstance(sfr_w, float): if len(sfr_w) != len(mass): return None dSFR = sfr_A * signal.square(sfr_w * (tcosmic - 6.9048 + sfr_d)) # z_cosmic = get_zsnap(tcosmic) sfr, sig_sfr = get_sfr_mstar_z_bestfit( mass, z_cosmic, Mrcut=18) return sfr + dSFR
def _generate(self, n): num_sines = n // 3 num_squares = n // 3 num_sawtooths = n - num_sines - num_squares # Set time and frequency t = np.divide(np.arange(0, self._sequence_len), self._sample_freq).reshape((1, self._sequence_len)) def _random_freqs(n): return np.random.rand(n).reshape( (n, 1)) * (self._freq_max - self._freq_min) + self._freq_min # Generate waveforms sawtooths = signal.sawtooth(2 * np.pi * _random_freqs(num_sawtooths) * t) squares = signal.square(2 * np.pi * _random_freqs(num_squares) * t) sines = np.cos(2 * np.pi * _random_freqs(num_sines) * t) # Concatenate and add noise sig = np.concatenate( [sawtooths, sines, squares], axis=0) + np.random.normal( scale=self._noise_level, size=n * self._sequence_len).reshape( (n, self._sequence_len)) # Clip and split sig = np.clip(sig, -1.0, 1.0).astype(np.float32) # Waveform labels waveform_labels = np.concatenate([ np.zeros(num_sawtooths), np.ones(num_sines), np.ones(num_squares) * 2 ]).astype(np.int32) return sig[:, :-1], sig[:, 1:], waveform_labels
def remove_10hz(baseline_subbed, zapped, tsamp): t = np.arange(baseline_subbed.shape[1] + 46) boxcar = square(t / (1. / 2. / np.pi / 10. / tsamp)) av_pwr = baseline_subbed.mean(axis=0) A = np.fft.fft(boxcar[:-46]) B = np.fft.fft(av_pwr) Br = B.conjugate() fftfreq = np.fft.fftfreq(B.shape[0], tsamp) tenHz_ind = np.where(np.abs(fftfreq - 10.) == np.abs(fftfreq - 10.).min())[0][0] if (B[tenHz_ind - 5:tenHz_ind + 5] * B[tenHz_ind - 5:tenHz_ind + 5].conjugate()).max() > 1e4: c = np.fft.ifft(A * Br) shift = np.argmax(c[:46]) + 1 boxcar = boxcar[shift:shift + baseline_subbed.shape[1]] amp = np.mean( np.array([ np.abs(np.median(av_pwr[np.where(boxcar > 0)])), np.abs(np.median(av_pwr[np.where(boxcar < 0)])) ])) boxcar = amp * boxcar boxcar_arr = np.ones(baseline_subbed.shape) * boxcar dont_subtract = np.where(zapped == 1) boxcar_arr[dont_subtract[0], dont_subtract[1]] = 0. no_boxcar = baseline_subbed - boxcar_arr baseline_no_boxcar = snd.uniform_filter1d(no_boxcar.mean(axis=0), int(smooth_time / tsamp)) data_out = no_boxcar - baseline_no_boxcar else: data_out = baseline_subbed return data_out
def sqr_pa2(): w, f, dB, phase, sys, w0, etha = pasa_alto_2orden.pa_2() duty = float(input())#input del duty f1 = float(input())#input de frec de la cuadrada w1 = f1 * 2 * np.pi t = np.linspace(0, 2, 500) # , endpoint=False A = float(input()) u = A * signal.square(2 * np.pi * w1 * t, duty) tout, y, x = signal.lsim(sys, u, t) fig, ((ax1), (ax2)) = plt.subplots(2, 1) ax1.plot(tout, y) ax1.set_xlabel('seg') ax1.set_ylabel('A (amplitud)') ax1.set_title('Señal de output') ax1.grid(True) ax2.plot(t, u) ax2.set_xlabel('seg') ax2.set_ylabel('A (amplitud)') ax2.set_title('Señal de input') ax2.grid() fig.tight_layout() plt.show()
def grating_byte(X, freq = 1): """ Unsigned 8 bit representation of a grating (square wave) """ grating_float = signal.square(X*freq) grating_transformed = (grating_float + 1)*127.5; #from 0-255 return np.uint8(grating_transformed)
def test_square_generate_data(self): for _ in range(self.__number_iterations): amplitude = random.uniform(1.0, self.__maximum_amplitude) frequency = random.randint(self.__minimum_frequency, self.__maximum_frequency / 2) sr = random.uniform(2 * frequency, self.__maximum_frequency) duty = random.uniform(0.0, 1.0) n = int(random.uniform(1.0, 3.0) * sr) init_t = random.uniform(0.0, 10.0) # Generate data from numpy samples = generate_timestamps(init_t, n, sr) reference = amplitude * sp.square(2 * np.pi * frequency * samples, duty=duty) square = oscillator.Square(amp=amplitude, sr=sr, f=frequency, duty=duty) square.set_timestamp(init_t) generated = square.generate(n) self.assertEqual(len(generated), n) self.assertAlmostEqual(samples[n - 1] + 1.0 / sr, square.timestamp()) np.testing.assert_array_almost_equal(np.abs(generated), np.abs(reference))
def squareWave( freq, time, duty_cycle=0.5, plot=False): """ Examples -------- Example 1:: freq=1e2 dt=1e-5 time=np.arange(10000)*dt fig,ax=plt.subplots() ax.plot( squareWave(freq,time)) """ from scipy import signal as sg y = _xr.DataArray( sg.square(2 * _np.pi * freq * time, duty=duty_cycle), dims=['t'], coords={'t':time}) # optional plot if plot==True: fig,ax=_plt.subplots() ax.plot(y) return y
def generateBackgroundImage(width, height, N, waveform, orientation): import numpy as np import cv2 from scipy.signal import kaiserord, lfilter, firwin, freqz, square from scipy import signal if orientation == 'vertical' or orientation == 'v' or orientation == 'V': W = width width = height height = W x = np.linspace(0, N * 2 * np.pi, height) if waveform == 'square' or waveform == 'sq' or waveform == 'SQ': y = signal.square(x) else: y = np.sin(x) Y = np.expand_dims(y, 1) #Y =np.resize(Y, (height,width) while Y.size < height * width: Y = np.append(Y, Y, axis=1) Y2 = Y[1:height, 1:width] if orientation == 'vertical' or orientation == 'v' or orientation == 'V': Y2 = np.rot90(Y2, k=1) return Y2
def gen_samples(self, time, seq_shape, kwargs): # TODO: MAKE IT DEPENDENT OF PARAMETERS, SAMPLE OUTSIDE if seq_shape == "constant": samples = np.ones(shape=time.shape) * kwargs["amp"] params = np.array([ kwargs["amp"], ]) return samples, params elif seq_shape in ["sinusoidal", "square", "sawtooth"]: samples = 0 if seq_shape == "sinusoidal": samples = np.sin(2 * np.pi * kwargs["freq"] * time + kwargs["phase"]) * kwargs["amp"] elif seq_shape == "square": samples = ss.square(2 * np.pi * kwargs["freq"] * time + kwargs["phase"]) * kwargs["amp"] elif seq_shape == "sawtooth": samples = ss.sawtooth(2 * np.pi * kwargs["freq"] * time + kwargs["phase"]) * kwargs["amp"] params = np.array([kwargs["amp"], kwargs["freq"], kwargs["phase"]]) return samples, params elif seq_shape == "gaussian_pulses": amp = np.random.uniform(low=self.amp_range[0], high=self.amp_range[1]) freq = np.random.uniform(low=self.freq_range[0], high=self.freq_range[1]) pulse_width = np.random.uniform(low=self.pulse_width_range[0], high=self.pulse_width_range[1]) params = np.array([0]) samples = ss.gausspulse(time, freq, pulse_width)
def generate_DBS_Signal(start_time, stop_time, dt, amplitude, frequency, pulse_width, offset): """Generate monophasic square-wave DBS signal Example inputs: start_time = 0 # ms stop_time = 12000 # ms dt = 0.01 # ms amplitude = -1.0 # mA - (amplitude<0 = cathodic stimulation, amplitude>0 = anodic stimulation) frequency = 130.0 # Hz pulse_width = 0.06 # ms offset = 0 # mA """ times = np.round(np.arange(start_time, stop_time, dt), 2) tmp = np.arange(0, stop_time - start_time, dt) / 1000.0 # Calculate the duty cycle of the DBS signal T = (1.0 / frequency) * 1000.0 # time is in ms, so *1000 is conversion to ms duty_cycle = ((pulse_width) / T) DBS_Signal = offset + 1.0 * (1.0 + signal.square( 2.0 * np.pi * frequency * tmp, duty=duty_cycle)) / 2.0 DBS_Signal[-1] = 0.0 # Calculate the time for the first pulse of the next segment last_pulse_index = np.where(np.diff(DBS_Signal) < 0)[0][-1] next_pulse_time = times[last_pulse_index] + T - pulse_width # Rescale amplitude DBS_Signal *= amplitude return DBS_Signal, times, next_pulse_time
def step_waves(I, f, duty, t, dt): times = fsutil.create_times(t, dt) wave = I * square(2 * np.pi * f * times - np.pi, duty=duty) wave[wave < 0] = 0.0 return wave
def sfr_squarewave_testing(mass, tcosmic, **sfr_param): ''' SFR determined by square function TESTING PURPOSE Parameters ---------- mass : stellar mass tcosmic : cosmic time sfr_param : SFR parameters (amplitude, phase, and frequency) Notes ----- * Arbitrary sfr_param will be fed to produce random SFRs ''' sfr_A = sfr_param['amp'] sfr_d = sfr_param['phase'] sfr_w = sfr_param['freq'] if not isinstance(sfr_w, float): if len(sfr_w) != len(mass): return None dSFR = sfr_A * signal.square(sfr_w * (tcosmic - 6.9048 + sfr_d)) # return dSFR #np.log10(dSFR)
def plot_both_pulses(pulse_data, pulse_square=None, pulse_freq=None, sampling_frequency=20000, start_time=0, end_time=3600, step_time=1, time_window=0.5): plt.interactive(True) fig = plt.figure() ax = fig.add_subplot(111) start_time = start_time end_time = end_time step_time = step_time time_window = time_window num_of_windows = int((end_time - start_time) / step_time) for win in range(num_of_windows): st = start_time + step_time * win et = st + time_window stp = int(st * sampling_frequency) etp = int(et * sampling_frequency) t = np.linspace(st, et, etp - stp) if pulse_square is None: square = ssig.square(2 * np.pi * pulse_freq * (t + 20 / sampling_frequency), duty=1.0 - 0.0434) / 2 + 0.5 + 65278 else: square = pulse_square[stp:etp] ax.clear() ax.plot(t, square, t, pulse_data[stp:etp]) plt.waitforbuttonpress()
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 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 generateBackgroundImage(width,height,N,waveform,orientation): import numpy as np import cv2 from scipy.signal import kaiserord, lfilter, firwin, freqz, square from scipy import signal if orientation == 'vertical' or orientation == 'v' or orientation == 'V': W=width width = height height = W x = np.linspace(0, N*2*np.pi, height) if waveform == 'square' or waveform == 'sq' or waveform == 'SQ': y = signal.square(x) else: y = np.sin(x) Y = np.expand_dims(y, 1) #Y =np.resize(Y, (height,width) while Y.size < height*width: Y = np.append(Y, Y, axis=1) Y2 = Y[1:height, 1:width] if orientation == 'vertical' or orientation == 'v' or orientation == 'V': Y2=np.rot90(Y2, k=1) return Y2
def rectangular(stimDur, amplitude, frequency, dutyCycle, waveform, delay=0, invert=False): """ Return rectangular signal (uses SciPy) :param stimDur: duration of stimulus signal :param amplitude: peak amplitude (not peak-to-peak) :param frequency: frequency :param dutyCycle: fraction of a period that is 'up' :param waveform: 'MONOPHASIC' or 'BIPHASIC' :param delay: onset of the stimulus in ms :param invert: invert the stimulus signal or not :return: rectangular stimulus signal """ timeRes = constants.timeResStim tGen = np.arange(0, stimDur, timeRes) if waveform == 'MONOPHASIC': stimulusSignal = amplitude * 0.5 * signal.square( 2 * np.pi * frequency * tGen, duty=dutyCycle) + amplitude * 0.5 elif waveform == 'BIPHASIC': stimulusSignal = amplitude * signal.square( 2 * np.pi * frequency * tGen, duty=dutyCycle) else: print "You didn't choose the right waveform either MONOPHASIC or BIPHASIC, it has been set to default MONOPHASIC" stimulusSignal = amplitude * 0.5 * signal.square( 2 * np.pi * frequency * tGen, duty=dutyCycle) + amplitude * 0.5 if invert: stimulusSignal = -stimulusSignal # finalize signal with a zero stimulusSignal = np.concatenate((stimulusSignal, [0])) # add delay stimulusSignalDelayed = np.concatenate( (np.zeros(int(delay / timeRes)), stimulusSignal)) # t = np.arange(len(stimulusSignalDelayed))*timeRes return stimulusSignalDelayed
def generate_waveform(self, freq, delta_t=0): wf = self.waveform if self._last_freq == 0: self._last_freq = freq if self._last_time + self.get_time_base() > time.time(): self._last_freq = freq f0 = self._last_freq f1 = freq t = time.time() if delta_t == 0: t0 = self._last_time self._last_time = t else: t0 = t - delta_t t1 = t0 + self.get_time_base() if self.continuous: f_int = freq #(f0*(t1-t)+f1*(t-t0))/(t1-t0) else: f_int = freq fchirp = np.linspace(f_int, freq, len(self.n)) self._last_freq = freq x = 2 * np.pi * fchirp / self.f_s * self.n if wf == 'sine': return self._generate_tone(x, [(1, 1)]) if wf == 'sawtooth': return signal.sawtooth(x) if wf == 'square': return signal.square(x) if wf == 'synthwave': return np.sin(x) + 0.25 * np.sin(2 * x) if wf == 'flute': harmonics = [(1, 0.6), (2.02, 0.06), (3, 0.02), (4, 0.006), (5, 0.004)] self.set_adsr(0.05, 0.2, 95, 0.1) return self._generate_tone(x, harmonics) if wf == 'piano': self.set_adsr(0.05, 0.3, 50, 0.4) harmonics = [(1, 0.1884), (2.05, 0.0596), (3.04, 0.0473), (3.97, 0.0631), (5.05, 0.0018), (6, 0.0112), (7, 0.02), (8, 0.005), (9, 0.005), (10, 0.0032), (12, 0.0032), (13, 0.001), (14, 0.001), (15, 0.0018)] return self._generate_tone(x, harmonics) if wf == 'celesta': self.set_adsr(0.1, 0.1, 50, 0.2) harmonics = [(1, 0.316), (4, 0.040)] return self._generate_tone(x, harmonics) if wf == 'pipe organ': self.set_adsr(0.1, 0.3, 20, 0.2) harmonics = [(0.5, 0.05), (1, 0.05), (2, 0.05), (4, 0.05), (6, 0.014), (0.25, 0.014), (0.75, 0.014), (1.25, 0.006), (1.5, 0.006)] return self._generate_tone(x, harmonics)
def otter(dut): """Test for adding 2 random numbers multiple times""" dut.data = 0 dut.rst = 0 dut.clk = 0 cocotb.fork(Clock(dut.clk, 5000).start()) yield RisingEdge(dut.clk) samplelenght = 4000 t = np.linspace(0, 8, samplelenght, endpoint=False) dataout1 = np.arange(samplelenght, dtype=np.int16) dataout2 = np.arange(samplelenght, dtype=np.int16) dataout3 = np.arange(samplelenght, dtype=np.int16) #datain = np.arange(samplelenght, dtype=np.int16) sig = np.sin(2 * np.pi * t) #datain = np.arange(samplelenght, dtype=np.int16)#signal.square(2 * np.pi * 40 * t, duty=(sig + 1)/2) * 0.5 + 0.5 datain = signal.square(2 * np.pi * 40 * t, duty=(sig + 1) / 2) * 0.5 + 0.5 #for i in datain: # datain[i] = 1 dut.rst = 1 yield RisingEdge(dut.clk) dut.rst = 0 yield RisingEdge(dut.clk) for i in range(samplelenght): data = int(datain[i]) dut.data = data yield RisingEdge(dut.clk) #print int(dut.out3) dataout1[i] = int(dut.out1) dataout2[i] = int(dut.out2) dataout3[i] = int(dut.out3) #dut._log.info("Ok!") print("max:") print(np.max(dataout3)) print("min:") print(np.min(dataout3)) plt.plot(t, dataout1, label="L1") plt.plot(t, (sig * 0.5 + 0.5) * 1024, label="original") plt.plot(t, dataout2, label="L2") plt.plot(t, dataout3, label="L3") plt.plot(t, datain * 1024, alpha=0.5, label="PDM") plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.) plt.xlabel('time (us)') plt.title('CRRS Filter for PDM') plt.grid(True) plt.savefig("test.png") plt.show()
def test_square(num_samps, duty): cpu_time = np.linspace(0, 10, num_samps) gpu_time = cp.asarray(cpu_time) cpu_pwm = signal.square(cpu_time, duty) gpu_pwm = cp.asnumpy(cusignal.square(gpu_time, duty)) assert array_equal(cpu_pwm, gpu_pwm)
def generateData(fun=0, noise=0, offset=0.05): t = np.arange(0, 2 * np.pi, 0.1) train = np.copy(t) valid = t + 0.05 if fun == 0: label = np.sin(2 * t) valid_label = np.sin(2 * valid) else: label = signal.square(2 * t) valid_label = signal.square(2 * valid) noi = np.random.normal(0, 0.1, len(train)) * noise label = label + noi valid_label = valid_label + noi return train, valid, label, valid_label
def c_ani(i): if type_modulation.current() <= 2: c_line.set_ydata(np.sin((x + i / 50.0) * c_frq) * c_amp) else: y_carry = signal.square((x + i / 50.0) * c_frq, duty=c_width) * c_amp y_max = max(y_carry) c_line.set_ydata(y_carry + y_max) return c_line,
def calculate_square(): time = np.linspace( start=0, stop=10, num=number_of_points ) # np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) square_build = signal.square(t=time, duty=0.5) # signal.square(t, duty=0.5) square = square_build.tolist() # List of Float return square
def discr_signal_gen(i): global bit_0 #inc = int(i/1.5712) inc = i / 20 inc2 = int(5 * i / np.pi) #inc2 = int(2*i) if 300 - inc2 < -1000: inc2 -= 2000 if 300 - inc2 > 0: y_signal = signal.square((np.pi * x + inc + 0) * 1) * s_amp + s_amp y_signal[300 - inc2:] = signal.square( (np.pi * x[300 - inc2:] + inc + np.pi) * 1) * s_amp + s_amp else: y_signal = signal.square((np.pi * x + inc + np.pi) * 1) * s_amp + s_amp y_signal[300 - inc2:] = signal.square( (np.pi * x[300 - inc2:] + inc + 0) * 1) * s_amp + s_amp return y_signal
def update(self): pos = self._amp * signal.square(self._freq * 2.0 * numpy.pi * self.elapsed_time + self._phase * numpy.pi / 180.0, self._duty) + self._offset for m in self.motor_list: m.goal_position = pos print(pos)
def update(self): pos = self._amp * signal.square(self._freq * 2.0 * numpy.pi * self.elapsed_time + self._phase * numpy.pi / 180.0, self._duty) + self._offset for m in self.motor_list: m.goal_position = pos print pos
def rectwave(pulsewidth, separation, numOfwaves): t = np.linspace(-(pulsewidth + separation) * (numOfwaves + 0.1) / 2, (pulsewidth + separation) * (numOfwaves + 0.1) / 2, 1000000) dutycycle = pulsewidth / (pulsewidth + separation) signal = sig.square(2 * np.pi * 1 / (pulsewidth + separation) * t, dutycycle) / 2 + 1 / 2 return t, signal
def square(freq, len): num_samples = int(len * sampling_rate) # linspace takes start, stop and number of data points as arguments data = np.linspace(0, num_samples, num_samples) square_wave = signal.square(2 * np.pi * freq * data) return square_wave
def test_get_wavelet_width_of_row_signal(self): t = np.linspace(0, 1, 500, endpoint=False) sig = signal.square(2 * np.pi * 5 * t) width = wmg.get_wavelet_width_of_row_signal(sig, max_width=200) ic.ic(width, 10 <= width <= 12) self.assertTrue(10 <= width <= 12)
def getSignals(self): self.phaze = self.test_sig_freq * self.t * 2 * np.pi self.sig['sine']['data'] = self.test_sig_ampl * np.sin(self.phaze) self.sig['meandr']['data'] = self.test_sig_ampl * \ signal.square(self.phaze) self.sig['sawtooth']['data'] = self.test_sig_ampl * \ signal.sawtooth(self.phaze)
def row_subset(self, l, phi, on, duty_cycle): x = arange(l) shut_f = self.shutter_frequency pix_f = self.pixel_frequency # TODO andrebbe riordinata, e magari unita con quella sopra r = square((2 * pi) * ((shut_f * x / pix_f) + phi - (0.5 - duty_cycle)/2 + 0.5 * (not on)), duty_cycle)/2 + 0.5 return r >= 0.5
def _generate_signal(self): if self._operation == 'sine': x = np.linspace(0, 1, self._n_samples) self.wave = self._amp * np.sin((2 * np.pi * self._freq * x) + self._phase) self.new_signal.emit(self.wave) else: x = np.linspace(0, 1, self._n_samples) self.wave = self._amp * signal.square((2 * np.pi *self._freq * x) + self._phase) self.new_signal.emit(self.wave)
def square_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.square(sample).astype(numpy.float32) return sample
def GenerateSquareData(freq, length, sampling_freq): """ Simple square signal synthesis """ end_time_s = float(length) / sampling_freq sampled_time = numpy.arange(0, end_time_s, 1.0 / sampling_freq) return signal.square(sampled_time * 2 * numpy.pi * freq)
def square_wave(self): self.t = np.arange(0., self.L, self.T_s) #Time array self.y_t = signal.square(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 noisedSqr(): # number = 10000 # number of points time = np.linspace(-np.pi * 100, np.pi * 100, number) # series = signal.square(time / 100) noise = np.random.uniform(0.0, 0.05, number) # data = series + noise # input data return data, time
def estimate_total_dits(self, data=None): if data is None: data = butter_bandpass_filter(self.audio_data, int(600 - 50 / 2), int(600 + 50 / 2), self.sample_rate, order=1) result = [] t = np.linspace(0, len(data) / self.sample_rate, len(data), endpoint=False) for num_dits in xrange(220, 360): dits = (-square(np.pi * num_dits / (len(data) / self.sample_rate) * t) + 1) / 2 err = abs(dits - (abs(data) / np.max(data))) result.append((num_dits, np.mean(err))) return sorted(result, key=itemgetter(1))[0][0]
def sim_wave(w_type='sine', time=np.linspace(0, 150, 150*1000, endpoint=False), s_freq=120, mag=1, phase=0): if w_type=='sine': wave = mag*np.sin(2*np.pi*s_freq*time+phase)+mag elif w_type=='square': wave = mag*signal.square(2*np.pi*s_freq*time+phase)+mag else: print 'Please enter sine or square for simulated wave type' return return wave
def reconstruct(self, timbre): pcm = np.zeros((timbre.shape[1]*self.subsample,)) angle = np.arange(timbre.shape[1]*self.subsample) * 2 * np.pi / self.samplerate for pitch in xrange(self.npitches): print pitch freq = self.lowfreq * 2.0**(pitch/12.0) square_wave = signal.square(angle*freq) triangle_wave = triangle(angle*freq) pcm += np.repeat(timbre[pitch, :, 1], self.subsample) * square_wave pcm += np.repeat(timbre[pitch, :, 2], self.subsample) * triangle_wave pcm /= np.max(pcm) return AudioData(pcm, self.samplerate)
def anim_calc(self, i): """Caluclation of the animation values""" x = np.linspace(0, 1, 1000) # Create an numpy array from 0 to 1000 with spacing of 1 amplitude = self.ud/self.num_mod # Split of the desired output aplitude over the number of submodules if self.ver_shift: # If a amplitude shift takes place then this is the output waveform self.mod_value[0] = amplitude * signal.square(2 * np.pi * (self.freq * 8) * (x + 0.01 * i) + self.phase_shift) + self.ud # Build the initial square wave A*square(2*pi*f*t + phase) + amplitude shift wx.PostEvent(self.panel, ModBotStateEvent(self.phase_shift, 0, self.mod_value[0][-1] - self.ud)) # Trigger the custom event to pass the individual submodule square wave information to the circuit else: # No amplitude shift means that the waveform is displaying the value of the arms self.mod_value[0] = amplitude * signal.square(2 * np.pi * (self.freq * 8) * (x + 0.01 * i) + self.phase_shift) # Build the initial square wave A*square(2*pi*f*t + phase) wx.PostEvent(self.panel, ModBotStateEvent(self.phase_shift, 0, self.mod_value[0][-1])) # Trigger the custom event to pass the individual submodule square wave information to the circuit self.total = self.mod_value[0] # Add the initial square wave to the output total for num in range(1, int(self.num_mod)): # Loop through all the remaining sub modules phase = np.pi/self.num_mod * num # Split 180 deg among the remaining submodules self.mod_value[num] = amplitude * signal.square(2 * np.pi * (self.freq * 8) * (x + 0.01 * i) + phase + self.phase_shift) # Build up each submodules squarewave A*square(2*pi*f*t + phase) self.total = self.total + self.mod_value[num] # Add each submodules squarewave to the output total wx.PostEvent(self.panel, ModBotStateEvent(self.phase_shift, num, self.mod_value[num][-1])) # Trigger the custom event to pass the individual submodule square wave information to the circuit self.value.set_data(x, self.total/2) # Place the aquired values of the 'x' and 'y' into the values variable (div by 2 to make sure ud is correct) return self.value,
def onRun(self): #limit = int(raw_input('Enter the time range :')) fig = plt.figure() ax = fig.add_subplot(111) ax.grid() ax.set_ylim(-(10*float(value4)+10), 10*float(value4)+10) ax.set_xlim(0,20) ax.set_ylabel('Voltage(V)') ax.set_xlabel('Time(MS)') ax.set_title('Channel 1') t = np.linspace(0, 20, 500, endpoint=False) plt.plot(t, 10*float(value4)*signal.square(2 * np.pi /float(value1) * t,duty=float(value3)/(float(value2)+float(value3))))
def initialize(self, ru_params, mixing_fraction): t = np.array(range(self.duration)) #These functions are getting spaghetti-like self.ugen = {} self.ugen['frequency'] = 0.01 # Hz self.ugen['fill'] = -1 self.ugen['buffer'] = 10 self.ugen['chronic'] = lambda timepoints: signal.square(2*np.pi*self.ugen['frequency']*timepoints) self.ugen['exposure'] = lambda timepoints: np.lib.pad(self.ugen['chronic'](t)[:int(1/self.ugen['frequency'])], (u['buffer'],len(timepoints)-int(1/self.ugen['frequency']+self.ugen['buffer'])), 'constant',constant_values=(self.ugen['fill'],self.ugen['fill'])) self.ugen['cessation'] = lambda timepoints: np.lib.pad(self.ugen['chronic'](t)[:5*int(1/self.ugen['frequency'])], (self.ugen['buffer'],len(timepoints)-5*int(1/self.ugen['frequency']+self.ugen['buffer'])), 'constant',constant_values=(self.ugen['fill'],self.ugen['fill'])) self.rgen = {} self.rgen['susceptible'] = self.loggauss() self.rgen['resilient'] = self.gauss() self.v = np.zeros((self.N['neurons'],self.duration),dtype=np.float16) #NEXT ABSTRACT OVER SCHEMES self.u = np.tile(self.ugen['chronic'](t),(self.N['neurons'],1)) #self.u = np.zeros_like(self.v,dtype=np.float16) self.r = np.zeros_like(self.v,dtype=np.float16) self.M = np.zeros((self.N['neurons'],self.N['neurons'],self.duration),dtype=np.float16) self.W = np.zeros_like(self.M,dtype=np.float16) self.Quu = np.zeros((self.N['neurons'],self.N['neurons'],self.duration),dtype=np.float16) self.Qru = np.zeros_like(self.Quu,dtype=np.float16) self.Qvu = np.zeros_like(self.Quu,dtype=np.float16) self.M[:,:,0] = np.array([np.outer(one,one) for one in self.memories.T]).sum(axis=0) self.M[:,:,0][np.diag_indices(self.N['neurons'])] = 0 self.memory_stability = np.zeros((self.N['memories'],self.duration)) self.v[:,0] = self.F((1-mixing_fraction)*self.memories[:,0] +\ mixing_fraction*(2*(np.random.random_integers(0,high=1,size=(self.N['neurons'],)))-1)) self.W[:,:,0] = np.random.random_sample(size=(self.N['neurons'],self.N['neurons'])) #Assume same number of inputs for now self.I = np.eye(self.N['neurons']) self.epsilon = 0.001 #ratio of membrane time constant to timestep self.chosen_ones = [random.choice(xrange(self.N['neurons'])) for _ in xrange(1,self.duration)]
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 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 osc_square(self, freq, length, rate): """ desc: A square-wave oscillator. visible: False """ length *= .001 t = np.linspace(0, length, length*rate) a = signal.square(2*np.pi*freq*t) return a
def harmonicradar_cw(t,fs,fc): ttxt = 'CW: {} Hz'.format(fc) #%% input x = sin(2*pi*fc*t) _,Pxx = periodogram(x,fs) #%% diode d = (square(2*pi*fc*t)) d[d<0] = 0. #%% output of diode y = x * d #y = x; y[y<0]=0. #shorthand way to say it, same result fax,Pyy = periodogram(y,fs) #%% results plotlf(t,x,d,y,ttxt) plots(fax,Pxx,Pyy,fc,ttxt)
def square_wave(): t = np.linspace(0, 150, 3600, endpoint=False) data = signal.square(2 * np.pi * 1 * t) dt = 1. / 24. #data is fractional day reported hourly time_base = 'days' xx = data variance = np.var(xx) #normalize print 'Variance = %s ' % (variance) x = (xx - np.mean(xx)) / np.sqrt(variance) variance = np.var(x) sl = len(x) time = (np.arange(0,sl ,1) * dt ) + 733890. #arbitrary start date for square wave return (data, x,dt,np.array(time), variance, time_base)
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 square_wave(f, fsamp=11.92, T=1.0, offset=0): ''' return numpy array with square wave usage: s, t = square_wave(f, fsamp, T, offset) f is the frequency of the signal in Hz. fsamp is the sampling frequency in Hz. T is the length of the data in seconds. offset is the phase offset in radians. ''' t = np.linspace(0, T, fsamp * T, endpoint=False) return signal.square(2*np.pi*f*t + offset), t
def sq_custom(f,T,a=0,b=0): """ Funkcja zwraca macierz reprezentujaca dzwiek stworzony za pomoca fali typu square. 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.square(2 * np.pi * f * t) return(np.hstack((S1,S2,S3))*S0)
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)