Set the instrument (i.e. tell cellpy the file-type you use).

        Args:
            instrument: (str) in ["arbin", "bio-logic-csv", "bio-logic-bin",...]

        Sets the instrument used for obtaining the data (i.e. sets fileformat)
16007
def set_instrument(self, instrument=None):
        
        if instrument is None:
            instrument = self.tester

        if instrument in ["arbin", "arbin_res"]:
            self._set_arbin()
            self.tester = "arbin"

        elif instrument == "arbin_sql":
            self._set_arbin_sql()
            self.tester = "arbin"

        elif instrument == "arbin_experimental":
            self._set_arbin_experimental()
            self.tester = "arbin"

        elif instrument in ["pec", "pec_csv"]:
            self._set_pec()
            self.tester = "pec"

        elif instrument in ["biologics", "biologics_mpr"]:
            self._set_biologic()
            self.tester = "biologic"

        elif instrument == "custom":
            self._set_custom()
            self.tester = "custom"

        else:
            raise Exception(f"option does not exist: '{instrument}'")
1086845
def Import(context, request, instrumentname='sysmex_xs_500i'):
    
    # I don't really know how this file works, for this reason I added an 'Analysis Service selector'.
    # If non Analysis Service is selected, each 'data' column will be interpreted as a different Analysis Service. In
    # the case that an Analysis Service was selected, all the data columns would be interpreted as different data from
    # an unique Analysis Service.
    formitems = getForm(instrumentname, request)
    infile = formitems['infile']
    fileformat = formitems['fileformat']
    artoapply = formitems['artoapply']
    override = formitems['override']
    instrument = formitems['instrument']
    errors = []
    logs = []
    warns = []

    # Load the most suitable parser according to file extension/options/etc...
    parser = None
    if not hasattr(infile, 'filename'):
        errors.append(_("No file selected"))
    if fileformat == 'csv':
        # Get the Analysis Service selected, if there is one.
        analysis = request.form.get('analysis_service', None)
        if analysis:
            # Get default result key
            defaultresult = request.form.get('default_result', None)
            # Rise an error if default result is missing.
            parser = SysmexXS500iCSVParser(infile, analysis, defaultresult) if defaultresult \
                     else errors.append(t(_("You should introduce a default result key.",
                                             mapping={"fileformat": fileformat})))
        else:
            parser = SysmexXS500iCSVParser(infile)
    else:
        errors.append(t(_("Unrecognized file format ${fileformat}",
                          mapping={"fileformat": fileformat})))

    if parser:
        # Load the importer
        status = ['sample_received', 'attachment_due', 'to_be_verified']
        if artoapply == 'received':
            status = ['sample_received']
        elif artoapply == 'received_tobeverified':
            status = ['sample_received', 'attachment_due', 'to_be_verified']

        over = [False, False]
        if override == 'nooverride':
            over = [False, False]
        elif override == 'override':
            over = [True, False]
        elif override == 'overrideempty':
            over = [True, True]

        importer = SysmexXS500iImporter(parser=parser,
                                        context=context,
                                        allowed_ar_states=status,
                                        allowed_analysis_states=None,
                                        override=over,
                                        instrument_uid=instrument)
        tbex = ''
        try:
            importer.process()
        except:
            tbex = traceback.format_exc()
        errors = importer.errors
        logs = importer.logs
        warns = importer.warns
        if tbex:
            errors.append(tbex)

    results = {'errors': errors, 'log': logs, 'warns': warns}

    return json.dumps(results)
435870
def getInstruments(self):
        
        query = {"portal_type": "Instrument", "is_active": True}

        if self.getRestrictToMethod():
            query.update({
                "getMethodUIDs": {
                    "query": api.get_uid(self.getRestrictToMethod()),
                    "operator": "or",
                }
            })

        instruments = api.search(query, "bika_setup_catalog")
        items = map(lambda i: (i.UID, i.Title), instruments)

        instrument = self.getInstrument()
        if instrument:
            instrument_uids = map(api.get_uid, instruments)
            if api.get_uid(instrument) not in instrument_uids:
                items.append(
                    (api.get_uid(instrument), api.get_title(instrument)))

        items.sort(lambda x, y: cmp(x[1], y[1]))
        items.insert(0, ("", _("No instrument")))

        return DisplayList(list(items))
1332845
def add_instruments(self, *instruments):
        
        for instrument in instruments:
            if isinstance(instrument, ezibpy.utils.Contract):
                instrument = self.ibConn.contract_to_tuple(instrument)
                contractString = self.ibConn.contractString(instrument)
                self.instruments[contractString] = instrument
                self.ibConn.createContract(instrument)

        self.symbols = list(self.instruments.keys())
1101014
def load_scripts(self):
            


            # update scripts so that current settings do not get lost
            for index in range(self.tree_scripts.topLevelItemCount()):
                script_item = self.tree_scripts.topLevelItem(index)
                self.update_script_from_item(script_item)


            dialog = LoadDialog(elements_type="scripts", elements_old=self.scripts,
                                filename=self.gui_settings['scripts_folder'])
            if dialog.exec_():
                self.gui_settings['scripts_folder'] = str(dialog.txt_probe_log_path.text())
                scripts = dialog.get_values()
                added_scripts = set(scripts.keys()) - set(self.scripts.keys())
                removed_scripts = set(self.scripts.keys()) - set(scripts.keys())

                if 'data_folder' in list(self.gui_settings.keys()) and os.path.exists(self.gui_settings['data_folder']):
                    data_folder_name = self.gui_settings['data_folder']
                else:
                    data_folder_name = None

                # create instances of new instruments/scripts
                self.scripts, loaded_failed, self.instruments = Script.load_and_append(
                    script_dict={name: scripts[name] for name in added_scripts},
                    scripts=self.scripts,
                    instruments=self.instruments,
                    log_function=self.log,
                    data_path=data_folder_name)

                # delete instances of new instruments/scripts that have been deselected
                for name in removed_scripts:
                    del self.scripts[name]
10802
def set_string(_bytearray, byte_index, value, max_size):
    
    if six.PY2:
        assert isinstance(value, (str, unicode))
    else:
        assert isinstance(value, str)

    size = len(value)
    # FAIL HARD WHEN trying to write too much data into PLC
    if size > max_size:
        raise ValueError('size %s > max_size %s %s' % (size, max_size, value))
    # set len count on first position
    _bytearray[byte_index + 1] = len(value)

    i = 0
    # fill array which chr integers
    for i, c in enumerate(value):
        _bytearray[byte_index + 2 + i] = ord(c)

    # fill the rest with empty space
    for r in range(i + 1, _bytearray[byte_index]):
        _bytearray[byte_index + 2 + r] = ord(' ')
270642
def load_config(self, filepath=None):
        

        # load config or default if invalid

        def load_settings(filepath):
            """
            loads a old_gui settings file (a json dictionary)
            - path_to_file: path to file that contains the dictionary

            Returns:
                - instruments: depth 1 dictionary where keys are instrument names and values are instances of instruments
                - scripts:  depth 1 dictionary where keys are script names and values are instances of scripts
                - probes: depth 1 dictionary where to be decided....?
            """

            instruments_loaded = {}
            probes_loaded = {}
            scripts_loaded = {}

            if filepath and os.path.isfile(filepath):
                in_data = load_b26_file(filepath)

                instruments = in_data['instruments'] if 'instruments' in in_data else {}
                scripts = in_data['scripts'] if 'scripts' in in_data else {}
                probes = in_data['probes'] if 'probes' in in_data else {}

                try:
                    instruments_loaded, failed = Instrument.load_and_append(instruments)
                    if len(failed) > 0:
                        print(('WARNING! Following instruments could not be loaded: ', failed))

                    scripts_loaded, failed, instruments_loaded = Script.load_and_append(
                        script_dict=scripts,
                        instruments=instruments_loaded,
                        log_function=self.log,
                        data_path=self.gui_settings['data_folder'])

                    if len(failed) > 0:
                        print(('WARNING! Following scripts could not be loaded: ', failed))

                    probes_loaded, failed, instruments_loadeds = Probe.load_and_append(
                        probe_dict=probes,
                        probes=probes_loaded,
                        instruments=instruments_loaded)

                    self.log('Successfully loaded from previous save.')
                except ImportError:
                    self.log('Could not load instruments or scripts from file.')
                    self.log('Opening with blank GUI.')
            return instruments_loaded, scripts_loaded, probes_loaded

        config = None

        try:
            config = load_b26_file(filepath)
            config_settings = config['gui_settings']
            if config_settings['gui_settings'] != filepath:
                print((
                'WARNING path to settings file ({:s}) in config file is different from path of settings file ({:s})'.format(
                    config_settings['gui_settings'], filepath)))
            config_settings['gui_settings'] = filepath
        except Exception as e:
            if filepath:
                self.log('The filepath was invalid --- could not load settings. Loading blank GUI.')
            config_settings = self._DEFAULT_CONFIG


            for x in self._DEFAULT_CONFIG.keys():
                if x in config_settings:
                    if not os.path.exists(config_settings[x]):
                        try:
                            os.makedirs(config_settings[x])
                        except Exception:
                            config_settings[x] = self._DEFAULT_CONFIG[x]
                            os.makedirs(config_settings[x])
                            print(('WARNING: failed validating or creating path: set to default path'.format(config_settings[x])))
                else:
                    config_settings[x] = self._DEFAULT_CONFIG[x]
                    os.makedirs(config_settings[x])
                    print(('WARNING: path {:s} not specified set to default {:s}'.format(x, config_settings[x])))

        # check if file_name is a valid filename
        if filepath is not None and os.path.exists(os.path.dirname(filepath)):
            config_settings['gui_settings'] = filepath

        self.gui_settings = config_settings

        if(config):
            self.gui_settings_hidden = config['gui_settings_hidden']
        else:
            self.gui_settings_hidden['script_source_folder'] = ''

        self.instruments, self.scripts, self.probes = load_settings(filepath)


        self.refresh_tree(self.tree_gui_settings, self.gui_settings)
        self.refresh_tree(self.tree_scripts, self.scripts)
        self.refresh_tree(self.tree_settings, self.instruments)

        self._hide_parameters(filepath)
1074342
def refresh_instruments(self):
        
        def list_access_nested_dict(dict, somelist):
            """
            Allows one to use a list to access a nested dictionary, for example:
            listAccessNestedDict({'a': {'b': 1}}, ['a', 'b']) returns 1
            Args:
                dict:
                somelist:

            Returns:

            """
            return reduce(operator.getitem, somelist, dict)

        def update(item):
            if item.isExpanded():
                for index in range(item.childCount()):
                    child = item.child(index)

                    if child.childCount() == 0:
                        instrument, path_to_instrument = child.get_instrument()
                        path_to_instrument.reverse()
                        try: #check if item is in probes
                            value = instrument.read_probes(path_to_instrument[-1])
                        except AssertionError: #if item not in probes, get value from settings instead
                            value = list_access_nested_dict(instrument.settings, path_to_instrument)
                        child.value = value
                    else:
                        update(child)

        #need to block signals during update so that tree.itemChanged doesn't fire and the gui doesn't try to
        #reupdate the instruments to their current value
        self.tree_settings.blockSignals(True)

        for index in range(self.tree_settings.topLevelItemCount()):
            instrument = self.tree_settings.topLevelItem(index)
            update(instrument)

        self.tree_settings.blockSignals(False)
1138159
def setInstrumentParameters(self, instrpars):
        
        pri_header = self._image[0].header
        self.proc_unit = instrpars['proc_unit']
        instrpars['gnkeyword'] = 'ATODGAIN'  # hard-code for WFPC2 data
        instrpars['rnkeyword'] = None

        if self._isNotValid (instrpars['exptime'], instrpars['expkeyword']):
            instrpars['expkeyword'] = 'EXPTIME'

        for chip in self.returnAllChips(extname=self.scienceExt):
            chip._headergain = self.getInstrParameter(
                instrpars['gain'], pri_header, instrpars['gnkeyword']
            )
            chip._exptime = self.getInstrParameter(
                instrpars['exptime'], pri_header, instrpars['expkeyword']
            )
            # We need to treat Read Noise as a special case since it is
            # not populated in the WFPC2 primary header
            if instrpars['rnkeyword'] is None:
                chip._rdnoise = None
            else:
                chip._rdnoise = self.getInstrParameter(
                    instrpars['rdnoise'], pri_header, instrpars['rnkeyword']
                )

            if chip._headergain is None or chip._exptime is None:
                print('ERROR: invalid instrument task parameter')
                raise ValueError

        # We need to determine if the user has used the default readnoise/gain value
        # since if not, they will need to supply a gain/readnoise value as well
        usingDefaultGain = instrpars['gnkeyword'] == 'ATODGAIN'
        usingDefaultReadnoise = instrpars['rnkeyword'] in [None, 'None']

        # If the user has specified either the readnoise or the gain, we need to make sure
        # that they have actually specified both values.  In the default case, the readnoise
        # of the system depends on what the gain

        if usingDefaultReadnoise and usingDefaultGain:
            self._setchippars()
        elif usingDefaultReadnoise and not usingDefaultGain:
            raise ValueError("ERROR: You need to supply readnoise information\n when not using the default gain for WFPC2.")
        elif not usingDefaultReadnoise and usingDefaultGain:
            raise ValueError("ERROR: You need to supply gain information when\n not using the default readnoise for WFPC2.")
        else:
            # In this case, the user has specified both a gain and readnoise values.  Just use them as is.
            for chip in self.returnAllChips(extname=self.scienceExt):
                chip._gain = chip._headergain
            print("Using user defined values for gain and readnoise")

        # Convert the science data to electrons
        self.doUnitConversions()
635543
def _set_field(self, fieldname, bytestring, transfunc=None):
        """"""
        if getattr(self, fieldname):  # do not overwrite existing data
            return
        value = bytestring if transfunc is None else transfunc(bytestring)
        if DEBUG:
            stderr('Setting field "%s" to "%s"' % (fieldname, value))
        if fieldname == 'genre' and value.isdigit() and int(value) < len(ID3.ID3V1_GENRES):
            # funky: id3v1 genre hidden in a id3v2 field
            value = ID3.ID3V1_GENRES[int(value)]
        if fieldname in ("track", "disc"):
            if type(value).__name__ in ('str', 'unicode') and '/' in value:
                current, total = value.split('/')[:2]
                setattr(self, "%s_total" % fieldname, total)
            else:
                current = value
            setattr(self, fieldname, current)
        else:
            setattr(self, fieldname, value)
212290
def act(self):
        
        g = get_root(self).globals
        fname = filedialog.askopenfilename(
            defaultextension='.json',
            filetypes=[('json files', '.json'), ('fits files', '.fits')],
            initialdir=g.cpars['app_directory'])
        if not fname:
            g.clog.warn('Aborted load from disk')
            return False

        # load json
        if fname.endswith('.json'):
            with open(fname) as ifname:
                json_string = ifname.read()
        else:
            json_string = jsonFromFits(fname)

        # load up the instrument settings
        g.ipars.loadJSON(json_string)

        # load up the run parameters
        g.rpars.loadJSON(json_string)

        return True
980762
def set_default(self, field):
        

        # Record specification fields
        if field in RECORD_SPECS.index:
            # Return if no default to set, or if the field is already
            # present.
            if RECORD_SPECS.loc[field, 'write_default'] is None or getattr(self, field) is not None:
                return
            setattr(self, field, RECORD_SPECS.loc[field, 'write_default'])

        # Signal specification fields
        # Setting entire list default, not filling in blanks in lists.
        elif field in SIGNAL_SPECS.index:

            # Specific dynamic case
            if field == 'file_name' and self.file_name is None:
                self.file_name = self.n_sig * [self.record_name + '.dat']
                return

            item = getattr(self, field)

            # Return if no default to set, or if the field is already
            # present.
            if SIGNAL_SPECS.loc[field, 'write_default'] is None or item is not None:
                return

            # Set more specific defaults if possible
            if field == 'adc_res' and self.fmt is not None:
                self.adc_res = _signal._fmt_res(self.fmt)
                return

            setattr(self, field,
                   [SIGNAL_SPECS.loc[field, 'write_default']] * self.n_sig)
261668
def value(self):
        

        value = getattr(self.instrument, self.probe_name)
        self.buffer.append(value)

        return value
888412
def Import(context, request):
    
    form = request.form
    # TODO form['file'] sometimes returns a list
    infile = form['instrument_results_file'][0] if \
        isinstance(form['instrument_results_file'], list) \
        else form['instrument_results_file']
    override = form['results_override']
    artoapply = form['artoapply']
    instrument = form.get('instrument', None)
    errors = []
    logs = []

    # Load the most suitable parser according to file extension/options/etc...
    parser = None
    if not hasattr(infile, 'filename'):
        errors.append(_("No file selected"))
    parser = GCMSQP2010SECSVParser(infile)

    if parser:
        # Load the importer
        status = ['sample_received', 'attachment_due', 'to_be_verified']
        if artoapply == 'received':
            status = ['sample_received']
        elif artoapply == 'received_tobeverified':
            status = ['sample_received', 'attachment_due', 'to_be_verified']

        over = [False, False]
        if override == 'nooverride':
            over = [False, False]
        elif override == 'override':
            over = [True, False]
        elif override == 'overrideempty':
            over = [True, True]

        importer = GCMSQP2010SEImporter(parser=parser,
                                        context=context,
                                        allowed_ar_states=status,
                                        allowed_analysis_states=None,
                                        override=over,
                                        instrument_uid=instrument)
        tbex = ''
        try:
            importer.process()
        except:
            tbex = traceback.format_exc()
        errors = importer.errors
        logs = importer.logs
        warns = importer.warns
        if tbex:
            errors.append(tbex)

    results = {'errors': errors, 'log': logs, 'warns': warns}

    return json.dumps(results)
339411
def set_str2(s, base, context=None):
    
    return _apply_function_in_current_context(
        BigFloat,
        _set_from_whole_string,
        (s, base),
        context,
    )
1330356
def get_instrument(self):
        

        if isinstance(self.value, Instrument):
            instrument = self.value
            path_to_instrument = []
        else:
            instrument = None
            parent = self.parent()
            path_to_instrument = [self.name]
            while parent is not None:
                if isinstance(parent.value, Instrument):
                    instrument = parent.value
                    parent = None
                else:
                    path_to_instrument.append(parent.name)
                    parent = parent.parent()

        return instrument, path_to_instrument
1291148
def save_b26_file(filename, instruments=None, scripts=None, probes=None, overwrite=False, verbose=False):
    

    # if overwrite is false load existing data and append to new instruments
    if os.path.isfile(filename) and overwrite == False:
        data_dict = load_b26_file(filename)
    else:
        data_dict = {}

    if instruments is not None:
        if 'instruments' in data_dict:
            data_dict['instruments'].update(instruments)
        else:
            data_dict['instruments'] = instruments

    if scripts is not None:
        if 'scripts' in data_dict:
            data_dict['scripts'].update(scripts)
        else:
            data_dict['scripts'] = scripts

    if probes is not None:
        probe_instruments = list(probes.keys())
        if 'probes' in data_dict:
            # all the instruments required for old and new probes
            probe_instruments= set(probe_instruments + list(data_dict['probes'].keys()))
        else:
            data_dict.update({'probes':{}})

        for instrument in probe_instruments:
            if instrument in data_dict['probes'] and instrument in probes:
                # update the data_dict
                data_dict['probes'][instrument] = ','.join(set(data_dict['probes'][instrument].split(',') + probes[instrument].split(',')))
            else:
                data_dict['probes'].update(probes)

    if verbose:
        print(('writing ', filename))

    if data_dict != {}:

        # if platform == 'Windows':
        #     # windows can't deal with long filenames so we have to use the prefix '\\\\?\\'
        #     if len(filename.split('\\\\?\\')) == 1:
        #         filename = '\\\\?\\'+ filename
        # create folder if it doesn't exist
        if verbose:
            print(('filename', filename))
            print(('exists', os.path.exists(os.path.dirname(filename))))

        if os.path.exists(os.path.dirname(filename)) is False:
            # print(('creating', os.path.dirname(filename)))
            os.makedirs(os.path.dirname(filename))

        with open(filename, 'w') as outfile:
            tmp = json.dump(data_dict, outfile, indent=4)