示例#1
0
def get_instr_param_from_hdf_file(instr_name, param_name, timestamp=None,
                                  folder=None, **params):
    """
    Extracts the value for the parameter specified by param_name for the
    instrument specified by instr_name from an HDF file.
    :param instr_name: str specifying the instrument name in the HDF file
    :param param_name: str specifyin the name of the parameter to extract
    :param timestamp: str of the form YYYYMMDD_hhmmss.
    :param folder: path to HDF file
    :param params: keyword arguments
    :return: value corresponding to param_name
    """
    if folder is None:
        if timestamp is None:
            raise ValueError('Please provide either timestamp or folder.')
        folder = a_tools.get_folder(timestamp)

    d = {}
    get_params_from_hdf_file(
        d, {'instr_param_val': f'Instrument settings.{instr_name}.{param_name}'},
        folder=folder)

    if 'instr_param_val' not in d:
        raise KeyError(f'Parameter {param_name} not found for instrument '
                       f'{instr_name}.')
    return d['instr_param_val']
示例#2
0
def get_data_from_hdf_file(timestamp=None, data_file=None,
                           close_file=True, file_id=None, mode='r'):
    """
    Return the measurement data stored in Experimental Data group of the file
    specified by timestamp.
    :param timestamp: (str) measurement timestamp of form YYYYMMDD_hhmmsss
    :param data_file: (HDF file) opened HDF5 file
    :param close_file: (bool) whether to close the HDF5 file
    :return: numpy array with measurement data
    """
    if data_file is None:
        if timestamp is None:
            raise ValueError('Please provide either timestamp or data_file.')
        folder = a_tools.get_folder(timestamp)
        h5filepath = a_tools.measurement_filename(folder, file_id=file_id)
        data_file = h5py.File(h5filepath, mode)
    try:
        group = data_file['Experimental Data']
        if 'Data' in group:
            dataset = np.array(group['Data'])
        else:
            raise KeyError('Data was not found in Experimental Data.')
        if close_file:
            data_file.close()
    except Exception as e:
        data_file.close()
        raise e
    return dataset
 def _next_folder(self):
     ts = self._current_timestamp()
     if ts is None:
         return None
     tss = a_tools.get_timestamps_in_range(ts, label='')
     if len(tss) < 2:
         return None
     return a_tools.get_folder(tss[1])
示例#4
0
def get_clf_params_from_hdf_file(timestamp, meas_obj_names, for_ge=True,
                                 **params):
    """
    Extracts the acquistion classifier parameters for the meas_obj_names from
    an HDF file.
    First tries to take them from the Analysis group (timestamp corresponds to
    an ssro calibration measurement). If a key error is raised, it will take
    them from the qubit parameter acq_classifier_params.
    :param timestamp: timestamp string
    :param meas_obj_names: list of measured object names
    :param for_ge: flag indicating whether to ignore the f-level classification
        (sets means to 1000 for the f-level)
    :param params: keyword arguments passed to get_params_from_hdf_file
    :return: dict with meas_obj_names as keys and classifier params as values
    """

    try:
        params_dict = {}
        params_dict.update({f'{qbn}':
                                f'Analysis.Processed data.analysis_params.'
                                f'classifier_params.{qbn}'
                            for qbn in meas_obj_names})
        classifier_params = get_params_from_hdf_file(
            {},  params_dict, folder=a_tools.get_folder(timestamp), **params)
    except KeyError:
        params_dict = {}
        params_dict.update({f'{qbn}':
                                f'Instrument settings.{qbn}.'
                                f'acq_classifier_params'
                            for qbn in meas_obj_names})
        classifier_params = get_params_from_hdf_file(
            {},  params_dict, folder=a_tools.get_folder(timestamp), **params)

    if for_ge:
        for qbn in classifier_params:
            classifier_params[qbn]['means_'][2, :] = [1000, 1000]

    return classifier_params
示例#5
0
    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())
示例#6
0
def get_value_names_from_timestamp(timestamp, file_id=None, mode='r'):
    """
    Returns value_names from the HDF5 file specified by timestamp.
    :param timestamp: (str) measurement timestamp of form YYYYMMDD_hhmmsss
    :return: list of value_names
    """
    folder = a_tools.get_folder(timestamp)
    h5filepath = a_tools.measurement_filename(folder, file_id=file_id)
    data_file = h5py.File(h5filepath, mode)
    try:
        channel_names = get_hdf_param_value(data_file['Experimental Data'],
                                            'value_names')
        data_file.close()
        return channel_names
    except Exception as e:
        data_file.close()
        raise e
示例#7
0
def get_param_from_metadata_group(timestamp=None, param_name=None, file_id=None,
                                  data_file=None, close_file=True, mode='r'):
    """
    Get a parameter with param_name from the Experimental Metadata group in
    the HDF5 file specified by timestamp, or return the whole group if
    param_name is None.
    :param timestamp: (str) measurement timestamp of form YYYYMMDD_hhmmsss
    :param param_name: (str) name of a key in Experimental Metadata group
    :param data_file: (HDF file) opened HDF5 file
    :param close_file: (bool) whether to close the HDF5 file
    :return: the value of the param_name or the whole experimental metadata
    dictionary
    """
    if data_file is None:
        if timestamp is None:
            raise ValueError('Please provide either timestamp or data_file.')
        folder = a_tools.get_folder(timestamp)
        h5filepath = a_tools.measurement_filename(folder, file_id=file_id)
        data_file = h5py.File(h5filepath, mode)

    try:
        if param_name is None:
            group = data_file['Experimental Data']
            return read_dict_from_hdf5({}, group['Experimental Metadata'])

        group = data_file['Experimental Data']['Experimental Metadata']
        if param_name in group:
            group = group[param_name]
            param_value = OrderedDict()
            if isinstance(group, h5py._hl.dataset.Dataset):
                param_value = list(np.array(group).flatten())
                param_value = [x.decode('utf-8') if isinstance(x, bytes)
                               else x for x in param_value]
            else:
                param_value = read_dict_from_hdf5(param_value, group)
        elif param_name in group.attrs:
            param_value = get_hdf_param_value(group, param_name)
        else:
            raise KeyError(f'{param_name} was not found in metadata.')
        if close_file:
            data_file.close()
    except Exception as e:
        data_file.close()
        raise e
    return param_value
示例#8
0
def open_hdf_file(timestamp=None, folder=None, filepath=None, mode='r', file_id=None):
    """
    Opens the hdf5 file with flexible input parameters. If no parameter is given,
    opens the  hdf5 of the last measurement in reading mode.
    Args:
        :param timestamp: (str) measurement timestamp of form YYYYMMDD_hhmmsss
        :param folder: (str) path to file location
        :param mode filepath: (str) path to hdf5 file. Overwrites timestamp
            and folder
        :param mode: (str) mode to open the file ('r' for read),
            ('r+' for read/write)
        :param file_id: (str) file id
    :return: opened HDF5 file

    """
    if filepath is None:
        if folder is None:
            assert timestamp is not None
            folder = a_tools.get_folder(timestamp)
        filepath = a_tools.measurement_filename(folder, file_id=file_id)
    return h5py.File(filepath, mode)
示例#9
0
def plot_and_save_cz_amp_sweep(cphases, soft_sweep_params_dict, fit_res,
                               qbc_name, qbt_name, save_fig=True, show=True,
                               plot_guess=False, timestamp=None):

    sweep_param_name = list(soft_sweep_params_dict)[0]
    sweep_points = soft_sweep_params_dict[sweep_param_name]['values']
    unit = soft_sweep_params_dict[sweep_param_name]['unit']
    best_val = fit_res.model.func(np.pi, **fit_res.best_values)
    fit_points_init = fit_res.model.func(cphases, **fit_res.init_values)
    fit_points = fit_res.model.func(cphases, **fit_res.best_values)

    fig, ax = plt.subplots()
    ax.plot(cphases*180/np.pi, sweep_points, 'o-')
    ax.plot(cphases*180/np.pi, fit_points, '-r')
    if plot_guess:
        ax.plot(cphases*180/np.pi, fit_points_init, '--k')
    ax.hlines(best_val, cphases[0]*180/np.pi, cphases[-1]*180/np.pi)
    ax.vlines(180, sweep_points.min(), sweep_points.max())
    ax.set_ylabel('Flux pulse {} ({})'.format(sweep_param_name, unit))
    ax.set_xlabel('Conditional phase (rad)')
    ax.set_title('CZ {}-{}'.format(qbc_name, qbt_name))

    ax.text(0.5, 0.95, 'Best {} = {:.6f} ({})'.format(
        sweep_param_name, best_val*1e9 if unit=='s' else best_val, unit),
            horizontalalignment='center', verticalalignment='top',
            transform=ax.transAxes)
    if save_fig:
        import datetime
        import os
        fig_title = 'CPhase_amp_sweep_{}_{}'.format(qbc_name, qbt_name)
        fig_title = '{}--{:%Y%m%d_%H%M%S}'.format(
            fig_title, datetime.datetime.now())
        if timestamp is None:
            save_folder = a_tools.latest_data()
        else:
            save_folder = a_tools.get_folder(timestamp)
        filename = os.path.abspath(os.path.join(save_folder, fig_title+'.png'))
        fig.savefig(filename, bbox_inches='tight')
    if show:
        plt.show()
示例#10
0
def read_analysis_file(timestamp=None, filepath=None, data_dict=None,
                       file_id=None, ana_file=None, close_file=True, mode='r'):
    """
    Creates a data_dict from an AnalysisResults file as generated by analysis_v3
    :param timestamp: str with a measurement timestamp
    :param filepath: (str) path to file
    :param data_dict: dict where to store the file entries
    :param file_id: suffix to the usual HDF measurement file found from giving
        a measurement timestamp. Defaults to '_AnalysisResults,' the standard
        suffix created by analysis_v3
    :param ana_file: HDF file instance
    :param close_file: whether to close the HDF file at the end
    :param mode: str specifying the HDF read mode (if ana_file is None)
    :return: the data dictionary
    """
    if data_dict is None:
        data_dict = {}
    try:
        if ana_file is None:
            if filepath is None:
                if file_id is None:
                    file_id = 'AnalysisResults'
                folder = a_tools.get_folder(timestamp)
                filepath = a_tools.measurement_filename(folder,
                                                        file_id=f'_{file_id}')
            ana_file = h5py.File(filepath, mode)
        read_from_hdf(data_dict, ana_file)
        if close_file:
            ana_file.close()
    except Exception as e:
        if close_file:
            try:
                ana_file.close()
            except AttributeError:
                # there was an exception before reaching the line above where
                # ana_file is opened
                pass
        raise e
    return data_dict
示例#11
0
def load_settings_onto_instrument(
    instrument, load_from_instr=None, folder=None, label=None, timestamp=None, **kw
):
    """
    Loads settings from an hdf5 file onto the instrument handed to the
    function.
    By default uses the last hdf5 file in the datadirectory.
    By giving a label or timestamp another file can be chosen as the
    settings file.
    """

    older_than = None
    instrument_name = instrument.name
    success = False
    count = 0
    while success is False and count < 10:
        try:
            if folder is None:
                folder = a_tools.get_folder(
                    timestamp=timestamp, older_than=older_than, **kw
                )
            else:
                folder = folder
            filepath = a_tools.measurement_filename(folder)
            f = h5py.File(filepath, "r")
            sets_group = f["Instrument settings"]
            if load_from_instr is None:
                ins_group = sets_group[instrument_name]
            else:
                ins_group = sets_group[load_from_instr]
            print("Loaded Settings Successfully")
            success = True
        except:
            older_than = (
                os.path.split(folder)[0][-8:] + "_" + os.path.split(folder)[1][:6]
            )
            folder = None
            success = False
        count += 1

    if not success:
        print('Could not open settings for instrument "%s"' % (instrument_name))
        return False

    for parameter, value in ins_group.attrs.items():
        if value != "None":  # None is saved as string in hdf5
            if type(value) == str:
                if value == "False":
                    try:
                        instrument.set(parameter, False)
                    except:
                        print(
                            'Could not set parameter: "%s" to "%s" for instrument "%s"'
                            % (parameter, value, instrument_name)
                        )
                else:
                    try:
                        instrument.set(parameter, float(value))
                    except Exception:
                        try:
                            instrument.set(parameter, value)
                        except:
                            try:
                                instrument.set(parameter, int(value))
                            except:
                                print(
                                    'Could not set parameter: "%s" to "%s" for instrument "%s"'
                                    % (parameter, value, instrument_name)
                                )
            else:
                instrument.set(parameter, value)
    f.close()
    return True
示例#12
0
def load_settings_onto_instrument_v2(instrument,
                                     load_from_instr: str = None,
                                     label: str = '',
                                     filepath: str = None,
                                     timestamp: str = None):
    '''
    Loads settings from an hdf5 file onto the instrument handed to the
    function. By default uses the last hdf5 file in the datadirectory.
    By giving a label or timestamp another file can be chosen as the
    settings file.

    Args:
        instrument (instrument) : instrument onto which settings should be
            loaded
        load_from_instr (str) : optional name of another instrument from
            which to load the settings.
        label (str)           : label used for finding the last datafile
        filepath (str)        : exact filepath of the hdf5 file to load.
            if filepath is specified, this takes precedence over the file
            locating options (label, timestamp etc.).
        timestamp (str)       : timestamp of file in the datadir


    '''

    older_than = None
    folder = None
    instrument_name = instrument.name
    success = False
    count = 0
    # Will try multiple times in case the last measurements failed and
    # created corrupt data files.
    while success is False and count < 3:
        if filepath is None:
            folder = a_tools.get_folder(timestamp=timestamp,
                                        label=label,
                                        older_than=older_than)
            filepath = a_tools.measurement_filename(folder)
        try:

            f = h5py.File(filepath, 'r')
            snapshot = {}
            h5d.read_dict_from_hdf5(snapshot, h5_group=f['Snapshot'])

            if load_from_instr is None:
                ins_group = snapshot['instruments'][instrument_name]
            else:
                ins_group = snapshot['instruments'][load_from_instr]
            success = True
        except Exception as e:
            logging.warning('Exception occured reading from {}'.format(folder))
            logging.warning(e)
            # This check makes this snippet a bit more robust
            if folder is not None:
                older_than = os.path.split(folder)[0][-8:] \
                    + '_' + os.path.split(folder)[1][:6]
            # important to set all to None, otherwise the try except loop
            # will not look for an earlier data file
            folder = None
            filepath = None
            success = False
        count += 1

    if not success:
        logging.warning('Could not open settings for instrument "%s"' %
                        (instrument_name))
        return False

    for parname, par in ins_group['parameters'].items():
        try:
            if hasattr(instrument.parameters[parname], 'set'):
                instrument.set(parname, par['value'])
        except Exception as e:
            print('Could not set parameter: "{}" to "{}" '
                  'for instrument "{}"'.format(parname, par['value'],
                                               instrument_name))
            logging.warning(e)
    f.close()
    return True
示例#13
0
def process_filter_coeffs_dict(flux_distortion, datadir=None, default_dt=None):
    """
    Prepares a distortion dictionary that can be stored into pulsar
    {AWG}_{channel}_distortion_dict based on information provided in a
    dictionary.

    :param flux_distortion: (dict) A dictionary of the format defined in
        QuDev_transmon.DEFAULT_FLUX_DISTORTION. In particular, the following
        keys FIR_filter_list and IIR_filter are processed by this function.
        They are list of dicts with a key 'type' and further keys.
        type 'csv': load filter from the file specified under the key
            'filename'. In case of an IIR filter, the filter will in
            addition be scaled by the value in the key 'scale_IIR'.
        type 'Gaussian': can be used for FIR filters. Gaussian kernel with
            parameters 'sigma', 'nr_sigma', and 'dt' specified in the
            respective keys. See gaussian_filter_kernel()
        type 'expmod': can be used for IIR filters. A filter that inverts an
            exponential model specified by the keys 'A', 'B', 'tau', and 'dt'.
            See convert_expmod_to_IIR().
        If flux_distortion in addition contains the keys FIR and/or IIR,
        the filters specified as described above will be appended to those
        already existing in FIR/IIR.
        If flux_distortion is already in the format to be stored in pulsar,
        it is returned unchanged.
        If flux_distortion contains the key FIR_n_force_zero_coeffs, its value
        is passed to combine_FIR_filters when combining FIR filters.
    :param datadir: (str) base dir for loading csv files. If None,
        it is assumed that the specified filename includes the full path.
    :param default_dt: (float) AWG sampling period to be used in cases where
        'dt' is needed, but not specified in a filter dict.

    """

    filterCoeffs = {}
    for fclass in 'IIR', 'FIR':
        filterCoeffs[fclass] = flux_distortion.get(fclass, [])
        if fclass == 'IIR' and len(filterCoeffs[fclass]) > 1:
            # convert coefficient lists into list of filters so that we can
            # append if needed
            filterCoeffs[fclass] = [[[a], [
                b
            ]] for a, b in zip(filterCoeffs['IIR'][0], filterCoeffs['IIR'][1])]
        for f in flux_distortion.get(f'{fclass}_filter_list', []):
            if f['type'] == 'Gaussian' and fclass == 'FIR':
                coeffs = gaussian_filter_kernel(f.get('sigma', 1e-9),
                                                f.get('nr_sigma', 40),
                                                f.get('dt', default_dt))
            elif f['type'] == 'expmod' and fclass == 'IIR':
                expmod = f.get('expmod', None)
                if expmod is None:
                    expmod = [f.get('A'), f.get('B'), f.get('tau')]
                if not hasattr(expmod[0], '__iter__'):
                    expmod = [expmod]
                coeffs = convert_expmod_to_IIR(expmod,
                                               dt=f.get('dt', default_dt),
                                               direct=f.get('direct', False))
            elif f['type'] == 'csv':
                if datadir is not None:
                    filename = os.path.join(datadir,
                                            f['filename'].lstrip(os.sep))
                else:
                    filename = f['filename']
                if (not os.path.exists(filename)
                        and a_tools.fetch_data_dir is not None
                        and filename.startswith(a_tools.datadir)):
                    # If the missing file is supposed to be stored inside
                    # the data folder, we can try to fetch it if a
                    # fetch_data_dir is configured in a_tools.
                    ts = filename.lstrip(a_tools.datadir).lstrip(
                        os.sep)[:15].replace(os.sep, '_')  # extract timestamp
                    a_tools.get_folder(ts)  # try to fetch the folder
                if fclass == 'IIR':
                    coeffs = import_iir(filename)
                    scale_and_negate_IIR(
                        coeffs, f.get('scale_IIR',
                                      flux_distortion['scale_IIR']))
                else:
                    coeffs = np.loadtxt(filename)
            else:
                raise NotImplementedError(f"Unknown filter type {f['type']}")
            filterCoeffs[fclass].append(coeffs)

    if len(filterCoeffs['FIR']) > 0:
        filterCoeffs['FIR'] = [
            combine_FIR_filters(filterCoeffs['FIR'],
                                FIR_n_force_zero_coeffs=flux_distortion.get(
                                    'FIR_n_force_zero_coeffs', None))
        ]
    else:
        del filterCoeffs['FIR']
    if len(filterCoeffs['IIR']) > 0:
        filterCoeffs['IIR'] = [
            np.concatenate([i[0] for i in filterCoeffs['IIR']]),
            np.concatenate([i[1] for i in filterCoeffs['IIR']])
        ]
    else:
        del filterCoeffs['IIR']
    return filterCoeffs
示例#14
0
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
示例#15
0
def load_settings_onto_instrument_v2(
    instrument,
    load_from_instr: str = None,
    label: str = "",
    filepath: str = None,
    timestamp: str = None,
    ignore_pars: set = None,
):
    """
    Loads settings from an hdf5 file onto the instrument handed to the
    function. By default uses the last hdf5 file in the datadirectory.
    By giving a label or timestamp another file can be chosen as the
    settings file.

    Args:
        instrument (instrument) : instrument onto which settings should be
            loaded
        load_from_instr (str) : optional name of another instrument from
            which to load the settings.
        label (str)           : label used for finding the last datafile
        filepath (str)        : exact filepath of the hdf5 file to load.
            if filepath is specified, this takes precedence over the file
            locating options (label, timestamp etc.).
        timestamp (str)       : timestamp of file in the datadir


    """

    older_than = None
    folder = None
    instrument_name = instrument.name
    success = False
    count = 0
    # Will try multiple times in case the last measurements failed and
    # created corrupt data files.
    while success is False and count < 3:
        if filepath is None:
            folder = a_tools.get_folder(
                timestamp=timestamp, label=label, older_than=older_than
            )
            filepath = a_tools.measurement_filename(folder)
        try:

            f = h5py.File(filepath, "r")
            snapshot = {}
            read_dict_from_hdf5(snapshot, h5_group=f["Snapshot"])

            if load_from_instr is None:
                ins_group = snapshot["instruments"][instrument_name]
            else:
                ins_group = snapshot["instruments"][load_from_instr]
            success = True
        except Exception as e:
            logging.warning("Exception occured reading from {}".format(folder))
            logging.warning(e)
            # This check makes this snippet a bit more robust
            if folder is not None:
                older_than = (
                    os.path.split(folder)[0][-8:] + "_" + os.path.split(folder)[1][:6]
                )
            # important to set all to None, otherwise the try except loop
            # will not look for an earlier data file
            folder = None
            filepath = None
            success = False
        count += 1

    if not success:
        logging.warning(
            'Could not open settings for instrument "%s"' % (instrument_name)
        )
        return False

    for parname, par in ins_group["parameters"].items():
        try:
            if hasattr(instrument.parameters[parname], "set") and (
                par["value"] is not None
            ):
                if ignore_pars is None or parname not in ignore_pars:
                    par_value = par["value"]
                    if type(par_value) == str:
                        try:
                            instrument.parameters[parname].validate(par_value)
                        except TypeError:
                            # This detects that in the hdf5 file the parameter
                            # was saved as string due to type incompatibility
                            par_value = eval(par_value)
                    instrument.set(parname, par_value)
        except Exception as e:
            print(
                'Could not set parameter: "{}" to "{}" '
                'for instrument "{}"'.format(parname, par["value"], instrument_name)
            )
            logging.warning(e)
    f.close()
    return True
示例#16
0
def load_settings_onto_instrument(instrument, load_from_instr=None, folder=None,
                                  label=None,
                                  timestamp=None, **kw):
        '''
        Loads settings from an hdf5 file onto the instrument handed to the
        function.
        By default uses the last hdf5 file in the datadirectory.
        By giving a label or timestamp another file can be chosen as the
        settings file.
        '''

        older_than = None
        instrument_name = instrument.name
        success = False
        count = 0
        while success is False and count < 10:
            try:
                if folder is None:
                    folder = a_tools.get_folder(timestamp, older_than, **kw)
                else:
                    folder = folder
                filepath = a_tools.measurement_filename(folder)
                f = h5py.File(filepath, 'r')
                sets_group = f['Instrument settings']
                if load_from_instr is None:
                    ins_group = sets_group[instrument_name]
                else:
                    ins_group = sets_group[load_from_instr]
                print('Loaded Settings Successfully')
                success = True
            except:
                older_than = os.path.split(folder)[0][-8:] \
                             +'_'+ os.path.split(folder)[1][:6]
                folder = None
                success = False
            count += 1

        if not success:
            print('Could not open settings for instrument "%s"' % (
                instrument_name))
            return False

        for parameter, value in ins_group.attrs.items():
            if value != 'None':  # None is saved as string in hdf5
                if type(value) == str:
                    if value == 'False':
                        instrument.set(parameter, False)
                    else:
                        try:
                            instrument.set(parameter, float(value))
                        except Exception:
                            try:
                                instrument.set(parameter, value)
                            except:
                                print('Could not set parameter: "%s" to "%s" for instrument "%s"' % (
                                    parameter, value, instrument_name))
                        except Exception:
                            try:
                                instrument.set(parameter, int(value))
                            except:
                                print('Could not set parameter: "%s" to "%s" for instrument "%s"' % (
                                    parameter, value, instrument_name))
                else:
                    instrument.set(parameter, value)
        f.close()
        return True
示例#17
0
def load_settings(instrument,
                  label: str = '',
                  folder: str = None,
                  timestamp: str = None,
                  update=True,
                  **kw):
    '''
    Loads settings from an hdf5 file onto the instrument handed to the
    function. By default uses the last hdf5 file in the datadirectory.
    By giving a label or timestamp another file can be chosen as the
    settings file.

    Args:
        instrument (instrument) : instrument onto which settings
            should be loaded. Can be an instrument name (str) if update is
            set to False.
        label (str)           : label used for finding the last datafile
        folder (str)        : exact filepath of the hdf5 file to load.
            if filepath is specified, this takes precedence over the file
            locating options (label, timestamp etc.).
        timestamp (str)       : timestamp of file in the datadir
        update (bool, default True): if set to False, the loaded settings
            will be returned instead of updating them in the instrument.

    Kwargs:
        params_to_set (list)    : list of strings referring to the parameters
            that should be set for the instrument
    '''
    from numpy import array  # DO not remove. Used in eval(array(...))
    if folder is None:
        folder_specified = False
    else:
        folder_specified = True

    if isinstance(instrument, str) and not update:
        instrument_name = instrument
    else:
        instrument_name = instrument.name
    verbose = kw.pop('verbose', True)
    older_than = kw.pop('older_than', None)
    success = False
    count = 0
    # Will try multiple times in case the last measurements failed and
    # created corrupt data files.
    while success is False and count < 10:
        if folder is None:
            folder = a_tools.get_folder(timestamp=timestamp,
                                        label=label,
                                        older_than=older_than)
        if verbose:
            print('Folder used: {}'.format(folder))

        try:
            filepath = a_tools.measurement_filename(folder)
            f = h5py.File(filepath, 'r')
            sets_group = f['Instrument settings']
            ins_group = sets_group[instrument_name]

            if verbose:
                print('Loaded settings successfully from the HDF file.')

            params_to_set = kw.pop('params_to_set', None)
            if params_to_set is not None:
                if len(params_to_set) == 0:
                    log.warning('The list of parameters to update is empty.')
                if verbose and update:
                    print('Setting parameters {} for {}.'.format(
                        params_to_set, instrument_name))
                params_to_set = [(param, val)
                                 for (param, val) in ins_group.attrs.items()
                                 if param in params_to_set]
            else:
                if verbose and update:
                    print('Setting parameters for {}.'.format(instrument_name))
                params_to_set = [(param, val)
                                 for (param, val) in ins_group.attrs.items()
                                 if param not in getattr(
                                     instrument, '_params_to_not_load', {})]

            if not update:
                params_dict = {parameter : value for parameter, value in \
                        params_to_set}
                f.close()
                return params_dict

            for parameter, value in params_to_set:
                if parameter in instrument.parameters.keys() and \
                        hasattr(instrument.parameters[parameter], 'set'):
                    if value == 'None':  # None is saved as string in hdf5
                        try:
                            instrument.set(parameter, None)
                        except Exception:
                            print('Could not set parameter "%s" to "%s" for '
                                  'instrument "%s"' %
                                  (parameter, value, instrument_name))
                    elif value == 'False':
                        try:
                            instrument.set(parameter, False)
                        except Exception:
                            print('Could not set parameter "%s" to "%s" for '
                                  'instrument "%s"' %
                                  (parameter, value, instrument_name))
                    elif value == 'True':
                        try:
                            instrument.set(parameter, True)
                        except Exception:
                            print('Could not set parameter "%s" to "%s" for '
                                  'instrument "%s"' %
                                  (parameter, value, instrument_name))
                    else:
                        try:
                            instrument.set(parameter, int(value))
                        except Exception:
                            try:
                                instrument.set(parameter, float(value))
                            except Exception:
                                try:
                                    instrument.set(parameter, eval(value))
                                except Exception:
                                    try:
                                        instrument.set(parameter, value)
                                    except Exception:
                                        log.error('Could not set parameter '
                                                  '"%s" to "%s" '
                                                  'for instrument "%s"' %
                                                  (parameter, value,
                                                   instrument_name))

            success = True
            f.close()
        except Exception as e:
            logging.warning(e)
            success = False
            try:
                f.close()
            except:
                pass
            if timestamp is None and not folder_specified:
                print('Trying next folder.')
                older_than = os.path.split(folder)[0][-8:] \
                             + '_' + os.path.split(folder)[1][:6]
                folder = None
            else:
                break
        count += 1

    if not success:
        log.error('Could not open settings for instrument {}.'.format(
            instrument_name))
    print()
    return