def main(): spot = 100 strikes = np.array([90, 100, 110]) t = .5 r = .008 q = r is_call = True args = (spot, strikes, t, r, q, is_call) ls_pars = (1.3, .25) vg_pars = (.5, -1, .1) he_pars = (3, .005, .001, .3, .001) he_prices = he.price_heston(pars=he_pars, args=args) vg_prices = vg.price_vg(pars=vg_pars, args=args) ls_prices = ls.price_ls(pars=ls_pars, args=args) he_prices_fft = FFT(model='heston', args=args).price(he_pars) ls_prices_fft = FFT(model='ls', args=args).price(ls_pars) vg_prices_fft = FFT(model='vg', args=args).price(vg_pars) for prices, prices_fft in [[he_prices, he_prices_fft], [vg_prices, vg_prices_fft], [ls_prices, ls_prices_fft]]: print(prices) print(prices_fft) print() assert np.all(np.abs(prices_fft - prices) < 1e-2) pass
def fft2(image): x = np.zeros_like(image) y = np.zeros_like(image) x = np.array(image) (N1, N2) = image.shape[:2] #print(N1, N2) # print(image); t = 0 b = 1024 - N2 l = 0 r = 1024 - N1 np.pad(x, ((t, b), (l, r)), 'constant') #np.pad(x, ((1024-N1),(1024-N1)), 'constant', constant_values=(0, 0)) print(x) for i in range(0, x.shape[0]): #print(x[i,:]) x[i, :] = np.trim_zeros(FFT(x[i, :])) y = np.transpose(x) #np.pad(y, ((1024-N2),(1024-N2)), 'constant', constant_values=(0, 0)) for i in range(0, y.shape[0]): x[:, i] = np.trim_zeros(FFT(y[:, i])) return x
def profile_ls(): sigma = .5 alpha = 1.6 p = (sigma, alpha) td_decorator(ls.price_ls, 'LS')(pars=p, args=a) td_decorator(FFT(model='ls', args=a).price, 'FFT LS')(p)
def spectrum(x, sample_rate=8192, win_len=128): assert bin(win_len).count('1') == 1 assert len(x) >= win_len def _next(): for _p in range(0, len(x) - win_len + 1, win_len // 2): yield x[_p:_p + win_len] raise StopIteration() h = hamming_window(win_len) f = FFT() fbins = mel_bins(24) ibins = np.floor((win_len + 1) * fbins / sample_rate).astype(np.int) ret = [] for win in _next(): s = f.fft(win * h) p = np.square(np.abs(s)) / win_len temp = [None] * (len(ibins) - 2) for i in range(len(ibins) - 2): a, b, c = ibins[i], ibins[i + 1], ibins[i + 2] left = np.sum(p[a:b] * np.linspace(0, 1, b - a)) right = np.sum(p[b:c] * np.linspace(1, 0, c - b)) temp[i] = np.log(left + right + 1e-100) ret.append(dct(np.array(temp, dtype=np.float))) return np.array(ret)
def getfftparams(self): self.fftflag = True lowerf = (self.lowfreq.get()) upperf = (self.highfreq.get()) self.sr = (self.samprate.get()) data = FFT(self.filename, lowerf, upperf, self.sr) self.tfdata, self.classes_fin = data.gettfdata()
def profile_vg(): nu = .1 theta = .1 sigma = .05 p = (nu, theta, sigma) td_decorator(vg.price_vg, 'VG')(pars=p, args=a) td_decorator(FFT(model='vg', args=a).price, 'FFT VG')(p)
def profile_heston(): kappa = 5 theta = 1 sigma = .5 rho = .5 v0 = .2 p = (kappa, theta, sigma, rho, v0) td_decorator(he.price_heston, 'Heston')(pars=p, args=a) td_decorator(FFT(model='heston', args=a).price, 'FFT Heston')(p)
def main(): builder = StreamBuilder(stream_type='file', filename='data/speech/train/fadg0_sa1.wav') file_stream = builder.get_instance() vad_stream = Vad(file_stream) fft_stream = FFT(vad_stream, 32, 16) dic = StaticDict('data/debug/noise', 'data/debug/speech', rank=config.rank) enhancer_stream = NmfEnhancer(fft_stream, dic) wav_writer = WavWriter(enhancer_stream, 'out.wav') for _ in wav_writer: pass
def __init__(self, size, sample_rate=16000, band_number=12, window=[50, 8000]): self.size = 1 << math.frexp(size - 1)[1] self.sample_rate = float(sample_rate) self.resolution = self.sample_rate / self.size # (sample_rate/2) / (band/2) self.set_band(band_number, window) self.fft = FFT(self.size)
def pricing(): times = 1000 he_pars = (17.1602851582, 0.0592887994217, 3.69111708705, -0.788742440245, 0.0396629204273) vg_pars = (0.838288226409, -0.188041460262, 0.179096605713) ls_pars = (1.45807445595, 0.115510363099) bs_pars = (.2,) spot = 1200 t = .76 r = .008 q = r is_call = True for n in [1, 10, 25, 50, 100, 200]: strikes = np.array([i * 50 + 500 for i in range(n)]) args = (spot, strikes, t, r, q, is_call) unit = td_decorator(func=lambda p: price_bs(pars=p, args=args), times=times, seconds=False)(bs_pars) he_time = td_decorator(func=FFT(model='heston', args=args).price, times=times, seconds=False)(he_pars) vg_time = td_decorator(func=FFT(model='vg', args=args).price, times=times, seconds=False)(vg_pars) ls_time = td_decorator(func=FFT(model='ls', args=args).price, times=times, seconds=False)(ls_pars) print(f"For {n} strikes: bs: {unit} heston: {he_time}, vg: {vg_time}, ls: {ls_time}")
def tuning(): times = 5 metric = 'RMSE' optimizer = differential_evolution actual_puts = np.ndarray([]) spot = 1200 t = .76 r = .008 q = r is_call = True logfile = open(f'{root_dir}/params/time_benchmark_{datetime.now()}.log', 'w') for n in [1, 10, 25, 50, 100, 200]: strikes = np.array([i * 50 + 500 for i in range(n)]) args = (spot, strikes, t, r, q, is_call) market = EvalArgs.from_tuple((spot, strikes, t, r, q, is_call)) call_prices = FFT(model='vg', args=args).price((0.838288226409, -0.188041460262, 0.179096605713)) def bs_func(): GenPricer(model='bs', market=market, use_fft=False) \ .optimize_pars(metric=metric, optimizer=optimizer, bounds=par_bounds['bs'], actual_puts=actual_puts, actual_calls=call_prices, polish=True) t0 = time() unit = td_decorator(func=bs_func, times=times, seconds=True, log_each=True)() hf.log_print(f'BS unit time for {n} strike(s): {unit}, real time: {(time() - t0) / times}', logfile) for model in ['heston', 'vg', 'ls']: def func(): GenPricer(model=model, market=market, use_fft=True) \ .optimize_pars(metric=metric, optimizer=optimizer, bounds=par_bounds[model], actual_puts=actual_puts, actual_calls=call_prices, polish=True, disp=True, maxiter=50) t0 = time() hf.log_print(f"{model}: {td_decorator(func=func, times=times, seconds=True, log_each=True)() / unit}" f" units, real time: {time() - t0}", logfile) hf.log_print("\n", logfile) logfile.close()
def filter2d_freq(inputImg, filter): print(inputImg.size) pxInput = inputImg.load() M, N = inputImg.size size = len(filter) fft = FFT() position = [i - i / 2 for i in range(size)] imgArray = np.zeros([M, N], dtype=np.complex) imgArray = fft.zeroPadding(imgArray) for x in range(M): for y in range(N): imgArray[x, y] = pxInput[x, y] M, N = imgArray.shape outputImg = Image.new('L', (M, N), 0) pxOutput = outputImg.load() filterArray = np.zeros([M, N], dtype=np.complex) for x in range(size): for y in range(size): filterArray[x, y] = filter[x][y] filterSpectrum = fft.fft2d(filterArray, -1) ans = np.fft.fft2(filterArray) print(np.allclose(filterSpectrum, ans)) imgSpectrum = fft.fft2d(imgArray, -1) ans = np.fft.fft2(imgArray) print(np.allclose(imgSpectrum, ans)) spectrum = np.zeros([M, N], dtype=np.complex) for x in range(M): for y in range(N): spectrum[x, y] = filterSpectrum[x, y] * imgSpectrum[x, y] spectrum = fft.fft2d(spectrum, 1) for x in range(M): for y in range(N): pxOutput[x, y] = (math.floor(spectrum[x, y].real / (M * N)), ) return outputImg
def generate_svmlight_file(folder): fft = FFT() files = glob.glob(folder + '.json') for f in files: json_file = open(f, 'r') marks = json.load(json_file) json_file.close() audio = fft.extract_audio(f.replace('.json', '.dat')) features = fft.spectrogram_energy(audio)[2] labels = {'friction': [0], 'negative': [1], 'footstep': [1]} X = [] y = [] for key, value in marks.items(): label = labels[key] for start, end in value: start = fft.frame_index(start) end = fft.frame_index(end) + 1 X.extend(features[start:end]) y.extend(label * (end - start)) dump_svmlight_file(np.array(X), np.array(y), f.replace('.json', '.svm'), zero_based=False)
def __init__(self): self._fft = FFT() self._gui = GUI()
def augment_file_time_freq(self,fname): # per trial 3s, dropout and add noise data = pd.read_csv(fname)# include header ! data.interpolate(method='linear', axis=0, inplace=True) # inplace=1 otherwise needs return val. data.fillna(0, inplace=True) nRow=data.shape[0] nCol=data.shape[1] pp = preProcessor(self.sampleRate, self.lowcut ,self.highcut,weight_decay=0.999, init_window_size=self.init_window_size) filt = FFT(N=self.nfft, sampleRate=self.sampleRate) for c in range(0,self.nFeatures): x=np.asarray(data.iloc[: , c]) if if_notch_filter: x = pp.filter_not( x ) x = pp.filter_high( x ) if if_normalize: x = pp.normalize(x) if x.shape[0]==1: x=x[0] bad=-1 if np.any(np.isnan(x)): bad=1 if bad==1: print("nan! when convert_file") print(data.iloc[: , c]) sys.exit(0) data.iloc[: , c] = x # print(x) # sys.exit(0) augtime = [] augfreq = [] auglabel = [] # original signal first ind = 0 dtime = [] dfreq = [] dlabel = [] SampPerFrame = int(self.sampleRate * self.secondPerFrame) while ind+SampPerFrame <=nRow: timeStep = [] freqStep = [] label=-1 for c in range(0,self.nFeatures): x=np.asarray(data.iloc[ind:ind+SampPerFrame , c]) # make copy timeStep.append(x) if if_sum_bands: filt.N_fft( x ) y=filt.sum_freq_band(bands) else: y=filt.get_rfft_without_DC(x) freqStep.append(y) label=(data.iloc[ind,self.nFeatures]) ind+=int(SampPerFrame * self.shiftRatio) dtime.append(timeStep) dfreq.append(freqStep) dlabel.append(label) if not (len(dtime)%self.stateStep==0): print(__file__.split("/")[-1],"bad len?",fname,len(dtime),nRow) # assert(len(dtime)%self.stateStep==0) augtime.append(dtime) # remain format of steps. augfreq.append(dfreq) auglabel.append(dlabel) # augment # times, increase to #+1 size: for i in range(self.augmentTimes): ind = 0 dtime = [] dfreq = [] dlabel = [] while ind+SampPerFrame <=nRow: timeStep = [] freqStep = [] label=-1 for c in range(0,self.nFeatures): x=np.asarray(data.iloc[ind:ind+SampPerFrame , c]) # make copy x1=pp.add_noise(x,nr=0.01) x1=pp.drop_zero_sparse(x1,ratio=0.1) # reshaped(1,-1) timeStep.append(x1[0]) x2 = pp.drop_zero_sparse(x,ratio=0.1) if if_sum_bands: filt.N_fft( x2 ) y=filt.sum_freq_band(bands) else: y=filt.get_rfft_without_DC(x2) freqStep.append(y) label=(data.iloc[ind,self.nFeatures]) ind+=int(SampPerFrame * self.shiftRatio) dtime.append(timeStep) dfreq.append(freqStep) dlabel.append(label) # assert(len(dtime)%self.stateStep==0) augtime.append(dtime) # remain format of steps. augfreq.append(dfreq) auglabel.append(dlabel) return augtime,augfreq,auglabel # [[ori],[aug],,],,
from filter import FilterFFT from low_pass_filter import LowPassFilter from high_pass_filter import HighPassFilter import numpy import math #class IntervalPassFilter(FilterFFT): # pass if __name__ == "__main__": import sys low_cut_distance = int(sys.argv[2]) high_cut_distance = int(sys.argv[3]) l = LowPassFilter(sys.argv[1]) low_filter = l.get_filter(low_cut_distance) m = HighPassFilter(sys.argv[1]) high_filter = m.get_filter(high_cut_distance) applied_filter = low_filter * high_filter i = FFT(sys.argv[1]) i.apply_inverse(applied_filter) i.save_to_file("output.png") l.apply() l.set(applied_filter * l.get()) l.display_normalize() l.save_to_file("spectrum.png")
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import os import time import matplotlib.pyplot as plt from fft import FFT from koheron import connect host = os.getenv('HOST', '192.168.1.11') client = connect(host, 'fft', restart=False) driver = FFT(client) print('Start test.py') n_pts = driver.n_pts fs = 250e6 psd = driver.read_psd() #plt.plot(10*np.log10(psd)) plt.plot(psd) plt.show() #freqs = np.array([0.01, 0.02, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 25, 27, 30, 33, 35, 37, 40, 43, 45, 47, 50, 53, 55, 57, 60, 63, 65, 67, 70, 73, 75, 77, 80, 83, 85, 87, 90, 93, 95, 97, 100, 103, 105, 107, 110, 113, 115, 117, 120, 123, 124]) * 1e6 freqs = np.linspace(0.01e6, 40e6,num=200) freqs = np.round(freqs / fs * n_pts) * fs / n_pts
def __init__(self): super(MyModel, self).__init__() self.fft = FFT()
fir_output_bits = fir.output_bit_width(input_bits) set_env("FIR_OUTPUT_WIDTH", fir_output_bits) # with open("coeff40_2.dat") as f: # taps = [float(line.rstrip("\n")) for line in f] # fir.taps = taps # fir.write_poly_taps_files( # ["../roms/fir/"], tap_bits, downsample_factor, True, False # ) # fir_response("40_2_response.dat", taps=taps, fs=40e6) # set_env("FIR_TAP_WIDTH", tap_bits) # set_env("FIR_NORM_SHIFT", fir.tap_normalization_shift()) # set_env("FIR_OUTPUT_WIDTH", fir.output_bit_width(input_bits)) # FFT roms fft = FFT(1024, 4) # fft_twiddle_bits = 10 fft_twiddle_bits = 18 fft.write_twiddle_roms(["src/roms/fft/"], fft_twiddle_bits) set_env("FFT_TWIDDLE_WIDTH", fft_twiddle_bits) set_env("FFT_OUTPUT_WIDTH", fft.output_bit_width(fir_output_bits)) # window roms N = 1024 COEFF_PREC = 16 w = np.kaiser(N, 6) w_int = [sub_integral_to_uint(i, COEFF_PREC) for i in w] with open("src/roms/window/coeffs.hex", "w") as f: for coeff in w_int:
GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) allIntents = [ "只是打招呼", "打電話", "文字辨識", "景象辨識", "發簡訊", "罵人", "認人", "拍照", "查詢餘額", "掰掰", "None" ] # run ls /dev/tty* before and after plugging in arduino to find out ser = serial.Serial('/dev/ttyACM0', 9600) # initilialize an Microsoft_ASR object tts = TTS() fft = FFT(time_gap=0.5) ms_asr = Microsoft_ASR() temperature_flag = False while True: #st = time.time() print("\rPress to activate your voice assistant...", end=' ') input_state = GPIO.input(18) ret = None if input_state == True: # Button Pressed print() intent, entities = callLUIS(ms_asr.listen_for_speech()) print('intent:', intent)