Perform the actual TH2 -> TH1 projection.

        This projection can only be to 1D.

        Args:
            hist (ROOT.TH2): Histogram from which the projections should be performed.
        Returns:
            ROOT.TH1: The projected histogram.
321603
def _project_TH2(self, hist: Hist) -> Any:
        
        if len(self.projection_axes) != 1:
            raise ValueError(len(self.projection_axes), "Invalid number of axes")

        #logger.debug(f"self.projection_axes[0].axis: {self.projection_axes[0].axis}, axis range name: {self.projection_axes[0].name}, axis_type: {self.projection_axes[0].axis_type}")
        # NOTE: We cannot use TH3.ProjectionZ(...) because it has different semantics than ProjectionX
        #       and ProjectionY. In particular, it doesn't respect the axis limits of axis onto which it
        #       is projected.  So we have to separate the projection by histogram type as opposed to axis
        #       length.
        projection_func_map = {
            TH1AxisType.x_axis.value: hist.ProjectionX,
            TH1AxisType.y_axis.value: hist.ProjectionY
        }

        # Determine the axis_type value
        # Use try here instead of checking for a particular type to protect against type changes (say
        # in the enum)
        try:
            # Try to extract the value from an enum
            axis_type = self.projection_axes[0].axis_type.value
        except ValueError:
            # Seems that we received an int, so just use that value
            axis_type = self.axis_type  # type: ignore

        projection_func = projection_func_map[axis_type]

        # Do the actual projection
        logger.info(f"Projecting onto axis range {self.projection_axes[0].name} from hist {hist.GetName()}")
        projected_hist = projection_func()

        return projected_hist
50633
def hist(*args, **kwargs):
    
    ax, args, kwargs = maybe_get_ax(*args, **kwargs)

    color_cycle = ax._get_lines.color_cycle
    # Reassign the default colors to Set2 by Colorbrewer
    if iterable(args[0]):
        if isinstance(args[0], list):
            ncolors = len(args[0])
        else:
            if len(args[0].shape) == 2:
                ncolors = args[0].shape[1]
            else:
                ncolors = 1
        kwargs.setdefault('color', [next(color_cycle) for _ in range(ncolors)])
    else:
        kwargs.setdefault('color', next(color_cycle))
    kwargs.setdefault('edgecolor', 'white')
    show_ticks = kwargs.pop('show_ticks', False)

    # If no grid specified, don't draw one.
    grid = kwargs.pop('grid', None)

    # print 'hist kwargs', kwargs
    patches = ax.hist(*args, **kwargs)
    remove_chartjunk(ax, ['top', 'right'], grid=grid, show_ticks=show_ticks)
    return patches
1357845
def get_histogram(data):
    

    count = len(data)

    if count < 2:
        raise StatisticsError('Too few data points ({}) for get_histogram'.format(count))

    min_ = data[0]
    max_ = data[-1]
    std = stdev(data)

    bins = get_histogram_bins(min_, max_, std, count)

    res = {x: 0 for x in bins}

    for value in data:
        for bin_ in bins:
            if value <= bin_:
                res[bin_] += 1
                break

    return sorted(iteritems(res))
313584
def select(self, axis, index, force_copy: bool = False):
        """"""
        if axis == 0:
            if index == slice(None) and not force_copy:
                return self
            return self[index]
        else:
            raise ValueError("In Histogram1D.select(), axis must be 0.")
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)
967617
def MakePmfFromHist(hist, name=None):
    
    if name is None:
        name = hist.name

    # make a copy of the dictionary
    d = dict(hist.GetDict())
    pmf = Pmf(d, name)
    pmf.Normalize()
    return pmf
961771
def interpol_hist2d(h2d, oversamp_factor=10):
    
    from rootpy import ROOTError

    xlim = h2d.bins(axis=0)
    ylim = h2d.bins(axis=1)
    xn = h2d.nbins(0)
    yn = h2d.nbins(1)
    x = np.linspace(xlim[0], xlim[1], xn * oversamp_factor)
    y = np.linspace(ylim[0], ylim[1], yn * oversamp_factor)
    mat = np.zeros((xn, yn))
    for xi in range(xn):
        for yi in range(yn):
            try:
                mat[xi, yi] = h2d.interpolate(x[xi], y[yi])
            except ROOTError:
                continue
    return mat, x, y
1085255
public BitSet projectG2(BitSet set) {
        BitSet projection = new BitSet(secondGraphSize);
        RNode xNode = null;

        for (int x = set.nextSetBit(0); x >= 0; x = set.nextSetBit(x + 1)) {
            xNode = (RNode) graph.get(x);
            projection.set(xNode.rMap.id2);
        }
        return projection;
    }
1168167
function _histc( vector, edges ) {
		
		var id, counts = [];

		// Initialize our counts vector: (all zeros)
		for ( var i = -1; i < edges.length; i++ ) {
			counts[ i+1 ] = 0;
		} // end FOR i

		// For each value in the vector, find where the value resides along the edge vector:
		for ( var j = 0; j < vector.length; j++ ) {

			// Perform a binary search to find the index where the value equals or exceeds the corresponding value in the edge vector:
			id = binarysearch( edges, vector[ j ] );

			// Update the counts for a bin:
			counts[ id+1 ] += 1;

		} // end FOR i

		// Return the counts:
		return counts;

	}
137689
def sha1(self):
        

        if self._sha1 is None:
            self._sha1 = hashlib.sha1(self.dump()).digest()
        return self._sha1
1078447
def projection(self, **kwargs):
        
        viewpoint = kwargs.pop('viewpoint', None)
        if viewpoint is None:
            ndim = self.shape[0]-1
            viewpoint = N.zeros(ndim)
        plane = self.polar_plane(viewpoint)
        return self.slice(plane, **kwargs)
1177558
def make_random_histogram(length=100, num_bins=10):
    ""

    hist, bin_edges = np.histogram(np.random.random(length),
                                   bins=num_bins, density=True)

    # to ensure they sum to 1.0
    hist = hist / sum(hist)

    if len(hist) < 2:
        raise ValueError('Invalid histogram')

    return hist
850499
def fill_array(self, array, weights=None):
        
        try:
            try:
                from root_numpy import fill_hist as fill_func
            except ImportError:
                from root_numpy import fill_array as fill_func
        except ImportError:
            log.critical(
                "root_numpy is needed for Hist*.fill_array. "
                "Is it installed and importable?")
            raise
        fill_func(self, array, weights=weights)
214849
def line(h1: Union[Histogram1D, "HistogramCollection"], ax: Axes, *, errors: bool = False, **kwargs):
    """"""


    show_stats = kwargs.pop("show_stats", False)
    show_values = kwargs.pop("show_values", False)
    density = kwargs.pop("density", False)
    cumulative = kwargs.pop("cumulative", False)
    value_format = kwargs.pop("value_format", None)
    text_kwargs = pop_kwargs_with_prefix("text_", kwargs)
    kwargs["label"] = kwargs.get("label", h1.name)

    data = get_data(h1, cumulative=cumulative, density=density)
    _apply_xy_lims(ax, h1, data, kwargs)
    _add_ticks(ax, h1, kwargs)
    _add_labels(ax, h1, kwargs)

    if errors:
        err_data = get_err_data(h1, cumulative=cumulative, density=density)
        ax.errorbar(h1.bin_centers, data, yerr=err_data, fmt=kwargs.pop(
            "fmt", "-"), ecolor=kwargs.pop("ecolor", "black"), **kwargs)
    else:
        ax.plot(h1.bin_centers, data, **kwargs)

    if show_stats:
        _add_stats_box(h1, ax, stats=show_stats)
    if show_values:
        _add_values(ax, h1, data, value_format=value_format, **text_kwargs)
565077
def _histplot_op(ax, data, **kwargs):
    """"""
    bins = get_bins(data)
    ax.hist(data, bins=bins, align="left", density=True, **kwargs)
    return ax
166941
def plot(self):
        
        # The PyTables node tied to the current leaf of the databases tree
        current = self.vtgui.dbs_tree_view.currentIndex()
        leaf = self.vtgui.dbs_tree_model.nodeFromIndex(current).node

        data_name = leaf.name

        hists_1d = ['HistRelBcid', 'HistErrorCounter', 'HistTriggerErrorCounter', 'HistServiceRecord', 'HistTot', 'HistTdc', 'HistClusterTot', 'HistClusterSize']
        hists_2d = ['HistOcc', 'Enable', 'Imon', 'C_High', 'EnableDigInj', 'C_Low', 'FDAC', 'TDAC', 'HistTdcPixel', 'HistTotPixel', 'HistThreshold', 'HistNoise', 'HistThresholdFitted', 'HistNoiseFitted', 'HistThresholdFittedCalib', 'HistNoiseFittedCalib']

        if data_name in hists_1d:
            plot_1d_hist(hist=leaf[:], title=data_name)
        elif data_name in hists_2d:
            if data_name == 'HistOcc':
                leaf = np.sum(leaf[:], axis=2)
            plot_2d_hist(hist=leaf[:], title=data_name)
        elif 'Table' in str(type(leaf)) and len(leaf[:].dtype.names) <= 3:  # detect tables with less than 4 columns
            plot_table(leaf[:], title=data_name)
        elif data_name == 'HitOrCalibration':
            print 'Comming soon'
        else:
            print 'Plotting', data_name, '(%s) is not supported!' % type(leaf)
455723
def inverseHistogram(hist, bin_range):
    
    data = hist.astype(float) / np.min(hist[np.nonzero(hist)])
    new_data = np.empty(shape=np.sum(data, dtype=int))
    i = 0
    xvals = np.linspace(bin_range[0], bin_range[1], len(data))
    for d, x in zip(data, xvals):
        new_data[i:i + d] = x
        i += int(d)
    return new_data