Exemple #1
0
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')
Exemple #2
0
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 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 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'
            })
Exemple #5
0
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
Exemple #6
0
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
Exemple #7
0
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')
Exemple #8
0
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)
Exemple #9
0
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)
Exemple #10
0
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)
Exemple #11
0
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')