Create histogram collection with shared binnning.
1020
def collection(data, bins=10, *args, **kwargs):
    """"""
    from physt.histogram_collection import HistogramCollection
    if hasattr(data, "columns"):
        data = {column: data[column] for column in data.columns}
    return HistogramCollection.multi_h1(data, bins, **kwargs)
528409
def binning(keys, start, end, count, axes=None):
    
    if isinstance(keys, tuple):
        n_keys = len(keys)
    else:
        n_keys = 1

    bins = np.linspace(start, end, count+1, endpoint=True)
    idx = np.searchsorted(bins, keys)
    if axes is None:
        axes = [-1]
824555
def packb(obj, **kwargs):
    """"""
    kwargs.setdefault('use_bin_type', True)
    return msgpack.packb(obj, **kwargs)
964338
def make_random_histogram(center=0.0, stdev=default_stdev, length=default_feature_dim, num_bins=default_num_bins):
    ""

    hist, bin_edges = np.histogram(get_distr(center, stdev, length),
                                   range=edge_range, 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, bin_edges
874540
def with_histogram(name, reservoir_type="uniform", *reservoir_args, **reservoir_kwargs):
    

    hmetric = get_or_create_histogram(name, reservoir_type, *reservoir_args, **reservoir_kwargs)

    def wrapper(f):

        @functools.wraps(f)
        def fun(*args, **kwargs):
            t1 = time.time()
            res = f(*args, **kwargs)
            t2 = time.time()

            hmetric.notify(t2-t1)
            return res

        return fun

    return wrapper
1204111
def _generate_collection(group, ax, ctype, colors):
    ''''''
    color = TREE_COLOR[ctype]

    # generate segment collection
    collection = PolyCollection(group, closed=False, antialiaseds=True,
                                edgecolors='face', facecolors=color)

    # add it to the axes
    ax.add_collection(collection)

    # dummy plot for the legend
    if color not in colors:
        label = str(ctype).replace('NeuriteType.', '').replace('_', ' ').capitalize()
        ax.plot((0., 0.), (0., 0.), c=color, label=label)
        colors.add(color)
843422
def add(self, histogram: Histogram1D):
        """"""
        if self.binning and not self.binning == histogram.binning:
            raise ValueError("Cannot add histogram with different binning.")
        self.histograms.append(histogram)
144722
def from_dict(cls, a_dict: Mapping[str, Any]) -> "HistogramBase":
        
        kwargs = cls._kwargs_from_dict(a_dict)
        return cls(**kwargs)
695875
def create_shared_noise(count):
    """"""
    seed = 123
    noise = np.random.RandomState(seed).randn(count).astype(np.float32)
    return noise
1306138
def create_from_dict(data: dict, format_name: str, check_version: bool = True) -> Union[HistogramBase, HistogramCollection]:
    
    # Version
    if check_version:
        compatible_version = data["physt_compatible"]
        require_compatible_version(compatible_version, format_name)

    # Construction
    histogram_type = data["histogram_type"]
    if histogram_type == "histogram_collection":
        klass = HistogramCollection
    else:
        klass = find_subclass(HistogramBase, histogram_type)
    return klass.from_dict(data)
408342
private Metric collectHistogram(String dropwizardName, Histogram histogram) {
    String metricName = DropWizardUtils.generateFullMetricName(dropwizardName, "histogram");
    String metricDescription =
        DropWizardUtils.generateFullMetricDescription(dropwizardName, histogram);
    return collectSnapshotAndCount(
        metricName, metricDescription, DEFAULT_UNIT, histogram.getSnapshot(), histogram.getCount());
  }
517734
public HistogramVisual asVisual()
  {
    float[] visualCounts = new float[bins.length - 2];
    for (int i = 0; i < visualCounts.length; ++i) {
      visualCounts[i] = (float) bins[i + 1];
    }
    return new HistogramVisual(breaks, visualCounts, new float[]{min, max});
  }
124681
def binPack(self, jobShapes):
        """"""
        # TODO: Check for redundancy with batchsystems.mesos.JobQueue() sorting
        logger.debug('Running bin packing for node shapes %s and %s job(s).',
                     self.nodeShapes, len(jobShapes))
        # Sort in descending order from largest to smallest. The FFD like-strategy will pack the
        # jobs in order from longest to shortest.
        jobShapes.sort()
        jobShapes.reverse()
        assert len(jobShapes) == 0 or jobShapes[0] >= jobShapes[-1]
        for jS in jobShapes:
            self.addJobShape(jS)
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
220299
def fill_n(self, values, weights=None, dropna: bool = True):
        
        # TODO: Unify with HistogramBase
        values = np.asarray(values)
        if dropna:
            values = values[~np.isnan(values)]
        if self._binning.is_adaptive():
            map = self._binning.force_bin_existence(values)
            self._reshape_data(self._binning.bin_count, map)
        if weights:
            weights = np.asarray(weights)
            self._coerce_dtype(weights.dtype)
        (frequencies, errors2, underflow, overflow, stats) = \
            calculate_frequencies(values, self._binning, dtype=self.dtype,
                                  weights=weights, validate_bins=False)
        self._frequencies += frequencies
        self._errors2 += errors2
        # TODO: check that adaptive does not produce under-/over-flows?
        if self.keep_missed:
            self.underflow += underflow
            self.overflow += overflow
        if self._stats:
            for key in self._stats:
                self._stats[key] += stats.get(key, 0.0)
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
964239
def _pack_bin(self, pix):
        

        r = (pix[0] >> 3) & 0x1F
        g = (pix[1] >> 2) & 0x3F
        b = (pix[2] >> 3) & 0x1F
        bits16 = (r << 11) + (g << 5) + b
        return struct.pack('H', bits16)