Area under the ROC curve (AUC).

    Args:
        truth (numpy 1d array): Set of truth samples.
        recommend (numpy 1d array): Ordered set of recommended samples.

    Returns:
        float: AUC.
166299
def auc(truth, recommend):
    
    tp = correct = 0.
    for r in recommend:
        if r in truth:
            # keep track number of true positives placed before
            tp += 1.
        else:
            correct += tp
    # number of all possible tp-fp pairs
    pairs = tp * (recommend.size - tp)

    # if there is no TP (or no FP), it's meaningless for this metric (i.e., AUC=0.5)
    if pairs == 0:
        return 0.5

    return correct / pairs
1241971
def check_recommended_attributes(self, dataset):
        '''
        
        '''
        results = []
        recommended_ctx = TestCtx(BaseCheck.MEDIUM, 'Recommended global attributes')
        # Check time_coverage_duration and resolution
        for attr in ['time_coverage_duration', 'time_coverage_resolution']:
            attr_value = getattr(dataset, attr, '')
            try:
                parse_duration(attr_value)
                recommended_ctx.assert_true(True, '')  # Score it True!
            except Exception:
                recommended_ctx.assert_true(False, '{} should exist and be ISO-8601 format (example: PT1M30S), currently: {}'.format(attr, attr_value))
        results.append(recommended_ctx.to_result())
        return results
357224
def accuracy(self, label, pred):
        
        hit = 0.
        total = 0.
        batch_size = label.shape[0]
        for i in range(batch_size):
            l = self._remove_blank(label[i])
            p = []
            for k in range(self.seq_len):
                p.append(np.argmax(pred[k * batch_size + i]))
            p = self.ctc_label(p)
            if len(p) == len(l):
                match = True
                for k, _ in enumerate(p):
                    if p[k] != int(l[k]):
                        match = False
                        break
                if match:
                    hit += 1.0
            total += 1.0
        assert total == batch_size
        return hit / total
602201
def recommend_for_record(self, record_id, depth=4, num_reco=10):
        """"""
        data = calc_scores_for_node(self._graph, record_id, depth, num_reco)
        return data.Node.tolist(), data.Score.tolist()
483886
def auc(y_true, y_pred, round=True):
    
    y_true, y_pred = _mask_value_nan(y_true, y_pred)

    if round:
        y_true = y_true.round()
    if len(y_true) == 0 or len(np.unique(y_true)) < 2:
        return np.nan
    return skm.roc_auc_score(y_true, y_pred)
186920
def _true_anom_to_phase(true_anom, period, ecc, per0):
    
    phshift = 0

    mean_anom = true_anom - (ecc*sin(true_anom))*u.deg

    Phi = (mean_anom + per0) / (360*u.deg) - 1./4

    # phase = Phi - (phshift - 0.25 + per0/(360*u.deg)) * period
    phase = (Phi*u.d - (phshift - 0.25 + per0/(360*u.deg)) * period)*(u.cycle/u.d)

    return phase
16331
def safe_unit_norm(a):
    
    if 1 == len(a.shape):
        n = np.linalg.norm(a)
        if n:
            return a / n
        return a

    norm = np.sum(np.abs(a) ** 2, axis=-1) ** (1. / 2)

    # Dividing by a norm of zero will cause a warning to be issued. Set those
    # values to another number. It doesn't matter what, since we'll be dividing
    # a vector of zeros by the number, and 0 / N always equals 0.
    norm[norm == 0] = -1e12
    return a / norm[:, np.newaxis]
1207540
def _aicc(model_results, nobs):
    """"""
    aic = model_results.aic
    df_model = model_results.df_model + 1  # add one for constant term
    return aic + 2. * df_model * (nobs / (nobs - df_model - 1.) - 1.)
544294
def accuracy(y_true, y_pred, round=True):
    
    y_true, y_pred = _mask_value_nan(y_true, y_pred)
    if round:
        y_true = np.round(y_true)
        y_pred = np.round(y_pred)
    return skm.accuracy_score(y_true, y_pred)
774584
def check_moving_average_bias_ratio(cls, data, sample=5,
                                        positive_or_negative=False):
        
        return cls.__cal_ma_bias_ratio_point(data, sample,
                                              positive_or_negative)
804926
def _calc_sizes(self, cnv_file, items):
        
        bp_per_bin = 100000  # same target as CNVkit
        range_map = {"target": (100, 250), "antitarget": (10000, 1000000)}
        target_bps = []
        anti_bps = []
        checked_beds = set([])
        for data in items:
            region_bed = tz.get_in(["depth", "variant_regions", "regions"], data)
            if region_bed and region_bed not in checked_beds:
                with utils.open_gzipsafe(region_bed) as in_handle:
                    for r in pybedtools.BedTool(in_handle).intersect(cnv_file):
                        if r.stop - r.start > range_map["target"][0]:
                            target_bps.append(float(r.name))
                with utils.open_gzipsafe(region_bed) as in_handle:
                    for r in pybedtools.BedTool(in_handle).intersect(cnv_file, v=True):
                        if r.stop - r.start > range_map["target"][1]:
                            anti_bps.append(float(r.name))
                checked_beds.add(region_bed)
        def scale_in_boundary(raw, round_interval, range_targets):
            min_val, max_val = range_targets
            out = int(math.ceil(raw / float(round_interval)) * round_interval)
            if out > max_val:
                return max_val
            elif out < min_val:
                return min_val
            else:
                return out
        if target_bps and np.median(target_bps) > 0:
            raw_target_bin = bp_per_bin / float(np.median(target_bps))
            target_bin = scale_in_boundary(raw_target_bin, 50, range_map["target"])
        else:
            target_bin = range_map["target"][1]

        if anti_bps and np.median(anti_bps) > 0:
            raw_anti_bin = bp_per_bin / float(np.median(anti_bps))
            anti_bin = scale_in_boundary(raw_anti_bin, 10000, range_map["antitarget"])
        else:
            anti_bin = range_map["antitarget"][1]
        return target_bin, anti_bin
148954
def auto_qc(dset,inside_perc=60,atlas=None,p=0.001):
    ''''''
    with nl.notify('Running quality check on %s:' % dset):
        if not os.path.exists(dset):
            nl.notify('Error: cannot find the file!',level=nl.level.error)
            return False
        
        info = nl.dset_info(dset)
        if not info:
            nl.notify('Error: could not read the dataset!',level=nl.level.error)
        
        if any(['stat' in x for x in info.subbricks]):
            with nl.notify('Statistical results detected...'):
                inside = inside_brain(dset,atlas=atlas,p=p)
                nl.notify('%.1f significant voxels inside brain')
                if inside<inside_perc:
                    nl.notify('Warning: below quality threshold!',level=nl.level.warning)
#                    return False
                nl.notify('Looks ok')
                return inside
        
        if len(info.subbricks)>1:
            with nl.notify('Time-series detected...'):
                return_val = True
                (cost,overlap) = atlas_overlap(dset)
                if cost>0.15 or overlap<80:
                    nl.notify('Warning: does not appear to conform to brain dimensions',level=nl.level.warning)
                    return_val = False
                if len(info.subbricks)>5:
                    (oc,perc_outliers) = outcount(dset)
                    if perc_outliers>0.1:
                        nl.notify('Warning: large amount of outlier time points',level=nl.level.warning)
                        return_val = False
            if return_val:
                nl.notify('Looks ok')
                return min(100*(1-cost),overlap,100*perc_outliers)
            return False
        
        with nl.notify('Single brain image detected...'):
            (cost,overlap) = atlas_overlap(dset)
            # Be more lenient if it's not an EPI, cuz who knows what else is in this image
            if cost>0.45 or overlap<70:
                nl.notify('Warning: does not appear to conform to brain dimensions',level=nl.level.warning)
                return False
            nl.notify('Looks ok')
            return min(100*(1-cost),overlap)
287786
def recommend(self, limit=10):
        '''
        
        '''
        expected_list = [(arm_id, beta_dist.expected_value()) for arm_id, beta_dist in self.__beta_dist_dict.items()]
        expected_list = sorted(expected_list, key=lambda x: x[1], reverse=True)
        return expected_list[:limit]
1028
def app_score(self):
        
        # compute curve
        precisions, pct_pred_pos, taus = self.precision_pct_pred_pos_curve(interval=False)

        # compute area
        app = 0
        total = 0
        for k in range(len(precisions)-1):
            # read cur data
            cur_prec = precisions[k]
            cur_pp = pct_pred_pos[k]
            cur_tau = taus[k]

            # read next data
            next_prec = precisions[k+1]
            next_pp = pct_pred_pos[k+1]
            next_tau = taus[k+1]
            
            # approximate with rectangles
            mid_prec = (cur_prec + next_prec) / 2.0
            width_pp = np.abs(next_pp - cur_pp)
            app += mid_prec * width_pp
            total += width_pp

        return app
1126815
def fit(self, scores, y_true):
        

        # to force equal priors, randomly select (and average over)
        # up to fifty balanced (i.e. #true == #false) calibration sets.
        if self.equal_priors:

            counter = Counter(y_true)
            positive, negative = counter[True], counter[False]

            if positive > negative:
                majority, minority = True, False
                n_majority, n_minority = positive, negative
            else:
                majority, minority = False, True
                n_majority, n_minority = negative, positive

            n_splits = min(50, n_majority // n_minority + 1)

            minority_index = np.where(y_true == minority)[0]
            majority_index = np.where(y_true == majority)[0]

            cv = []
            for _ in range(n_splits):
                test_index = np.hstack([
                    np.random.choice(majority_index,
                                     size=n_minority,
                                     replace=False),
                    minority_index])
                cv.append(([], test_index))
            cv = _CVIterableWrapper(cv)

        # to estimate priors from the data itself, use the whole set
        else:
            cv = 'prefit'

        self.calibration_ = CalibratedClassifierCV(
            base_estimator=_Passthrough(), method=self.method, cv=cv)
        self.calibration_.fit(scores.reshape(-1, 1), y_true)

        return self
1302868
private double compute_auc() {
    if (_fps[_nBins-1] == 0) return 1.0; //special case
    if (_tps[_nBins-1] == 0) return 0.0; //special case

    // All math is computed scaled by TP and FP.  We'll descale once at the
    // end.  Trapezoids from (tps[i-1],fps[i-1]) to (tps[i],fps[i])
    double tp0 = 0, fp0 = 0;
    double area = 0;
    for( int i=0; i<_nBins; i++ ) {
      area += (_fps[i]-fp0)*(_tps[i]+tp0)/2.0; // Trapezoid
      tp0 = _tps[i];  fp0 = _fps[i];
    }
    // Descale
    return area/_p/_n;
  }
233897
def ecc(self, n):
        

        """
        ny, nx = self._profile.shape
        xmax, ymax = self._xymax
        xcm, ycm = self._cm

        # create (X, Y) grids relative to CM
        Y, X = np.mgrid[ymax:-ymax:1j*ny, -xmax:xmax:1j*nx]
        X -= xcm
        Y -= ycm

        # create grid of weights = profile * R^n
        Rsq = X*X + Y*Y
        if n == 1:
            W = np.sqrt(Rsq, out=Rsq)
        elif n == 2:
            W = Rsq
        else:
            if n & 1:  # odd n
                W = np.sqrt(Rsq)
            else:  # even n
                W = np.copy(Rsq)
            # multiply by R^2 until W = R^n
            for _ in range(int((n-1)/2)):
                W *= Rsq
        W *= self._profile

        # create grid of e^{i*n*phi} * W
        i_n_phi = np.zeros_like(X, dtype=complex)
        np.arctan2(Y, X, out=i_n_phi.imag)
        i_n_phi.imag *= n
        exp_phi = np.exp(i_n_phi, out=i_n_phi)
        exp_phi *= W

        return abs(exp_phi.sum()) / W.sum()