Perform confidence interval based prioritization for CNVs.
965861
def _cnv_prioritize(data):
    
    supported = {"cnvkit": {"inputs": ["call_file", "segmetrics"], "fn": _cnvkit_prioritize}}
    pcall = None
    priority_files = None
    for call in data.get("sv", []):
        if call["variantcaller"] in supported:
            priority_files = [call.get(x) for x in supported[call["variantcaller"]]["inputs"]]
            priority_files = [x for x in priority_files if x is not None and utils.file_exists(x)]
            if len(priority_files) == len(supported[call["variantcaller"]]["inputs"]):
                pcall = call
                break
    prioritize_by = tz.get_in(["config", "algorithm", "svprioritize"], data)
    if pcall and prioritize_by:
        out_file = "%s-prioritize.tsv" % utils.splitext_plus(priority_files[0])[0]
        gene_list = _find_gene_list_from_bed(prioritize_by, out_file, data)
        if gene_list:
            with open(gene_list) as in_handle:
                genes = [x.strip() for x in in_handle]
            args = [dd.get_sample_name(data), genes] + priority_files
            df = supported[pcall["variantcaller"]]["fn"](*args)
            with file_transaction(data, out_file) as tx_out_file:
                df.to_csv(tx_out_file, sep="\t", index=False)
            pcall["priority"] = out_file
    return data
376700
function analyzeNumericArray( v, include_costly ) {
	var min = v[0], max = min, is_int = false, is_float = false, is_same = true,
		dmin=0, dmax=0, is_dfloat = false,
		mean=0, n_type=0, d_mode=0, f_type=[0, NUMTYPE.UNKNOWN], 
		c_same=0, same=0,
		s_min = [min,min,min,min,min], s_min_i=0, s_max = [min,min,min,min,min], s_max_i=0, samples,
		a, b, d_type, cd, cv, lv = v[0];

	// Anlyze array items
	for (var i=0, l=v.length; i<l; ++i) {
		cv = v[i];

		// Exit on non-numeric cases
		if (typeof cv !== 'number')
			return null;

		// Update mean
		mean += cv;

		// Include costly calculations if enabled
		if (include_costly) {

			// Update delta
			if (i !== 0) {
				cd = lv - cv; if (cd < 0) cd = -cd;
				if (i === 1) {
					dmin = cd;
					dmax = cd;
				} else {
					if (cd < dmin) dmin = cd;
					if (cd > dmax) dmax = cd;
				}

				// Check if delta is float
				if ((cd !== 0) && (cd % 1 !== 0))
					is_dfloat = true;
			}

			// Update bounds & Keep samples
			if (cv < min) {
				min = cv;
				s_min[s_min_i] = cv;
				if (++s_min_i>5) s_min_i=0;
			}
			if (cv > max) {
				max = cv;
				s_max[s_max_i] = cv;
				if (++s_max_i>5) s_max_i=0;
			}

		} else {

			// Update bounds
			if (cv < min) min = cv;
			if (cv > max) max = cv;

		}

		// Check for same values
		if (cv === lv) {
			c_same++;
		} else {
			if (c_same > same)
				same = c_same;
			is_same = false;
			c_same = 0;
		}

		// Keep last value
		lv = cv;

		// Skip zeros from further analysis
		if (cv === 0) continue;

		// Update integer/float
		if (cv % 1 !== 0) {
			is_float = true;
		} else {
			is_int = true;
		}

	}

	// Finalize counters
	if (c_same > same) same = c_same;
	mean /= v.length;

	// Guess numerical type
	n_type = getNumType( min, max, is_float );

	// Calculate delta-encoding details
	d_type = NUMTYPE.UNKNOWN;
	if (include_costly) {
		if (!is_float && is_int) {

			// INTEGERS : Use Delta-Encoding (d_mode=1)

			if ((dmin > INT8_MIN) && (dmax < INT8_MAX)) {
				d_type = NUMTYPE.INT8;
				d_mode = 1;
			} else if ((dmin > INT16_MIN) && (dmax < INT16_MAX)) {
				d_type = NUMTYPE.INT16;
				d_mode = 1;
			} else if ((dmin > INT32_MIN) && (dmax < INT32_MAX)) {
				d_type = NUMTYPE.INT32;
				d_mode = 1;
			}

		} else if (is_float) {

			// FLOATS : Use Rebase Encoding (d_mode=2)

			// Get a couple more samples
			samples = [].concat(
				s_min, s_max,
				[
					v[Math.floor(Math.random()*v.length)],
					v[Math.floor(Math.random()*v.length)],
					v[Math.floor(Math.random()*v.length)],
					v[Math.floor(Math.random()*v.length)],
					v[Math.floor(Math.random()*v.length)],
				]
			);

			// Calculate float scale
			f_type = getFloatScale( v, min, max, 0.01 );
			if (f_type[1] != NUMTYPE.UNKNOWN) {
				d_type = f_type[1];
				d_mode = 2;
			}

		}
	}

	// Based on information detected so far, populate
	// the analysis results
	return {

		// Get numeric type
		'type'		: n_type,
		'delta_type': d_type,

		// Percentage of same items
		'psame'		: same / v.length,

		// Log numeric bounds
		'min'		: min,
		'max'		: max,
		'mean'		: mean,

		// Log delta bounds
		'dmin'		: dmin,
		'dmax' 		: dmax,

		// Delta mode
		'dmode'		: d_mode,
		'fscale' 	: f_type[0],

		// Expose information details
		'integer' 	: is_int && !is_float,
		'float' 	: is_float && !is_int,
		'mixed' 	: is_float && is_int,
		'same'		: is_same && (v.length > 1),

	};

}
383341
def confidence_interval_hazard_(self):
        
        return self._compute_confidence_bounds_of_transform(self._hazard, self.alpha, self._ci_labels)
1140888
def _adjust_probability_vec_best(population, fitnesses, probability_vec,
                                 adjust_rate):
    """"""
    best_solution = max(zip(fitnesses, population))[1]

    # Shift probabilities towards best solution
    return _adjust(probability_vec, best_solution, adjust_rate)
676991
def estimate_lambda(pv):
    """"""
    LOD2 = sp.median(st.chi2.isf(pv,1))
    L = (LOD2/0.456)
    return (L)
462435
def _highest_degree_variable_chooser(problem, variables, domains):
    '''
    
    '''
    # the variable involved in more constraints
    return sorted(variables, key=lambda v: problem.var_degrees[v], reverse=True)[0]
41148
def normalize_result(result, default, threshold=0.2):
    """"""
    if result is None:
        return default
    if result.get('confidence') is None:
        return default
    if result.get('confidence') < threshold:
        return default
    return normalize_encoding(result.get('encoding'),
                              default=default)
343798
def _pvals_from_chi_squared(self, pairwise_chisq):
        
        return self._intersperse_insertion_rows_and_columns(
            1.0 - WishartCDF(pairwise_chisq, self._n_min, self._n_max).values
        )
18797
def obfn_g1var(self):
        
        """

        # Use of self.block_sep1(self.AXnr) instead of self.cnst_A1(self.X)
        # reduces number of calls to self.cnst_A0
        return self.var_y1() if self.opt['gEvalY'] else \
            self.block_sep1(self.AXnr)
374407
def bound_variables(xmrs):
    """"""
    bvs = set(
        ep.intrinsic_variable for ep in xmrs.eps()
        if ep.is_quantifier() and ep.intrinsic_variable is not None
    )
    return sorted(bvs, key=var_id)
1167176
def cv_residuals(self, cv=True):
        """"""
        vals = self.cv_values(cv)
        return (self.y - vals) / self.dy
682201
def compute(self):
        """"""
        self._compute_primary_smooths()
        self._smooth_the_residuals()
        self._select_best_smooth_at_each_point()
        self._enhance_bass()
        self._smooth_best_span_estimates()
        self._apply_best_spans_to_primaries()
        self._smooth_interpolated_smooth()
        self._store_unsorted_results(self.smooth_result, numpy.zeros(len(self.smooth_result)))
368015
def optimize_rfc(data, targets):
    """"""
    def rfc_crossval(n_estimators, min_samples_split, max_features):
        """Wrapper of RandomForest cross validation.

        Notice how we ensure n_estimators and min_samples_split are casted
        to integer before we pass them along. Moreover, to avoid max_features
        taking values outside the (0, 1) range, we also ensure it is capped
        accordingly.
        """
        return rfc_cv(
            n_estimators=int(n_estimators),
            min_samples_split=int(min_samples_split),
            max_features=max(min(max_features, 0.999), 1e-3),
            data=data,
            targets=targets,
        )

    optimizer = BayesianOptimization(
        f=rfc_crossval,
        pbounds={
            "n_estimators": (10, 250),
            "min_samples_split": (2, 25),
            "max_features": (0.1, 0.999),
        },
        random_state=1234,
        verbose=2
    )
    optimizer.maximize(n_iter=10)

    print("Final result:", optimizer.max)
900222
def decision_function(self, X, **kwargs):
        ""
        if X is None:
            return self._hy_test
        X = self.convert_features(X)
        if len(X) < self.nvar:
            _ = 'Number of variables differ, trained with %s given %s' % (self.nvar, len(X))
            raise RuntimeError(_)
        hist = self._hist
        for node in hist:
            if node.height:
                node.eval(hist)
            else:
                node.eval(X)
        node.normalize()
        r = node.hy
        for i in hist[:-1]:
            i.hy = None
            i.hy_test = None
        gc.collect()
        return r
308521
def _set_defaults(self, defaults):
        """"""
        self.n_res = defaults.n_res
        self.n_sub = defaults.n_sub
        self.randomize = defaults.randomize
        self.return_median = defaults.return_median
        self.efficient = defaults.efficient
        self.return_only_bw = defaults.return_only_bw
        self.n_jobs = defaults.n_jobs
370801
def _expectation(self, X):
        """"""

        # Calculate probabilities of X belonging to the different clusters
        weighted_likelihoods = self._get_likelihoods(X) * self.priors
        sum_likelihoods = np.expand_dims(np.sum(weighted_likelihoods, axis=1), axis=1)
        # Determine responsibility as P(X|y)*P(y)/P(X)
        self.responsibility = weighted_likelihoods / sum_likelihoods
        # Assign samples to cluster that has largest probability
        self.sample_assignments = self.responsibility.argmax(axis=1)
        # Save value for convergence check
        self.responsibilities.append(np.max(self.responsibility, axis=1))
828845
def confidence_interval_dichotomous(
        point_estimate,
        sample_size,
        confidence=.95,
        bias=False,
        percentage=True,
        **kwargs
):
    """"""
    alpha = ppf((confidence + 1) / 2, sample_size - 1)
    p = point_estimate
    if percentage:
        p /= 100

    margin = sqrt(p * (1 - p) / sample_size)
    if bias:
        margin += .5 / sample_size
    if percentage:
        margin *= 100

    return (point_estimate - alpha * margin, point_estimate + alpha * margin)