max-div 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
max_div/__init__.py ADDED
File without changes
@@ -0,0 +1 @@
1
+ from .sample_int import benchmark_sample_int
@@ -0,0 +1,85 @@
1
+ import math
2
+
3
+ import numpy as np
4
+
5
+ from max_div.internal.benchmarking import BenchmarkResult, benchmark
6
+ from max_div.internal.compat import is_numba_installed
7
+ from max_div.sampling.discrete import sample_int
8
+
9
+
10
+ def benchmark_sample_int(turbo: bool = False) -> None:
11
+ """
12
+ Benchmarks the `sample_int` function from `max_div.sampling.discrete`.
13
+
14
+ Different scenarios are tested:
15
+
16
+ * with & without replacement
17
+ * uniform & non-uniform sampling
18
+ * `use_numba` True and False
19
+ * different sizes of (`n`, `k`):
20
+ * (10, 1), (100, 1), (1000, 1), (5000, 1), (10000, 1)
21
+ * (10000, 10), (10000, 100), (10000, 1000), (10000, 5000), (10000, 10000)
22
+
23
+ :param turbo: If `True`, a much shorter (but less reliable) benchmark is run; intended for testing purposes.
24
+ """
25
+
26
+ if not is_numba_installed():
27
+ print("====================================================================================")
28
+ print(" WARNING: Numba is not installed!!!")
29
+ print("====================================================================================")
30
+
31
+ print("Benchmarking `sample_int`...")
32
+ print()
33
+ print("".ljust(30) + "use_numba=False".rjust(25) + "use_numba=True".rjust(25))
34
+
35
+ for replace, use_p, desc in [
36
+ (True, False, "with replacement, uniform"),
37
+ (False, False, "without replacement, uniform"),
38
+ (True, True, "with replacement, non-uniform"),
39
+ (False, True, "without replacement, non-uniform"),
40
+ ]:
41
+ print(desc.upper())
42
+
43
+ for n, k in [
44
+ (10, 1),
45
+ (100, 1),
46
+ (1000, 1),
47
+ (5000, 1),
48
+ (10000, 1),
49
+ (10000, 10),
50
+ (10000, 100),
51
+ (10000, 1000),
52
+ (10000, 5000),
53
+ (10000, 10000),
54
+ ]:
55
+ size_str = f"{k:<6_} out of {n:<6_}"
56
+
57
+ results: list[BenchmarkResult] = []
58
+ for use_numba in [False, True]:
59
+ if use_p:
60
+ p = np.random.rand(n)
61
+ p /= p.sum()
62
+ else:
63
+ p = None
64
+
65
+ def func_to_benchmark():
66
+ sample_int(n=n, k=k, replace=replace, p=p, use_numba=use_numba)
67
+
68
+ results.append(
69
+ benchmark(
70
+ f=func_to_benchmark,
71
+ t_per_run=0.001 if turbo else 0.1,
72
+ n_warmup=3 if turbo else 10,
73
+ n_benchmark=3 if turbo else 30,
74
+ silent=True,
75
+ )
76
+ )
77
+
78
+ print(
79
+ (" " * 4)
80
+ + size_str.ljust(26)
81
+ + results[0].t_sec_with_uncertainty_str.rjust(25)
82
+ + results[1].t_sec_with_uncertainty_str.rjust(25)
83
+ )
84
+
85
+ print()
File without changes
@@ -0,0 +1,2 @@
1
+ from ._micro_benchmark import BenchmarkResult, benchmark
2
+ from ._timer import Timer
@@ -0,0 +1,112 @@
1
+ from dataclasses import dataclass
2
+ from typing import Callable
3
+
4
+ import numpy as np
5
+
6
+ from max_div.internal.formatting import format_short_time_duration
7
+ from max_div.internal.utils import clip
8
+
9
+ from ._timer import Timer
10
+
11
+
12
+ # =================================================================================================
13
+ # BenchmarkResult
14
+ # =================================================================================================
15
+ @dataclass(frozen=True)
16
+ class BenchmarkResult:
17
+ t_sec_q_25: float
18
+ t_sec_q_50: float
19
+ t_sec_q_75: float
20
+
21
+ @property
22
+ def t_sec_str(self) -> str:
23
+ s_median = format_short_time_duration(dt_sec=self.t_sec_q_50, right_aligned=True, spaced=True, long_units=True)
24
+ return s_median
25
+
26
+ @property
27
+ def t_sec_with_uncertainty_str(self) -> str:
28
+ s_median = self.t_sec_str
29
+ s_perc = f"{50 * (self.t_sec_q_75 - self.t_sec_q_25) / self.t_sec_q_50:.1f}%"
30
+ return f"{s_median} ± {s_perc}"
31
+
32
+
33
+ # =================================================================================================
34
+ # Main benchmarking function
35
+ # =================================================================================================
36
+ def benchmark(
37
+ f: Callable,
38
+ t_per_run: float = 0.1,
39
+ n_warmup: int = 10,
40
+ n_benchmark: int = 30,
41
+ silent: bool = False,
42
+ ) -> BenchmarkResult:
43
+ """
44
+ Adaptive micro-benchmarking function, to determine the duration/execution of the provided callable `f`.
45
+
46
+ :param f: (Callable) Function to benchmark. Should take no arguments.
47
+ :param t_per_run: (float, default=0.1) time in seconds we want to target per benchmarking run.
48
+ # of executions/run is adjusted to meet this target.
49
+ :param n_warmup: (int, default=10) Number of warmup runs to perform before benchmarking.
50
+ :param n_benchmark: (int, default=30) Number of benchmark runs to perform.
51
+ :param silent: (bool, default=False) If True, suppresses any output during benchmarking.
52
+ :return: Median estimate of duration/execution of `f` in seconds.
53
+ """
54
+
55
+ # --- init --------------------------------------------
56
+ lst_t = [] # list of measured times per execution in seconds
57
+ n_executions = 1 # number of executions per run, adjusted dynamically
58
+ f_baseline = _baseline_fun # baseline function to subtract overhead
59
+
60
+ if not silent:
61
+ print("Benchmarking: ", end="")
62
+
63
+ # --- main loop ---------------------------------------
64
+ for i in range(n_warmup + n_benchmark):
65
+ # run
66
+ with Timer() as timer_tot:
67
+ # baseline
68
+ with Timer() as timer_baseline:
69
+ for _ in range(n_executions):
70
+ f_baseline()
71
+ t_baseline = timer_baseline.t_elapsed_sec()
72
+
73
+ # actual function
74
+ with Timer() as timer_f:
75
+ for _ in range(n_executions):
76
+ f()
77
+ t_f = timer_f.t_elapsed_sec()
78
+
79
+ # store results of benchmark runs
80
+ if i >= n_warmup:
81
+ lst_t.append(abs(t_f - t_baseline) / n_executions) # abs value to avoid negative times for very fast 'f'.
82
+ if not silent:
83
+ print(".", end="")
84
+ else:
85
+ if not silent:
86
+ print("w", end="")
87
+
88
+ # adjust n_executions
89
+ t_tot = timer_tot.t_elapsed_sec()
90
+ n_executions = round(
91
+ clip(
92
+ value=n_executions * (t_per_run / t_tot),
93
+ min_value=max(1.0, n_executions / 10),
94
+ max_value=n_executions * 10,
95
+ )
96
+ )
97
+
98
+ # --- finalize ----------------------------------------
99
+ q25, q50, q75 = np.percentile(lst_t, [25, 50, 75])
100
+ result = BenchmarkResult(t_sec_q_25=q25, t_sec_q_50=q50, t_sec_q_75=q75)
101
+ if not silent:
102
+ print(f" {result.t_sec_with_uncertainty_str} per execution")
103
+
104
+ # --- return result -----------------------------------
105
+ return result
106
+
107
+
108
+ # =================================================================================================
109
+ # Baseline benchmarks
110
+ # =================================================================================================
111
+ def _baseline_fun():
112
+ pass
@@ -0,0 +1,35 @@
1
+ import time
2
+
3
+
4
+ class Timer:
5
+ """
6
+ Class acting as a context manager to measure time elapsed. Elapsed time can be retrieved using t_elapsed().
7
+ """
8
+
9
+ # --- constructor -------------------------------------
10
+ def __init__(self):
11
+ self._start: float | None = None
12
+ self._end: float | None = None
13
+
14
+ # --- context manager ---------------------------------
15
+ def __enter__(self):
16
+ self._start = time.perf_counter_ns()
17
+ return self
18
+
19
+ def __exit__(self, exc_type, exc_val, exc_tb):
20
+ self._end = time.perf_counter_ns()
21
+
22
+ # --- extract results ---------------------------------
23
+ def t_elapsed_nsec(self) -> float:
24
+ if self._start is None:
25
+ raise RuntimeError("Timer has not been started.")
26
+
27
+ if self._end is None:
28
+ # timer still running
29
+ return time.perf_counter_ns() - self._start
30
+ else:
31
+ # timer finished
32
+ return self._end - self._start
33
+
34
+ def t_elapsed_sec(self) -> float:
35
+ return self.t_elapsed_nsec() / 1e9
@@ -0,0 +1 @@
1
+ from ._numba import is_numba_installed, numba
@@ -0,0 +1,14 @@
1
+ # =================================================================================================
2
+ # Transparant handling of original numba vs dummy numba
3
+ # =================================================================================================
4
+ try:
5
+ import numba
6
+ except ImportError:
7
+ from ._dummy_numba import Numba as numba
8
+
9
+
10
+ # =================================================================================================
11
+ # Helpers
12
+ # =================================================================================================
13
+ def is_numba_installed() -> bool:
14
+ return numba.__version__ != "0.0.0"
@@ -0,0 +1,94 @@
1
+ """
2
+ Implements a dummy version of Numba for environments where Numba is not available.
3
+ Main goal is that code that uses @numba.njit or numba.tuped.Dict, ... does not break and transparently falls back to standard Python.
4
+ """
5
+
6
+ from ._helpers import dummy_decorator
7
+
8
+
9
+ # =================================================================================================
10
+ # Dummy typed containers
11
+ # =================================================================================================
12
+ class NumbaTypedDict(dict):
13
+ @staticmethod
14
+ def empty(*args, **kwargs):
15
+ return dict()
16
+
17
+
18
+ class NumbaTypedList(list):
19
+ @staticmethod
20
+ def empty_list(*args, **kwargs):
21
+ return list()
22
+
23
+
24
+ # =================================================================================================
25
+ # Main dummy package tree
26
+ # =================================================================================================
27
+ class NumbaTyped:
28
+ # implements subset
29
+ Dict = NumbaTypedDict
30
+ List = NumbaTypedList
31
+
32
+
33
+ class NumbaTypes:
34
+ # implements dummies for all members of numba.types.__all__
35
+ int8 = object()
36
+ int16 = object()
37
+ int32 = object()
38
+ int64 = object()
39
+ uint8 = object()
40
+ uint16 = object()
41
+ uint32 = object()
42
+ uint64 = object()
43
+ intp = object()
44
+ uintp = object()
45
+ intc = object()
46
+ uintc = object()
47
+ ssize_t = object()
48
+ size_t = object()
49
+ boolean = object()
50
+ float32 = object()
51
+ float64 = object()
52
+ complex64 = object()
53
+ complex128 = object()
54
+ bool_ = object()
55
+ byte = object()
56
+ char = object()
57
+ uchar = object()
58
+ short = object()
59
+ ushort = object()
60
+ int_ = object()
61
+ uint = object()
62
+ long_ = object()
63
+ ulong = object()
64
+ longlong = object()
65
+ ulonglong = object()
66
+ double = object()
67
+ void = object()
68
+ none = object()
69
+ b1 = object()
70
+ i1 = object()
71
+ i2 = object()
72
+ i4 = object()
73
+ i8 = object()
74
+ u1 = object()
75
+ u2 = object()
76
+ u4 = object()
77
+ u8 = object()
78
+ f4 = object()
79
+ f8 = object()
80
+ c8 = object()
81
+ c16 = object()
82
+ optional = object()
83
+ ffi_forced_object = object()
84
+ ffi = object()
85
+ deferred_type = object()
86
+ bool = object()
87
+
88
+
89
+ class Numba:
90
+ __version__ = "0.0.0"
91
+ jit = dummy_decorator
92
+ njit = dummy_decorator
93
+ typed = NumbaTyped
94
+ types = NumbaTypes
@@ -0,0 +1,14 @@
1
+ from typing import Callable
2
+
3
+
4
+ def dummy_decorator(*args, **kwargs):
5
+ # dummy decorator that does nothing and can be used with or without arguments
6
+ if len(args) == 1 and isinstance(args[0], Callable):
7
+ # decorator used without arguments
8
+ return args[0]
9
+ else:
10
+ # decorator used with arguments
11
+ def decorator(func):
12
+ return func
13
+
14
+ return decorator
@@ -0,0 +1 @@
1
+ from ._time_duration import format_long_time_duration, format_short_time_duration, format_time_duration
@@ -0,0 +1,175 @@
1
+ from typing import Literal
2
+
3
+ from max_div.internal.utils import HALF_EPS
4
+
5
+
6
+ # =================================================================================================
7
+ # Main entrypoints
8
+ # =================================================================================================
9
+ def format_time_duration(dt_sec: float, n_chars: int = 10) -> str:
10
+ """Format a time duration in seconds."""
11
+ if dt_sec < 1.0:
12
+ return format_short_time_duration(dt_sec, n_chars=n_chars, spaced=False, long_units=False, right_aligned=False)
13
+ else:
14
+ return format_long_time_duration(dt_sec, n_chars=n_chars)
15
+
16
+
17
+ def format_long_time_duration(dt_sec: float, n_chars: int = 10) -> str:
18
+ """
19
+ Format a time duration that is expected to be ~1sec or larger.
20
+
21
+ The max lengths of the resulting string (n_chars) will always be exactly matched if n_chars>=5 and dt_sec<100d.
22
+ """
23
+ # --- main loop ---------------------------------------
24
+ result = ""
25
+ for precision in ["d", "h", "m", "s", "s.s", "s.ss"]:
26
+ # choose representation with the highest precision with length <= n_chars
27
+ cand = _format_long_time_duration_to_spec(dt_sec, precision)
28
+ if (result == "") or (len(cand) <= n_chars):
29
+ result = cand
30
+
31
+ # --- final result ------------------------------------
32
+ result = result.rjust(n_chars) # pad with spaces on the left, if too short
33
+ return result
34
+
35
+
36
+ def format_short_time_duration(
37
+ dt_sec: float,
38
+ n_chars: int = 10,
39
+ right_aligned: bool | None = None,
40
+ spaced: bool | None = None,
41
+ long_units: bool | None = None,
42
+ ) -> str:
43
+ """
44
+ Format a time duration that is expected to be <<1sec. Different styling options are chosen to optimally meet
45
+ the given character count.
46
+
47
+ The options 'right_aligned', 'spaced', and 'long_units' are optional and, when omitted, automatically chosen
48
+ based on heuristics.
49
+
50
+ The requested n_chars is guaranteed to be met exactly if n_chars>=5, dt_sec<999.5 and with default styling options.
51
+
52
+ :param dt_sec: (float) Time duration in seconds.
53
+ :param n_chars: (int >= 5) Desired number of characters in the output
54
+ :param right_aligned: (bool) If True, the result is right-aligned such that values & units align vertically.
55
+ :param spaced: (bool) If True, a space is added between the number and the unit.
56
+ :param long_units: (bool) If True, long unit names are used (e.g. "nsec" instead of "ns").
57
+ """
58
+
59
+ # --- styling heuristics ------------------------------
60
+ if right_aligned is None:
61
+ right_aligned = n_chars > 6
62
+ if spaced is None:
63
+ spaced = n_chars > 8
64
+ if long_units is None:
65
+ long_units = n_chars > 10
66
+
67
+ # --- main loop ---------------------------------------
68
+ result = ""
69
+ for n_digits in range(n_chars - 2):
70
+ # choose representation with largest n_digits with length <= n_chars
71
+ cand = _format_short_time_duration_to_spec(dt_sec, n_digits, right_aligned, spaced, long_units)
72
+ if (result == "") or (len(cand) <= n_chars):
73
+ result = cand
74
+
75
+ # --- final result ------------------------------------
76
+ result = result.rjust(n_chars) # pad with spaces on the left, if too short
77
+ return result
78
+
79
+
80
+ # =================================================================================================
81
+ # Helpers
82
+ # =================================================================================================
83
+ def _format_long_time_duration_to_spec(
84
+ dt_sec: float, precision: str = Literal["d", "h", "m", "s", "s.s", "s.ss", "s.sss"]
85
+ ) -> str:
86
+ # --- rounding ----------------------------------------
87
+ match precision:
88
+ case "d":
89
+ round_to = 60 * 60 * 24
90
+ case "h":
91
+ round_to = 60 * 60
92
+ case "m":
93
+ round_to = 60
94
+ case "s":
95
+ round_to = 1
96
+ case "s.s":
97
+ round_to = 0.1
98
+ case "s.ss":
99
+ round_to = 0.01
100
+ dt_sec = round_to * round(dt_sec / round_to) * (1 + HALF_EPS) # avoid rounding issues
101
+
102
+ # --- split in components -----------------------------
103
+ rem_m, s = divmod(dt_sec, 60)
104
+ rem_h, m = divmod(rem_m, 60)
105
+ d, h = divmod(rem_h, 24)
106
+
107
+ # --- construct string-valued components --------------
108
+ d, h, m, s = int(d), int(h), int(m), s # convert to int where appropriate
109
+ match precision:
110
+ case "d":
111
+ components = [f"{d}d"]
112
+ case "h":
113
+ components = [f"{d}d", f"{h}h"]
114
+ case "m":
115
+ components = [f"{d}d", f"{h}h", f"{m}m"]
116
+ case "s":
117
+ components = [f"{d}d", f"{h}h", f"{m}m", f"{int(s)}s"]
118
+ case "s.s":
119
+ components = [f"{d}d", f"{h}h", f"{m}m", f"{s:.1f}s"]
120
+ case "s.ss":
121
+ components = [f"{d}d", f"{h}h", f"{m}m", f"{s:.2f}s"]
122
+
123
+ # prune leading zero components
124
+ while (len(components) > 1) and components[0].startswith("0"):
125
+ components.pop(0)
126
+
127
+ # --- build final result ------------------------------
128
+ return "".join(components)
129
+
130
+
131
+ def _format_short_time_duration_to_spec(
132
+ dt_sec: float, n_digits: int, right_aligned: bool, spaced: bool, long_units: bool
133
+ ) -> str:
134
+ """
135
+ Format a time duration that is expected to be <<1sec to the given specification.
136
+ :param dt_sec: (float) Time duration in seconds.
137
+ :param n_digits: (int >= 0) Number of digits to show after the decimal point.
138
+ :param right_aligned: (bool) If True, the result is right-aligned such that values & units align vertically.
139
+ :param spaced: (bool) If True, a space is added between the number and the unit.
140
+ :param long_units: (bool) If True, long unit names are used (e.g. "nsec" instead of "ns").
141
+ :return: string representation of the time duration.
142
+ """
143
+
144
+ # --- init --------------------------------------------
145
+ if long_units:
146
+ c_and_unit = [
147
+ (1.0, "sec " if right_aligned else "s"),
148
+ (1e3, "msec"),
149
+ (1e6, "μsec"),
150
+ (1e9, "nsec"),
151
+ ]
152
+ else:
153
+ c_and_unit = [
154
+ (1.0, "s " if right_aligned else "s"),
155
+ (1e3, "ms"),
156
+ (1e6, "μs"),
157
+ (1e9, "ns"),
158
+ ]
159
+
160
+ # --- main loop ---------------------------------------
161
+ value_str, unit_str = "", ""
162
+ for c, unit in c_and_unit:
163
+ value = round(dt_sec * c, ndigits=n_digits)
164
+ if (value < 1000) or (value_str == ""):
165
+ unit_str = unit
166
+ if n_digits > 0:
167
+ value_str = f"{value:.{n_digits}f}".lstrip()
168
+ else:
169
+ value_str = str(int(value))
170
+
171
+ # --- final result ------------------------------------
172
+ if spaced:
173
+ return f"{value_str} {unit_str}"
174
+ else:
175
+ return f"{value_str}{unit_str}"
@@ -0,0 +1,2 @@
1
+ from ._clip import clip
2
+ from ._precision import EPS, HALF_EPS
@@ -0,0 +1,5 @@
1
+ def clip(value: float | int, min_value: float | int, max_value: float | int) -> float | int:
2
+ if min_value >= max_value:
3
+ return (min_value + max_value) / 2
4
+ else:
5
+ return max(min_value, min(max_value, value))
@@ -0,0 +1,5 @@
1
+ import math
2
+ import sys
3
+
4
+ EPS = sys.float_info.epsilon # Machine epsilon for 64-bit float (float64)
5
+ HALF_EPS = math.sqrt(EPS)
@@ -0,0 +1 @@
1
+ from .discrete import sample_int
@@ -0,0 +1,176 @@
1
+ import numpy as np
2
+
3
+ from max_div.internal.compat import numba
4
+
5
+
6
+ # =================================================================================================
7
+ # sample_int
8
+ # =================================================================================================
9
+ def sample_int(
10
+ n: int,
11
+ k: int | None = None,
12
+ replace: bool = True,
13
+ p: np.ndarray[float] | None = None,
14
+ seed: int | None = None,
15
+ use_numba: bool = True,
16
+ ) -> int | np.ndarray[np.int64]:
17
+ """
18
+ Randomly sample `k` integers from range `[0, n-1]`, optionally with replacement and per-value probabilities.
19
+
20
+ Different implementation is used, depending on the case:
21
+
22
+ | `use_numba` | `p` specified | `replace` | `k` | Method Used | Complexity |
23
+ |----------------|----------------|------------|------|------------------------------------------|-----------------|
24
+ | No | Any | Any | Any | `np.random.choice` | depends |
25
+ | Yes | No | True | Any | `np.random.randint`, uniform sampling | O(k) |
26
+ | Yes | No | False | Any | k-element Fisher-Yates shuffle | O(n) |
27
+ | Yes | Yes | Any | 1 | Multinomial sampling using CDF | O(n + log(n)) |
28
+ | Yes | Yes | True | >1 | Multinomial sampling using CDF | O(n + k log(n)) |
29
+ | Yes | Yes | False | >1 | Efraimidis-Spirakis sampling + exponential key sampling (Gumbel-Max Trick) using the Ziggurat algorithm. | O(n) |
30
+
31
+ :param n: defines population to sample from as range [0, n-1]. `n` must be >0.
32
+ :param k: The number of integers to sample (>0). `k=None` indicates a single integer sample.
33
+ :param replace: Whether to sample with replacement.
34
+ :param p: Optional 1D array of probabilities associated with each integer in the range.
35
+ Size must be equal to max_value + 1 and sum to 1.
36
+ :param seed: Optional random seed for reproducibility.
37
+ :param use_numba: Use the self-implemented algorithm (which is `numba`-accelerated if `numba` is installed)
38
+ :return: `k=None` --> single integer; `k>=1` --> (k,)-sized array with sampled integers.
39
+ """
40
+
41
+ # -------------------------------------------------------------------------
42
+ # Don't try using numba
43
+ # -------------------------------------------------------------------------
44
+ if not use_numba:
45
+ # --- argument handling ---------------------------
46
+ if (k == 1) or (k is None):
47
+ replace = True # single sample, replacement makes no difference, so we can fall back to faster methods
48
+
49
+ # --- argument validation -------------------------
50
+ if n < 1:
51
+ raise ValueError(f"n must be >=1. (here: {n})")
52
+ if k is not None:
53
+ if k < 1:
54
+ raise ValueError(f"k must be >=1. (here: {k})")
55
+ if (not replace) and (k > n):
56
+ raise ValueError(f"Cannot sample {k} unique values from range [0, {n}) without replacement.")
57
+
58
+ # --- sampling ------------------------------------
59
+ if seed is not None:
60
+ np.random.seed(seed)
61
+
62
+ if k is None:
63
+ # returns scalar
64
+ return np.random.choice(n, size=None, replace=replace, p=p)
65
+ else:
66
+ # returns array
67
+ return np.random.choice(n, size=k, replace=replace, p=p)
68
+
69
+ # -------------------------------------------------------------------------
70
+ # Try using numba
71
+ # -------------------------------------------------------------------------
72
+ else:
73
+ # --- argument handling ---------------------------
74
+ k_orig = k # remember, to know what return value we need
75
+ if (k == 1) or (k is None):
76
+ k = 1 # make sure we always have an integer for the numba function
77
+ replace = True # single sample, replacement makes no difference, so we can fall back to faster methods
78
+ if p is None:
79
+ use_p = False
80
+ p = np.zeros(0, dtype=np.float64) # dummy value
81
+ else:
82
+ use_p = True
83
+ if seed is None:
84
+ use_seed = False
85
+ seed = 42 # dummy value
86
+ else:
87
+ use_seed = True
88
+
89
+ # --- argument validation -------------------------
90
+ if n < 1:
91
+ raise ValueError(f"n must be >=1. (here: {n})")
92
+ if k < 1:
93
+ raise ValueError(f"k must be >=1. (here: {k})")
94
+ if (not replace) and (k > n):
95
+ raise ValueError(f"Cannot sample {k} unique values from range [0, {n}) without replacement.")
96
+ if use_p:
97
+ if (p.ndim != 1) or (p.size != n):
98
+ raise ValueError(f"p must be a 1D array of size {n}. (here: shape={p.shape})")
99
+
100
+ # --- call numba function -------------------------
101
+ samples = sample_int_numba(n=n, k=k, replace=replace, use_p=use_p, p=p, use_seed=use_seed, seed=seed)
102
+ if k_orig is None:
103
+ return samples[0]
104
+ else:
105
+ return samples
106
+
107
+
108
+ @numba.njit
109
+ def sample_int_numba(
110
+ n: int,
111
+ k: int,
112
+ replace: bool,
113
+ use_p: bool = False,
114
+ p: np.ndarray[float] = np.zeros(0),
115
+ use_seed: bool = False,
116
+ seed: int = 42,
117
+ ) -> np.ndarray[int]:
118
+ """
119
+ See native python version docstring. We split the implementation into a core numba-decorated function and
120
+ a Python front-end, because numba-decorated functions do not allow for multiple possible return types.
121
+ """
122
+ if use_seed:
123
+ np.random.seed(seed)
124
+
125
+ if (k == n) and (not replace):
126
+ # corner case: return all elements in random order
127
+ population = np.arange(n, dtype=np.int64)
128
+ np.random.shuffle(population)
129
+ return population
130
+
131
+ if not use_p:
132
+ if replace:
133
+ # UNIFORM sampling with replacement
134
+ return np.random.choice(n, size=k) # O(k)
135
+ else:
136
+ # UNIFORM sampling without replacement using Fisher-Yates shuffle
137
+ population = np.arange(n, dtype=np.int64) # O(n)
138
+ for i in range(k): # k x O(1)
139
+ j = np.random.randint(i, n)
140
+ population[i], population[j] = population[j], population[i]
141
+ return population[:k] # O(k)
142
+ else:
143
+ if replace:
144
+ # NON-UNIFORM sampling with replacement using CDF
145
+ cdf = np.empty(n) # O(n)
146
+ csum = 0.0
147
+ for i in range(n): # n x O(1)
148
+ csum += p[i]
149
+ cdf[i] = csum
150
+ samples = np.empty(k, dtype=np.int64) # O(k)
151
+ for i in range(k): # k x O(log(n))
152
+ r = np.random.random()
153
+ idx = np.searchsorted(cdf, r)
154
+ samples[i] = idx
155
+ return samples
156
+ else:
157
+ # NON-UNIFORM sampling without replacement using Efraimidis-Spirakis + Exponential keys
158
+ # algorithm description:
159
+ # Efraimidis: select k elements corresponding to k largest values of u_i^{1/p_i} (u_i ~ U(0,1))
160
+ # Gumbel-Max Trick: select k smallest values of -log(u_i)/p_i (u_i ~ U(0,1))
161
+ # Ziggurat: (TODO) generate log(u_i) more efficiently, applying the Ziggurat algorithm
162
+ # to the exponential distribution, which avoids usage of transcendental
163
+ # functions for the majority of the samples.
164
+ keys = np.empty(n, dtype=np.float64) # O(n)
165
+ u = np.random.random(n) # O(n)
166
+ for i in range(n): # n x O(1)
167
+ if p[i] == 0.0:
168
+ keys[i] = np.inf
169
+ else:
170
+ keys[i] = -np.log(u[i]) / p[i]
171
+
172
+ # Get indices of k smallest keys
173
+ if k > 1:
174
+ return np.argpartition(keys, k)[:k] # O(n) average case
175
+ else:
176
+ return np.array([np.argmin(keys)]) # O(n)
@@ -0,0 +1,33 @@
1
+ Metadata-Version: 2.4
2
+ Name: max-div
3
+ Version: 0.0.3
4
+ Summary: Flexible Solver for Maximum Diversity Problems with Fairness Constraints.
5
+ Project-URL: Documentation, https://max-div.readthedocs.io/
6
+ Project-URL: Source, https://github.com/bertpl/max-div
7
+ Project-URL: ChangeLog, https://github.com/bertpl/max-div/blob/develop/CHANGELOG.md
8
+ Project-URL: Issues, https://github.com/bertpl/max-div/issues
9
+ Project-URL: Roadmap, https://github.com/bertpl/max-div/milestones
10
+ Author-email: Bert Pluymers <bert.pluymers@gmail.com>
11
+ License-File: LICENSE
12
+ Requires-Python: >=3.11
13
+ Requires-Dist: numpy>=2.0.0
14
+ Provides-Extra: docs
15
+ Requires-Dist: mkdocs-autoapi[python]>=0.4.1; extra == 'docs'
16
+ Requires-Dist: mkdocs-include-markdown-plugin>=7.2.0; extra == 'docs'
17
+ Requires-Dist: mkdocs-material>=9.0.0; extra == 'docs'
18
+ Requires-Dist: mkdocs>=1.6.1; extra == 'docs'
19
+ Requires-Dist: mkdocstrings[python]>=0.24.0; extra == 'docs'
20
+ Requires-Dist: ruff>=0.14.0; extra == 'docs'
21
+ Provides-Extra: numba
22
+ Requires-Dist: numba>=0.57; extra == 'numba'
23
+ Description-Content-Type: text/markdown
24
+
25
+ ![shields.io-python-versions](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13-blue)
26
+ ![genbadge-test-count](https://bertpl.github.io/max-div/version_artifacts/release/v0.0.3/badge-test-count.svg)
27
+ ![genbadge-test-coverage](https://bertpl.github.io/max-div/version_artifacts/release/v0.0.3/badge-coverage.svg)
28
+ ![max-div logo](https://bertpl.github.io/max-div/version_artifacts/release/v0.0.3/splash.webp)
29
+
30
+ # max-div
31
+ Configurable Solver for Maximum Diversity Problems with Fairness Constraints.
32
+
33
+ ### --- ***Under Development*** ---
@@ -0,0 +1,23 @@
1
+ max_div/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ max_div/benchmark/__init__.py,sha256=wzyPThNW4GETpkPh5yXDKTkQbJQ1ulungL2jQL8Ak2s,45
3
+ max_div/benchmark/sample_int.py,sha256=mueD3v0tqP0zTN9Gf1LjnvrCEm0fV3zlgcE-Eh3V0vQ,2817
4
+ max_div/internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ max_div/internal/benchmarking/__init__.py,sha256=WNjrLlGI_vkI-nZkQMPICgi67rTVole_MCc4jNe_OxI,83
6
+ max_div/internal/benchmarking/_micro_benchmark.py,sha256=hvQxmKG72MnG9dANrLbYm8D7NsJP-2pGapl5idX_E7I,4183
7
+ max_div/internal/benchmarking/_timer.py,sha256=gpA3KgreDTtK2QUARJKI4Ir9dTDMKW7B5GQuThRbYh8,1050
8
+ max_div/internal/compat/__init__.py,sha256=ApHeMuO_9zlP34BnSZMRVLVyEEv1VEkGXNJzw5ddaK4,46
9
+ max_div/internal/compat/_numba/__init__.py,sha256=fKwHEiafrYMmk_GOaOKZBb3rDU9q0sYqzi3BPPtV0A4,631
10
+ max_div/internal/compat/_numba/_dummy_numba.py,sha256=FPguZfpQzpWRxmc4pYSGVCoPzgofsgQO_bknF_bK8aQ,2341
11
+ max_div/internal/compat/_numba/_helpers.py,sha256=pQqAjHYbSwPos9011xpmbkJeZ5cPBUZq14qh8G6GtjQ,402
12
+ max_div/internal/formatting/__init__.py,sha256=UMim6fo_e4JGJo7pl8FZ1nNpmStlfbGB7O49LhCZwWo,104
13
+ max_div/internal/formatting/_time_duration.py,sha256=dO88GPZeMbxVk0YF9Zr2Y0NLCXaiW_HwTa7S-PT9e9E,6740
14
+ max_div/internal/utils/__init__.py,sha256=Xqb7Rh9Lq6WsUK-5B9aouwWMhAh0c1a7pF0rdaP5kgo,62
15
+ max_div/internal/utils/_clip.py,sha256=kWUCKG9uFxNvFWvThMyFdWLlzVb9cFADngpBYl5b38U,230
16
+ max_div/internal/utils/_precision.py,sha256=3eEUdJQmXA3Q6Tg4jb3vG0RTwOBNgnc09j5ts0gcIdw,125
17
+ max_div/sampling/__init__.py,sha256=_tsDiQNr4brsMiROQVbJFpq7Um79HV7P0ec6ChMd_iY,33
18
+ max_div/sampling/discrete.py,sha256=VYBpeYYIUbLeuA3Ld4PTBkVwq6ziIBW0KlkJVqmqNuU,8048
19
+ max_div-0.0.3.dist-info/METADATA,sha256=PwZtrIAsZRKs5bCVw_SzDOQpfPtCVOcDxHTvuBRrLAM,1604
20
+ max_div-0.0.3.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
21
+ max_div-0.0.3.dist-info/entry_points.txt,sha256=EL6VQ4tIThMRtNqBtQvj2yAMBJm-7OM801VYPBsRwp4,80
22
+ max_div-0.0.3.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
23
+ max_div-0.0.3.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ benchmark_sample_int = max_div.benchmark:benchmark_sample_int
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.