Find the optimal number of bins.
    Available methods : Freedman, Scott
433807
def _optimize_binning(x, range, method='Freedman'):
    
    N = x.shape[0]
    if method.lower() == 'freedman':
        s = sort(x)
        IQR = s[int(N * .75)] - s[int(
            N * .25)]  # Interquantile range (75% -25%)
        width = 2 * IQR * N ** (-1. / 3)

    elif method.lower() == 'scott':
        width = 3.49 * x.std() * N ** (-1. / 3)
    else:
        raise ValueError('Method must be Scott or Freedman', method)
    return int(diff(range) / width)
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
858236
def _set_rho_grids(self):
        
        rho_grids = np.arange(self.rho_bins) * 2 / self.rho_bins - 1 \
            + 1 / self.rho_bins
        rho_weights = np.ones(self.rho_bins) / self.rho_bins
        return rho_grids, rho_weights
1127733
def bin_find(self):
        
        flag = []
        options = [
            "-f",
            "--find"
        ]
        additional_options = ["--case-ins"]
        for arg in self.args:
            if arg in additional_options:
                flag.append(arg)
                self.args.remove(arg)
        packages = self.args[1:]
        if len(self.args) > 1 and self.args[0] in options:
            PackageManager(packages).find(flag)
        else:
            usage("")
970626
def left(self, f, n=1):
        
        intervals = self.intervals[f.chrom]
        if intervals == []: return []

        iright = binsearch_left_start(intervals, f.start, 0 , len(intervals)) + 1
        ileft  = binsearch_left_start(intervals, f.start - self.max_len[f.chrom] - 1, 0, 0)

        results = sorted((distance(other, f), other) for other in intervals[ileft:iright] if other.end < f.start and distance(f, other) != 0)
        if len(results) == n:
            return [r[1] for r in results]

        # have to do some extra work here since intervals are sorted
        # by starts, and we dont know which end may be around...
        # in this case, we got some extras, just return as many as
        # needed once we see a gap in distances.
        for i in range(n, len(results)):
            if results[i - 1][0] != results[i][0]:
                return [r[1] for r in results[:i]]

        if ileft == 0:
            return [r[1] for r in results]

        # here, didn't get enough, so move left and try again. 
        1/0
821434
def bin_number(datapoint, intervals):
  
  index = numpy.searchsorted(intervals, datapoint)
  return [0 if index != i else 1 for i in range(len(intervals) + 1)]
612093
def range_hist(items, bins):
    
    big_hist = ut.dict_hist(items)
    hist = ut.odict([(b, 0) for b in bins])

    for k, v in big_hist.items():
        for b in bins:
            if isinstance(b, (list, tuple)):
                if k >= b[0] and k < b[1]:
                    hist[b] += v
            elif k == b:
                hist[b] += v
    return hist
1254696
def _histplot_bins(column, bins=100):
    """"""
    col_min = np.min(column)
    col_max = np.max(column)
    return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))
442839
def bin_data(data, dim = 40, num_bins = 10):
  
  intervals = generate_RF_bins(data, dim, num_bins)
  binned_data = [numpy.concatenate([bin_number(data[x][i], intervals[i])
      for i in range(len(data[x]))]) for x in range(len(data))]
  return binned_data
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)
662587
def static_binning(data=None, bins=None, **kwargs) -> StaticBinning:
    """"""
    return StaticBinning(bins=make_bin_array(bins), **kwargs)
934471
def bin_spikes(spike_times, binsz):
    
    bins = np.empty((len(spike_times),), dtype=int)
    for i, stime in enumerate(spike_times):
        # around to fix rounding errors
        bins[i] = np.floor(np.around(stime/binsz, 5))
    return bins
54380
def bin(self):
        
        bin = self._query(('MBIN?', Integer, Integer), self.idx)
        return None if bin == -1 else bin
909998
def _get_bin_width(stdev, count):
    

    w = int(round((3.5 * stdev) / (count ** (1.0 / 3))))
    if w:
        return w
    else:
        return 1
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
1107131
def bincount(dig, weight, minlength):
    
    if numpy.isscalar(weight):
        return numpy.bincount(dig, minlength=minlength) * weight
    else:
        return numpy.bincount(dig, weight, minlength)
695420
public static AssociativeArray optimumSampleSize(int n, AssociativeArray populationNh, AssociativeArray populationStdh) {
        AssociativeArray nh = new AssociativeArray();
        
        double sumNhSh = 0.0;
        for(Map.Entry<Object, Object> entry : populationNh.entrySet()) {
            Object strata = entry.getKey();
            Integer populationInStrata = ((Number)entry.getValue()).intValue();
            Double populationStd = populationStdh.getDouble(strata);
            
            if(populationStd == null || populationInStrata <=0.0) {
                throw new IllegalArgumentException("Invalid strata population or strata std.");
            }
            
            double NhSh = populationInStrata*populationStd;
            
            sumNhSh+=NhSh;

            nh.put(strata, n*NhSh);
        }
        
        if(sumNhSh<=0) {
            throw new IllegalArgumentException("Invalid strata populations.");
        }
        
        for(Map.Entry<Object, Object> entry : nh.entrySet()) {
            Object strata = entry.getKey();
            nh.put(strata, TypeInference.toDouble(entry.getValue())/sumNhSh);
        }
        
        return nh;
    }