Return optimal bins given the input parameters
777480
def get_histogram_bins(min_, max_, std, count):
    

    width = _get_bin_width(std, count)
    count = int(round((max_ - min_) / width) + 1)

    if count:
        bins = [i * width + min_ for i in xrange(1, count + 1)]
    else:
        bins = [min_]

    return bins
385345
def rippe_parameters(matrix, positions, lengths=None, init=None, circ=False):
    

    n, _ = matrix.shape

    if lengths is None:
        lengths = np.abs(np.diff(positions))

    measurements, bins = [], []
    for i in range(n):
        for j in range(1, i):
            mean_length = (lengths[i] + lengths[j]) / 2.
            if positions[i] < positions[j]:
                d = (((positions[j] - positions[i] -
                     lengths[i]) + mean_length) /
                     1000.)
            else:
                d = (((positions[i] - positions[j] -
                     lengths[j]) + mean_length) /
                     1000.)

            bins.append(np.abs(d))
            measurements.append(matrix[i, j])
    parameters = estimate_param_rippe(measurements, bins, init=init, circ=circ)
    print(parameters)
    return parameters[0]
1229314
def calc_bin(self, _bin=None):
        
        if _bin is None:
            try:
                _bin = bins.bins(self.start, self.end, one=True)
            except TypeError:
                _bin = None
        return _bin
1309205
def _bin_zfill(num, width=None):
    
    s = bin(num)[2:]
    return s if width is None else s.zfill(width)
869954
function getBestBinFit( start, len, blocks ) {
	var b, s, e, end = start + len, found = false,
		c, last_c = 0, last_s = 0, last_i = -1, last_bin = null;

	// Find the biggest chunk that can fit on these data
	for (var bi=0, bl=blocks.length; bi<bl; ++bi) {
		b = blocks[bi]; found = false;
		for (var i=0, il=b.length; i<il; ++i) {
			s = b[i][0]; e = s + b[i][1];

			// Find the common region of block-scan frame
			if ( ((s >= start) && (s < end-1)) ||	// Start in bounds
				 ((e >= start) && (e < end-1)) ||	// End in bounds
				 ((s <= start) && (e >= end)) )		// 
			{

				// Check bounds
				if (s < start) s = start;
				if (s > end-2) continue;
				if (e > end) e = end;
				if (s === e) continue;

				// Test coverage
				c = e - s;
				if (c > last_c) {
					last_c = c;
					last_s = s;
					last_bin = b[i];
					found = true;
				}

			}

		}

		// Prefer priority to length across different blocks
		// on the first block (repeated)
		if ((bi === 0) && found)
			return last_bin;

	}

	// Update bounds
	if (last_bin) {
		last_bin = last_bin.slice();
		last_bin[0] = last_s;
		last_bin[1] = last_c;
	}

	// Return last bin
	return last_bin;
}
486363
def bins(start, end):
        
        if end - start < 536870912:
            offsets = [585, 73, 9, 1]
        else:
            raise BigException
            offsets = [4681, 585, 73, 9, 1]
        binFirstShift = 17
        binNextShift = 3

        start = start >> binFirstShift
        end = (end - 1)  >> binFirstShift

        bins = [1]
        for offset in offsets:
            bins.extend(range(offset + start, offset + end + 1))
            start >>= binNextShift
            end >>= binNextShift
        return frozenset(bins)
647825
def optimize_NxN(x, y, fit_offset=False, perc=None):
    
    if perc is not None:
        if not fit_offset and isinstance(perc, (list, tuple)): perc = perc[1]
        weights = get_weight(x, y, perc).astype(bool)
        if issparse(weights): weights = weights.A
    else:
        weights = None

    x, y = x.astype(np.float64), y.astype(np.float64)

    n_vars = x.shape[1]
    offset, gamma = np.zeros(n_vars), np.zeros(n_vars)

    for i in range(n_vars):
        xi = x[:, i] if weights is None else x[:, i][weights[:, i]]
        yi = y[:, i] if weights is None else y[:, i][weights[:, i]]

        if fit_offset:
            offset[i], gamma[i] = minimize(lambda m: np.sum((-yi + xi * m[1] + m[0])**2), method="L-BFGS-B",
                                           x0=(0, 0.1), bounds=[(0, None), (None, None)]).x
        else:
            gamma[i] = minimize(lambda m: np.sum((-yi + xi * m) ** 2), x0=0.1, method="L-BFGS-B").x
    offset[np.isnan(offset)], gamma[np.isnan(gamma)] = 0, 0
    return offset, gamma
1156552
def get_bin_index(self, value):
        """"""
        if value == self.max_value:
            return self.num_bins - 1

        return int(self.C * log(value / self.min_value))
1247329
def get_distbins(start=100, bins=2500, ratio=1.01):
    
    b = np.ones(bins, dtype="float64")
    b[0] = 100
    for i in range(1, bins):
        b[i] = b[i - 1] * ratio
    bins = np.around(b).astype(dtype="int")
    binsizes = np.diff(bins)
    return bins, binsizes
54380
def bin(self):
        
        bin = self._query(('MBIN?', Integer, Integer), self.idx)
        return None if bin == -1 else bin
253409
def calc_bins(n, min_val, max_val, h=None, binwidth=None):
    
    if not h:
        h = max(10, math.log(n + 1, 2))
    if binwidth == 0:
        binwidth = 0.1
    if binwidth is None:
        binwidth = (max_val - min_val) / h
    for b in drange(min_val, max_val, step=binwidth, include_stop=True):
        if b.is_integer():
            yield int(b)
        else:
            yield b
1301447
def binned_bitsets_by_chrom( f, chrom, chrom_col=0, start_col=1, end_col=2):
    """"""
    bitset = BinnedBitSet( MAX )
    for line in f:
        if line.startswith("#"): continue
        fields = line.split()
        if fields[chrom_col] == chrom:
            start, end = int( fields[start_col] ), int( fields[end_col] )
            bitset.set_range( start, end-start )
    return bitset
1140285
def _bin_from_dict(d):
    
    try:
        start = int(d['start'])
        end = int(d['end'])
        return bins.bins(start, end, one=True)

    # e.g., if "."
    except ValueError:
        return None
387593
def _get_optimal_thresholds(nd_dict, quantized_dtype, num_bins=8001, num_quantized_bins=255, logger=None):
    """"""
    if stats is None:
        raise ImportError('scipy.stats is required for running entropy mode of calculating'
                          ' the optimal thresholds for quantizing FP32 ndarrays into int8.'
                          ' Please check if the scipy python bindings are installed.')
    assert isinstance(nd_dict, dict)
    if logger is not None:
        logger.info('Calculating optimal thresholds for quantization using KL divergence'
                    ' with num_bins=%d and num_quantized_bins=%d' % (num_bins, num_quantized_bins))
    th_dict = {}
    # copy nd_dict keys since the keys() only returns a view in python3
    layer_names = list(nd_dict.keys())
    for name in layer_names:
        assert name in nd_dict
        min_val, max_val, min_divergence, opt_th = \
            _get_optimal_threshold(nd_dict[name], quantized_dtype, num_bins=num_bins,
                                   num_quantized_bins=num_quantized_bins)
        del nd_dict[name]  # release the memory of ndarray
        if min_val < 0:
            th_dict[name] = (-opt_th, opt_th)
        else:
            th_dict[name] = (0, opt_th)
        if logger is not None:
            logger.info('layer=%s, min_val=%f, max_val=%f, min_divergence=%f, optimal_threshold=%f'
                        % (name, min_val, max_val, min_divergence, opt_th))
    return th_dict
337782
def _get_nr_bins(count):
    
    if count <= 30:
        # use the square-root choice, used by Excel and Co
        k = np.ceil(np.sqrt(count))
    else:
        # use Sturges' formula
        k = np.ceil(np.log2(count)) + 1
    return int(k)
194732
def __range(a, bins):
    ''''''
    a = numpy.asarray(a)
    a_max = a.max()
    a_min = a.min()
    s = 0.5 * (a_max - a_min) / float(bins - 1)
    return (a_min - s, a_max + s)
693850
def getDefaultL2Params(self, inputSize, numInputBits):
    
    if numInputBits == 20:
      sampleSizeProximal = 10
      minThresholdProximal = 5
    elif numInputBits == 10:
      sampleSizeProximal = 6
      minThresholdProximal = 3
    else:
      sampleSizeProximal = int(numInputBits * .6)
      minThresholdProximal = int(sampleSizeProximal * .6)

    return {
      "inputWidth": inputSize * 16,
      "cellCount": 4096,
      "sdrSize": 40,
      "synPermProximalInc": 0.1,
      "synPermProximalDec": 0.001,
      "initialProximalPermanence": 0.6,
      "minThresholdProximal": minThresholdProximal,
      "sampleSizeProximal": sampleSizeProximal,
      "connectedPermanenceProximal": 0.5,
      "synPermDistalInc": 0.1,
      "synPermDistalDec": 0.001,
      "initialDistalPermanence": 0.41,
      "activationThresholdDistal": 13,
      "sampleSizeDistal": 20,
      "connectedPermanenceDistal": 0.5,
      "seed": self.seed,
      "learningMode": True,
    }