summaryrefslogtreecommitdiff
path: root/silx/math/histogram.py
blob: af9ee68bfc647273d511cebfcfb23e367dbfdc13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# coding: utf-8
# /*##########################################################################
# Copyright (C) 2016 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ############################################################################*/


"""
This module provides a function and a class to compute multidimensional
histograms.


Classes
=======

- :class:`Histogramnd` : multi dimensional histogram.
- :class:`HistogramndLut` : optimized to compute several histograms from data sharing the same coordinates.

Examples
========

Single histogram
----------------

Given some 3D data:

>>> import numpy as np
>>> shape = (10**7, 3)
>>> sample = np.random.random(shape) * 500
>>> weights = np.random.random((shape[0],))

Computing the histogram with Histogramnd :

>>> from silx.math import Histogramnd
>>> n_bins = 35
>>> ranges = [[40., 150.], [-130., 250.], [0., 505]]
>>> histo, w_histo, edges = Histogramnd(sample, n_bins=n_bins, histo_range=ranges, weights=weights)

Histogramnd can accumulate sets of data that don't have the same
coordinates :

>>> from silx.math import Histogramnd
>>> histo_obj = Histogramnd(sample, n_bins=n_bins, histo_range=ranges, weights=weights)
>>> sample_2 = np.random.random(shape) * 200
>>> weights_2 = np.random.random((shape[0],))
>>> histo_obj.accumulate(sample_2, weights=weights_2)

And then access the results:

>>> histo = histo_obj.histo
>>> weighted_histo = histo_obj.weighted_histo

or even:

>>> histo, w_histo, edges = histo_obj

Accumulating histograms (LUT)
-----------------------------
In some situations we need to compute the weighted histogram of several
sets of data (weights) that have the same coordinates (sample).

Again, some data (2 sets of weights) :

>>> import numpy as np
>>> shape = (10**7, 3)
>>> sample = np.random.random(shape) * 500
>>> weights_1 = np.random.random((shape[0],))
>>> weights_2 = np.random.random((shape[0],))

And getting the result with HistogramLut :

>>> from silx.math import HistogramndLut

>>> n_bins = 35
>>> ranges = [[40., 150.], [-130., 250.], [0., 505]]

>>> histo_lut = HistogramndLut(sample, ranges, n_bins)
                           
First call, with weight_1 :

>>> histo_lut.accumulate(weights_1)

Second call, with weight_2 :

>>> histo_lut.accumulate(weights_2)

Retrieving the results (this is a copy of what's actually stored in
this instance) :

>>> histo = histo_lut.histo
>>> w_histo = histo_lut.weighted_histo

Note that the following code gives the same result, but the
HistogramndLut instance does not store the accumulated weighted histogram.

First call with weights_1

>>> histo, w_histo = histo_lut.apply_lut(weights_1)

Second call with weights_2

>>> histo, w_histo = histo_lut.apply_lut(weights_2, histo=histo, weighted_histo=w_histo)

Bin edges
---------
When computing an histogram the caller is asked to provide the histogram
range along each coordinates (parameter *histo_range*). This parameter must
be given a [N, 2] array where N is the number of dimensions of the histogram.

In other words, the caller must provide, for each dimension,
the left edge of the first (*leftmost*) bin, and the right edge of the
last (*rightmost*) bin.

E.g. : for a 1D sample, for a histo_range equal to [0, 10] and n_bins=4, the
bins ranges will be :

* [0, 2.5[, [2.5, 5[, [5, 7.5[, [7.5, 10 **[** if last_bin_closed = **False**
* [0, 2.5[, [2.5, 5[, [5, 7.5[, [7.5, 10 **]** if last_bin_closed = **True**

....
"""

__authors__ = ["D. Naudet"]
__license__ = "MIT"
__date__ = "02/10/2017"

import numpy as np
from .chistogramnd import chistogramnd as _chistogramnd  # noqa
from .chistogramnd_lut import histogramnd_get_lut as _histo_get_lut
from .chistogramnd_lut import histogramnd_from_lut as _histo_from_lut


class Histogramnd(object):
    """
    Computes the multidimensional histogram of some data.
    """

    def __init__(self,
                 sample,
                 histo_range,
                 n_bins,
                 weights=None,
                 weight_min=None,
                 weight_max=None,
                 last_bin_closed=False,
                 wh_dtype=None):
        """
        :param sample:
            The data to be histogrammed.
            Its shape must be either
            (N,) if it contains one dimensional coordinates,
            or an (N,D) array where the rows are the
            coordinates of points in a D dimensional space.
            The following dtypes are supported : :class:`numpy.float64`,
            :class:`numpy.float32`, :class:`numpy.int32`.

            .. warning:: if sample is not a C_CONTIGUOUS ndarray (e.g : a non
                contiguous slice) then histogramnd will have to do make an internal
                copy.
        :type sample: :class:`numpy.array`

        :param histo_range:
            A (N, 2) array containing the histogram range along each dimension,
            where N is the sample's number of dimensions.
        :type histo_range: array_like

        :param n_bins:
            The number of bins :
                * a scalar (same number of bins for all dimensions)
                * a D elements array (number of bins for each dimensions)
        :type n_bins: scalar or array_like

        :param weights:
            A N elements numpy array of values associated with
            each sample.
            The values of the *weighted_histo* array
            returned by the function are equal to the sum of
            the weights associated with the samples falling
            into each bin.
            The following dtypes are supported : :class:`numpy.float64`,
            :class:`numpy.float32`, :class:`numpy.int32`.

            .. note:: If None, the weighted histogram returned will be None.
        :type weights: *optional*, :class:`numpy.array`

        :param weight_min:
            Use this parameter to filter out all samples whose
            weights are lower than this value.

            .. note:: This value will be cast to the same type
                as *weights*.
        :type weight_min: *optional*, scalar

        :param weight_max:
            Use this parameter to filter out all samples whose
            weights are higher than this value.

            .. note:: This value will be cast to the same type
                as *weights*.

        :type weight_max: *optional*, scalar

        :param last_bin_closed:
            By default the last bin is half
            open (i.e.: [x,y) ; x included, y
            excluded), like all the other bins.
            Set this parameter to true if you want
            the LAST bin to be closed.
        :type last_bin_closed: *optional*, :class:`python.boolean`

        :param wh_dtype: type of the weighted histogram array.
            If not provided, the weighted histogram array will contain values
            of type numpy.double. Allowed values are : `numpy.double` and
            `numpy.float32`
        :type wh_dtype: *optional*, numpy data type
        """

        self.__histo_range = histo_range
        self.__n_bins = n_bins
        self.__last_bin_closed = last_bin_closed
        self.__wh_dtype = wh_dtype

        if sample is None:
            self.__data = [None, None, None]
        else:
            self.__data = _chistogramnd(sample,
                                        self.__histo_range,
                                        self.__n_bins,
                                        weights=weights,
                                        weight_min=weight_min,
                                        weight_max=weight_max,
                                        last_bin_closed=self.__last_bin_closed,
                                        wh_dtype=self.__wh_dtype)

    def __getitem__(self, key):
        """
        If necessary, results can be unpacked from an instance of Histogramnd :
        *histogram*, *weighted histogram*, *bins edge*.

        Example :

        .. code-block:: python

            histo, w_histo, edges = Histogramnd(sample, histo_range, n_bins, weights)

        """
        return self.__data[key]

    def accumulate(self,
                   sample,
                   weights=None,
                   weight_min=None,
                   weight_max=None):
        """
        Computes the multidimensional histogram of some data and accumulates it
        into the histogram held by this instance of Histogramnd.

        :param sample:
            The data to be histogrammed.
            Its shape must be either
            (N,) if it contains one dimensional coordinates,
            or an (N,D) array where the rows are the
            coordinates of points in a D dimensional space.
            The following dtypes are supported : :class:`numpy.float64`,
            :class:`numpy.float32`, :class:`numpy.int32`.

            .. warning:: if sample is not a C_CONTIGUOUS ndarray (e.g : a non
                contiguous slice) then histogramnd will have to do make an internal
                copy.
        :type sample: :class:`numpy.array`

        :param weights:
            A N elements numpy array of values associated with
            each sample.
            The values of the *weighted_histo* array
            returned by the function are equal to the sum of
            the weights associated with the samples falling
            into each bin.
            The following dtypes are supported : :class:`numpy.float64`,
            :class:`numpy.float32`, :class:`numpy.int32`.

            .. note:: If None, the weighted histogram returned will be None.
        :type weights: *optional*, :class:`numpy.array`

        :param weight_min:
            Use this parameter to filter out all samples whose
            weights are lower than this value.

            .. note:: This value will be cast to the same type
                as *weights*.
        :type weight_min: *optional*, scalar

        :param weight_max:
            Use this parameter to filter out all samples whose
            weights are higher than this value.

            .. note:: This value will be cast to the same type
                as *weights*.
        :type weight_max: *optional*, scalar
        """
        result = _chistogramnd(sample,
                               self.__histo_range,
                               self.__n_bins,
                               weights=weights,
                               weight_min=weight_min,
                               weight_max=weight_max,
                               last_bin_closed=self.__last_bin_closed,
                               histo=self.__data[0],
                               weighted_histo=self.__data[1],
                               wh_dtype=self.__wh_dtype)
        if self.__data[0] is None:
            self.__data = result
        elif self.__data[1] is None and result[1] is not None:
            self.__data = result

    histo = property(lambda self: self[0])
    """ Histogram array, or None if this instance was initialized without
        <sample> and accumulate has not been called yet.

        .. note:: this is a **reference** to the array store in this
             Histogramnd instance, use with caution.
    """
    weighted_histo = property(lambda self: self[1])
    """ Weighted Histogram, or None if this instance was initialized without
        <sample>, or no weights have been passed to __init__ nor accumulate.

        .. note:: this is a **reference** to the array store in this
            Histogramnd instance, use with caution.
    """
    edges = property(lambda self: self[2])
    """ Bins edges, or None if this instance was initialized without
        <sample> and accumulate has not been called yet.
    """


class HistogramndLut(object):
    """
    The HistogramndLut class allows you to bin data onto a regular grid.
    The use of HistogramndLut is interesting when several sets of data that
    share the same coordinates (*sample*) have to be mapped onto the same grid.
    """

    def __init__(self,
                 sample,
                 histo_range,
                 n_bins,
                 last_bin_closed=False,
                 dtype=None):
        """
        :param sample:
            The coordinates of the data to be histogrammed.
            Its shape must be either (N,) if it contains one dimensional
            coordinates, or an (N, D) array where the rows are the
            coordinates of points in a D dimensional space.
            The following dtypes are supported : :class:`numpy.float64`,
            :class:`numpy.float32`, :class:`numpy.int32`.
        :type sample: :class:`numpy.array`

        :param histo_range:
            A (N, 2) array containing the histogram range along each dimension,
            where N is the sample's number of dimensions.
        :type histo_range: array_like

        :param n_bins:
            The number of bins :
                * a scalar (same number of bins for all dimensions)
                * a D elements array (number of bins for each dimensions)
        :type n_bins: scalar or array_like

        :param dtype: data type of the weighted histogram. If None, the data type
            will be the same as the first weights array provided (on first call of
            the instance).
        :type dtype: `numpy.dtype`

        :param last_bin_closed:
            By default the last bin is half
            open (i.e.: [x,y) ; x included, y
            excluded), like all the other bins.
            Set this parameter to true if you want
            the LAST bin to be closed.
        :type last_bin_closed: *optional*, :class:`python.boolean`
        """
        lut, histo, edges = _histo_get_lut(sample,
                                           histo_range,
                                           n_bins,
                                           last_bin_closed=last_bin_closed)

        self.__n_bins = np.array(histo.shape)
        self.__histo_range = histo_range
        self.__lut = lut
        self.__histo = None
        self.__weighted_histo = None
        self.__edges = edges
        self.__dtype = dtype
        self.__shape = histo.shape
        self.__last_bin_closed = last_bin_closed
        self.clear()

    def clear(self):
        """
        Resets the instance (zeroes the histograms).
        """
        self.__weighted_histo = None
        self.__histo = None

    @property
    def lut(self):
        """
        Copy of the Lut
        """
        return self.__lut.copy()

    def histo(self, copy=True):
        """
        Histogram (a copy of it), or None if `~accumulate` has not been called yet
        (or clear was just called).
        If *copy* is set to False then the actual reference to the array is
        returned *(use with caution)*.
        """
        if copy and self.__histo is not None:
            return self.__histo.copy()
        return self.__histo

    def weighted_histo(self, copy=True):
        """
        Weighted histogram (a copy of it), or None if `~accumulate` has not been called yet
        (or clear was just called). If *copy* is set to False then the actual
        reference to the array is returned *(use with caution)*.
        """
        if copy and self.__weighted_histo is not None:
            return self.__weighted_histo.copy()
        return self.__weighted_histo

    @property
    def histo_range(self):
        """
        Bins ranges.
        """
        return self.__histo_range.copy()

    @property
    def n_bins(self):
        """
        Number of bins in each direction.
        """
        return self.__n_bins.copy()

    @property
    def bins_edges(self):
        """
        Bins edges of the histograms, one array for each dimensions.
        """
        return tuple([edges[:] for edges in self.__edges])

    @property
    def last_bin_closed(self):
        """
        Returns True if the rightmost bin in each dimension is close (i.e :
        values equal to the rightmost bin edge is included in the bin).
        """
        return self.__last_bin_closed

    def accumulate(self,
                   weights,
                   weight_min=None,
                   weight_max=None):
        """
        Computes the multidimensional histogram of some data and adds it to
        the current histogram stored by this instance. The results can be
        retrieved with the :attr:`~.histo` and :attr:`~.weighted_histo`
        properties.

        :param weights:
            A numpy array of values associated with each sample. The number of
            elements in the array must be the same as the number of samples
            provided at instantiation time.
        :type histo_range: array_like

        :param weight_min:
            Use this parameter to filter out all samples whose
            weights are lower than this value.

            .. note:: This value will be cast to the same type
                as *weights*.
        :type weight_min: *optional*, scalar

        :param weight_max:
            Use this parameter to filter out all samples whose
            weights are higher than this value.

            .. note:: This value will be cast to the same type
                as *weights*.

        :type weight_max: *optional*, scalar
        """
        if self.__dtype is None:
            self.__dtype = weights.dtype

        histo, w_histo = _histo_from_lut(weights,
                                         self.__lut,
                                         histo=self.__histo,
                                         weighted_histo=self.__weighted_histo,
                                         shape=self.__shape,
                                         dtype=self.__dtype,
                                         weight_min=weight_min,
                                         weight_max=weight_max)

        if self.__histo is None:
            self.__histo = histo

        if self.__weighted_histo is None:
            self.__weighted_histo = w_histo

    def apply_lut(self,
                  weights,
                  histo=None,
                  weighted_histo=None,
                  weight_min=None,
                  weight_max=None):
        """
        Computes the multidimensional histogram of some data and returns the
        result (it is NOT added to the current histogram stored by this
        instance).

        :param weights:
            A numpy array of values associated with each sample. The number of
            elements in the array must be the same as the number of samples
            provided at instantiation time.
        :type histo_range: array_like

        :param histo:
            Use this parameter if you want to pass your
            own histogram array instead of the one
            created by this function. New values
            will be added to this array. The returned array
            will then be this one.
        :type histo: *optional*, :class:`numpy.array`

        :param weighted_histo:
            Use this parameter if you want to pass your
            own weighted histogram array instead of
            the created by this function. New
            values will be added to this array. The returned array
            will then be this one (same reference).
        :type weighted_histo: *optional*, :class:`numpy.array`

        :param weight_min:
            Use this parameter to filter out all samples whose
            weights are lower than this value.

            .. note:: This value will be cast to the same type
                as *weights*.
        :type weight_min: *optional*, scalar

        :param weight_max:
            Use this parameter to filter out all samples whose
            weights are higher than this value.

            .. note:: This value will be cast to the same type
                as *weights*.
        :type weight_max: *optional*, scalar
        """
        histo, w_histo = _histo_from_lut(weights,
                                         self.__lut,
                                         histo=histo,
                                         weighted_histo=weighted_histo,
                                         shape=self.__shape,
                                         dtype=self.__dtype,
                                         weight_min=weight_min,
                                         weight_max=weight_max)
        self.__dtype = w_histo.dtype
        return histo, w_histo

if __name__ == '__main__':
    pass