median_indices = OrderedDict() median_images = OrderedDict() full_slice_dict = OrderedDict() for ctr, (data_file, label) in enumerate([(lasing_off_file, 'Lasing Off'), (data_files[-1], 'Lasing On')]): data_dict = loadH5Recursive(data_file) images = data_dict['pyscan_result']['image'].astype(np.float64) x_axis = data_dict['pyscan_result']['x_axis'].astype(np.float64) y_axis = data_dict['pyscan_result']['y_axis'].astype(np.float64) projx = images.sum(axis=-2) median_index = misc.get_median(projx, output='index') median_indices[label] = median_index print(label, median_index) sp_ctr = np.inf ny, nx = 3, 3 subplot = ms.subplot_factory(ny, nx) full_slice_dict[label] = np.zeros([len(images), 5, n_slices]) if ctr == 1: ref_y = full_slice_dict['Lasing Off'][:, 4, 0].mean() for n_image, image in enumerate(images): image_obj = iap.Image(image, x_axis,
raw_data = data_dict['raw_data'] meta_data = data_dict['meta_data'] offset_index = -1 gaps = [10e-3, 9.94e-3] streaker_offset = 372e-6 beam_offsets = [0, -(meta_data['offsets'][offset_index] - streaker_offset)] tracker.set_simulator(raw_data['meta_data_begin']) projx = raw_data['pyscan_result']['image'][offset_index].astype( np.float64).sum(axis=-2) x_axis = raw_data['pyscan_result']['x_axis_m'] median_proj = misc.get_median(projx) meas_screen = misc.proj_to_screen(median_proj, x_axis, True, meta_data['screen_x0']) recon_kwargs['meas_screen'] = meas_screen recon_kwargs['gaps'] = gaps recon_kwargs['beam_offsets'] = beam_offsets recon_kwargs['n_streaker'] = 1 recon_kwargs['method'] = 'centroid' recon_kwargs['sig_t_range'] = np.array([5., 75.]) * 1e-15 #analysis.current_profile_rec_gauss(tracker, recon_kwargs) profile_output = cProfile.run( 'analysis.current_profile_rec_gauss(tracker, recon_kwargs)', filename='./profile.txt')
def reconstruct_current(data_file_or_dict, n_streaker, beamline, tracker_kwargs_or_tracker, rec_mode, kwargs_recon, screen_x0, streaker_centers, blmeas_file=None, plot_handles=None, do_plot=True): if type(tracker_kwargs_or_tracker) is dict: tracker = tracking.Tracker(**tracker_kwargs_or_tracker) elif type(tracker_kwargs_or_tracker) is tracking.Tracker: tracker = tracker_kwargs_or_tracker else: raise ValueError(type(tracker_kwargs_or_tracker)) if type(data_file_or_dict) is dict: screen_data = data_file_or_dict else: screen_data = h5_storage.loadH5Recursive(data_file_or_dict) if 'meta_data' in screen_data: meta_data = screen_data['meta_data'] elif 'meta_data_begin' in screen_data: meta_data = screen_data['meta_data_begin'] else: print(screen_data.keys()) raise ValueError if 'pyscan_result' in screen_data: pyscan_data = screen_data['pyscan_result'] else: pyscan_data = screen_data x_axis = pyscan_data['x_axis_m'] projx = pyscan_data['image'].sum(axis=-2) if rec_mode == 'Median': median_projx = misc.get_median(projx) proj_list = [median_projx] elif rec_mode == 'All': proj_list = projx tracker.set_simulator(meta_data) if x_axis[1] < x_axis[0]: revert = True x_axis = x_axis[::-1] else: revert = False output_dicts = [] for proj in proj_list: if revert: proj = proj[::-1] meas_screen = tracking.ScreenDistribution(x_axis, proj) kwargs_recon['meas_screen'] = meas_screen #print('Analysing reconstruction') kwargs = copy.deepcopy(kwargs_recon) gaps, streaker_offsets = get_gap_and_offset(meta_data, beamline) kwargs['meas_screen']._xx = kwargs['meas_screen']._xx - screen_x0 kwargs['beam_offsets'] = -(streaker_offsets - streaker_centers) kwargs['gaps'] = gaps kwargs['meas_screen'].cutoff2(tracker.screen_cutoff) kwargs['meas_screen'].crop() kwargs['meas_screen'].reshape(tracker.len_screen) kwargs['n_streaker'] = n_streaker # Only allow one streaker at the moment for n in (0,1): if n != kwargs['n_streaker']: kwargs['beam_offsets'][n] = 0 gauss_dict = current_profile_rec_gauss(tracker, kwargs, plot_handles, blmeas_file, do_plot=do_plot) output_dict = { 'input': { 'data_file_or_dict': data_file_or_dict, 'n_streaker': n_streaker, 'beamline': beamline, 'tracker_kwargs': tracker_kwargs_or_tracker, 'rec_mode': rec_mode, 'kwargs_recon': kwargs_recon, 'screen_x0': screen_x0, 'streaker_centers': streaker_centers, 'blmeas_file': blmeas_file, }, 'gauss_dict': gauss_dict, } output_dicts.append(output_dict) if rec_mode == 'Median': return output_dict elif rec_mode == 'All': return output_dicts else: print(rec_mode)
true_offsets = [] lims_neg = -0.5, 3 lims_pos = -2, 0.5 sp_pos.set_xlim(*lims_pos) sp_neg.set_xlim(*lims_neg) delta_offset = 0e-6 all_xt = [] for n_offset, offset in enumerate(offsets[:-1]): images = streaker_calib['raw_data']['pyscan_result']['image'][ n_offset].astype(float) projections = images.sum(axis=-2) median_proj = misc.get_median(projections, method='gf_sigma') screen = misc.proj_to_screen(median_proj, x_axis, subtract_min=True) screen._xx = screen._xx - x0 screen.cutoff(5e-2) screen.crop() screen.reshape(len_profile) beam_offsets = [0, -(offset - streaker_offset) + delta_offset] gaps = [10e-3, 10e-3] distance = (gaps[1] / 2. - abs(beam_offsets[1])) * np.sign(beam_offsets[1]) forward_dict = tracker.matrix_forward(profile_from_blmeas, gaps, beam_offsets) screen_forward = forward_dict['screen'] if offset == 0: continue
def reconstruct_lasing(file_or_dict_on, file_or_dict_off, screen_center, structure_center, structure_length, file_current, r12, disp, energy_eV, charge, streaker, plot_handles, pulse_energy, n_slices, len_profile): if type(file_or_dict_on) is dict: dict_on = file_or_dict_on else: dict_on = h5_storage.loadH5Recursive(file_or_dict_on) dict_on_p = dict_on['pyscan_result'] dict_on_m = dict_on['meta_data_end'] if type(file_or_dict_off) is dict: dict_off = file_or_dict_off else: dict_off = h5_storage.loadH5Recursive(file_or_dict_off) dict_off_p = dict_off['pyscan_result'] dict_off_m = dict_off['meta_data_end'] if energy_eV == 'file': if 'SARBD01-MBND100:ENERGY-OP' in dict_on_m: energy_eV = dict_on_m['SARBD01-MBND100:ENERGY-OP']*1e6 elif 'SARBD01-MBND100:P-SET' in dict_on_m: energy_eV = dict_on_m['SARBD01-MBND100:P-SET']*1e6 else: raise ValueError('No energy saved!') input_dict = { 'file_or_dict_on': file_or_dict_on, 'file_or_dict_off': file_or_dict_off, 'screen_center': screen_center, 'structure_center': structure_center, 'structure_length': structure_length, 'file_current': file_current, 'r12': r12, 'disp': disp, 'energy_eV': energy_eV, 'charge': charge, 'streaker': streaker, 'pulse_energy': pulse_energy, } gaps, beam_offsets = [], [] for dict_ in dict_off_m, dict_on_m: gaps.append(dict_[streaker+':GAP']*1e-3) beam_offsets.append(-(dict_[streaker+':CENTER']*1e-3-structure_center)) if abs(gaps[0] - gaps[1]) > 1e-6: print('Gaps not the same!', gaps) if abs(beam_offsets[0] - beam_offsets[1]) > 1e-6: print('Beam offsets not the same!', beam_offsets) gap = np.mean(gaps) beam_offset = np.mean(beam_offsets) if pulse_energy is None: try: pulse_energy = dict_on_m[config.gas_monitor_pvs['Aramis']]*1e-6 except KeyError: print('No pulse energy found! Use 100 uJ') pulse_energy = 100e-6 images0 = dict_off_p['image'].astype(np.float64) images0_on = dict_on_p['image'].astype(np.float64) if 'x_axis_m' in dict_off_p: x_axis0 = dict_off_p['x_axis_m'].astype(np.float64) y_axis0 = dict_off_p['y_axis_m'].astype(np.float64) else: x_axis0 = dict_off_p['x_axis'].astype(np.float64) y_axis0 = dict_off_p['y_axis'].astype(np.float64) projx0 = images0.sum(axis=-2) median_index = misc.get_median(projx0, output='index') median_image_off = iap.Image(images0[median_index], x_axis0, y_axis0, x_offset=screen_center) projx0_on = images0_on.sum(axis=-2) median_index = misc.get_median(projx0_on, output='index') median_image_on = iap.Image(images0_on[median_index], x_axis0, y_axis0, x_offset=screen_center) current_dict = h5_storage.loadH5Recursive(file_current) if 'gaussian_reconstruction' in current_dict: wake_profile_dict = current_dict['gaussian_reconstruction']['reconstructed_profile'] wake_profile = iap.BeamProfile.from_dict(wake_profile_dict) else: wake_profile = iap.profile_from_blmeas(current_dict, 200e-15, charge, energy_eV, True) wake_profile.cutoff2(0.1) wake_profile.crop() wake_profile.reshape(len_profile) wake_t, wake_x = wake_profile.get_x_t(gap, beam_offset, structure_length, r12) lasing_dict = lasing.obtain_lasing(median_image_off, median_image_on, n_slices, wake_x, wake_t, len_profile, disp, energy_eV, charge, pulse_energy=pulse_energy, debug=False) if plot_handles is None: plot_handles = lasing_figures() (fig, (sp_profile, sp_wake, sp_off, sp_on, sp_off_cut, sp_on_cut, sp_off_tE, sp_on_tE)) = plot_handles[0] (fig, (sp_power, sp_current, sp_centroid, sp_slice_size)) = plot_handles[1] slice_time = lasing_dict['slice_time'] all_slice_dict = lasing_dict['all_slice_dict'] power_from_Eloss = lasing_dict['power_Eloss'] power_from_Espread = lasing_dict['power_Espread'] sp_current.plot(slice_time*1e15, all_slice_dict['Lasing_off']['slice_current'], label='Off') sp_current.plot(slice_time*1e15, all_slice_dict['Lasing_on']['slice_current'], label='On') lasing_dict['all_images']['Lasing_off']['image_tE'].plot_img_and_proj(sp_off_tE) lasing_dict['all_images']['Lasing_on']['image_tE'].plot_img_and_proj(sp_on_tE) lasing_dict['all_images']['Lasing_off']['image_cut'].plot_img_and_proj(sp_off_cut) lasing_dict['all_images']['Lasing_on']['image_cut'].plot_img_and_proj(sp_on_cut) for key, sp_tE in [('Lasing_off',sp_off_tE), ('Lasing_on',sp_on_tE)]: slice_sigma = all_slice_dict[key]['slice_sigma'] slice_centroid = all_slice_dict[key]['slice_mean'] sp_slice_size.plot(slice_time*1e15, slice_sigma/1e6, label=key) sp_centroid.plot(slice_time*1e15, slice_centroid/1e6, label=key) lims = sp_tE.get_ylim() sp_tE.errorbar(slice_time*1e15, slice_centroid/1e6, yerr=slice_sigma/1e6, ls='None', marker='+', color='red') sp_tE.set_ylim(*lims) sp_power.plot(slice_time*1e15, power_from_Eloss/1e9, label='$\Delta$E') sp_power.plot(slice_time*1e15, power_from_Espread/1e9, label='$\Delta\sigma_E$') sp_current.legend() sp_power.legend() sp_slice_size.legend() sp_centroid.legend() median_image_off.plot_img_and_proj(sp_off) median_image_on.plot_img_and_proj(sp_on) sp_wake.plot(wake_t*1e15, wake_x*1e3) wake_profile.plot_standard(sp_profile) if type(input_dict['file_or_dict_on']) is dict: del input_dict['file_or_dict_on'] if type(input_dict['file_or_dict_off']) is dict: del input_dict['file_or_dict_off'] output = { 'input': input_dict, 'lasing_dict': lasing_dict, } #import pdb; pdb.set_trace() return output
screen_calib_raw_image = screen_calib_dict['pyscan_result']['image'][0].astype( float) x_axis_calib = screen_calib_dict['pyscan_result']['x_axis_m'] screen_x0 = gaussfit.GaussFit(x_axis_calib, screen_calib_raw_image.sum(axis=0)).mean x_axis_calib -= screen_x0 y_axis_calib = screen_calib_dict['pyscan_result']['y_axis_m'] screen_calib_raw_image -= np.median(screen_calib_raw_image) screen_calib_image = iap.Image(screen_calib_raw_image, x_axis_calib, y_axis_calib) images = image_dict['pyscan_result']['image'].astype(float) x_axis = image_dict['pyscan_result']['x_axis_m'] - screen_x0 y_axis = image_dict['pyscan_result']['y_axis_m'] projx = images.sum(axis=-2) median_index = misc.get_median(projx, method='mean', output='index') raw_image1 = images[median_index] raw_image1 -= np.median(raw_image1) image1 = iap.Image(raw_image1, x_axis, y_axis) strong_streaking_file = data_dir1 + '2021_05_18-23_43_39_Lasing_False_SARBD02-DSCR050.h5' strong_streaking_dict = h5_storage.loadH5Recursive(strong_streaking_file) meta_data2 = strong_streaking_dict['meta_data_begin'] strong_calib_file = data_dir1 + '2021_05_18-23_32_12_Calibration_SARUN18-UDCP020.h5' strong_calib_dict = h5_storage.loadH5Recursive(strong_calib_file) screen_x0 = strong_calib_dict['meta_data']['screen_x0'] index = np.argwhere(strong_calib_dict['meta_data']['offsets'] == 0) raw_image = ((strong_calib_dict['raw_data']['pyscan_result']['image'] )[index, 0]).astype(float).squeeze() raw_image2 = ((strong_calib_dict['raw_data']['pyscan_result']['image'])[0, 0]
title='Screen distributions', xlabel='x (mm)', ylabel='intensity (arb. units)') sp_ctr += 1 sp_screen_neg = subplot(sp_ctr, title='Screen distributions', xlabel='x (mm)', ylabel='intensity (arb. units)') sp_ctr += 1 for n_offset, offset in enumerate(offsets): label = '%.2f mm' % (offset * 1e3) projections = projx[n_offset] median_proj = misc.get_median(projections, method='std') screen = misc.proj_to_screen(median_proj, x_axis, True, x_offset=screen_center) screen.cutoff2(screen_cutoff) screen.crop() screen.reshape(len_profile) if offset == 0: for sp_screen in sp_screen_pos, sp_screen_neg: screen.plot_standard(sp_screen, label=label) continue elif offset > 0: sp_screen = sp_screen_pos
for streaker_offset_mm in all_offsets: if streaker_offset_mm > 0: sp_screen, sp_profile = sp_screen0, sp_profile0 if streaker_offset_mm < 0: sp_screen, sp_profile = sp_screen1, sp_profile1 streaker_offset = streaker_offset_mm * 1e-3 file_off0 = offset_file_dict['OFF'][streaker_offset_mm] file_off = data_dir + os.path.basename(file_off0) dict_off = loadH5Recursive(file_off)['pyscan_result'] all_proj = dict_off['image'].astype(float).sum(axis=-2) x_axis = dict_off['x_axis'].astype(float) median_proj = misc.get_median(all_proj) meas_screen = misc.proj_to_screen(median_proj, x_axis, True, screen_x0) gauss_kwargs2 = copy.deepcopy(gauss_kwargs) gauss_kwargs2['beam_offsets'] = [0, -(streaker_offset - streaker_center)] del gauss_kwargs2['meas_screen_intensity'] del gauss_kwargs2['meas_screen_x'] gauss_kwargs2['meas_screen'] = meas_screen gauss_kwargs2['sig_t_range'] = np.arange(20, 50.01, 5) * 1e-15 gauss_dict = tracker.find_best_gauss(**gauss_kwargs2) profile = gauss_dict['reconstructed_profile'] screen = gauss_dict['reconstructed_screen'] _label = '%.2f mm %i fs' % (streaker_offset_mm, profile.rms() * 1e15) profile.plot_standard(sp_profile, label=_label, center='Gauss')
for streaker_offset_mm in all_offsets: if streaker_offset_mm > 0: sp_screen, sp_profile = sp_screen0, sp_profile0 if streaker_offset_mm < 0: sp_screen, sp_profile = sp_screen1, sp_profile1 streaker_offset = streaker_offset_mm * 1e-3 file_off0 = offset_file_dict['OFF'][streaker_offset_mm] file_off = data_dir + os.path.basename(file_off0) dict_off = loadH5Recursive(file_off)['pyscan_result'] all_proj = dict_off['image'].astype(float).sum(axis=-2) x_axis = dict_off['x_axis'].astype(float) median_index = misc.get_median(all_proj, output='index') median_proj = all_proj[median_index] meas_screen = misc.proj_to_screen(median_proj, x_axis, True, screen_x0) gauss_kwargs2 = copy.deepcopy(gauss_kwargs) gauss_kwargs2['beam_offsets'] = [0, -(streaker_offset - streaker_center)] del gauss_kwargs2['meas_screen_intensity'] del gauss_kwargs2['meas_screen_x'] gauss_kwargs2['meas_screen'] = meas_screen gauss_kwargs2['sig_t_range'] = np.arange(20, 50.01, 5) * 1e-15 gauss_dict = tracker.find_best_gauss(**gauss_kwargs2) profile = gauss_dict['reconstructed_profile'] screen = gauss_dict['reconstructed_screen'] _label = '%.2f mm %i fs' % (streaker_offset_mm, profile.rms() * 1e15)