def time_sort(in_dir_name, dir_params, main_dir): ''' Spectrums/Images captured using splicco's automatic data capture/timed sequential function are automatically given a user defined file name and a time and date stamp of the moment a measurement was taken (file created). This function converts the time stamp given into a value in seconds by splitting the file name into sections, reversing the order and splitting the time stamp at 'h' 'm' and 's' then converting to seconds. The function then adds all the values together to give a total time in seconds, concatenates this with the original file name, and saves the original data out with a new file name as a numpy array. Args: in_dir_name: <string> directory name containing spectrum files dir_params: <array> directories are given a name equivalent to the individual file names, the dir_params function splits the directory name into an array that can be used to find the correct spectrum files. main_dir: <string> current working directory ''' file_string = '_'.join(dir_params) print(f'\n{dir_params}') data_files = of.extract_files(dir_name=in_dir_name, file_string=file_string) for index, selected_file in enumerate(data_files): file = os.path.join(in_dir_name, selected_file) wavelength, intensity, file_name = bc.read_in_values(file) data = np.vstack((wavelength, intensity)).T split_file = file_name.split('_')[::-1] hrs_split = split_file[0].split('h') mins_split = hrs_split[1].split('m') secs_split = mins_split[1].split('s') total_seconds = convert_to_seconds(hours=hrs_split[0], minutes=mins_split[0], seconds=secs_split[0], milliseconds=secs_split[1]) out_dir_name = '_'.join(dir_params) + '_TimeAdjusted' out_dir = os.path.join(main_dir, out_dir_name) of.check_dir_exists(out_dir) joined = [] joined.append(file_string) joined.append(str(total_seconds)) new_file_name = '_'.join(joined) of.array_save(array_name=data, file_name=new_file_name, dir_name=out_dir) of.update_progress(index / len(data_files))
def time_correct(in_dir_name, dir_params, main_dir): ''' Spectrums/Images time adjusted in TimeSort function above are loaded in and the data is maintained. The file name is split and the first file captured is set to 0, the following files within the directory are given a time stamp respective to the zero file (a time step). This is useful for later processing. Args: in_dir_name: <string> directory name containind time adjusted spectrum files dir_params: <array> directories are given a name equivalent to the individual file names, the dir_params function splits the directory name into an array that can be used to find the correct spectrum files. main_dir: <string> current working directory ''' file_string = '_'.join(dir_params[0:2]) print(' ') print(dir_params) data_files = of.extract_files(dir_name=in_dir_name, file_string=file_string) zero_file_name = data_files[0] zero_time_stamp = (zero_file_name.split('_')[::-1])[0] for index, selected_file in enumerate(data_files): file = os.path.join(in_dir_name, selected_file) data = np.load(file) file_name = bc.get_filename(file) split_file = file_name.split('_')[::-1] time_correction = int( float(split_file[0]) - float(zero_time_stamp[0:-4])) out_dir_name = '_'.join(dir_params[0:-1]) + '_TimeCorrected' out_dir = os.path.join(main_dir, out_dir_name) of.check_dir_exists(out_dir) joined = [] joined.append(file_string) joined.append(str(time_correction)) new_file_name = '_'.join(joined) of.array_save(array_name=data, file_name=new_file_name, dir_name=out_dir) os.remove(file) of.update_progress(index / len(data_files))
def plot_spectrum(file, dir_params, main_dir, show=False, save=True): ''' Uses the ReadInParams function to get wavelength, intensity and file name parameters from a given file. Uses SoluteFinder to determine which solute and what concentration is being analysed and plots the spectrum. Can show or save out the figure into a given directory. Args: file: <string> file path dir_params: <array> Output of the SoluteFinder function to determine solute and concentration parameters. show: <bool> shows the plot if True save: <bool> saves the plot if True ''' wavelength, intensity, file_name = read_in_params(file=file) fig, ax = plt.subplots(1, 1, figsize=[10, 7]) ax.plot(wavelength, intensity, 'b', lw=2, label=file_name) ax.grid(True) ax.legend(frameon=True, loc=0, ncol=1, prop={'size': 12}) ax.set_xlabel('Wavelength [nm]', fontsize=14) ax.set_ylabel('Intensity [au]', fontsize=14) ax.set_title(file_name, fontsize=18) ax.tick_params(axis='both', which='major', labelsize=14) fig.tight_layout() if show: plt.show() if save: out_dir_name = '_'.join(dir_params[0:-1]) + '_Graphs' out_dir = os.path.join(main_dir, out_dir_name) of.check_dir_exists(out_dir) out_path = os.path.join(out_dir, file_name + '.png') plt.savefig(out_path) fig.clf() plt.close(fig)
main_dir=selected_dir) dir_params = tc.solute_finder(f'{solute_dir}_TimeAdjusted') tc.time_correct(in_dir_name=f'{solute_dir}_TimeAdjusted', dir_params=dir_params, main_dir=selected_dir) os.rmdir(f'{solute_dir}_TimeAdjusted') time_c_dir = f'{solute_dir}_TimeCorrected' print('\nFinding Peaks') dir_params = tc.solute_finder(time_c_dir) print(' ') print(dir_params) results_dir = os.path.join(selected_dir, 'Results') of.check_dir_exists(results_dir) data_files = of.extract_files(dir_name=time_c_dir, file_string='_'.join( dir_params[0:2])) outfile_name = file_name = '_'.join( dir_params[0:-1]) + '_Peaks.csv' with open(outfile_name, 'a', newline='') as outfile: writer = csv.writer(outfile, delimiter=',') writer.writerow(['Wavelength [nm]'] + ['Peak [nm]'] + ['Peak Shift [nm]']) for index, selected_file in enumerate(data_files): file = os.path.join(time_c_dir, selected_file) zero_file_name = f'{sensor}_Background.csv'
def plot_peak_shift(file, bg_dir, file_params, sensor, main_dir, show=False, save=False): ''' Loads in the results file previously saved as time, peak, peak shift and the background calibration file with the file name, peak and peak shift. Using an array (bg_file_string) to find the relevant reference files within the background calibration file, it plots the peak shift as a function of time, and adds the peak or peak shift wavelengths of the references as horizontal lines with the file name as text. Args: file: <string> file path to results csv bg_dir: <string> directory path to background calibration directory dir_params: <array> SoluteFinder function to determine solute and concentration sensor: <string> set within the code to the biosensor used show: <bool> show plot save: <bool> saves plot to results directory ''' file_string = '_'.join(file_params[0:2]) out_dir = os.path.join(main_dir, 'Results') of.check_dir_exists(out_dir) bg_file_string = [ '1M_Salt_Background.csv', file_string + '_Background.csv', '1M_Salt_Paper_Background.csv', file_string + '_Paper_Background.csv', sensor + '_Background.csv' ] bg_file_string = [ '1M_Salt_Background', file_string + '_Background', '1M_Salt_Paper_Background', file_string + '_Paper_Background', sensor + '_Background' ] bg_file = os.path.join(bg_dir, 'Background_Peaks.csv') name_string, bg_peak, bg_peak_shift = np.genfromtxt(bg_file, delimiter=',', usecols=(0, 1, 2), dtype=(str), unpack=True) time, peak, peak_shift = np.genfromtxt(file, delimiter=',', unpack=True) time *= 1 / 60 file_name = bc.get_filename(file) fig, ax = plt.subplots(1, 1, figsize=[10, 7]) ax.plot(time, peak_shift, 'r.', label=' '.join(file_name.split('_')[0:2])) ax.grid(True) ax.legend(frameon=True, loc=0, ncol=1, prop={'size': 12}) for index, name in enumerate(name_string): if name in bg_file_string: ax.axhline(y=float(bg_peak_shift[index]), linewidth=2, color='C' + str(index % 9), linestyle=':') ax.text(x=2 * index, y=(float(bg_peak_shift[index])), s=' '.join(name.split('_')[0:-1]), bbox=dict(facecolor='white', edgecolor='none', alpha=0.5), horizontalalignment='center', verticalalignment='center', fontsize=8) ax.set_xlabel('Time [min]', fontsize=14) ax.set_ylabel('Peak Shift [nm]', fontsize=14) ax.set_title(' '.join(file_name.split('_')[0:2]), fontsize=18) ax.tick_params(axis='both', which='major', labelsize=14) fig.tight_layout() if show: plt.show() if save: plt.savefig(file_name + '_Shift.png') copy(file_name + '_Shift.png', out_dir) os.remove(file_name + '_Shift.png') fig.clf() plt.close(fig)