def prepare_cos_fit_dict(data_dict, keys_in=None, **params): fit_dicts = OrderedDict() data_to_proc_dict = hlp_mod.get_data_to_process(data_dict, keys_in) cp, sp, mospm, mobjn = hlp_mod.get_measurement_properties( data_dict, props_to_extract=['cp', 'sp', 'mospm', 'mobjn'], **params) indep_var_array = hlp_mod.get_param('indep_var_array', data_dict, raise_error=False, **params) if indep_var_array is None: indep_var_array = sp[0][mospm[mobjn][0]][0] plot_params = hlp_mod.get_param('plot_params', data_dict, default_value={}, **params) if 'setlabel' not in plot_params: plot_params['setlabel'] = 'CosFit' params_to_print = hlp_mod.get_param('params_to_print', data_dict, default_value=None, **params) fit_name = hlp_mod.get_param('fit_name', data_dict, raise_error=False, **params) for keyi, data in data_to_proc_dict.items(): data_fit = hlp_mod.get_msmt_data(data, cp, mobjn) cos_mod = lmfit.Model(fit_mods.CosFunc) guess_pars = fit_mods.Cos_guess(model=cos_mod, t=indep_var_array, data=data_fit) guess_pars['amplitude'].vary = True guess_pars['amplitude'].min = -10 guess_pars['offset'].vary = True guess_pars['frequency'].vary = True guess_pars['phase'].vary = True fit_name_to_set = fit_name if fit_name_to_set is None: fit_name_to_set = 'CosFit' fit_name_to_set += keyi fit_dicts[fit_name_to_set] = { 'fit_fn': fit_mods.CosFunc, 'fit_xvals': { 't': indep_var_array }, 'fit_yvals': { 'data': data_fit }, 'guess_pars': guess_pars, 'params_to_print': params_to_print, **plot_params } hlp_mod.add_param('fit_dicts', fit_dicts, data_dict, add_param_method='update')
def analyze_ramsey_fit_results(data_dict, keys_in, **params): # Get from the hdf5 file any parameters specified in # params_dict and numeric_params. mobjn = hlp_mod.get_measurement_properties(data_dict, props_to_extract=['mobjn'], **params) params_dict = {} s = 'Instrument settings.' + mobjn for trans_name in ['ge', 'ef']: params_dict[f'{mobjn}.{trans_name}_freq'] = s + f'.{trans_name}_freq' hlp_mod.get_params_from_hdf_file(data_dict, params_dict=params_dict, numeric_params=list(params_dict), **params) fit_names = hlp_mod.get_param('fit_names', params, raise_error=True) artificial_detuning_dict = hlp_mod.get_param('artificial_detuning_dict', data_dict, raise_error=True, **params) fit_dicts = hlp_mod.get_param('fit_dicts', data_dict, raise_error=True) for keyi in keys_in: trans_name = 'ef' if 'f' in keyi else 'ge' old_qb_freq = hlp_mod.get_param(f'{mobjn}.{trans_name}_freq', data_dict) if old_qb_freq != old_qb_freq: old_qb_freq = 0 hlp_mod.add_param(f'{mobjn}.old_freq', old_qb_freq, data_dict, add_param_method='replace') for fit_name in fit_names: key = fit_name + keyi fit_res = fit_dicts[key]['fit_res'] hlp_mod.add_param(f'{mobjn}.new_freq ' + fit_name, old_qb_freq + artificial_detuning_dict[mobjn] - fit_res.best_values['frequency'], data_dict, add_param_method='replace') hlp_mod.add_param(f'{mobjn}.new_freq ' + fit_name + '_stderr', fit_res.params['frequency'].stderr, data_dict, add_param_method='replace') hlp_mod.add_param(f'{mobjn}.T2_star ' + fit_name, fit_res.best_values['tau'], data_dict, add_param_method='replace') hlp_mod.add_param(f'{mobjn}.T2_star ' + fit_name + '_stderr', fit_res.params['tau'].stderr, data_dict, add_param_method='replace')
def dump_fit_results(self, entry_point): """ Saves the fit results from data_dict['fit_dicts'] :param entry_point: HDF5 file object to save to or a group within this file """ try: group = entry_point.create_group('Fit Results') except ValueError: # If the analysis group already exists. group = entry_point['Fit Results'] # Iterate over all the fit result dicts as not to overwrite # old/other analysis fit_dicts = hlp_mod.get_param('fit_dicts', self.data_dict) for fr_key, fit_dict in fit_dicts.items(): fit_res = fit_dict['fit_res'] try: fr_group = group.create_group(fr_key) except ValueError: # If the analysis sub group already exists # (each fr_key should be unique) # Delete the old group and create a new group # (overwrite). del group[fr_key] fr_group = group.create_group(fr_key) d = _convert_dict_rec(fit_res) h5d.write_dict_to_hdf5(d, entry_point=fr_group)
def __init__(self, data_dict, savedir=None, save_processed_data=True, save_figures=True, filename=None, file_suffix=None, extension='hdf5', filter_keys=None, add_timestamp=False, **save_figs_params): opt = np.get_printoptions() np.set_printoptions(threshold=sys.maxsize) try: self.data_dict = data_dict if filter_keys is None: filter_keys = [] self.filter_keys = filter_keys + ['fit_dicts', 'plot_dicts', 'axes', 'figures', 'data_files'] if savedir is None: savedir = hlp_mod.get_param('folders', data_dict) if savedir is None: savedir = hlp_mod.get_param( 'timestamps', data_dict, raise_error=True, error_message='Either folders or timestamps must be ' 'in data_dict if save_dir is not ' 'specified.') savedir = a_tools.get_folder(savedir[-1]) else: savedir = savedir[-1] self.savedir = savedir if file_suffix is None: file_suffix = 'AnalysisResults' if filename is not None: filename = filename + f'.{extension}' else: filename = self.savedir.split('\\')[-1] + f'_{file_suffix}.{extension}' if add_timestamp: filename = '{:%Y%m%d_%H%M%S}--{}'.format( datetime.datetime.now(), filename) self.filepath = self.savedir + '\\' + filename if save_processed_data: self.save_data_dict() if save_figures and hlp_mod.get_param('figures', self.data_dict) \ is not None: self.save_figures(**save_figs_params) np.set_printoptions(**opt) except Exception: np.set_printoptions(**opt) log.warning("Unhandled error during saving!") log.warning(traceback.format_exc())
def analyze_rabi_fit_results(data_dict, keys_in, **params): sp, mospm, mobjn = hlp_mod.get_measurement_properties( data_dict, props_to_extract=['sp', 'mospm', 'mobjn'], **params) physical_swpts = sp[0][mospm[mobjn][0]][0] fit_dicts = hlp_mod.get_param('fit_dicts', data_dict, raise_error=True) for keyi in keys_in: fit_res = fit_dicts['rabi_fit' + keyi]['fit_res'] rabi_amps_dict = extract_rabi_amplitudes(fit_res=fit_res, sweep_points=physical_swpts) for k, v in rabi_amps_dict.items(): hlp_mod.add_param(f'{mobjn}.{k}', v, data_dict, add_param_method='replace')
def prepare_ramsey_fitting(data_dict, keys_in, **params): fit_names = hlp_mod.get_param('fit_names', params, raise_error=True) sp, mospm, mobjn = hlp_mod.get_measurement_properties( data_dict, props_to_extract=['sp', 'mospm', 'mobjn'], **params) physical_swpts = sp[0][mospm[mobjn][0]][0] for i, fit_name in enumerate(fit_names): fit_mod.prepare_expdamposc_fit_dict( data_dict, keys_in=keys_in, meas_obj_names=mobjn, fit_name=fit_name, indep_var_array=physical_swpts, guess_params={'n': i + 1}, plot_params={ 'color': 'r' if i == 0 else 'C4', 'setlabel': 'expFit' if i == 0 else 'gaussFit' })
def ramsey_analysis(data_dict, keys_in, **params): data_to_proc_dict = hlp_mod.get_data_to_process(data_dict, keys_in) keys_in = list(data_to_proc_dict) prep_fit_dicts = params.pop('prep_fit_dicts', True) do_fitting = params.pop('do_fitting', True) prepare_plotting = params.pop('prepare_plotting', True) do_plotting = params.pop('do_plotting', True) # prepare fitting if prep_fit_dicts: fit_gaussian_decay = hlp_mod.get_param('fit_gaussian_decay', data_dict, default_value=True, **params) if fit_gaussian_decay: fit_names = ['exp_decay', 'gauss_decay'] else: fit_names = ['exp_decay'] params.update({'fit_names': fit_names}) prepare_ramsey_fitting(data_dict, keys_in, **params) if do_fitting: getattr(fit_mod, 'run_fitting')(data_dict, keys_in=list(data_dict['fit_dicts']), **params) # calculate new qubit frequecy, extract T2 star analyze_ramsey_fit_results(data_dict, keys_in, **params) # prepare plots if prepare_plotting: prepare_ramsey_plots(data_dict, data_to_proc_dict, **params) if do_plotting: getattr(plot_mod, 'plot')(data_dict, keys_in=list(data_dict['plot_dicts']), **params)
def get_rabi_textbox_properties(data_dict, textstr='', transition='ge', **params): mobjn = hlp_mod.get_measurement_properties( data_dict, props_to_extract=['mobjn'], **params) # Get from the hdf5 file any parameters specified in # params_dict and numeric_params. params_dict = {} s = 'Instrument settings.' + mobjn params_dict[f'{mobjn}.{transition}_amp180'] = \ s + f'.{transition}_amp180' params_dict[f'{mobjn}.{transition}_amp90scale'] = \ s + f'.{transition}_amp90_scale' hlp_mod.get_params_from_hdf_file(data_dict, params_dict=params_dict, numeric_params=list(params_dict), **params) # create textstring old_pipulse_val = hlp_mod.get_param(f'{mobjn}.{transition}_amp180', data_dict, default_value=0.0) # if old_pipulse_val != old_pipulse_val: # old_pipulse_val = 0 old_pihalfpulse_val = hlp_mod.get_param(f'{mobjn}.{transition}_amp90scale', data_dict, default_value=0.0) # if old_pihalfpulse_val != old_pihalfpulse_val: # old_pihalfpulse_val = 0 old_pihalfpulse_val *= old_pipulse_val textstr += (' $\pi-Amp$:\n {:.3f} V'.format( hlp_mod.get_param(f'{mobjn}.piPulse_value', data_dict)) + '$\pm$ {:.3f} V '.format( hlp_mod.get_param(f'{mobjn}.piPulse_stderr', data_dict)) + '\n$\pi/2-Amp$:\n {:.3f} V '.format( hlp_mod.get_param(f'{mobjn}.piHalfPulse_value', data_dict)) + ' $\pm$ {:.3f} V '.format( hlp_mod.get_param(f'{mobjn}.piHalfPulse_stderr', data_dict)) + '\n $\pi-Amp_{old}$ = ' + '{:.3f} V '.format( old_pipulse_val) + '\n$\pi/2-Amp_{old}$ = ' + '{:.3f} V '.format( old_pihalfpulse_val)) hp = -0.135 vp = -0.3 return textstr, hp, vp
def prepare_rabi_plots(data_dict, data_to_proc_dict, **params): cp, sp, mospm, mobjn = \ hlp_mod.get_measurement_properties( data_dict, props_to_extract=['cp', 'sp', 'mospm', 'mobjn'], **params) physical_swpts = sp[0][mospm[mobjn][0]][0] # check whether active reset was used reset_reps = hlp_mod.get_reset_reps_from_data_dict(data_dict) # prepare raw data plot if reset_reps != 0: swpts = deepcopy(physical_swpts) swpts = np.concatenate([ swpts, hlp_mod.get_cal_sweep_points( physical_swpts, cp, mobjn)]) swpts = np.repeat(swpts, reset_reps+1) swpts = np.arange(len(swpts)) plot_mod.prepare_1d_raw_data_plot_dicts( data_dict, xvals=swpts, **params) filtered_raw_keys = [k for k in data_dict.keys() if 'filter' in k] if len(filtered_raw_keys) > 0: plot_mod.prepare_1d_raw_data_plot_dicts( data_dict=data_dict, keys_in=filtered_raw_keys, figure_name='raw_data_filtered', **params) else: plot_mod.prepare_1d_raw_data_plot_dicts(data_dict, **params) plot_dicts = OrderedDict() # the prepare plot dict functions below also iterate over data_to_proc_dict, # however the prepare functions add all the data corresponding to keys_in # to the same figure. # Here we want a figure for each keyi for keyi, data in data_to_proc_dict.items(): figure_name = 'Rabi_' + keyi sp_name = mospm[mobjn][0] # plot data plot_mod.prepare_1d_plot_dicts(data_dict=data_dict, keys_in=[keyi], figure_name=figure_name, sp_name=sp_name, do_plotting=False, **params) if len(cp.states) != 0: # plot cal states plot_mod.prepare_cal_states_plot_dicts(data_dict=data_dict, keys_in=[keyi], figure_name=figure_name, sp_name=sp_name, do_plotting=False, **params) if 'fit_dicts' in data_dict: # plot fits fit_dicts = data_dict['fit_dicts'] fit_name = 'rabi_fit' + keyi textstr = '' plot_mod.prepare_fit_plot_dicts(data_dict=data_dict, figure_name=figure_name, fit_names=[fit_name], do_plotting=False, **params) fit_res = fit_dicts[fit_name]['fit_res'] piPulse_amp = hlp_mod.get_param(f'{mobjn}.piPulse_value', data_dict, default_value=0.0) # pi-pulse marker plot_dicts['piamp_marker_' + keyi] = { 'fig_id': figure_name, 'plotfn': 'plot_line', 'xvals': np.array([piPulse_amp]), 'yvals': np.array([fit_res.model.func(piPulse_amp, **fit_res.best_values)]), 'setlabel': '$\pi$ amp', 'color': 'r', 'marker': 'o', 'line_kws': {'markersize': plot_mod.get_default_plot_params( set_params=False, return_full_rc_params=True).get( 'lines.markersize', 2) + 2}, 'linestyle': '', 'legend_ncol': 2, 'legend_bbox_to_anchor': (1.02, -0.2), 'do_legend': True} # pi-pulse dashed line plot_dicts['piamp_hline_' + keyi] = { 'fig_id': figure_name, 'plotfn': 'plot_hlines', 'y': np.array([fit_res.model.func(piPulse_amp, **fit_res.best_values)]), 'xmin': physical_swpts[0], 'xmax': hlp_mod.get_cal_sweep_points(physical_swpts, cp, mobjn)[-1], 'colors': 'gray'} piHalfPulse_amp = hlp_mod.get_param(f'{mobjn}.piHalfPulse_value', data_dict, default_value=0.0) # piHalf-pulse marker plot_dicts['pihalfamp_marker_' + keyi] = { 'fig_id': figure_name, 'plotfn': 'plot_line', 'xvals': np.array([piHalfPulse_amp]), 'yvals': np.array([fit_res.model.func(piHalfPulse_amp, **fit_res.best_values)]), 'setlabel': '$\pi /2$ amp', 'color': 'm', 'marker': 'o', 'line_kws': {'markersize': plot_mod.get_default_plot_params( set_params=False, return_full_rc_params=True).get( 'lines.markersize', 2) + 2}, 'linestyle': '', 'do_legend': True, 'legend_bbox_to_anchor': (1.02, -0.2),#'right', 'legend_ncol': 2} # piHalf-pulse dashed line plot_dicts['pihalfamp_hline_' + keyi] = { 'fig_id': figure_name, 'plotfn': 'plot_hlines', 'y': np.array([fit_res.model.func(piHalfPulse_amp, **fit_res.best_values)]), 'xmin': physical_swpts[0], 'xmax': hlp_mod.get_cal_sweep_points(physical_swpts, cp, mobjn)[-1], 'colors': 'gray'} # plot textbox textstr, _, _ = get_rabi_textbox_properties( data_dict, textstr, transition='ef' if 'f' in keyi else 'ge', **params) plot_dicts['text_msg_' + keyi] = { 'fig_id': figure_name, 'ypos': -0.15, 'xpos': -0.13, 'horizontalalignment': 'left', 'verticalalignment': 'top', 'plotfn': 'plot_text', 'text_string': textstr} hlp_mod.add_param('plot_dicts', plot_dicts, data_dict, add_param_method='update')
def prepare_rbleakage_fit_dict(data_dict, keys_in=None, **params): """ :param data_dict: OrderedDict containing data to be processed and where processed data is to be stored :param keys_in: list of key names or dictionary keys paths in data_dict for the data to be processed :param params: keyword args do_fitting (bool, default: False): whether to perform the fit guess_params (dict, default: dict()): dict of guess pars for fit :return: adds fit_dicts to data_dict """ fit_dicts = OrderedDict() data_to_proc_dict = hlp_mod.get_data_to_process(data_dict, keys_in) cp, sp, mospm, mobjn = hlp_mod.get_measurement_properties( data_dict, props_to_extract=['cp', 'sp', 'mospm', 'mobjn'], **params) indep_var_array = hlp_mod.get_param('indep_var_array', data_dict, raise_error=False, **params) if indep_var_array is None: indep_var_array = sp[0][mospm[mobjn][0]][0] plot_params = hlp_mod.get_param('plot_params', data_dict, default_value={}, **params) if 'setlabel' not in plot_params: plot_params['setlabel'] = 'RBLeakageFit' params_to_print = hlp_mod.get_param('params_to_print', data_dict, default_value=None, **params) fit_name = hlp_mod.get_param('fit_name', data_dict, raise_error=False, **params) for keyi, data in data_to_proc_dict.items(): data_fit = hlp_mod.get_msmt_data(data, cp, mobjn) rbleak_mod = lmfit.Model(fit_mods.RandomizedBenchmarkingLeakage) guess_pars = rbleak_mod.make_params(pu=0.01, pd=0.05, p0=0) guess_params_new = hlp_mod.get_param('guess_params', data_dict, default_value=dict(), raise_error=False, **params) update_fit_guess_pars(guess_params_new, guess_pars) fit_name_to_set = fit_name if fit_name_to_set is None: fit_name_to_set = 'rbleak_fit' fit_name_to_set += keyi fit_dicts[fit_name_to_set] = { 'fit_fn': fit_mods.RandomizedBenchmarkingLeakage, 'fit_xvals': { 'numCliff': indep_var_array }, 'fit_yvals': { 'data': data_fit }, 'guess_pars': guess_pars, 'params_to_print': params_to_print, **plot_params } hlp_mod.add_param('fit_dicts', fit_dicts, data_dict, add_param_method='update') if params.get('do_fitting', False): run_fitting(data_dict, keys_in=list(fit_dicts), **params)
def save_figures(self, **params): """ Saves figures from self.data_dict['figures']. :param params: keyword arguments keys_in (list; default 'auto'): list of keys in data_dict['figures'] denoting which figures to save. If "auto", all figures will be saved. fmt (str; default: 'png'): figures format dpi (int; default: 300): figures dpi tag_tstamp(bool; default: True): whether to add the last timestamp in data_dict['timestamps'] to the figure title savebase (str; default: None): base of the figure name presentation_mode (bool; default: False): whether to save and 'svg file in addition to the figure """ keys_in = params.get('keys_in', 'auto') fmt = params.get('fmt', 'png') dpi = params.get('dpi', 300) tag_tstamp = params.get('tag_tstamp', True) savebase = params.get('savebase', None) if savebase is None: savebase = '' if tag_tstamp: timestamps = hlp_mod.get_param( 'timestamps', self.data_dict, raise_error=True, error_message='"tag_tstamp" == True but "timestamps" not found ' 'in data_dict.') tstag = '_' + timestamps[-1] else: tstag = '' # get figures from data_dict figs = hlp_mod.get_param('figures', self.data_dict, raise_error=True) if isinstance(figs, list): figs_dicts = OrderedDict() for fig_dict in figs: figs_dicts.update(fig_dict) else: figs_dicts = figs if keys_in == 'auto' or keys_in is None: keys_in = list(figs_dicts) for key in keys_in: if params.get('presentation_mode', False): savename = os.path.join(self.savedir, savebase + key + tstag + 'presentation' + '.' + fmt) figs_dicts[key].savefig(savename, bbox_inches='tight', format=fmt, dpi=dpi) savename = os.path.join(self.savedir, savebase + key + tstag + 'presentation' + '.svg') figs_dicts[key].savefig(savename, bbox_inches='tight', format='svg') else: savename = os.path.join(self.savedir, savebase + key + tstag + '.' + fmt) figs_dicts[key].savefig(savename, bbox_inches='tight', format=fmt, dpi=dpi) if params.get('close_figs', True): plt.close(figs_dicts[key])
def extract_data_hdf(data_dict=None, timestamps=None, params_dict=OrderedDict(), numeric_params=None, append_data=False, replace_data=False, **params): """ Extracts the data specified in params_dict and pumeric_params from each timestamp in timestamps and stores it into data_dict Args: data_dict (dict): place where extracted data will be stored, under the keys of params_dict timestamps (list): list of timestamps from where to extract data. If not specified, they will be taken from data_dict, and, if not found there, from get_timestamps params_dict (dict): if the form {storing_key: path_to_data}, where storing_key will be created in data_dict for storing the data indicated by path_to_data as a parameter name or a path + parameter name inside an HDF file. numeric_params (list or tuple): passed to get_params_from_hdf_file, see docstring there. append_data (bool): passed to add_measured_data_hdf, see docstring there replace_data (bool): passed to add_measured_data_hdf, see docstring there Keyword args (**params) passed to get_timestamps and add_measured_data_dict Returns data_dict containing the extracted data """ if data_dict is None: data_dict = OrderedDict() # Add flag that this is an analysis_v3 data_dict. This is used by the # Saving class. data_dict['is_data_dict'] = True if timestamps is None: timestamps = hlp_mod.get_param('timestamps', data_dict) if timestamps is None: get_timestamps(data_dict, **params) timestamps = hlp_mod.get_param('timestamps', data_dict) if isinstance(timestamps, str): timestamps = [timestamps] hlp_mod.add_param('timestamps', timestamps, data_dict, add_param_method='replace') data_dict['folders'] = [] for i, timestamp in enumerate(timestamps): folder = a_tools.get_folder(timestamp) data_dict['folders'] += [folder] # extract the data array and add it as data_dict['measured_data']. add_measured_data_hdf(data_dict, folder, append_data, replace_data) # extract exp_metadata separately, then call # combine_metadata_list, then extract all other parameters. # Otherwise, data_dict['exp_metadata'] is a list and it is unclear # from where to extract parameters. hlp_mod.get_params_from_hdf_file( data_dict, params_dict={ 'exp_metadata': 'Experimental Data.Experimental Metadata' }, folder=folder, add_param_method='append') if len(timestamps) > 1: # If data_dict['exp_metadata'] is a list, then the following functions # defines exp_metadata in data_dict as the combined version of the list # of metadata dicts extracted above for each timestamp combine_metadata_list(data_dict, **params) # call get_params_from_hdf_file which gets values for params # in params_dict and adds them to the dictionary data_dict params_dict_temp = params_dict params_dict = OrderedDict({ 'exp_metadata.sweep_parameter_names': 'sweep_parameter_names', 'exp_metadata.sweep_parameter_units': 'sweep_parameter_units', 'exp_metadata.value_names': 'value_names', 'exp_metadata.value_units': 'value_units', 'exp_metadata.measurementstrings': 'measurementstring' }) params_dict.update(params_dict_temp) hlp_mod.get_params_from_hdf_file(data_dict, params_dict=params_dict, numeric_params=numeric_params, folder=data_dict['folders'][-1], add_param_method=params.get( 'add_param_method', 'replace')) # add entries in data_dict for each readout channel and its corresponding # data array. add_measured_data_dict(data_dict, **params) return data_dict
def prepare_joint_residzz_fit_dict(data_dict, keys_in=None, **params): """ This function does a joint fit to Ramsey data without and with the other qubit in the |e> state. keys_in should have two entries corresponding to two 1d arrays for the data mentioned above, IN THAT ORDER. :param data_dict: OrderedDict containing data to be processed and where processed data is to be stored :param keys_in: list of key names or dictionary keys paths in data_dict for the data to be processed :param params: keyword args do_fitting (bool, default: False): whether to perform the fit guess_params (dict, default: dict()): dict of guess pars for fit :return: adds fit_dicts to data_dict """ if len(keys_in) != 2: raise ValueError('keys_in must have two entries.') fit_dicts = OrderedDict() data_to_proc_dict = hlp_mod.get_data_to_process(data_dict, keys_in) cp, sp, mospm, mobjn = hlp_mod.get_measurement_properties( data_dict, props_to_extract=['cp', 'sp', 'mospm', 'mobjn'], **params) indep_var_array = hlp_mod.get_param('indep_var_array', data_dict, raise_error=False, **params) if indep_var_array is None: indep_var_array = sp[0][mospm[mobjn][0]][0] plot_params = hlp_mod.get_param('plot_params', data_dict, default_value={}, **params) if 'setlabel' not in plot_params: plot_params['setlabel'] = 'JointResidZZFit' params_to_print = hlp_mod.get_param('params_to_print', data_dict, default_value=None, **params) data_wo_pulse = hlp_mod.get_msmt_data( list(data_to_proc_dict.values())[0], cp, mobjn) data_w_pulse = hlp_mod.get_msmt_data( list(data_to_proc_dict.values())[1], cp, mobjn) residzz_mod = lmfit.Model(fit_mods.ResidZZFuncJoint) guess_pars = fit_mods.exp_damp_osc_guess(model=residzz_mod, t=indep_var_array, data=data_wo_pulse) guess_pars['alpha'].value = -50e3 guess_pars['alpha'].max = 0 # guess_pars['x'].value = 12e-6*guess_pars['alpha'].value guess_pars['t11'].value = 12e-6 guess_pars['t11'].min = 0 guess_pars['offset'].value = np.mean(data_wo_pulse) guess_pars['amplitude1'].value = guess_pars['amplitude'].value # guess_pars['phase1'].value = guess_pars['phase'].value + np.pi/2 # guess_pars['amplitude'].min = -1 # guess_pars['amplitude1'].min = -1 # guess_pars['amplitude'].max = 1 # guess_pars['amplitude1'].max = 1 for par in guess_pars: guess_pars[par].vary = True guess_pars['offset'].vary = False guess_params_new = hlp_mod.get_param('guess_params', data_dict, default_value=dict(), raise_error=False, **params) update_fit_guess_pars(guess_params_new, guess_pars) fit_name = hlp_mod.get_param('fit_name', data_dict, raise_error=False, **params) fit_name_to_set = fit_name if fit_name_to_set is None: fit_name_to_set = 'residzz_fit' fit_name_to_set += ','.join(mobjn) fit_dicts[fit_name] = { 'fit_fn': fit_mods.ResidZZFuncJoint, 'fit_xvals': { 't': indep_var_array }, 'fit_yvals': { 'data': (data_wo_pulse, data_w_pulse) }, 'guess_pars': guess_pars, 'params_to_print': params_to_print, **plot_params } hlp_mod.add_param('fit_dicts', fit_dicts, data_dict, add_param_method='update') if params.get('do_fitting', False): run_fitting(data_dict, keys_in=list(fit_dicts), **params)
def prepare_ramsey_plots(data_dict, data_to_proc_dict, **params): cp, sp, mospm, mobjn = \ hlp_mod.get_measurement_properties( data_dict, props_to_extract=['cp', 'sp', 'mospm', 'mobjn'], **params) physical_swpts = sp[0][mospm[mobjn][0]][0] # check whether active reset was used reset_reps = hlp_mod.get_reset_reps_from_data_dict(data_dict) # prepare raw data plot if reset_reps != 0: swpts = deepcopy(physical_swpts) swpts = np.concatenate( [swpts, hlp_mod.get_cal_sweep_points(physical_swpts, cp, mobjn)]) swpts = np.repeat(swpts, reset_reps + 1) swpts = np.arange(len(swpts)) plot_mod.prepare_1d_raw_data_plot_dicts(data_dict, xvals=swpts, **params) filtered_raw_keys = [k for k in data_dict.keys() if 'filter' in k] if len(filtered_raw_keys) > 0: plot_mod.prepare_1d_raw_data_plot_dicts( data_dict=data_dict, keys_in=filtered_raw_keys, figure_name='raw_data_filtered', **params) else: plot_mod.prepare_1d_raw_data_plot_dicts(data_dict, **params) fit_names = hlp_mod.pop_param('fit_names', params, raise_error=True) artificial_detuning_dict = hlp_mod.get_param('artificial_detuning_dict', data_dict, raise_error=True, **params) plot_dicts = OrderedDict() # the prepare plot dict functions below also iterate over data_to_proc_dict, # however the prepare functions add all the data corresponding to keys_in # to the same figure. # Here we want a figure for each keyi for keyi, data in data_to_proc_dict.items(): figure_name = 'Ramsey_' + keyi sp_name = mospm[mobjn][0] # plot data plot_mod.prepare_1d_plot_dicts(data_dict=data_dict, keys_in=[keyi], figure_name=figure_name, sp_name=sp_name, do_plotting=False, **params) if len(cp.states) != 0: # plot cal states plot_mod.prepare_cal_states_plot_dicts(data_dict=data_dict, keys_in=[keyi], figure_name=figure_name, sp_name=sp_name, do_plotting=False, **params) if 'fit_dicts' in data_dict: textstr = '' T2_star_str = '' for i, fit_name in enumerate(fit_names): plot_mod.prepare_fit_plot_dicts(data_dict=data_dict, figure_name=figure_name, fit_names=[fit_name + keyi], plot_params={ 'legend_bbox_to_anchor': (1, -0.55), 'legend_ncol': 1 }, do_plotting=False, **params) fit_res = data_dict['fit_dicts'][fit_name + keyi]['fit_res'] if i != 0: textstr += '\n' textstr += \ ('$f_{{qubit \_ new \_ {{{key}}} }}$ = '.format( key=('exp' if i == 0 else 'gauss')) + '{:.6f} GHz '.format(hlp_mod.get_param( f'{mobjn}.new_freq '+fit_name, data_dict)*1e-9) + '$\pm$ {:.2E} GHz '.format(hlp_mod.get_param( f'{mobjn}.new_freq ' + fit_name + '_stderr', data_dict)*1e-9)) T2_star_str += \ ('\n$T_{{2,{{{key}}} }}^\star$ = '.format( key=('exp' if i == 0 else 'gauss')) + '{:.2f} $\mu$s'.format( fit_res.params['tau'].value*1e6) + ' $\pm$ {:.2f} $\mu$s'.format( fit_res.params['tau'].stderr*1e6)) fit_name = 'exp_decay' fit_res = data_dict['fit_dicts'][fit_name + keyi]['fit_res'] old_qb_freq = hlp_mod.get_param(f'{mobjn}.old_freq', data_dict) textstr += '\n$f_{qubit \_ old}$ = ' + '{:.6f} GHz '.format( old_qb_freq * 1e-9) textstr += ('\n$\Delta f$ = {:.4f} MHz '.format( (hlp_mod.get_param(f'{mobjn}.new_freq ' + fit_name, data_dict) - old_qb_freq) * 1e-6) + '$\pm$ {:.2E} MHz'.format( fit_res.params['frequency'].stderr * 1e-6) + '\n$f_{Ramsey}$ = ' + '{:.4f} MHz $\pm$ {:.2E} MHz'.format( fit_res.params['frequency'].value * 1e-6, fit_res.params['frequency'].stderr * 1e-6)) textstr += T2_star_str textstr += '\nartificial detuning = {:.2f} MHz'.format( artificial_detuning_dict[mobjn] * 1e-6) plot_dicts['text_msg_' + keyi] = { 'fig_id': figure_name, 'ypos': -0.3, 'xpos': -0.125, 'horizontalalignment': 'left', 'verticalalignment': 'top', 'plotfn': 'plot_text', 'text_string': textstr } plot_dicts['half_hline_' + keyi] = { 'fig_id': figure_name, 'plotfn': 'plot_hlines', 'y': 0.5, 'xmin': physical_swpts[0], 'xmax': hlp_mod.get_cal_sweep_points(physical_swpts, cp, mobjn)[-1], 'colors': 'gray' } hlp_mod.add_param('plot_dicts', plot_dicts, data_dict, add_param_method='update')
def add_measured_data_hdf(data_dict, folder=None, append_data=False, replace_data=False, **params): """ Extracts the dataset from the "Experimental Data" data of an HDF file and stores it in data_dict under "measured_data". Args: data_dict (dict): extracted dataset will be stored here under the key "measured_data" folder (str): full path to an hdf file append_data (bool): if True, and "measured_data" exists in data_dict, the new dataset will be appended replace_data (bool): if True, and "measured_data" exists in data_dict, it will be replaced by the new dataset Keyword args (**params) passed to helper_functions.py/add_param, see docstring there Returns data_dict containing the extracted dataset """ if folder is None: folder = hlp_mod.get_param('folders', data_dict, raise_error=True, **params) if len(folder) > 0: folder = folder[-1] h5mode = hlp_mod.get_param('h5mode', data_dict, default_value='r+', **params) dtype = hlp_mod.get_param('meas_data_dtype', data_dict, default_value=None, **params) if dtype is not None: log.warning(f'Setting Experimental data type: {dtype}') h5filepath = a_tools.measurement_filename(folder) data_file = h5py.File(h5filepath, h5mode) meas_data_array = np.array(data_file['Experimental Data']['Data'], dtype=dtype).T if 'measured_data' in data_dict: if replace_data: data_dict['measured_data'] = meas_data_array data_dict['data_replaced'] = True elif append_data: if not isinstance(data_dict['measured_data'], list): data_dict['measured_data'] = [data_dict['measured_data']] data_dict['measured_data'] += [meas_data_array] data_dict['data_appended'] = True else: raise ValueError( 'Both "append_data" and "replace_data" are False. ' 'Unclear how to add "measured_data" to data_dict.') else: data_dict['measured_data'] = meas_data_array return data_dict
def add_measured_data_dict(data_dict, **params): """ Adds to the data_dict the acquisition channels with the corresponding data array taken from "measured_data," which must exist in data_dict. Args: data_dict (dict): the measured data dict will be stored here Keyword args (**params) passed to helper_functions.py/get_param, helper_functions.py/pop_param, and helper_functions.py/add_param, see docstrings there This function expects to find the following parameters: - exp_metadata must exist in data_dict - value_names must exist in exp_metadata - meas_obj_value_names_map must exist in data_dict Other possible keywargs - TwoD (bool; default: False) whether the measurement had two sweep dimensions - compression_factor (int; default: 1) sequence compression factor (see Sequence.compress_2D_sweep) - percentage_done (int; default: 100) for interrupted measurements; indicates percentage of the total data that was acquired Returns data_dict containing the following entries: - acquisition channels (keys of the meas_obj_value_names_map) with the corresponding raw data - sweep points (if not already in data_dict) """ metadata = hlp_mod.get_param('exp_metadata', data_dict, raise_error=True) TwoD = hlp_mod.get_param('TwoD', data_dict, default_value=False, **params) compression_factor = hlp_mod.get_param('compression_factor', data_dict, default_value=1, **params) if 'measured_data' in data_dict and 'value_names' in metadata: value_names = metadata['value_names'] rev_movnm = hlp_mod.get_measurement_properties( data_dict, props_to_extract=['rev_movnm']) if rev_movnm is not None: data_key = lambda ro_ch, rev_movnm=rev_movnm: f'{rev_movnm[ro_ch]}.{ro_ch}' else: data_key = lambda ro_ch: ro_ch [ hlp_mod.add_param(data_key(ro_ch), [], data_dict) for ro_ch in value_names ] measured_data = data_dict.pop('measured_data') if not isinstance(measured_data, list): measured_data = [measured_data] for meas_data in measured_data: data = meas_data[-len(value_names):] if data.shape[0] != len(value_names): raise ValueError( 'Shape mismatch between data and ro channels.') mc_points = meas_data[:-len(value_names)] hsp = np.unique(mc_points[0]) if mc_points.shape[0] > 1: ssp, counts = np.unique(mc_points[1:], return_counts=True) if counts[0] != len(hsp): # ssro data hsp = np.tile(hsp, counts[0] // len(hsp)) # if needed, decompress the data # (assumes hsp and ssp are indices) if compression_factor != 1: hsp = hsp[:int(len(hsp) / compression_factor)] ssp = np.arange(len(ssp) * compression_factor) for i, ro_ch in enumerate(value_names): if TwoD: meas_data = np.reshape(data[i], (len(ssp), len(hsp))).T else: meas_data = data[i] hlp_mod.add_param(data_key(ro_ch), [meas_data], data_dict, add_param_method='append') for ro_ch in value_names: data = hlp_mod.pop_param(data_key(ro_ch), data_dict) if len(data) == 1: hlp_mod.add_param(data_key(ro_ch), data[0], data_dict) else: hlp_mod.add_param(data_key(ro_ch), np.array(data), data_dict) # check for and deal with interrupted measurements perc_done = hlp_mod.get_param('percentage_done', data_dict, default_value=100, **params) if perc_done < 100 and mc_points.shape[0] > 1: sp = hlp_mod.get_measurement_properties(data_dict, props_to_extract=['sp'], raise_error=False) if len(sp): # above call returns [] if sp not found sp_new = sp_mod.SweepPoints([sp.get_sweep_dimension(0)]) sp_new.add_sweep_dimension() for param_name, props_tup in sp.get_sweep_dimension(1).items(): sp_new.add_sweep_parameter(param_name, props_tup[0][:len(ssp)], props_tup[1], props_tup[2]) hlp_mod.add_param('sweep_points', sp_new, data_dict, **params) else: log.warning('sweep_points not found. Cannot deal with ' 'interrupted measurements.') else: raise ValueError('Either "measured_data" was not found in data_dict ' 'or "value_names" was not found in metadata. ' '"measured_data" was not added.') return data_dict
def prepare_residzz_fit_dict(data_dict, keys_in=None, **params): """ This function does a fit to Ramsey data with the other qubit in the |e> state. :param data_dict: OrderedDict containing data to be processed and where processed data is to be stored :param keys_in: list of key names or dictionary keys paths in data_dict for the data to be processed :param params: keyword args do_fitting (bool, default: False): whether to perform the fit guess_params (dict, default: dict()): dict of guess pars for fit :return: adds fit_dicts to data_dict """ fit_dicts = OrderedDict() data_to_proc_dict = hlp_mod.get_data_to_process(data_dict, keys_in) cp, sp, mospm, mobjn = hlp_mod.get_measurement_properties( data_dict, props_to_extract=['cp', 'sp', 'mospm', 'mobjn'], **params) indep_var_array = hlp_mod.get_param('indep_var_array', data_dict, raise_error=False, **params) if indep_var_array is None: indep_var_array = sp[0][mospm[mobjn][0]][0] plot_params = hlp_mod.get_param('plot_params', data_dict, default_value={}, **params) if 'setlabel' not in plot_params: plot_params['setlabel'] = 'ResidZZFit' params_to_print = hlp_mod.get_param('params_to_print', data_dict, default_value=None, **params) fit_name = hlp_mod.get_param('fit_name', data_dict, raise_error=False, **params) for keyi, data in data_to_proc_dict.items(): data_fit = hlp_mod.get_msmt_data(data, cp, mobjn) residzz_mod = lmfit.Model(fit_mods.ResidZZFunc) guess_pars = fit_mods.exp_damp_osc_guess(model=residzz_mod, t=indep_var_array, data=data_fit) guess_pars['alpha'].value = -50e3 guess_pars['x'].value = 12e-6 * guess_pars['alpha'].value guess_pars['offset'].value = np.mean(data_fit) # guess_pars['amplitude'].min = -1 # guess_pars['amplitude'].max = 1 guess_params_new = hlp_mod.get_param('guess_params', data_dict, default_value=dict(), raise_error=False, **params) update_fit_guess_pars(guess_params_new, guess_pars) fit_name_to_set = fit_name if fit_name_to_set is None: fit_name_to_set = 'residzz_fit' fit_name_to_set += keyi fit_dicts[fit_name_to_set] = { 'fit_fn': fit_mods.ResidZZFunc, 'fit_xvals': { 't': indep_var_array }, 'fit_yvals': { 'data': data_fit }, 'guess_pars': guess_pars, 'params_to_print': params_to_print, **plot_params } hlp_mod.add_param('fit_dicts', fit_dicts, data_dict, add_param_method='update') if params.get('do_fitting', False): run_fitting(data_dict, keys_in=list(fit_dicts), **params)
def process_pipeline(data_dict, processing_pipeline=None, append_pipeline=False, save_processed_data=True, save_figures=True, **params): """ Calls all the classes/functions found in processing_pipeline, which is a list of dictionaries of the form: [ {'node_name': function_name0, **node_params0}, {'node_name': function_name1, **node_params1}, ] All node functions must exist in the modules specified in the global vaiable "search_modules" define at the top of this module, and will process the data corresponding to the keys specified as "keys_in" in the **node_params of each node. Each node in the pipeline will put the processed data in the data_dict, under the key(s)/dictionary key path(s) specified in 'keys_out' in the the **node_params of each node. """ # Add flag that this is an analysis_v3 data_dict. This is used by the # Saving class. if 'is_data_dict' not in data_dict: data_dict['is_data_dict'] = True if processing_pipeline is None: processing_pipeline = hlp_mod.get_param('processing_pipeline', data_dict, raise_error=True) elif append_pipeline: for node_params in processing_pipeline: hlp_mod.add_param('processing_pipeline', [node_params], data_dict, append_value=True) # Instantiate a ProcessingPipeline instance in case it is an ordinary list processing_pipeline = ProcessingPipeline(processing_pipeline) for node_params in processing_pipeline: try: node = None for module in search_modules: try: node = getattr(module, node_params["node_name"]) break except AttributeError: continue if node is None: raise KeyError(f'Node function "{node_params["node_name"]}" ' f'not recognized') node(data_dict=data_dict, **node_params) except Exception: log.warning( f'Unhandled error during node {node_params["node_name"]}!') log.warning(traceback.format_exc()) if save_figures and hlp_mod.get_param('figures', data_dict) is None: log.warning('save_figures is True but there are no figures to save.') save_figures = False if save_processed_data or save_figures: save_mod.Save(data_dict, save_processed_data=save_processed_data, save_figures=save_figures, **params)
def prepare_expdamposc_fit_dict(data_dict, keys_in=None, **params): """ This function does a to Ramsey data :param data_dict: OrderedDict containing data to be processed and where processed data is to be stored :param keys_in: list of key names or dictionary keys paths in data_dict for the data to be processed :param params: keyword args do_fitting (bool, default: False): whether to perform the fit guess_params (dict, default: dict()): dict of guess pars for fit fit_name indep_var_array plot_params params_to_print :return: adds fit_dicts to data_dict """ fit_dicts = OrderedDict() data_to_proc_dict = hlp_mod.get_data_to_process(data_dict, keys_in) cp, sp, mospm, mobjn = hlp_mod.get_measurement_properties( data_dict, props_to_extract=['cp', 'sp', 'mospm', 'mobjn'], **params) indep_var_array = hlp_mod.get_param('indep_var_array', data_dict, raise_error=False, **params) if indep_var_array is None: indep_var_array = sp[0][mospm[mobjn][0]][0] plot_params = hlp_mod.get_param('plot_params', data_dict, default_value={}, **params) if 'setlabel' not in plot_params: plot_params['setlabel'] = 'ExpDampOscFit' params_to_print = hlp_mod.get_param('params_to_print', data_dict, default_value=None, **params) fit_name = hlp_mod.get_param('fit_name', data_dict, raise_error=False, **params) for keyi, data in data_to_proc_dict.items(): data_fit = hlp_mod.get_msmt_data(data, cp, mobjn) exp_damped_decay_mod = lmfit.Model(fit_mods.ExpDampOscFunc) guess_pars = fit_mods.exp_damp_osc_guess(model=exp_damped_decay_mod, data=data_fit, t=indep_var_array, n_guess=1) guess_pars['amplitude'].vary = False guess_pars['amplitude'].value = 0.5 guess_pars['frequency'].vary = True guess_pars['tau'].vary = True guess_pars['phase'].vary = True guess_pars['n'].vary = False guess_pars['oscillation_offset'].vary = False guess_pars['exponential_offset'].vary = True guess_params_new = hlp_mod.get_param('guess_params', data_dict, default_value=dict(), raise_error=False, **params) update_fit_guess_pars(guess_params_new, guess_pars) fit_name_to_set = fit_name if fit_name_to_set is None: fit_name_to_set = 'expdamposc_fit' fit_name_to_set += keyi fit_dicts[fit_name_to_set] = { 'fit_fn': fit_mods.ExpDampOscFunc, 'fit_xvals': { 't': indep_var_array }, 'fit_yvals': { 'data': data_fit }, 'guess_pars': guess_pars, 'params_to_print': params_to_print, 'plot_params': plot_params } hlp_mod.add_param('fit_dicts', fit_dicts, data_dict, add_param_method='update') if params.get('do_fitting', False): run_fitting(data_dict, keys_in=list(fit_dicts), **params)