Returns the percentage of gaps in the prediction
 with respect to the statistical model
 Params:
 +prediction+: +String+ corresponding to the prediction sequence
 +sm+: +String+ corresponding to the statistical model
 Output:
 +Fixnum+ with the score
775543
def gap_validation(prediction_raw, sm)
      return 1 if prediction_raw.length != sm.length
      # find gaps in the prediction and
      # not in the statistical model
      no_gaps = 0
      (0..sm.length - 1).each do |i|
        no_gaps += 1 if prediction_raw[i] == '-' && sm[i] != '-'
      end
      no_gaps / (sm.length + 0.0)
    end
60484
def estimate_params(self,burn=None,clip=10.0,alpha=0.32):
        
        mle = self.get_mle()
        out = odict()
        for param in mle.keys():
            out[param] = self.estimate(param,burn=burn,clip=clip,alpha=alpha)
        return out
1086993
public double score(List<L> guesses, List<L> trueLabels) {
    clearCounts();
    addGuesses(guesses, trueLabels);
    finalizeCounts();
    return getFMeasure();
  }
1331872
def precision_at(y_true, y_score, proportion, ignore_nas=False):
    '''
    
    '''
    # Sort scores in descending order
    scores_sorted = np.sort(y_score)[::-1]

    # Based on the proportion, get the index to split the data
    # if value is negative, return 0
    cutoff_index = max(int(len(y_true) * proportion) - 1, 0)
    # Get the cutoff value
    cutoff_value = scores_sorted[cutoff_index]

    # Convert scores to binary, by comparing them with the cutoff value
    scores_binary = np.array([int(y >= cutoff_value) for y in y_score])
    # Calculate precision using sklearn function
    if ignore_nas:
        precision = __precision(y_true, scores_binary)
    else:
        precision = precision_score(y_true, scores_binary)

    return precision, cutoff_value
475319
def initial_guesses(self):
        
        return np.array([param.value for param in self.model.params])
109653
def as_percent(self, percent):
        
        if not self:
            return self.wrap_str()

        length = len(self)
        # Using mod 100, to provide some kind of "auto reset". 0 is 0 though.
        percentmod = (int(percent) % 100) or min(percent, 100)
        index = int((length / 100) * percentmod)
        try:
            barstr = str(self[index])
        except IndexError:
            barstr = self[-1]

        return self.wrap_str(barstr)
961
def guessFormat(self):
        ''''''

        c = [ord(x) for x in self.quals]
        mi, ma = min(c), max(c)
        r = []
        for entry_format, v in iteritems(RANGES):
            m1, m2 = v
            if mi >= m1 and ma < m2:
                r.append(entry_format)
        return r
1180438
def run_gap_k_selection(data, k_min=1, k_max=50, B=5,
        skip=5, **kwargs):
    
    if k_min == k_max:
        return k_min
    gap_vals = []
    sk_vals = []
    k_range = list(range(k_min, k_max, skip))
    min_k = 0
    min_i = 0
    for i, k in enumerate(k_range):
        km = KMeans(k)
        clusters = km.fit_predict(data)
        gap, sk = calculate_gap(data, clusters, km, B=B)
        if len(gap_vals) > 1:
            if gap_vals[-1] >= gap - (skip+1)*sk:
                min_i = i
                min_k = k_range[i-1]
                break
                #return k_range[-1], gap_vals, sk_vals
        gap_vals.append(gap)
        sk_vals.append(sk)
    if min_k == 0:
        min_k = k_max
    if skip == 1:
        return min_k, gap_vals, sk_vals
    gap_vals = []
    sk_vals = []
    for k in range(min_k - skip, min_k + skip):
        km = KMeans(k)
        clusters = km.fit_predict(data)
        gap, sk = calculate_gap(data, clusters, km, B=B)
        if len(gap_vals) > 1:
            if gap_vals[-1] >= gap - sk:
                min_k = k-1
                return min_k, gap_vals, sk_vals
        gap_vals.append(gap)
        sk_vals.append(sk)
    return k, gap_vals, sk_vals
637463
def feasible_ratio(self, solutions):
        
        raise NotImplementedError('Solution class disappeared')
        count = np.zeros(len(solutions[0]))
        for x in solutions:
            count += x.unrepaired == x
        return count / float(len(solutions))
561347
def load_a3m(fasta, max_gap_fraction=0.9):
    
    mapping = {'-': 21, 'A': 1, 'B': 21, 'C': 2, 'D': 3, 'E': 4, 'F': 5,
               'G': 6, 'H': 7, 'I': 8, 'K': 9, 'L': 10, 'M': 11,
               'N': 12, 'O': 21, 'P': 13, 'Q': 14, 'R': 15, 'S': 16, 'T': 17,
               'V': 18, 'W': 19, 'Y': 20,
               'U': 21, 'Z': 21, 'X': 21, 'J': 21}

    # We want to exclude the lowercase, not ignore the uppercase because of gaps.
    lowercase = set('abcdefghijklmnopqrstuvwxyz')

    # Figure out the length of the sequence
    f = open(fasta)
    for line in f:
        if line.startswith('>'):
            continue
        seq_length = len(line.strip())
        break
    else:
        raise RuntimeError('I cannot find the first sequence')
    f.seek(0)

    parsed = []
    for line in f:
        if line.startswith('>'):
            continue
        line = line.strip()
        gap_fraction = line.count('-') / seq_length
        if gap_fraction <= max_gap_fraction:
            parsed.append([mapping.get(ch, 22) for ch in line
                           if ch not in lowercase])

    return np.array(parsed, dtype=np.int8).T
726957
def choose_solution_using_percentiles(
        X_original,
        solutions,
        parameters=None,
        verbose=False,
        percentiles=list(range(10, 100, 10))):
    
    missing_mask = np.isnan(X_original)
    min_mse = np.inf
    best_solution = None
    for i, candidate in enumerate(solutions):
        for col_idx in range(X_original.shape[1]):
            col_data = candidate[:, col_idx]
            col_missing = missing_mask[:, col_idx]
            col_observed = ~col_missing
            if col_missing.sum() < 2:
                continue
            elif col_observed.sum() < 2:
                continue
            missing_data = col_data[col_missing]
            observed_data = col_data[col_observed]

            missing_percentiles = np.array([
                np.percentile(missing_data, p)
                for p in percentiles])

            observed_percentiles = np.array([
                np.percentile(observed_data, p)
                for p in percentiles])

            mse = np.mean((missing_percentiles - observed_percentiles) ** 2)
        if mse < min_mse:
            min_mse = mse
            best_solution = candidate
        if verbose:
            print("Candidate #%d/%d%s: %f" % (
                i + 1,
                len(solutions),
                (" (parameter=%s) " % parameters[i]
                    if parameters is not None
                    else ""),
                mse))
    return best_solution
285467
def QA_indicator_MIKE(DataFrame, N=12):
    
    HIGH = DataFrame.high
    LOW = DataFrame.low
    CLOSE = DataFrame.close

    TYP = (HIGH+LOW+CLOSE)/3
    LL = LLV(LOW, N)
    HH = HHV(HIGH, N)

    WR = TYP+(TYP-LL)
    MR = TYP+(HH-LL)
    SR = 2*HH-LL
    WS = TYP-(HH-TYP)
    MS = TYP-(HH-LL)
    SS = 2*LL-HH
    return pd.DataFrame({
        'WR': WR, 'MR': MR, 'SR': SR,
        'WS': WS, 'MS': MS, 'SS': SS
    })
1249027
def read_scoring_scheme( f, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ):
    
    close_it = False
    if (type(f) == str):
        f = file(f,"rt")
        close_it = True
    ss = build_scoring_scheme("".join([line for line in f]),gap_open, gap_extend, gap1=gap1, gap2=gap2, **kwargs)
    if (close_it):
        f.close()
    return ss
729909
def classify_predict(fqdn, result, yP=None, *argl, **argd):
    
    #For now, just to make sure the machinery works correctly, let's return the
    #percentage correct. This is a terrible metric in practice.
    out = {}
    _percent_match(result, out, yP, *argl)

    if auto_print:
        msg.okay(out, -1)

    return out
970201
def _percent_match(result, out, yP=None, *argl):
    
    if len(argl) > 1:
        if yP is None:
            Xt = argl[1]
            key = id(Xt)
            if key in _splits:
                yP = _splits[key][3]
                
        if yP is not None:
            import math
            out["%"] = round(1.-sum(abs(yP - result))/float(len(result)), 3)
121494
def scores_to_preds(self, threshold, use_probs = True):
        
        self.threshold = threshold

        if use_probs:
            if self.probs is None:
                raise DataError("Probabilities are not available to make "
                                "predictions.")
            else:
                word = "probabilities"
                scores = self.probs
        else:
            if self.scores is None:
                raise DataError("Scores are not available to make predictions.")
            else:
                word = "scores"
                scores = self.scores

        if threshold > np.max(scores) or threshold < np.min(scores):
            warnings.warn("Threshold {} is outside the range of the "
                          "{}.".format(self.threshold, word))

        if self.preds is not None:
            warnings.warn("Overwriting predictions")
        self.preds = (scores >= threshold)*1
435744
def generate_predict_json(position1_result, position2_result, ids, passage_tokens):
    '''
    
    '''
    predict_len = len(position1_result)
    logger.debug('total prediction num is %s', str(predict_len))

    answers = {}
    for i in range(predict_len):
        sample_id = ids[i]
        passage, tokens = passage_tokens[i]
        kbest = find_best_answer_span(
            position1_result[i], position2_result[i], len(tokens), 23)
        _, start, end = kbest[0]
        answer = passage[tokens[start]['char_begin']:tokens[end]['char_end']]
        answers[sample_id] = answer
    logger.debug('generate predict done.')
    return answers