Extract the qwikcord current measurements from val (CTavg, CTsum).
547935
def decode_qwikcord(packet, channel=1):
    """"""
    val = str(packet.get('val', ''))
    if len(val) != 16:
        return None
    if channel == 1:
        return int(val[6:12], 16)  # CTavg
    return int(val[12:], 16)
1259693
def read_data(self,variable_instance):
        
        if self.inst is None:
             return
        vp_func = variable_instance.variableproperty_set.filter(name=':FUNC').first()
        measure_function = ''
        if vp_func:
            if vp_func.value():
                measure_function = ':FUNC "%s";'%vp_func.value()

        trig_delay = 0.1
        if variable_instance.visavariable.device_property.upper() == 'PRESENT_VALUE':
            return self.parse_value(self.inst.query(':FETCH?'))
        m = re.search('(PRESENT_VALUE_CH)([0-9]*)', variable_instance.visavariable.device_property.upper())
        if m:
            return self.parse_value(
                        self.inst.query(':route:close (@%s);%s:TRIG:DEL %1.3f;:fetch?'%(m.group(2),measure_function,trig_delay)))
        return self.parse_value(self.inst.query(variable_instance.visavariable.device_property.upper()))
1029058
def load_crmod_volt(self, filename):
        
        with open(filename, 'r') as fid:
            nr_of_configs = int(fid.readline().strip())
            measurements = np.loadtxt(fid)
            if nr_of_configs != measurements.shape[0]:
                raise Exception(
                    'indicated number of measurements does not equal ' +
                    'to actual number of measurements')
        ABMN = self._crmod_to_abmn(measurements[:, 0:2])
        if self.configs is None:
            self.configs = ABMN
        else:
            # check that configs match
            if not np.all(ABMN == self.configs):
                raise Exception(
                    'previously stored configurations do not match new ' +
                    'configurations')

        # add data
        cid_mag = self.add_measurements(measurements[:, 2])
        cid_pha = self.add_measurements(measurements[:, 3])
        return [cid_mag, cid_pha]
979350
def _parse_radic_header(header_group, dipole_mode="all"):
    
    header = ''.join(header_group[1])

    nr_of_electrodes = _get_nr_of_electrodes(header.split('\n'))
    groups = itertools.groupby(
        header.split('\n'),
        lambda line: (
            line.startswith('[End Readings]') or
            line.startswith('[Begin Readings]')
        )
    )

    for key, group in groups:
        # there is only one group we are interested in: the first one
        if key:
            tmp = np.array(
                [
                    np.fromstring(
                        x, sep=' ', dtype=int
                    )
                    for x in next(groups)[1]
                ],
            )

            # curpots = tmp.T.copy()
            # curpots.resize(nr_of_electrodes + 2, tmp.shape[0])
            break

    # now we have the raw readings, pad them with zeros
    readings = []
    for raw_reading in tmp:
        voltage_rus = raw_reading[3:]
        # note that we now have the last electrode in here, too (so one more
        # than we have RUs. This electrode is always 0
        normed_reading = np.zeros(nr_of_electrodes)
        for i in voltage_rus[np.where(voltage_rus > 0)]:
            normed_reading[i - 1] = i
        readings.append(np.hstack((raw_reading[0:3], normed_reading)))

    # now generate the available configurations
    # add calibration
    reading_configs = {}
    for nr, reading in enumerate(readings):
        # nr = reading[0]
        A = reading[1]
        B = reading[2]

        voltages = []

        # loop over the RU-settings
        # we always measure to the next zero electrode
        for i in range(3, nr_of_electrodes + 3):
            for j in range(i + 1, nr_of_electrodes + 3):
                if reading[j] == 0:
                    M = i - 2
                    N = j - 2
                    all_active = ((reading[i] == 0) and (reading[j] == 0))
                    # print('a', 'b', 'm, n', A, B, M, N, all_active)
                    voltages.append((A, B, M, N, all_active))
                    break

        reading_configs[nr + 1] = np.array(voltages)
    return reading_configs
532509
def getVC(self):
        
        _Cr = decompose_GxE(self.fr['Cr'])
        RV = {}
        for key in list(_Cr.keys()):
            RV['var_%s' % key] = sp.array([var_CoXX(_Cr[key], self.Xr)])
        RV['var_g'] = sp.array([var_CoXX(self.fr['Cg'], self.XXh)])
        RV['var_n'] = sp.array([var_CoXX(self.fr['Cn'], sp.eye(self.XXh.shape[0]))])
        return RV
819038
def extract(what, calc_id, webapi=True):
    
    with performance.Monitor('extract', measuremem=True) as mon:
        if webapi:
            obj = WebExtractor(calc_id).get(what)
        else:
            obj = Extractor(calc_id).get(what)
        fname = '%s_%d.hdf5' % (what.replace('/', '-').replace('?', '-'),
                                calc_id)
        obj.save(fname)
        print('Saved', fname)
    if mon.duration > 1:
        print(mon)
399810
def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types):
        
        return self.kwargs[str(imt)].get_mean_and_stddevs(
            sctx, rctx, dctx, imt, stddev_types)
1232148
def parse_reports(parent_module):
    

    # get data
    data = collect_data(parent_module)

    # Filter to strip out ignored sample names
    data = parent_module.ignore_samples(data)

    # Reference data in parent module
    parent_module.picard_variantCalling_data = data

    if len(data) > 0:
        derive_data(data)

        # Write parsed data to a file
        parent_module.write_data_file(data, 'multiqc_picard_varientCalling')

        parent_module.general_stats_headers['DBSNP_TITV'] = {
            'title': 'TiTV ratio (known)',
            'description': "The Transition/Transversion ratio of the passing bi-allelic SNP calls made at SNP-database sites.",
            'min': 0,
            'scale': 'Blues',
            'shared_key': 'titv_ratio'
        }

        parent_module.general_stats_headers['NOVEL_TITV'] = {
            'title': 'TiTV ratio (novel)',
            'description': "The Transition/Transversion ratio of the passing bi-allelic SNP calls made at non-SNP-database sites.",
            'min': 0,
            'scale': 'Blues',
            'shared_key': 'titv_ratio'
        }

        parent_module.general_stats_headers['DBSNP_INS_DEL_RATIO'] = {
            'title': 'InDel ratio (known)',
            'description': "The Insertion / Deletion ratio of the passing bi-allelic SNP calls made at SNP-database sites.",
            'min': 0,
            'scale': 'Greens',
            'shared_key': 'indel_ratio',
            'hidden': True,
        }

        parent_module.general_stats_headers['NOVEL_INS_DEL_RATIO'] = {
            'title': 'InDel ratio (novel)',
            'description': "The Insertion / Deletion ratio of the passing bi-allelic SNP calls made at non-SNP-database sites.",
            'min': 0,
            'scale': 'Greens',
            'shared_key': 'indel_ratio',
            'hidden': True,
        }


        parent_module.general_stats_headers['total_called_variants_known'] = {
            'title': 'Called Variants (known)',
            'description': "Total counts of variants in SNP-database sites.",
            'shared_key': 'variant_count',
            'min': 0,
            'format': '{0:,.0f}',
            'hidden': True,
        }

        parent_module.general_stats_headers['total_called_variants_novel'] = {
            'title': 'Called Variants (novel)',
            'description': "Total counts of variants in non-SNP-database sites.",
            'shared_key': 'variant_count',
            'min': 0,
            'format': '{0:,.0f}',
            'hidden': True,
        }

        for s_name in data:
            if s_name not in parent_module.general_stats_data:
                parent_module.general_stats_data[s_name] = dict()
            parent_module.general_stats_data[s_name].update(data[s_name])


        # Variant Counts Bargraph
        parent_module.add_section(
            name='Variant Types',
            anchor='picard-variants-types',
            description='Variants that have been called, looking at variant types. Optionally filtered on label.',
            helptext="""
            Only passing variants are shown (i.e. non-filtered).\n
            SNPs are bi-allelic.\n
            Complex InDels are both an insertion and a deletion.
            """,
            plot=compare_variant_type_plot(data)
        )

        # Variant Counts Table
        parent_module.add_section(
            name='Variant Labels',
            anchor='picard-variants-labels',
            description='Variants that have been called, comparing with known variant sites.',
            helptext="""
            Only passing variants are shown (i.e. non-filtered).\n
            Variants contain bi-allelic SNPs, multi-allelic SNPs, simple and complex inserts and deletions.
            """,
            plot=compare_variants_label_plot(data)
        )

    return len(data)
342863
def get_quantmap(features, acc_col, quantfields):
    """"""
    qmap = {}
    for feature in features:
        feat_acc = feature.pop(acc_col)
        qmap[feat_acc] = {qf: feature[qf] for qf in quantfields}
    return qmap
1128106
def extract_aggregate(dstore, what):
    
    name, qstring = what.split('?', 1)
    info = get_info(dstore)
    qdic = parse(qstring, info)
    suffix = '-rlzs' if qdic['rlzs'] else '-stats'
    tagnames = qdic.get('tag', [])
    assetcol = dstore['assetcol']
    ltypes = qdic.get('loss_type', [])
    if ltypes:
        array = dstore[name + suffix][:, qdic['k'][0], ltypes[0]]
    else:
        array = dstore[name + suffix][:, qdic['k'][0]]
    aw = ArrayWrapper(assetcol.aggregate_by(tagnames, array), {})
    for tagname in tagnames:
        setattr(aw, tagname, getattr(assetcol.tagcol, tagname))
    aw.tagnames = encode(tagnames)
    if not ltypes:
        aw.extra = ('loss_type',) + tuple(info['loss_types'])
    return aw
25202
def get_info(self):
        
        return {
            self.get_plugin_name() : {
                "version" : self.get_version(),
                "params" : {
                    "icmp_check_interval" : self.conf['icmp_check_interval'],
                },
                "stats" : self.get_stats()
            }
        }
111973
def proc_val(key, val):
        
        float_keys = ('etot_conv_thr','forc_conv_thr','conv_thr','Hubbard_U','Hubbard_J0','defauss',
                      'starting_magnetization',)

        int_keys = ('nstep','iprint','nberrycyc','gdir','nppstr','ibrav','nat','ntyp','nbnd','nr1',
                    'nr2','nr3','nr1s','nr2s','nr3s','nspin','nqx1','nqx2','nqx3','lda_plus_u_kind',
                    'edir','report','esm_nfit','space_group','origin_choice','electron_maxstep',
                    'mixing_ndim','mixing_fixed_ns','ortho_para','diago_cg_maxiter','diago_david_ndim',
                    'nraise','bfgs_ndim','if_pos','nks','nk1','nk2','nk3','sk1','sk2','sk3','nconstr')

        bool_keys = ('wf_collect','tstress','tprnfor','lkpoint_dir','tefield','dipfield','lelfield',
                     'lorbm','lberry','lfcpopt','monopole','nosym','nosym_evc','noinv','no_t_rev',
                     'force_symmorphic','use_all_frac','one_atom_occupations','starting_spin_angle',
                     'noncolin','x_gamma_extrapolation','lda_plus_u','lspinorb','london',
                     'ts_vdw_isolated','xdm','uniqueb','rhombohedral','realxz','block',
                     'scf_must_converge','adaptive_thr','diago_full_acc','tqr','remove_rigid_rot',
                     'refold_pos')

        def smart_int_or_float(numstr):
            if numstr.find(".") != -1 or numstr.lower().find("e") != -1:
                return float(numstr)
            else:
                return int(numstr)

        try:
            if key in bool_keys:
                if val.lower() == ".true.":
                    return True
                elif val.lower() == ".false.":
                    return False
                else:
                    raise ValueError(key + " should be a boolean type!")

            if key in float_keys:
                return float(re.search(r"^-?\d*\.?\d*d?-?\d*", val.lower()).group(0).replace("d", "e"))

            if key in int_keys:
                return int(re.match(r"^-?[0-9]+", val).group(0))

        except ValueError:
            pass

        try:
            val = val.replace("d","e")
            return smart_int_or_float(val)
        except ValueError:
            pass

        if "true" in val.lower():
            return True
        if "false" in val.lower():
            return False

        m = re.match(r"^[\"|'](.+)[\"|']$", val)
        if m:
            return m.group(1)
664751
def retrieveVals(self):
        """"""
        if self.hasGraph('sys_loadavg'):
            self._loadstats = self._sysinfo.getLoadAvg()
            if self._loadstats:
                self.setGraphVal('sys_loadavg', 'load15min', self._loadstats[2])
                self.setGraphVal('sys_loadavg', 'load5min', self._loadstats[1])
                self.setGraphVal('sys_loadavg', 'load1min', self._loadstats[0])
        if self._cpustats and self.hasGraph('sys_cpu_util'):
            for field in self.getGraphFieldList('sys_cpu_util'):
                self.setGraphVal('sys_cpu_util', 
                                 field, int(self._cpustats[field] * 1000))
        if self._memstats:
            if self.hasGraph('sys_mem_util'):
                for field in self.getGraphFieldList('sys_mem_util'):
                    self.setGraphVal('sys_mem_util', 
                                     field, self._memstats[field])
            if self.hasGraph('sys_mem_avail'):
                for field in self.getGraphFieldList('sys_mem_avail'):
                    self.setGraphVal('sys_mem_avail', 
                                     field, self._memstats[field])
            if self.hasGraph('sys_mem_huge'):
                for field in ['Rsvd', 'Surp', 'Free']:
                    fkey = 'HugePages_' + field
                    if self._memstats.has_key(fkey):
                        self.setGraphVal('sys_mem_huge', field, 
                            self._memstats[fkey] * self._memstats['Hugepagesize'])
        if self.hasGraph('sys_processes'):
            if self._procstats is None:
                self._procstats = self._sysinfo.getProcessStats()
            if self._procstats:
                self.setGraphVal('sys_processes', 'running', 
                                 self._procstats['procs_running'])
                self.setGraphVal('sys_processes', 'blocked', 
                                 self._procstats['procs_blocked'])
        if self.hasGraph('sys_forks'):
            if self._procstats is None:
                self._procstats = self._sysinfo.getProcessStats()
            if self._procstats:
                self.setGraphVal('sys_forks', 'forks', 
                                 self._procstats['processes'])
        if self.hasGraph('sys_intr_ctxt'):
            if self._procstats is None:
                self._procstats = self._sysinfo.getProcessStats()
            if self._procstats:
                for field in self.getGraphFieldList('sys_intr_ctxt'):
                    self.setGraphVal('sys_intr_ctxt', field, 
                                     self._procstats[field])
        if self.hasGraph('sys_vm_paging'):
            if self._vmstats is None:
                self._vmstats = self._sysinfo.getVMstats()
            if self._vmstats:
                self.setGraphVal('sys_vm_paging', 'in', 
                                 self._vmstats['pgpgin'])
                self.setGraphVal('sys_vm_paging', 'out', 
                                 self._vmstats['pgpgout'])
        if self.hasGraph('sys_vm_swapping'):
            if self._vmstats is None:
                self._vmstats = self._sysinfo.getVMstats()
            if self._vmstats:
                self.setGraphVal('sys_vm_swapping', 'in', 
                                 self._vmstats['pswpin'])
                self.setGraphVal('sys_vm_swapping', 'out', 
                                 self._vmstats['pswpout'])
1220050
def load(self, dtype_out_time, dtype_out_vert=False, region=False,
             plot_units=False, mask_unphysical=False):
        """"""
        msg = ("Loading data from disk for object={0}, dtype_out_time={1}, "
               "dtype_out_vert={2}, and region="
               "{3}".format(self, dtype_out_time, dtype_out_vert, region))
        logging.info(msg + ' ({})'.format(ctime()))
        # Grab from the object if its there.
        try:
            data = self.data_out[dtype_out_time]
        except (AttributeError, KeyError):
            # Otherwise get from disk.  Try scratch first, then archive.
            try:
                data = self._load_from_disk(dtype_out_time, dtype_out_vert,
                                            region=region)
            except IOError:
                data = self._load_from_tar(dtype_out_time, dtype_out_vert)
        # Copy the array to self.data_out for ease of future access.
        self._update_data_out(data, dtype_out_time)
        # Apply desired plotting/cleanup methods.
        if mask_unphysical:
            data = self.var.mask_unphysical(data)
        if plot_units:
            data = self.var.to_plot_units(data, dtype_vert=dtype_out_vert)
        return data
1224452
def power_source_str(self):
        """"""
        if DeviceInfo.ATTR_POWER_SOURCE not in self.raw:
            return None
        return DeviceInfo.VALUE_POWER_SOURCES.get(self.power_source, 'Unknown')
679855
def _seg_to_vcf(vals):
    
    call_to_cn = {"+": 3, "-": 1}
    call_to_type = {"+": "DUP", "-": "DEL"}
    if vals["CALL"] not in ["0"]:
        info = ["FOLD_CHANGE_LOG=%s" % vals["MEAN_LOG2_COPY_RATIO"],
                "PROBES=%s" % vals["NUM_POINTS_COPY_RATIO"],
                "SVTYPE=%s" % call_to_type[vals["CALL"]],
                "SVLEN=%s" % (int(vals["END"]) - int(vals["START"])),
                "END=%s" % vals["END"],
                "CN=%s" % call_to_cn[vals["CALL"]]]
        return [vals["CONTIG"], vals["START"], ".", "N", "<%s>" % call_to_type[vals["CALL"]], ".",
                ".", ";".join(info), "GT", "0/1"]
538053
def accel_calibration(self):
        """"""
        self.calibration_state = self.CAL_ACC
        self.acc_dialog = SK8AccDialog(self.sk8.get_imu(self.spinIMU.value()), self)
        if self.acc_dialog.exec_() == QDialog.Rejected:
            return
        
        self.calculate_acc_calibration(self.acc_dialog.samples)