|
6 | 6 | import unyt
|
7 | 7 |
|
8 | 8 |
|
| 9 | +adaptive_bin_cache = {} |
| 10 | + |
| 11 | + |
| 12 | +def adaptive_bin_hash( |
| 13 | + values, |
| 14 | + lowest_value, |
| 15 | + highest_value, |
| 16 | + base_n_bins, |
| 17 | + minimum_in_bin, |
| 18 | + logarithmic, |
| 19 | + stretch_final_bin, |
| 20 | +): |
| 21 | + """ |
| 22 | + Hash for adaptive binning. Note that this can raise AttributeError |
| 23 | + in the case where the array is unhashable. |
| 24 | + """ |
| 25 | + |
| 26 | + this_hash = ( |
| 27 | + f"{values.size}{values.name}{lowest_value}{highest_value}" |
| 28 | + f"{base_n_bins}{minimum_in_bin}{logarithmic}{stretch_final_bin}" |
| 29 | + ) |
| 30 | + |
| 31 | + return this_hash |
| 32 | + |
| 33 | + |
9 | 34 | def create_adaptive_bins(
|
10 | 35 | values: unyt.unyt_array,
|
11 | 36 | lowest_value: unyt.unyt_quantity,
|
@@ -58,7 +83,36 @@ def create_adaptive_bins(
|
58 | 83 | bin_edges: unyt.unyt_array, optional
|
59 | 84 | Bin edges that were used in the binning process.
|
60 | 85 |
|
| 86 | + Notes |
| 87 | + ----- |
| 88 | +
|
| 89 | + Caches the output as this procedure can be very expensive, and will be |
| 90 | + repeated several times. |
| 91 | +
|
61 | 92 | """
|
| 93 | + |
| 94 | + # First we check in the cache to see if we have already performed |
| 95 | + # the binning procedure. |
| 96 | + try: |
| 97 | + this_hash = adaptive_bin_hash( |
| 98 | + values=values, |
| 99 | + lowest_value=lowest_value, |
| 100 | + highest_value=highest_value, |
| 101 | + base_n_bins=base_n_bins, |
| 102 | + minimum_in_bin=minimum_in_bin, |
| 103 | + logarithmic=logarithmic, |
| 104 | + stretch_final_bin=stretch_final_bin, |
| 105 | + ) |
| 106 | + except AttributeError: |
| 107 | + this_hash = False |
| 108 | + |
| 109 | + if this_hash: |
| 110 | + try: |
| 111 | + return adaptive_bin_cache[this_hash] |
| 112 | + except: |
| 113 | + # Not created yet! |
| 114 | + pass |
| 115 | + |
62 | 116 | assert (
|
63 | 117 | values.units == lowest_value.units and lowest_value.units == highest_value.units
|
64 | 118 | ), "Please ensure that all value quantities have the same units."
|
@@ -162,5 +216,8 @@ def create_adaptive_bins(
|
162 | 216 | np.array([*bin_edges_left, bin_edges_right[-1]]), units=values.units
|
163 | 217 | )
|
164 | 218 |
|
| 219 | + if this_hash: |
| 220 | + adaptive_bin_cache[this_hash] = (bin_centers, bin_edges) |
| 221 | + |
165 | 222 | return bin_centers, bin_edges
|
166 | 223 |
|
0 commit comments