Obtain the true number of entries in the bin weighted by w^2
356090
def get_sum_w2(self, ix, iy=0, iz=0):
        
        if self.GetSumw2N() == 0:
            raise RuntimeError(
                "Attempting to access Sumw2 in histogram "
                "where weights were not stored")
        xl = self.nbins(axis=0, overflow=True)
        yl = self.nbins(axis=1, overflow=True)
        idx = xl * yl * iz + xl * iy + ix
        if not 0 <= idx < self.GetSumw2N():
            raise IndexError("bin index out of range")
        return self.GetSumw2().At(idx)
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
527879
def histogram(a, bins):
    
    if any(map(lambda x: x < 0, diff(bins))):
        raise ValueError(
            'bins must increase monotonically.')

    try:
        sa = sorted(a)
    except TypeError:
        # Perhaps just a single value? Treat as a list and carry on
        sa = sorted([a])

    # import numpy as np
    # nl = np.searchsorted(sa, bins[:-1], 'left')
    # nr = np.searchsorted(sa, bins[-1], 'right')
    # nn = np.r_[nl, nr]
    #
    # # cl = list(accumulate(Counter(map(lambda x: bisect_left(bins[:-1], x), sa)))
    # # print("cl")
    # # print([cl[i] for i in range(len(bins))])
    # print("nl")
    # print(list(nl))
    # # print(Counter(map(lambda x: bisect_right([bins[-1]], x), sa)))
    # print("nr")
    # print([nr])
    # print("nn")
    # print(list(nn))
    # print("hist")
    # print(list(np.diff(nn)))
    # print(list(np.histogram(a, bins)[0]))

    nl = list(accumulate([Counter(map(lambda x: bisect_left(bins[:-1], x), sa))[i] for i in range(len(bins) - 1)]))
    # print("nl")
    # print(nl)
    nr = Counter(map(lambda x: bisect_right([bins[1]], x), sa))[1]
    # print(nl)
    # print(nr)
    n = list(nl) + [nr]

    return diff(n), bins
1313188
def entropy_score(var,bins, w=None, decimate=True):
    '''
    
    '''
    if w is None:
        n = len(var)
        w = np.arange(0,n,n//bins) / float(n)
    if decimate:
        n = len(var)
        var = var[0:n:n//bins]
    score = w * np.log(var * w * np.sqrt(2*np.pi*np.exp(1)))
    score[np.isnan(score)]=np.Inf
    return score
287447
static double weightedAverage(double x1, double w1, double x2, double w2) {
        if (x1 <= x2) {
            return weightedAverageSorted(x1, w1, x2, w2);
        } else {
            return weightedAverageSorted(x2, w2, x1, w1);
        }
    }
574318
function (start, end) {
    var total = 0;

    start = start || 0;
    end = end || this.binCount;

    for (var i = start; i < end; i++) {
      total += this.frequencyByteData[i];
    }

    return total / (end - start);
  }
644158
def number_of_sub_file_entries(self):
    """"""
    if self._directory is None:
      self._directory = self._GetDirectory()

    if self._directory is None:
      return 0

    # We cannot use len(self._directory.entries) since entries is a generator.
    return sum(1 for path_spec in self._directory.entries)
1049287
def _weighted_selection(l, n):
    
    cuml = []
    items = []
    total_weight = 0.0
    for weight, item in l:
        total_weight += weight
        cuml.append(total_weight)
        items.append(item)

    return [items[bisect.bisect(cuml, random.random()*total_weight)] for _ in range(n)]
126958
def _fast_count_smallints(arr):
    """"""
    counts = np.bincount(arr.astype(np.int_))
    nz = counts.nonzero()[0]
    return np.c_[nz, counts[nz]]
598980
def _heuristic_bin_width(obs):
    """"""
    IQR = sp.percentile(obs, 75) - sp.percentile(obs, 25)
    N = len(obs)
    return 2*IQR*N**(-1/3)
1313413
def analyzeWeightDistribution(weights,base):
  """"""
  weights = weights.numpy()
  weights = weights.reshape(28*28*500)
  bins = np.linspace(-0.1, 0.1, 50)
  nz = weights.nonzero()[0]
  nzw = weights[nz]
  print("zero before and after:", (weights==0).sum(), (nzw==0).sum())
  print("Small weights:", (abs(nzw)>0.0).sum(), (abs(nzw)<0.01).sum(), (abs(nzw)<0.02).sum(), (abs(nzw)<0.03).sum())
  plt.hist(nzw, bins, alpha=0.5, label='All cols')
  plt.legend(loc='upper right')
  plt.xlabel("Weight values")
  plt.ylabel("Frequency")
  plt.title("Histogram of non-zero weight values")
  plt.savefig(base+"_weights")
  plt.close()
425477
def n_tasks(dec_num):
    
    bitstring = ""
    try:
        bitstring = dec_num[2:]
    except:
        bitstring = bin(int(dec_num))[2:]  # cut off 0b
    # print bin(int(dec_num)), bitstring
    return bitstring.count("1")
991755
def _locate_bin(bins, n):
    
    while bins[n] != n:
        n = bins[n]
    return n
252647
def success_count(self):
        
        return len([i for i, result in enumerate(self.data) if result.success])
604791
def calcFnWeight(node):
    ''''''
    stack = [node]
    count = 0
    while len(stack) > 0:
        node = stack.pop()
        children = [x for x in ast.iter_child_nodes(node)]
        count += len(children)
        stack = stack + children
    return count
1259953
def count(self, weighted=True):
        """"""
        return self._measures.weighted_n if weighted else self._measures.unweighted_n
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