Get sensitivity, specificity and accuracy given gff_file, and a query range
    that look like "chr1:1-10000".
499964
def get_accuracy(query, gff_file, evidences_bed, sizesfile, type, key):
    
    from jcvi.formats.bed import evaluate

    bed_file = get_bed_file(gff_file, type, key)
    b = evaluate([bed_file, evidences_bed, sizesfile, "--query={0}".format(query)])

    return b
215618
def _chien_search_fast(self, sigma):
        ''''''
        # TODO: doesn't work when fcr is different than 1 (X values are incorrectly "shifted"...)
        # TODO: try to mix this approach with the optimized walk on only interesting values, implemented in _chien_search_faster()
        X = []
        j = []
        p = GF2int(self.generator)
        if not hasattr(self, 'const_poly'): self.const_poly = [GF2int(self.generator)**(i+self.fcr) for i in _range(self.gf2_charac, -1, -1)] # constant polynomial that will allow us to update the previous polynomial evaluation to get the next one
        const_poly = self.const_poly # caching for more efficiency since it never changes
        ev_poly, ev = sigma.evaluate_array( p**1 ) # compute the first polynomial evaluation
        # Try for each possible location
        for l in _range(1, self.gf2_charac+1): # range 1:256 is important: if you use range 0:255, if the last byte of the ecc symbols is corrupted, it won't be correctable! You need to use the range 1,256 to include this last byte.
            #l = (i+self.fcr)

            # Check if it's a root for the polynomial
            if ev == 0: # If it's 0, then bingo! It's an error location
                # Compute the error location polynomial X (will be directly used to compute the errors magnitudes inside the Forney algorithm)
                X.append( p**(-l) )
                # Compute the coefficient position (not the error position, it's actually the reverse: we compute the degree of the term where the error is located. To get the error position, just compute n-1-j).
                # This is different than the notes, I think the notes were in error
                # Notes said j values were just l, when it's actually 255-l
                j.append(self.gf2_charac - l)

            # Update the polynomial evaluation for the next iteration
            # we simply multiply each term[k] with alpha^k (where here alpha = p = GF2int(generator)).
            # For more info, see the presentation by Andrew Brown, or this one: http://web.ntpu.edu.tw/~yshan/BCH_decoding.pdf
            # TODO: parallelize this loop
            for i in _range(1, len(ev_poly)+1): # TODO: maybe the fcr != 1 fix should be put here?
                ev_poly[-i] *= const_poly[-i]
            # Compute the new evaluation by just summing
            ev = sum(ev_poly)

        return X, j
1089323
def loadCoeffs(filename):
    
    gh = []
    gh2arr = []
    with open(filename) as f:
        text = f.readlines()
        for a in text:
            if a[:2] == 'g ' or a[:2] == 'h ':
                b = a.split()[3:]
                b = [float(x) for x in b]
                gh2arr.append(b)
        gh2arr = np.array(gh2arr).transpose()
        N = len(gh2arr)
        for i in range(N):
            if i < 19:
                for j in range(120):
                    gh.append(gh2arr[i][j])
            else:
                for p in gh2arr[i]:
                    gh.append(p)
        gh.append(0)
        return gh
724927
def __findout_range(self, name, decl_type, recursive):
        """"""
        if not self._optimized:
            self._logger.debug(
                'running non optimized query - optimization has not been done')
            decls = self.declarations
            if recursive:
                decls = make_flatten(self.declarations)
            if decl_type:
                decls = [d for d in decls if isinstance(d, decl_type)]
            return decls

        if name and templates.is_instantiation(name):
            # templates has tricky mode to compare them, so lets check the
            # whole range
            name = None

        if name and decl_type:
            impl_match = scopedef_t._impl_matchers[scopedef_t.decl](name=name)
            if impl_match.is_full_name():
                name = impl_match.decl_name_only
            if recursive:
                self._logger.debug(
                    'query has been optimized on type and name')
                return self._type2name2decls[decl_type].get(name, [])

            self._logger.debug(
                'non recursive query has been optimized on type and name')
            return self._type2name2decls_nr[decl_type].get(name, [])
        elif decl_type:
            if recursive:
                self._logger.debug('query has been optimized on type')
                return self._type2decls[decl_type]

            self._logger.debug(
                'non recursive query has been optimized on type')
            return self._type2decls_nr[decl_type]
        else:
            if recursive:
                self._logger.debug((
                    'query has not been optimized ( hint: query does not ' +
                    'contain type and/or name )'))
                return self._all_decls

            self._logger.debug((
                'non recursive query has not been optimized ( hint: ' +
                'query does not contain type and/or name )'))
            return self._all_decls_not_recursive
1108467
def get_range(self):
        """"""
        (min, max) = (100000, -1)
        for cont in self.bar:
            for note in cont[2]:
                if int(note) < int(min):
                    min = note
                elif int(note) > int(max):
                    max = note
        return (min, max)
306090
def gwcalctyp(self):
        """"""
        dig0 = str(self._SIGMA_TYPES[self.type])
        dig1 = str(self._SC_MODES[self.sc_mode])
        return dig1.strip() + dig0.strip()
307377
def _is_version_range(req):
    """"""

    assert len(req.specifier) > 0
    specs = list(req.specifier)
    if len(specs) == 1:
        # "foo > 2.0" or "foo == 2.4.3"
        return specs[0].operator != '=='
    else:
        # "foo > 2.0, < 3.0"
        return True
977595
def get_range_string(self):
    """"""
    return self.left.chr+":"+str(self.left.end)+'/'+self.right.chr+":"+str(self.right.start)
921959
def _get_data_dtype(self):
        """"""

        pkhrec = [
            ('GP_PK_HEADER', GSDTRecords.gp_pk_header),
            ('GP_PK_SH1', GSDTRecords.gp_pk_sh1)
        ]
        pk_head_dtype = np.dtype(pkhrec)

        def get_lrec(cols):
            lrec = [
                ("gp_pk", pk_head_dtype),
                ("version", np.uint8),
                ("satid", np.uint16),
                ("time", (np.uint16, 5)),
                ("lineno", np.uint32),
                ("chan_id", np.uint8),
                ("acq_time", (np.uint16, 3)),
                ("line_validity", np.uint8),
                ("line_rquality", np.uint8),
                ("line_gquality", np.uint8),
                ("line_data", (np.uint8, cols))
            ]

            return lrec

        # each pixel is 10-bits -> one line of data has 25% more bytes
        # than the number of columns suggest (10/8 = 1.25)
        visir_rec = get_lrec(int(self.mda['number_of_columns'] * 1.25))
        number_of_visir_channels = len(
            [s for s in self.mda['channel_list'] if not s == 'HRV'])
        drec = [('visir', (visir_rec, number_of_visir_channels))]

        if self.mda['available_channels']['HRV']:
            hrv_rec = get_lrec(int(self.mda['hrv_number_of_columns'] * 1.25))
            drec.append(('hrv', (hrv_rec, 3)))

        return np.dtype(drec)
192229
def _get_min_val(spaceshift, *params):
    """

    # Get parameters from tuples
    spacing, shift = spaceshift
    n, fI, fC, r, r_def, error, reim, cvar, verb, plot, log = params

    # Get filter for these parameters
    dlf = _calculate_filter(n, spacing, shift, fI, r_def, reim, 'filt')

    # Calculate rhs-response with this filter
    k = dlf.base/r[:, None]

    # Loop over transforms
    for i, f in enumerate(fC):
        # Calculate lhs and rhs; rhs depends on ftype
        lhs = f.lhs(k)
        if f.name == 'j2':
            rhs0 = np.dot(lhs[0], getattr(dlf, 'j0'))/r
            rhs1 = np.dot(lhs[1], getattr(dlf, 'j1'))/r**2
            rhs = rhs0 + rhs1
        else:
            rhs = np.dot(lhs, getattr(dlf, f.name))/r

        # Get relative error
        rel_error = np.abs((rhs - f.rhs)/f.rhs)

        # Get indices where relative error is bigger than error
        imin0 = np.where(rel_error > error)[0]

        # Find first occurrence of failure
        if np.all(rhs == 0) or np.all(np.isnan(rhs)):
            # if all rhs are zeros or nans, the filter is useless
            imin0 = 0

        elif imin0.size == 0:
            # if imin0.size == 0:  # empty array, all rel_error < error.
            imin0 = rhs.size-1  # set to last r
            if verb > 0 and log['warn-r'] == 0:
                print('* WARNING :: all data have error < ' + str(error) +
                      '; choose larger r or set error-level higher.')
                log['warn-r'] = 1  # Only do this once

        else:
            # Kind of a dirty hack: Permit to jump up to four bad values,
            # resulting for instance from high rel_error from zero crossings
            # of the transform pair. Should be made an input argument or
            # generally improved.
            if imin0.size > 4:
                imin0 = np.max([0, imin0[4]-5])
            else:  # just take the first one (no jumping allowed; normal case)
                imin0 = np.max([0, imin0[0]-1])
            # Note that both version yield the same result if the failure is
            # consistent.

        # Depending on cvar, store minimum amplitude or 1/maxr
        if cvar == 'amp':
            min_val0 = np.abs(rhs[imin0])
        else:
            min_val0 = 1/r[imin0]

        # Check if this inversion is better than previous ones
        if i == 0:  # First run, store these values
            imin = dc(imin0)
            min_val = dc(min_val0)
        else:  # Replace imin, min_val if this one is better
            if min_val0 > min_val:
                min_val = dc(min_val0)
                imin = dc(imin0)

        # QC plot
        if plot > 2:
            _plot_inversion(f, rhs, r, k, imin0, spacing, shift, cvar)

    # If verbose, print progress
    if verb > 1:
        log = _print_count(log)

    # If there is no point with rel_error < error (imin=0) it returns np.inf.
    return np.where(imin == 0, np.inf, min_val)
992691
def QueryInfoKey(key):
  """"""
  regqueryinfokey = advapi32["RegQueryInfoKeyW"]
  regqueryinfokey.restype = ctypes.c_long
  regqueryinfokey.argtypes = [
      ctypes.c_void_p, ctypes.c_wchar_p, LPDWORD, LPDWORD, LPDWORD, LPDWORD,
      LPDWORD, LPDWORD, LPDWORD, LPDWORD, LPDWORD,
      ctypes.POINTER(FileTime)
  ]

  null = LPDWORD()
  num_sub_keys = ctypes.wintypes.DWORD()
  num_values = ctypes.wintypes.DWORD()
  ft = FileTime()
  rc = regqueryinfokey(key.handle, ctypes.c_wchar_p(), null, null,
                       ctypes.byref(num_sub_keys), null, null,
                       ctypes.byref(num_values), null, null, null,
                       ctypes.byref(ft))
  if rc != ERROR_SUCCESS:
    raise ctypes.WinError(2)

  last_modified = ft.dwLowDateTime | (ft.dwHighDateTime << 32)
  last_modified = last_modified // 10000000 - WIN_UNIX_DIFF_MSECS

  return (num_sub_keys.value, num_values.value, last_modified)
1159908
def check_case_sensitivity (self):
        
        if os.name != 'nt':
            return
        path = self.get_os_filename()
        realpath = get_nt_filename(path)
        if path != realpath:
            self.add_warning(_("The URL path %(path)r is not the same as the "
                            "system path %(realpath)r. You should always use "
                            "the system path in URLs.") % \
                            {"path": path, "realpath": realpath},
                               tag=WARN_FILE_SYSTEM_PATH)
1154146
def __query_spec(self):
        """"""
        spec = self.__spec
        if not self.__is_command and "$query" not in self.__spec:
            spec = SON({"$query": self.__spec})
        if self.__ordering:
            spec["$orderby"] = self.__ordering
        if self.__explain:
            spec["$explain"] = True
        if self.__hint:
            spec["$hint"] = self.__hint
        if self.__comment:
            spec["$comment"] = self.__comment
        if self.__snapshot:
            spec["$snapshot"] = True
        if self.__max_scan:
            spec["$maxScan"] = self.__max_scan
        return spec
146422
def get_sensitivity(self, scalar=None):
        """"""
        # to get a Series instead of a dict:
        # (np.diag(c).astype(float) / c.T.sum())
        #     == pd.Series(self.sensitivity)
        if ((not self._scalar_stats and not scalar and self._num_classes > 2) or
                ((scalar is False or self._scalar_stats is False) and self._num_classes > 1)):
            return pd.Series(PrettyDict([(k, safe_div(self[k][k], self.loc[k].sum())) for k in self.columns]))
        return self._binary_sensitivity
501986
def _q(self, number, precision='.00001'):
        """"""
        if np.isinf(number):
            return np.nan
        else:
            return D(D(number).quantize(D(precision)))
775023
def GenomicRangeFromString(range_string,payload=None,dir=None):
  """"""
  m = re.match('^(.+):(\d+)-(\d+)$',range_string)
  if not m:  
    sys.stderr.write("ERROR bad genomic range string\n"+range_string+"\n")
    sys.exit()
  chr = m.group(1)
  start = int(m.group(2))
  end = int(m.group(3))
  return GenomicRange(chr,start,end,payload,dir)
886794
def validate_regular_sampling(values, rtol=10e-6):
    
    diffs = np.diff(values)
    return (len(diffs) < 1) or abs(diffs.min()-diffs.max()) < abs(diffs.min()*rtol)