def get_cepstrum(function): spectrum = rfft(function) return irfft(np.abs(spectrum))
parser.add_argument('filename', help='Sample data for designing and testing filter. Should contain a single column of numeric values.') parser.add_argument('-f', help='Sample frequency (how fast the data was recorded, in samples per second)', type=float) args = parser.parse_args() print("Loading file...") nyquist = 1 if args.f: nyquist = nyquist * args.f/2 data = np.loadtxt(args.filename) # Plot the input data plt.subplot(121) plt.plot(data) plt.title("Input Waveform") plt.subplot(122) f = fft.rfft(data) w = np.linspace(0, nyquist, len(f)) plt.semilogy(w, np.absolute(f)) plt.title("Frequency Components") plt.show() def get_params(): wp = float(input("Passband Frequency? "))/nyquist ws = float(input("Stopband Frequency? "))/nyquist gstop = float(input("Min Stopband Attenuation? (in dB) ")) gpass = float(input("Max Passband Ripple? (in dB) ")) params = dict() params['wp']=wp params['ws']=ws params['gstop']=gstop params['gpass']=gpass
tr_edit_hp = tr_edit.copy( ) # hago una copia para no modificarel evento original # Defino frec angular digital para el filtro (frec ang dig = frec[Hz]/fm) dt = tr.meta.delta fm = 1 / dt # frec de muestreo w_hp = 0.1 / fm tr_edit_hp = tr_edit_hp.filter("highpass", freq=w_hp, corners=2, zerophase=False) ns = len(tr_edit_hp) dt = tr.meta.delta f = rfftfreq(ns, dt) fft_tr_hp = rfft(tr_edit_hp) # fft de la señal con taper fft_evento_sin_medio = rfft( evento_sin_medio_copy) # fft de la señal evento sin taper # Grafico para comparar plt.figure(11) plt.title("Comparación de espectros") plt.plot(f, np.abs(fft_evento_sin_medio), color="black", label="señal sin HP") plt.plot(f, np.abs(fft_tr_hp), color="violet", label="señal con HP a 0.1Hz") plt.legend() #%% #----------------------------------------------------------------------------- # 6. Aplico taper #----------------------------------------------------------------------------- # El pre y post evento equivalen a un 18,18% del total de la señal a analizar.
def test_irfft(self): x = random(30) assert_array_almost_equal(x, fft.irfft(fft.rfft(x))) assert_array_almost_equal( x, fft.irfft(fft.rfft(x, norm="ortho"), norm="ortho"))
def main(): # =================================================================== # # =================================================================== # # PREPARATION STEP # # =================================================================== # # =================================================================== # # For more information on try/except structures, see https://www.tutorialsteacher.com/python/exception-handling-in-python try: # Get the size of the terminal in order to have a prettier output, if you need something more robust, go check http://granitosaurus.rocks/getting-terminal-size.html columns, rows = shutil.get_terminal_size() # Output Header print("".center(columns, "*")) print("") print("EXECUTION OF THE PULSES PLOTTING SCRIPT BEGINS NOW".center( columns)) print("") print("".center(columns, "*")) # ========================================================= # # Read command line arguments # # ========================================================= # args = parser.parse_args() # Required arguments out_dir = args.out_dir # Directory where the graphs will be stored single_mol = args.single # Molecule directory containing the results files that need to be processed. multiple_mol = args.multiple # Directory containing multiple molecule directories. # Optional arguments config_file = args.config # YAML configuration file threshold = args.threshold # Quality threshold below which graphs won't be created # ========================================================= # # Define codes directory # # ========================================================= # # Determined by getting the path to the directory of this script code_dir = os.path.dirname( os.path.realpath(os.path.abspath(getsourcefile(lambda: 0)))) print("{:<40} {:<100}".format('\nCodes directory:', code_dir)) # ========================================================= # # Check and load the YAML configuration file # # ========================================================= # if config_file: config_file = results_common.check_abspath( config_file, "Command line argument -cf / --config", "file") else: # If no value has been provided through the command line, take the results_config.yml file in the same directory as this script config_file = os.path.join(code_dir, "results_config.yml") print("{:<40} {:<99}".format('\nLoading the configuration file', config_file + " ..."), end="") with open(config_file, 'r') as f_config: config = yaml.load(f_config, Loader=yaml.FullLoader) print('%12s' % "[ DONE ]") # ========================================================= # # Check molecule directories # # ========================================================= # if multiple_mol: multiple_mol = results_common.check_abspath( multiple_mol, "Command line argument -m / --multiple", "directory") mol_inp_path = multiple_mol print("{:<40} {:<99}".format( "\nLooking for every molecule directory in", mol_inp_path + " ..."), end="") # We need to look for directories in the multiple_mol directory (see https://stackoverflow.com/questions/800197/how-to-get-all-of-the-immediate-subdirectories-in-python for reference). mol_inp_list = [ dir.name for dir in os.scandir(mol_inp_path) if dir.is_dir() ] if mol_inp_list == []: raise results_common.ResultsError( "ERROR: Can't find any directory in %s" % mol_inp_path) print('%12s' % "[ DONE ]") else: single_mol = results_common.check_abspath( single_mol, "Command line argument -s / --single", "directory") print("{:<40} {:<100}".format('\nMolecule directory:', single_mol)) mol_inp_path = os.path.dirname(single_mol) mol_name = os.path.basename(single_mol) mol_inp_list = [mol_name] # ========================================================= # # Check arguments # # ========================================================= # out_dir = results_common.check_abspath( out_dir, "Command line argument -o / --out_dir", "directory") print("{:<40} {:<100}".format('\nOutput directory:', out_dir)) if threshold and (threshold < 0 or threshold > 1): raise results_common.ResultsError( "The value for the quality threshold (%s) must be comprised between 0 and 1." % threshold) # ========================================================= # # Exception handling for the preparation step # # ========================================================= # except results_common.ResultsError as error: print("") print(error) exit(-1) # =================================================================== # # =================================================================== # # GRAPHS GENERATION # # =================================================================== # # =================================================================== # for mol_name in mol_inp_list: mol_dir = os.path.join(mol_inp_path, mol_name) console_message = "Start procedure for the molecule " + mol_name print("") print(''.center(len(console_message) + 11, '*')) print(console_message.center(len(console_message) + 10)) print(''.center(len(console_message) + 11, '*')) # =================================================================== # # =================================================================== # # MOLECULE INFORMATION # # =================================================================== # # =================================================================== # # For more information on try/except structures, see https://www.tutorialsteacher.com/python/exception-handling-in-python try: print("{:<140}".format('\nFetching molecular information ...'), end="") # Check the data directory data_dir = results_common.check_abspath( os.path.join(mol_dir, "CONTROL", "data"), "Data directory created by control_launcher.py", "directory") # Load the eigenstates list eigenstates_file = results_common.check_abspath( os.path.join(data_dir, "eigenstates.csv"), "Eigenstates file", "file") with open(eigenstates_file, 'r', newline='') as csv_file: eigenstates_content = csv.DictReader(csv_file, delimiter=';') eigenstates_list = list(eigenstates_content) eigenstates_header = eigenstates_content.fieldnames # Check the eigenstates list required_keys = ['Number', 'Label'] results_common.check_keys( required_keys, eigenstates_list, "Eigenstates list file at %s" % eigenstates_file) # Load the transitions list transitions_file = results_common.check_abspath( os.path.join(data_dir, "transitions.csv"), "Transitions file", "file") with open(transitions_file, 'r', newline='') as csv_file: transitions_content = csv.DictReader(csv_file, delimiter=';') transitions_list = list(transitions_content) transitions_header = transitions_content.fieldnames # Check the transitions list required_keys = ['Label'] results_common.check_keys( required_keys, transitions_list, "Transitions list file at %s" % transitions_file) print('%12s' % "[ DONE ]") # ========================================================= # # Exception handling for the molecular information # # ========================================================= # except results_common.ResultsError as error: print(error) print("Skipping %s molecule" % mol_name) continue # =================================================================== # # =================================================================== # # DATA TREATMENT # # =================================================================== # # =================================================================== # # Look for directories in the results CONTROL directory (see https://stackoverflow.com/questions/800197/how-to-get-all-of-the-immediate-subdirectories-in-python for reference). control_dir = os.path.join(mol_dir, "CONTROL") dir_list_all = [ dir.name for dir in os.scandir(control_dir) if dir.is_dir() ] # Only keep the 'transition_config'-type directories dir_list = [] for transition in transitions_list: # Get the initial and target state number init_label = transition[ 'Initial file name'][:-2] # [:-2] to remove the trailing "_1" init_number = eigenstates_list.index( next(eigenstate for eigenstate in eigenstates_list if eigenstate['Label'] == init_label)) target_label = transition[ 'Target file name'][:-2] # [:-2] to remove the trailing "_1" target_number = eigenstates_list.index( next(eigenstate for eigenstate in eigenstates_list if eigenstate['Label'] == target_label)) # Get the transition energy, which corresponds to the central frequency of the pulse omegazero_au = abs( float(eigenstates_list[init_number]['Energy (Ha)']) - float(eigenstates_list[target_number]['Energy (Ha)'])) omegazero = results_common.energy_unit_conversion( omegazero_au, 'Ha', 'cm-1') for dirname in dir_list_all: # For more information on try/except structures, see https://www.tutorialsteacher.com/python/exception-handling-in-python try: # Define the 'transition_config' regex and apply it to the dirname pattern = re.compile(r"^" + re.escape(transition["Label"]) + r"_(?P<config>.*)$") matching_dir = pattern.match(dirname) # If it is a '<transition>_<config>' directory, collect the data and start generating the graphs if matching_dir is not None: dir_list.append(dirname) config_name = pattern.match(dirname).group('config') print("{:<140}".format( "\nTreating the %s transition with the '%s' config ..." % (transition["Label"], config_name))) # Check key files iter_file = results_common.check_abspath( os.path.join(control_dir, dirname, "obj.res"), "Iterations QOCT-GRAD results file", "file") guess_pulse_file = results_common.check_abspath( os.path.join(control_dir, dirname, "Pulse", "Pulse_init"), "Guess pulse file", "file") pulse_file = results_common.check_abspath( os.path.join(control_dir, dirname, "Pulse", "Pulse_best"), "Best pulse file", "file") pop_file = results_common.check_abspath( os.path.join(control_dir, dirname, "PCP", "pop1"), "PCP eigenstates populations file", "file") config_file = results_common.check_abspath( os.path.join(control_dir, dirname, config_name + ".yml"), "YAML configuration file", "file") # =================================================================== # # =================================================================== # # QUALITY THRESHOLD CHECK # # =================================================================== # # =================================================================== # if threshold: print("{:<133}".format('\n\tChecking quality ...'), end="") # Open the PCP results file to get the fidelity of the pulse pcp_iter_file = results_common.check_abspath( os.path.join(control_dir, dirname, "PCP/obj.res"), "PCP Iterations QOCT-GRAD results file", "file") with open(pcp_iter_file, 'r') as iter_f: pcp_iter_content = iter_f.read() # Define the expression patterns for the lines of the iterations file # For example " 0 1 1sec |Proba_moy 0.693654D-04 |Fidelity(U) 0.912611D-01 |Chp 0.531396D-04 -0.531399D-04 |Aire -0.202724D-03 |Fluence 0.119552D-03 |Recou(i) 0.693654D-04 |Tr_dist(i) -0.384547D-15 |Tr(rho)(i) 0.100000D+01 |Tr(rho^2)(i) 0.983481D+00 |Projector 0.100000D+01" rx_iter_line = re.compile( r"^\s+\d+\s+\d+\s+\d+sec\s\|Proba_moy\s+\d\.\d+D[+-]\d+\s\|Fidelity\(U\)\s+(?P<fidelity>\d\.\d+D[+-]\d+)\s\|Chp\s+\d\.\d+D[+-]\d+\s+-?\d\.\d+D[+-]\d+\s\|Aire\s+-?\d\.\d+D[+-]\d+\s\|Fluence\s+\d\.\d+D[+-]\d+\s\|Recou\(i\)\s+\d\.\d+D[+-]\d+\s\|Tr_dist\(i\)\s+-?\d\.\d+D[+-]\d+\s\|Tr\(rho\)\(i\)\s+\d\.\d+D[+-]\d+\s\|Tr\(rho\^2\)\(i\)\s+\d\.\d+D[+-]\d+\s\|Projector\s+\d\.\d+D[+-]\d+" ) # Get the fidelity pcp_iter_data = rx_iter_line.match( pcp_iter_content) if pcp_iter_data is not None: fidelity_raw = pcp_iter_data.group("fidelity") fidelity = float( re.compile( r'(\d*\.\d*)[dD]([-+]?\d+)').sub( r'\1E\2', fidelity_raw) ) # Replace the possible d/D from Fortran double precision float format with an "E", understandable by Python) else: raise results_common.ResultsError( "ERROR: Unable to get the fidelity from the file %s" % pcp_iter_file) # Compare the fidelity to the quality threshold if fidelity < threshold: print( "The fidelity for this pulse (%s) is inferior to the specified quality threshold (%s)" % (fidelity, threshold)) print("Skipping %s directory" % dirname) continue print('%12s' % "[ DONE ]") # =================================================================== # # =================================================================== # # PULSES TREATMENT # # =================================================================== # # =================================================================== # # Load the YAML configuration file print("{:<133}".format( '\n\tLoading the configuration file ...'), end="") with open(config_file, 'r') as f_config: config = yaml.load(f_config, Loader=yaml.FullLoader) print('%12s' % "[ DONE ]") # Get the bandwidth from the configuration file try: bandwidth = config['qoctra']['opc']['bandwidth'] except KeyError as error: raise results_common.ResultsError( 'ERROR: The "%s" key is missing in the "%s" configuration file.' % (error, config_name + ".yml")) # Define the figure that will host the six pulse graphs for this specific '<transition>_<config>' directory fig, ((ax_gpulse_time, ax_pulse_time), (ax_gpulse_freq, ax_pulse_freq), (ax_gpulse_zoomfreq, ax_pulse_zoomfreq)) = plt.subplots(nrows=3, ncols=2) # ========================================================= # # Guess pulse treatment # # ========================================================= # print("{:<133}".format( '\n\tTreating the guess pulse values ...'), end="") # Import the pulse values guess_pulse = np.loadtxt(guess_pulse_file) time_au = guess_pulse[:, 0] field_au = guess_pulse[:, 1] time_step_au = time_au[1] - time_au[0] # Convert them from atomic units to SI units time = time_au * constants.value('atomic unit of time') field = field_au * constants.value( 'atomic unit of electric field') time_step = time_step_au * constants.value( 'atomic unit of time') # Plot the temporal profile ax_gpulse_time.plot(time * 1e12, field) ax_gpulse_time.set_xlabel("Time (ps)") ax_gpulse_time.set_ylabel("Electric field (V/m)") ax_gpulse_time.set_title("Guess Pulse") # Compute the FFT (see tutorial at https://realpython.com/python-scipy-fft/) intensity = rfft(field) freq = rfftfreq(len(time), time_step) freq = results_common.energy_unit_conversion( freq, 'Hz', 'cm-1') # Plot the spectral profile ax_gpulse_freq.plot(freq, np.abs(intensity)) ax_gpulse_freq.set_xlabel("Wavenumbers (cm-1)") ax_gpulse_freq.set_ylabel("Intensity") # Zoom on the spectral profile full_bandwidth = ( bandwidth * 6 ) / 2.35 # Conversion from FWHM to full width for a gaussian xdomain = full_bandwidth * 1.1 upper_limit = omegazero + xdomain / 2 lower_limit = omegazero - xdomain / 2 ax_gpulse_zoomfreq.plot(freq, np.abs(intensity)) ax_gpulse_zoomfreq.set_xlim([lower_limit, upper_limit]) ax_gpulse_zoomfreq.set_xlabel("Wavenumbers (cm-1)") ax_gpulse_zoomfreq.set_ylabel("Intensity") print('%12s' % "[ DONE ]") # ========================================================= # # Final pulse treatment # # ========================================================= # print("{:<133}".format( '\n\tTreating the final pulse values ...'), end="") # Import the pulse values pulse = np.loadtxt(pulse_file) time_au = pulse[:, 0] field_au = pulse[:, 1] time_step_au = time_au[1] - time_au[0] # Convert them from atomic units to SI units time = time_au * constants.value('atomic unit of time') field = field_au * constants.value( 'atomic unit of electric field') time_step = time_step_au * constants.value( 'atomic unit of time') # Plot the temporal profile ax_pulse_time.plot(time * 1e12, field) ax_pulse_time.set_xlabel("Time (ps)") ax_pulse_time.set_ylabel("Electric field (V/m)") ax_pulse_time.set_title("Final Pulse") # Compute the FFT (see tutorial at https://realpython.com/python-scipy-fft/) intensity = rfft(field) freq = rfftfreq(len(time), time_step) freq = results_common.energy_unit_conversion( freq, 'Hz', 'cm-1') # Plot the spectral profile ax_pulse_freq.plot(freq, np.abs(intensity)) ax_pulse_freq.set_xlabel("Wavenumbers (cm-1)") ax_pulse_freq.set_ylabel("Intensity") # Zoom on the spectral profile ax_pulse_zoomfreq.plot(freq, np.abs(intensity)) ax_pulse_zoomfreq.set_xlim([lower_limit, upper_limit]) ax_pulse_zoomfreq.set_xlabel("Wavenumbers (cm-1)") ax_pulse_zoomfreq.set_ylabel("Intensity") print('%12s' % "[ DONE ]") # Save the figure fig.set_size_inches(8, 10) fig.suptitle(mol_name + "_" + dirname) plt.tight_layout() plt.savefig(os.path.join( out_dir, '%s_%s_pulses.png' % (mol_name, dirname)), dpi=200) plt.close() # =================================================================== # # =================================================================== # # POPULATIONS TREATMENT # # =================================================================== # # =================================================================== # # Define the figure that will host the population graph and the fidelity graph for this specific '<transition>_<config>' directory fig2, (ax_pop, ax_fidel) = plt.subplots(nrows=2, ncols=1) print("{:<133}".format( '\n\tTreating the post-controle values ...'), end="") # Load the populations file pop_file_content = np.loadtxt(pop_file) # Import the time values and convert them to seconds time_au = pop_file_content[:, 0] time = time_au * constants.value('atomic unit of time') # Iterate over each state and plot the populations current_column = 0 for eigenstate in eigenstates_list: current_column += 1 #TODO: Only plot columns where population is not always zero. ax_pop.plot(time * 1e12, pop_file_content[:, current_column], label=eigenstate['Label']) # Legend the graph ax_pop.set_xlabel("Time (ps)") ax_pop.set_ylabel("Population") ax_pop.legend() print('%12s' % "[ DONE ]") # =================================================================== # # =================================================================== # # FIDELITIES TREATMENT # # =================================================================== # # =================================================================== # print("{:<133}".format( '\n\tTreating the fidelities values ...'), end="") # Load the iterations file with open(iter_file, 'r') as file: iter_content = file.read().splitlines() # Define the expression patterns for the lines of the iterations file # For example " 300 2 2sec |Proba_moy 0.000000E+00 |Fidelity(U) 0.000000E+00 |Chp 0.123802E+00 -0.119953E+00 |Aire 0.140871E-03 |Fluence 0.530022E+01 |Recou(i) 0.000000E+00 |Tr_dist(i) -0.500000E+00 |Tr(rho)(i) 0.100000E+01 |Tr(rho^2)(i) 0.100000E+01 |Projector 0.479527E-13 rx_iter_line = re.compile( r"^\s+(?P<niter>\d+)\s+\d+\s+\d+sec\s\|Proba_moy\s+\d\.\d+D[+-]\d+\s\|Fidelity\(U\)\s+(?P<fidelity>\d\.\d+D[+-]\d+)\s\|Chp\s+\d\.\d+D[+-]\d+\s+-?\d\.\d+D[+-]\d+\s\|Aire\s+-?\d\.\d+D[+-]\d+\s\|Fluence\s+\d\.\d+D[+-]\d+\s\|Recou\(i\)\s+\d\.\d+D[+-]\d+\s\|Tr_dist\(i\)\s+-?\d\.\d+D[+-]\d+\s\|Tr\(rho\)\(i\)\s+\d\.\d+D[+-]\d+\s\|Tr\(rho\^2\)\(i\)\s+\d\.\d+D[+-]\d+\s\|Projector\s+\d\.\d+D[+-]\d+" ) # Extract the number of iterations and the fidelity for each line of the iterations file iterations = [] fidelities = [] for line in iter_content: iter_data = rx_iter_line.match(line) if iter_data is not None: niter = int(iter_data.group("niter")) iterations.append(niter) fidelity_raw = iter_data.group("fidelity") fidelity = float( re.compile( r'(\d*\.\d*)[dD]([-+]?\d+)').sub( r'\1E\2', fidelity_raw) ) # Replace the possible d/D from Fortran double precision float format with an "E", understandable by Python) fidelities.append(fidelity) # Plot the evolution of fidelity over iterations ax_fidel.plot(iterations, fidelities) ax_fidel.set_xlabel("Number of iterations") ax_fidel.set_ylabel("Fidelity") print('%12s' % "[ DONE ]") # Save the figure fig2.set_size_inches(8, 10) fig2.suptitle(mol_name + "_" + dirname) plt.tight_layout() plt.savefig(os.path.join( out_dir, '%s_%s_pop_fid.png' % (mol_name, dirname)), dpi=200) plt.close() # ========================================================= # # Exception handling for the pulse treatment # # ========================================================= # except results_common.ResultsError as error: print(error) print("Skipping %s directory" % dirname) continue console_message = "End of procedure for the molecule " + mol_name print("") print(''.center(len(console_message) + 10, '*')) print(console_message.center(len(console_message) + 10)) print(''.center(len(console_message) + 10, '*')) print("") print("".center(columns, "*")) print("") print("END OF EXECUTION".center(columns)) print("") print("".center(columns, "*"))
# Generando ruido _, noise1 = generate_sine_wave(NOISE, FS, DURATION) mixed_tone = tone + noise1 normalized = np.int16((mixed_tone / mixed_tone.max()) * 32767) print('Generando audio con ruido') write_wav(audio_filename, FS, normalized) plt.plot(normalized[:muestras_grafica]) plt.xlabel('Tiempo') plt.ylabel('Amplitud') plt.title('Señal Tono + Ruido') plt.show() # FFT # Note the extra 'r' at the front N = FS * DURATION yf = rfft(normalized) xf = rfftfreq(N, 1 / FS) plt.plot(xf, np.abs(yf)) plt.xlabel('Frecuencia') plt.title('Cuadrante positivo') plt.show() # Filtrando la señal # The maximum frequency is half the sample rate points_per_freq = len(xf) / (FS / 2) print(f'points_per_freq {points_per_freq}') # Our target frequency is noise freq in Hz target_idx = int(points_per_freq * NOISE) yf[target_idx - 1:target_idx + 2] = 0 plt.plot(xf, np.abs(yf)) plt.xlabel('Frecuencia')
def getChunkSpectrum(sampling_rate, audio_chunk): N = len(audio_chunk) yf = rfft(audio_chunk) xf = rfftfreq(N, 1 / sampling_rate) return xf, yf
def _setup_cuda_fft_multiply_repeated(n_jobs, h, n_fft, kind='FFT FIR filtering'): """Set up repeated CUDA FFT multiplication with a given filter. Parameters ---------- n_jobs : int | str If n_jobs == 'cuda', the function will attempt to set up for CUDA FFT multiplication. h : array The filtering function that will be used repeatedly. n_fft : int The number of points in the FFT. kind : str The kind to report to the user. Returns ------- n_jobs : int Sets n_jobs = 1 if n_jobs == 'cuda' was passed in, otherwise original n_jobs is passed. cuda_dict : dict Dictionary with the following CUDA-related variables: use_cuda : bool Whether CUDA should be used. fft_plan : instance of FFTPlan FFT plan to use in calculating the FFT. ifft_plan : instance of FFTPlan FFT plan to use in calculating the IFFT. x_fft : instance of gpuarray Empty allocated GPU space for storing the result of the frequency-domain multiplication. x : instance of gpuarray Empty allocated GPU space for the data to filter. h_fft : array | instance of gpuarray This will either be a gpuarray (if CUDA enabled) or ndarray. Notes ----- This function is designed to be used with fft_multiply_repeated(). """ from scipy.fft import rfft, irfft cuda_dict = dict(n_fft=n_fft, rfft=rfft, irfft=irfft, h_fft=rfft(h, n=n_fft)) if n_jobs == 'cuda': n_jobs = 1 init_cuda() if _cuda_capable: import cupy try: # do the IFFT normalization now so we don't have to later h_fft = cupy.array(cuda_dict['h_fft']) logger.info('Using CUDA for %s' % kind) except Exception as exp: logger.info('CUDA not used, could not instantiate memory ' '(arrays may be too large: "%s"), falling back to ' 'n_jobs=1' % str(exp)) cuda_dict.update(h_fft=h_fft, rfft=_cuda_upload_rfft, irfft=_cuda_irfft_get) else: logger.info('CUDA not used, CUDA could not be initialized, ' 'falling back to n_jobs=1') return n_jobs, cuda_dict
rd.read_snapshot(time) grd = Grid(rd.snapshots[time], size = float(sys.argv[1])) rrange = int(sys.argv[2]) num = floor(grd.num_z/2) plt.figure(1) for r in range(rrange): a = grd.compute_density_correlation(r) plt.plot(np.linspace(0, grd.length_z/2, num), a, label=f'R={r}') if r == 8: # f = fftshift(fft(a)) # freq = fftshift(fftfreq(len(a))) f = rfft(a) / len(a) freq = rfftfreq(len(a)) plt.figure(2) plt.plot(freq[:], f.real[:], 'k-', marker='o') # plt.plot([min(freq[1:20]), max(freq[1:20])], [0,0], 'r-.') # plt.ylim(-0.6,3) plt.plot([0, 0.15], [0, 0], 'b--') plt.xlim(-0.01,0.15) plt.savefig(f'gif2/{time}.png', format='png') plt.close(2) if float('Nan') in a: continue plt.xlabel(r'$\delta z$')
def get_filter(n, filter_name: str, degree=None): """ Compute the frequency coefficients of the filter for the FBP. Only the positive frequencies are computed for use with RFFT/IRFFT (scipy). Parameters ---------- n : int Size of the filter. filter_name : str Type of filter, one of: ['None', 'Ram-Lak', 'Shepp-Logan', 'Cosine']. degree : int, optional Degree of the filter, when applicable, by default None Returns ------- numpy.ndarray The frequency coefficients of the FBP filter. Raises ------ ValueError If the type of filter asked is not known. """ filter_name = filter_name.upper() pre_filter = True freq = np.concatenate( (np.arange(1, n / 2 + 1, 2, dtype=int), np.arange(n / 2 - 1, 0, -2, dtype=int))) filter_f = np.zeros(n) filter_f[0] = 0.25 filter_f[1::2] = -1 / (np.pi * freq)**2 filter_f = 2 * np.real(fft.rfft(filter_f)) if filter_name == 'NONE': filter_f = np.ones(filter_f.shape) elif filter_name == 'RAM-LAK': pass elif filter_name == 'SHEPP-LOGAN': omega = np.pi * fft.rfftfreq(n)[1:] filter_f[1:] *= np.sin(omega) / omega elif filter_name == 'COSINE': freq = np.linspace(np.pi / 2, np.pi, filter_f.size, endpoint=False) cosine_filter = np.sin(freq) filter_f *= cosine_filter else: nu = np.arange((n + 1) / 2) n0 = 3 k = 50 k_vector = np.arange(-k, k + 0.5) k_vector = k_vector[..., np.newaxis] pre_filter = False if filter_name == 'B-SPLINE': filter_f = np.abs(nu) / np.sum( np.power(np.sinc(nu + k_vector), degree + 1), 0) elif filter_name == 'OBLIQUE': filter_f = np.abs(nu) / np.power(np.sinc(nu), degree + 1) elif filter_name == 'FRACTIONAL': filter_f = np.abs(np.sin(np.pi * nu) / np.pi) / \ np.sum(np.power(np.abs(np.sinc(nu + k_vector)), degree + 2), 0) elif filter_name == 'FRACTIONALOBLIQUE': filter_f = np.abs(np.sin(np.pi * nu) / 2) / \ np.power(np.abs(np.sinc(nu)), degree + 2) elif filter_name == 'BSPLINEPROJ': nu_k = nu + k_vector filter_f = np.sum( np.abs(nu_k) * np.power(np.sinc(nu_k), degree + 2 + n0), 0 ) / (np.sum(np.power(np.sinc(nu_k), n0 + 1), 0) * np.sum( np.power(np.abs(np.power(np.sinc(nu_k), degree + 1)), 2), 0)) else: raise ValueError('Illegal filter name: {}'.format(filter_name)) return filter_f, pre_filter
#10. We now plot the power spectral density of our signal, as a function of the frequency (in unit of 1/year). # We choose a logarithmic scale for the y axis (decibels): fig, ax = plt.subplots(1, 1, figsize=(8, 4)) ax.plot(fftfreq[i], 10 * np.log10(temp_psd[i])) ax.set_xlim(0, 5) ax.set_xlabel('Frequency (1/30 days)') ax.set_ylabel('PSD (dB)') ##################################################################################### ##Another example #Generating the fourier transform of the two data series from scipy.fft import rfft pressure_inlet_ultra_filtration_30days_fft = rfft( pressure_inlet_ultra_filtration_30days["Pressure_bar"].values) #Taking the absolute value of the fft and scaling the amplitude pressure_inlet_ultra_filtration_30days_fft = (1 / ( (len(pressure_inlet_ultra_filtration_30days_fft) - 1) * 2)) * np.abs(pressure_inlet_ultra_filtration_30days_fft) #Creating Frequency Values in Hz pressure_inlet_ultra_filtration_30days_frenquency = rfftfreq( len(clockingfftOriginal), 1) #Period X Axis #draw the chart #%matplotlib qt import matplotlib.pyplot as plt
frameCurrent_FFT = [] framePrevious_FFT = [] #arrays for features across all frames centroids = [] rolloffs = [] specFluxes = [] N = 0 #count number of frames. frameStart = 0 while (frameStart <= len(trackLPCM) - FRAMESIZE): #get FFT of current frame frameCurrent = frame(trackLPCM, frameStart, FRAMESIZE) frameCurrent_FFT = abs(FF.rfft(frameCurrent)) #find and store centroid, and rolloff of current frame frameCentroid = centroid(frameCurrent_FFT, FREQBINS) centroids.append(frameCentroid) frameRolloff = rolloff(frameCurrent_FFT, FREQBINS) rolloffs.append(frameRolloff) frameSpecFlux = 0 #if frame is not first frame, if framePrevious_FFT != []: #compare spectra for current and previous frame to get spec flux. frameSpecFlux = specFlux(frameCurrent_FFT, framePrevious_FFT) specFluxes.append(frameSpecFlux) #necessary updates
def convolve(ar1, ar2): return fft.irfft( fft.rfft(np.hamming(ar1.size) * ar1) * np.conj(fft.rfft(np.hamming(ar2.size) * ar2)))
sample_rate, data = wavfile.read("fake_data.wav") mic_space = 0.1 speed_sound = 340 max_shift = int(np.ceil((mic_space / speed_sound) * sample_rate)) print("max shift to solve for:", max_shift) conv = np.abs(convolve(data[:, 0], data[:, 1])) print(np.argmax(conv)) plt.plot(conv) plt.show() dir_audio = [] dirs = np.arange(-max_shift, max_shift) sig1_ft = fft.rfft(data[:, 0]) sig2_ft = fft.rfft(data[:, 1]) conv = fft.irfft(sig1_ft * np.conj(sig2_ft)) conv = conv / np.max(np.abs(conv)) for direct in dirs: conv[:max_shift] = 0 conv[-max_shift:] = 0 conv[direct] = 1 plt.plot(conv) plt.show() conv_ft = fft.rfft(conv) res_audio = fft.irfft(conv_ft / np.conj(sig1_ft)) res_audio = np.asarray(res_audio / np.max(np.abs(res_audio)) * 32767, dtype=np.int16) dir_audio.append(res_audio) wavfile.write("outputs/dir_audio" + str(direct) + ".wav", sample_rate,
rssis = [] with open(sys.argv[1]) as f: reader = csv.reader(f) for r in reader: rssis.append(float(r[0])) fs = 1000 # sample freq ts = np.arange(len(rssis)) / fs rssis = np.array(rssis) from scipy.ndimage import median_filter window_size = 5 # should be odd rssis = median_filter(rssis, window_size, origin=(window_size - 1) // 2) F = rfft(rssis, norm='forward') freqs = rfftfreq(rssis.size, 1 / fs) fig, axs = plt.subplots(1, 2, figsize=(12, 6)) axs[0].set_title('Signal') axs[0].set_ylabel('RSSI') axs[0].set_xlabel('Time / s') axs[0].plot(ts, rssis) axs[1].set_title('Spectrum') axs[1].set_xlabel('Frequency / Hz') axs[1].plot(freqs, np.abs(F)) fig.tight_layout() plt.show() ccs = ph.calculatePeakPersistentHomology(rssis) ccs = ph.sortByLifetime(ccs)
meanMatrix = np.mean(fullData, axis=3) fullData = np.transpose( np.transpose(fullData, (3, 0, 1, 2)) - meanMatrix, (1, 2, 3, 0)) #%% # timediff = np.mean(np.diff(fullTimestamps[0,0])) # bar, timediffLinspace = np.linspace(fullTimestamps[0,0,0], fullTimestamps[0,0,-1], numSamples, retstep=True) # print("They are the same") fullTimestampsLinear, timediffLinspace = np.linspace(fullTimestamps[:, :, 0], fullTimestamps[:, :, -1], numSamples, retstep=True, axis=2) #%% fourier_B = 2.0 / numSamples * np.abs(fft.rfft( fullData, axis=3)) #Should be the same length as the spectrum array fig, axs = plt.subplots(4, 6, figsize=(100, 100)) for wellNum in range(numWells): row = int(wellNum / 6) col = int(wellNum % 6) for (sensorNum, axisNum), status in np.ndenumerate(config[wellNum]): if status: spectrum_f = fft.rfftfreq(numSamples, d=(timediffLinspace[wellNum, sensorNum])) axs[row, col].semilogy( spectrum_f[1:], fourier_B[wellNum, sensorNum, axisNum, 1:], label=f'Sensor {sensorNum + 1} Axis {axisMap[axisNum]}') axs[row, col].set_title(f'Well {wellMap[wellNum]}', fontsize=60) axs[row, col].set_xlabel('Frequency (Hz)', fontsize=30) axs[row, col].set_ylabel('Magnitude (mT)', fontsize=20)
ax.set(xlabel='Time (sec)', ylabel='Amplitude', title='Calibrated', xlim=t[[0, -1]]) ax.legend() fig.tight_layout() ############################################################################### # Examine spectra # --------------- # We can also look at the spectra of these stimuli to get a sense of how the # SNR varies as a function of frequency. from scipy.fft import rfft, rfftfreq # noqa f = rfftfreq(len(target), 1. / fs) T = np.abs(rfft(target)) / np.sqrt(len(target)) # normalize the FFT properly M = np.abs(rfft(masker)) / np.sqrt(len(target)) fig, ax = plt.subplots() ax.plot(f, T, label='target', alpha=0.5, color=colors[0], lw=0.5) ax.plot(f, M, label='masker', alpha=0.5, color=colors[1], lw=0.5) T_rms = rms(T) M_rms = rms(M) print('Parseval\'s theorem: target RMS still %s' % (T_rms, )) print('dB TMR is still %s' % (20 * np.log10(T_rms / M_rms), )) ax.axhline(T_rms, label='target RMS', color=colors[0], lw=1) ax.axhline(M_rms, label='masker RMS', color=colors[1], lw=1) ax.set(xlabel='Freq (Hz)', ylabel='Amplitude', title='Spectrum', xlim=f[[0, -1]]) ax.legend()
ax1_ins.plot(x[4000:6000], d1[4000:6000]) ax1_ins.set_xticklabels('') ax1_ins.set_yticklabels('') ax1.indicate_inset_zoom(ax1_ins) ax1.set_xlabel('Time (s)') ax1.set_ylabel('ADC Code') ax1.set_title('Sample Recording') plt.show() # %% sample_rate = 100000 n = 8192 win = np.hamming(n) samp_sig = d1[3000:11192]-np.round(np.mean(d1[3000:11192])) * win yf = rfft(samp_sig) xf = rfftfreq(n,1/sample_rate) ref = 4096 yf_mag = np.abs(yf) * 2 / np.sum(win) yf_dbfs = 20 * np.log10(yf_mag/ref) fig2, ax2 = plt.subplots(figsize = [10,5]) ax2.semilogx(xf, yf_dbfs) ax2.grid(True) ax2.set_xlabel('Frequency [Hz]') ax2.set_ylabel('Amplitude [dBfs]') ax2.set_title('FFT of Sample Signal') peakf = xf[np.argmax(yf_dbfs)]
filename = f'{ccw_tag}_spacing{i_s}_angle{i_a}.png' index['category'].append(ccw_tag) index['path'].append(os.path.join(ccw_tag, filename)) img_i = i_a * len(spacings) + i_s index['n'].append(img_i) index['neg_n'].append(cat_max_i - img_i) pd.DataFrame(index).to_csv(os.path.join(output_dir, 'ccw_index.csv'), index=False) plt.imshow(direction) plt.show() stutter_noise = np.random.normal(size=W) stutter_spect = fft.rfft(stutter_noise) freqs = fft.fftfreq(W)[:W // 2 + 1][1:-2] plt.plot(freqs, abs(stutter_spect)[1:-2]) plt.plot(freqs, abs(stutter_spect[1:-2] * (freqs.min() / freqs))) plt.yscale('log') plt.xscale('log') plt.plot(freqs, (freqs).min() / freqs**2) plt.yscale('log') plt.xscale('log') def noise1d(NW, FALLOFF_LENGTH, FALLOFF_MIN): stutter_noise = np.random.normal(size=NW) stutter_spect = fft.rfft(stutter_noise) freqs = fft.fftfreq(NW)[:NW // 2 + 1][1:-2]
def getFFT(self, y): x_fourier = fft.rfftfreq(len( self.samples), 1 / self.sampling_rate) # generate frequency vector y_fourier = fft.rfft(y) # take real fft of signal return x_fourier, y_fourier
hanning = np.hanning(FFT_WINDOW) while end <= total_samples: modulator_window = modulator_data[start:end] carrier_window = carrier_data[start:end] assert len(modulator_window) == FFT_WINDOW assert len(carrier_window) == FFT_WINDOW # the modulator and carrier signals are split into multiple frequency bands modulator_window = np.multiply( modulator_window, hanning) # the taper the ends of the window signal using a carrier_window = np.multiply( carrier_window, hanning) # hanning window. Combined with the overlapping modulator_fft = rfft( modulator_window ) # FFT windows, this reduces the buzzing caused by carrier_fft = rfft( carrier_window ) # discontinuities between reconstructed FFT windows. assert len(modulator_fft) == len(carrier_fft) if args.frequency: # fft is symmetric, so we only need to use half freqs = rfftfreq(FFT_WINDOW, d=1. / modulator_wav.rate) plt.clf() plt.subplot(211) plt.title('Modulator FFT') plt.plot(freqs, np.abs(modulator_fft)) plt.subplot(212) plt.title('Carrier FFT')
labels = f.readline() labels = labels.split()[1:] labels[0] = 'freq' labels = ' '.join(labels) snap = 500 file = dir + f'/{snap}.dat' while os.path.isfile(file): print(file) data = read_dat(file) num = len(data['dz']) #-1 if num % 2 == 0: row = int((num / 2) + 1) else: row = int((num + 1) / 2) col = len(data) fourier = np.empty((row, col)) fourier[:, :] = np.NaN for i in range(1, col): if not np.any(np.isnan(data[str(i - 1)])): # fourier[:, i] = abs(rfft(data[str(i-1)])) fourier[:, i] = rfft(data[str(i - 1)][0:]) fourier[:, 0] = rfftfreq(num) fourier_dat = Dat(fourier, labels=labels) fourier_dat.write_file(f'{snap}', dir=dir_out) snap += 6 file = dir + f'/{snap}.dat'
plt.show() # calculating the Fourier transform yf = fft(normalized_tone) xf = fftfreq(N, 1 / SAMPLE_RATE) # plot the values plt.plot(xf, np.abs(yf)) plt.show() # Making It Faster yf = fft(normalized_tone) xf = fftfreq(N, 1 / SAMPLE_RATE) # Note the extra 'r' at the front yf = rfft(normalized_tone) xf = rfftfreq(N, 1 / SAMPLE_RATE) plt.plot(xf, np.abs(yf)) plt.show() # Filtering the Signal (fixing) # The maximum frequency is half the sample rate points_per_freq = len(xf) / (SAMPLE_RATE / 2) # Our target frequency is 4000 Hz target_idx = int(points_per_freq * 4000) yf[target_idx - 1 : target_idx + 2] = 0 plt.plot(xf, np.abs(yf))
def test_dtypes(self, dtype): # make sure that all input precisions are accepted x = random(30).astype(dtype) assert_array_almost_equal(fft.ifft(fft.fft(x)), x) assert_array_almost_equal(fft.irfft(fft.rfft(x)), x) assert_array_almost_equal(fft.hfft(fft.ihfft(x), len(x)), x)
'T2M': 'temperature', 'PS': 'pressure', 'QV2M': 'humidity' }, inplace=True) print('Date Describtion:', data['date'].describe()) data.set_index('date', inplace=True) # List missing date values, i.e. gaps full_date_range = pd.date_range(min(data.index), max(data.index), freq='1D') missing_dates = full_date_range[~full_date_range.isin(data.index)] print('Missing Dates:', missing_dates) # FFT fft_temp = fft.rfft(data['temperature'].values) fftfreq_daily = fft.rfftfreq(data['temperature'].size, 1) fft_data = pd.DataFrame(data={'fft raw': fft_temp}, index=fftfreq_daily) fft_data['real'] = np.real(fft_data['fft raw']) fft_data['imag'] = np.imag(fft_data['fft raw']) fft_data['psd'] = np.abs(fft_data['fft raw']) fft_data['phase'] = np.arctan2(fft_data['real'], fft_data['imag']) # Clean Data -> keep biggest N peaks N = 5 cut_off = fft_data['psd'].sort_values().values[-N] fft_data['cleaned'] = fft_data['fft raw'] clean_mask = fft_data['psd'].values < cut_off fft_data.loc[clean_mask, 'cleaned'] = 0 data['ifft'] = fft.irfft(fft_data['cleaned'].values)
def get_real_fast_fourier_transform(function): return rfft(function)
def recsound(self,v): global soundin # global kaiser initsound() soundin.start() snd=soundin.read(65536)[0][:,0] soundin.stop() np.savetxt("real.txt",snd) # snd*=kaiser # window didn't really help ft=fft.rfft(snd) a=np.absolute(ft) np.savetxt("fft.txt",a) p=np.angle(ft)*180./pi np.savetxt("pha.txt",p) # If there is only a single strong peak (or maybe 2) the CCF approach won't work very well, but the peak itself should be good # h=np.argwhere(a>np.max(a)/20.0) # if len(h)<3: h=np.min(h) # else: fta=fft.rfft(a) fta=fta*np.conj(fta) fta=fft.irfft(fta) np.savetxt("fta.txt",fta) # peak filter, but wasn't useful # ftap=np.roll(fta,1,0) # ftam=np.roll(fta,-1,0) # fta=np.where(fta>ftap,fta,np.zeros(len(fta))) # fta=np.where(fta>ftam,fta,np.zeros(len(fta))) # np.savetxt("ftaf.txt",fta) # ftac=fta.copy() # # need a clever way to do this in numpy # for i in range(1,32767): # if fta[i-1]>fta[i] or fta[i+1]>fta[i] : ftac[i]=0 h=(np.argmax(fta[200:20000])+200)//2 f1=22050.0/32768.0 # lowest frequency pixel, scaling factor for frequency axis # sum the first 8 harmonics for each fundamental # hsum=a[:4096]*1.25 # *1.25 helps make sure a solo peak shows up as the first harmonic not a higher one # for i in range(2,9): hsum+=a[:4096*i:i] # hsum=np.fmin(hsum,a[:4096]*25.0) # np.savetxt("fsum.txt",hsum) # hsum=hsum[100:] # h=np.min(np.argwhere(hsum>np.std(hsum)*2.0))+100 # h=np.argmax(hsum[100:])+100 maxf=f1*h # should correspond to the strongest single frequency based on harmonic sum print(f"peak {h} -> {maxf}") self.vrootf.setValue(floor(maxf)) # pull out the values for up to the first 33 harmonics sca=0.5/np.max(a[h::h]) for i in range(1,33): j=h*i # harmonic peak index (rounded) if j>32767 : self.wamp[i].setValue(0,True) continue amp=float(abs(ft[j]))*sca pha=float(cmath.phase(ft[j]))*180.0/pi self.wamp[i].setValue(amp,True) self.wpha[i].setValue(pha,True) self.recompute()
(46, 36, 31, 75), (46, 35, 31, 75), (46, 36, 31, 75), (46, 35, 31, 75), (46, 35, 31, 75), (46, 35, 31, 75), (46, 35, 31, 75), (46, 36, 31, 75), (46, 36, 31, 75), (46, 35, 31, 75), (46, 36, 31, 75), (46, 35, 31, 75), (46, 36, 31, 75), (46, 36, 31, 75), (46, 35, 31, 75)] for element in inputlist: roodlist.append(element[0]) roodlist = roodlist[:15] xlist = np.arange(len(roodlist)) plt.plot(xlist, roodlist) plt.show() plt.plot(rfftfreq(15,1),np.abs(rfft(roodlist))) plt.show() x = np.linspace(0, 5, 10*5, endpoint=False) y = np.sin(2* np.pi * x) plt.plot(x, y) plt.show() plt.plot(rfftfreq(10*5,1/10),np.abs(rfft(y))) plt.show()
ax.plot(sound_filter) fig,ax=plt.subplots() ax.plot(filtered_sound) fig,ax=plt.subplots() ax.scatter(Frequencies,Amplitudes) #%% file_loc = "/home/stellarremnants/Desktop/Bag_Of_Holding/Universal_Shared/Personal_Projects/OrcResta/OrcaStra/" file_name="GuitarTest_Stereo.wav" wav_smpr,wav_file = wav_read(file_loc+file_name) # %% mono_wav = wav_file[:,0] real_fft = abs(fft.rfft(mono_wav)) real_freqs = fft.rfftfreq(len(mono_wav), 1./wav_smpr) Peak_indices = sig.find_peaks(real_fft, height=np.max(real_fft)*0.01)[0] fig,ax=plt.subplots() ax.plot(real_freqs, real_fft) PeakAmplitudes = [] PeakFrequencies = [] for i in Peak_indices: PeakAmplitudes.append(real_fft[i]) PeakFrequencies.append(real_freqs[i]) ax.scatter(PeakFrequencies, PeakAmplitudes) ampmax = np.max(real_fft)
def GCC(x,y,filt="unfiltered",fftshift=1, b=None, a=None): """ Generalized Cross-Correlation of _real_ signals x and y with specified pre-whitening filter. The GCC is computed with a pre-whitening filter onto the cross-power spectrum in order to weight the magnitude value against its SNR. The weighted CPS is used to obtain the cross-correlation in the time domain with an inverse FFT. The result is _not_ normalized. See "The Generalized Correlation Method for Estimation of Time Delay" by Charles Knapp and Clifford Carter, programmed with looking at the matlab GCC implementation by Davide Renzi. x, y input signals on which gcc is calculated filt the pre-whitening filter type (explanation see below) fftshift if not zero the final ifft will be shifted returns the gcc in time-domain descibtion of pre-whitening filters: 'unfiltered': performs simply a crosscorrelation 'roth': this processor suppress frequency regions where the noise is large than signals. 'scot': Smoothed Coherence Transform (SCOT) this processor exhibits the same spreading as the Roth processor. 'phat': Phase Transform (PHAT) ad hoc technique devoleped to assign a specified weight according to the SNR. 'cps-m': SCOT filter modified this processor computes the Cross Power Spectrum Density and apply the SCOT filter with a power at the denominator to avoid ambient reverberations that causes false peak detection. 'ht': Hannah and Thomson filter (HT) HT processor computes a PHAT transform weighting the phase according to the strength of the coherence. 'prefilter': general IIR prefilter with b and a a transfer function of an IIR filter can be given, which will be used as a prefilter (can be a "non-whitening" filter) 2007, Georg Holzmann """ L = max( len(x), len(y) ) fftsize = int(2**ceil(log(L)/log(2))) # next power2 X = np.fft.rfft(x, fftsize) Y = np.fft.rfft(y, fftsize) # calc crosscorrelation Gxy = X.conj() * Y # calc the filters if( filt == "unfiltered" ): Rxy = Gxy elif( filt == "roth" ): Gxx = X.conj() * X W = ones(Gxx.shape,Gxx.dtype) W[Gxx!=0] = 1. / Gxx[Gxx!=0] Rxy = Gxy * W elif( filt == 'scot' ): Gxx = X.conj() * X Gyy = Y.conj() * Y W = ones(Gxx.shape,Gxx.dtype) tmp = sqrt(Gxx * Gyy) W[tmp!=0] = 1. / tmp[tmp!=0] Rxy = Gxy * W elif( filt == 'phat' ): W = ones(Gxy.shape,Gxy.dtype) Gxx = X.conj() * X tmp = abs(Gxy) #W[tmp>10] = 1. / tmp[tmp>10] #W=abs(Gxy); W[tmp>=10]=1./tmp[tmp>=10]; #plotFrequency(np.fft.irfft(W)) #show() Rxy = Gxy * W elif( filt == 'cps-m' ): Gxx = X.conj() * X Gyy = Y.conj() * Y W = ones(Gxx.shape,Gxx.dtype) factor = 0.75 # common value between .5 and 1 tmp = (Gxx * Gyy)**factor W[tmp!=0] = 1. / tmp[tmp!=0] Rxy = Gxy * W elif( filt == 'ht' ): Gxx = X.conj() * X Gyy = Y.conj() * Y W = ones(Gxy.shape,Gxy.dtype) gamma = W.copy() # coherence function evaluated along the frame tmp = sqrt(Gxx * Gyy) gamma[tmp!=0] = abs(Gxy[tmp!=0]) / tmp[tmp!=0] # HT filter tmp = abs(Gxy) * (1-gamma) W[tmp!=0] = gamma[tmp!=0] / tmp[tmp!=0] Rxy = Gxy * W elif( filt == 'prefilter' ): # calc frequency response of b,a filter impulse = zeros(fftsize) impulse[0] = 1 h = signal.lfilter(b,a,impulse) H = fft.rfft(h, fftsize) Rxy = H * Gxy # hm ... conj da irgendwo ? else: raise ValueError, "wrong pre-whitening filter !" # inverse transform with optional fftshift if( fftshift!=0 ): gcc = fftpack.fftshift( np.fft.irfft( Rxy ) ) else: gcc = np.fft.irfft( Rxy ) return gcc
_, nice_tone = generate_sine_wave(400, SAMPLE_RATE, DURATION) _, noise_tone = generate_sine_wave(4000, SAMPLE_RATE, DURATION) noise_tone = noise_tone * 0.3 mixed_tone = nice_tone + noise_tone normalized_tone = np.int16((mixed_tone / mixed_tone.max()) * (2**15 - 1)) from scipy.io.wavfile import read audio = read("noise.wav") fs = audio[0] # samples per second audio = numpy.array(audio[1], dtype=float) plt.plot(normalized_tone[:100]) plt.show() from scipy.io import wavfile wavfile.write("mix.wav", SAMPLE_RATE, normalized_tone) from scipy.fft import fft, fftfreq, rfft, rfftfreq # Number of samples in normalized_tone N = audio.shape[0] yf = rfft(audio) xf = rfftfreq(N, 1 / fs) plt.plot(xf, np.abs(yf)) plt.show()