snuffled 0.1.0__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.
- snuffled/__init__.py +12 -0
- snuffled/_core/__init__.py +12 -0
- snuffled/_core/analysis/__init__.py +2 -0
- snuffled/_core/analysis/_function_sampler.py +257 -0
- snuffled/_core/analysis/_property_extractor.py +75 -0
- snuffled/_core/analysis/diagnostic/__init__.py +1 -0
- snuffled/_core/analysis/diagnostic/diagnostic_analyser.py +66 -0
- snuffled/_core/analysis/function/__init__.py +1 -0
- snuffled/_core/analysis/function/function_analyser.py +123 -0
- snuffled/_core/analysis/function/helpers_discontinuous.py +219 -0
- snuffled/_core/analysis/function/helpers_non_monotonic.py +88 -0
- snuffled/_core/analysis/roots/__init__.py +1 -0
- snuffled/_core/analysis/roots/curve_fitting/__init__.py +3 -0
- snuffled/_core/analysis/roots/curve_fitting/brute_force/__init__.py +7 -0
- snuffled/_core/analysis/roots/curve_fitting/brute_force/_fit_optimal_with_uncertainty.py +97 -0
- snuffled/_core/analysis/roots/curve_fitting/shared/__init__.py +2 -0
- snuffled/_core/analysis/roots/curve_fitting/shared/_curves_and_costs.py +63 -0
- snuffled/_core/analysis/roots/curve_fitting/shared/_function_sampling.py +78 -0
- snuffled/_core/analysis/roots/curve_fitting/specialized/__init__.py +4 -0
- snuffled/_core/analysis/roots/curve_fitting/specialized/_explore_uncertainty.py +97 -0
- snuffled/_core/analysis/roots/curve_fitting/specialized/_fit_exact.py +58 -0
- snuffled/_core/analysis/roots/curve_fitting/specialized/_fit_optimal.py +199 -0
- snuffled/_core/analysis/roots/curve_fitting/specialized/_fit_optimal_with_uncertainty.py +119 -0
- snuffled/_core/analysis/roots/curve_fitting/specialized/_helpers.py +119 -0
- snuffled/_core/analysis/roots/roots_analyser.py +58 -0
- snuffled/_core/analysis/roots/single_root_one_side_analyser.py +244 -0
- snuffled/_core/analysis/roots/single_root_two_side_analyser.py +141 -0
- snuffled/_core/analysis/snuffler.py +68 -0
- snuffled/_core/compatibility/__init__.py +2 -0
- snuffled/_core/compatibility/_numba.py +26 -0
- snuffled/_core/compatibility/_strenum.py +6 -0
- snuffled/_core/models/__init__.py +11 -0
- snuffled/_core/models/base/__init__.py +1 -0
- snuffled/_core/models/base/_named_array.py +68 -0
- snuffled/_core/models/properties/__init__.py +5 -0
- snuffled/_core/models/properties/_all.py +61 -0
- snuffled/_core/models/properties/_diagnostic.py +17 -0
- snuffled/_core/models/properties/_function.py +19 -0
- snuffled/_core/models/properties/_property_extraction_stats.py +9 -0
- snuffled/_core/models/properties/_root.py +19 -0
- snuffled/_core/models/root_analysis/__init__.py +1 -0
- snuffled/_core/models/root_analysis/_root.py +66 -0
- snuffled/_core/utils/__init__.py +0 -0
- snuffled/_core/utils/constants.py +23 -0
- snuffled/_core/utils/math.py +97 -0
- snuffled/_core/utils/noise.py +23 -0
- snuffled/_core/utils/numba.py +35 -0
- snuffled/_core/utils/root_finding.py +186 -0
- snuffled/_core/utils/sampling.py +188 -0
- snuffled/_core/utils/signs.py +16 -0
- snuffled/_core/utils/statistics/__init__.py +1 -0
- snuffled/_core/utils/statistics/_estimate_sign_flip_frequency.py +127 -0
- snuffled-0.1.0.dist-info/METADATA +25 -0
- snuffled-0.1.0.dist-info/RECORD +56 -0
- snuffled-0.1.0.dist-info/WHEEL +4 -0
- snuffled-0.1.0.dist-info/licenses/LICENSE +201 -0
snuffled/__init__.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import math
|
|
2
|
+
from collections.abc import Callable
|
|
3
|
+
from functools import cache
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from snuffled._core.models.root_analysis import Root
|
|
8
|
+
from snuffled._core.utils.constants import EPS, SEED_OFFSET_FUNCTION_SAMPLER
|
|
9
|
+
from snuffled._core.utils.math import smooth_sign_array
|
|
10
|
+
from snuffled._core.utils.root_finding import find_odd_root
|
|
11
|
+
from snuffled._core.utils.sampling import multi_scale_samples, sample_integers
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class FunctionSampler:
|
|
15
|
+
"""
|
|
16
|
+
Class holding (cached) data related to a specific function, shared across different analyses.
|
|
17
|
+
All the following classes make use of this class to access the data they need for their analyses:
|
|
18
|
+
- FunctionAnalyser
|
|
19
|
+
- RootAnalyser
|
|
20
|
+
- DiagnosticAnalyser
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
# -------------------------------------------------------------------------
|
|
24
|
+
# Constructor
|
|
25
|
+
# -------------------------------------------------------------------------
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
fun: Callable[[float], float],
|
|
29
|
+
x_min: float,
|
|
30
|
+
x_max: float,
|
|
31
|
+
dx: float,
|
|
32
|
+
seed: int,
|
|
33
|
+
n_fun_samples: int = 1_000,
|
|
34
|
+
n_roots: int = 100,
|
|
35
|
+
rel_tol_scale: float = 10.0,
|
|
36
|
+
):
|
|
37
|
+
# --- randomization -------------------------------
|
|
38
|
+
self._seed = seed + SEED_OFFSET_FUNCTION_SAMPLER
|
|
39
|
+
|
|
40
|
+
# --- function properties -------------------------
|
|
41
|
+
self._fun = fun
|
|
42
|
+
self.x_min = x_min
|
|
43
|
+
self.x_max = x_max
|
|
44
|
+
|
|
45
|
+
# --- settings ------------------------------------
|
|
46
|
+
self.dx = dx
|
|
47
|
+
self.n_fun_samples = n_fun_samples
|
|
48
|
+
self.n_roots = n_roots
|
|
49
|
+
self.rel_tol = EPS * rel_tol_scale
|
|
50
|
+
|
|
51
|
+
# --- cache ---------------------------------------
|
|
52
|
+
self._fun_cache: dict[float, float] = dict()
|
|
53
|
+
|
|
54
|
+
# -------------------------------------------------------------------------
|
|
55
|
+
# Low-level generic functionality
|
|
56
|
+
# -------------------------------------------------------------------------
|
|
57
|
+
def f(self, x: float | list[float]) -> float | list[float]:
|
|
58
|
+
# simple cached version of fun(x), without size limit (and simpler than lru_cache, so less overhead)
|
|
59
|
+
if isinstance(x, list):
|
|
60
|
+
# --- get MULTIPLE f(x) values ------
|
|
61
|
+
fx_values = []
|
|
62
|
+
for single_x in x:
|
|
63
|
+
if not (self.x_min <= single_x <= self.x_max):
|
|
64
|
+
raise ValueError(f"x={single_x} is out of bounds [{self.x_min}, {self.x_max}]")
|
|
65
|
+
elif single_x not in self._fun_cache:
|
|
66
|
+
self._fun_cache[single_x] = fx = self._fun(single_x)
|
|
67
|
+
else:
|
|
68
|
+
fx = self._fun_cache[single_x]
|
|
69
|
+
fx_values.append(fx)
|
|
70
|
+
return fx_values
|
|
71
|
+
else:
|
|
72
|
+
# --- get SINGLE f(x) values --------
|
|
73
|
+
if x in self._fun_cache:
|
|
74
|
+
return self._fun_cache[x]
|
|
75
|
+
elif self.x_min <= x <= self.x_max:
|
|
76
|
+
fx = self._fun(x)
|
|
77
|
+
self._fun_cache[x] = fx
|
|
78
|
+
return fx
|
|
79
|
+
else:
|
|
80
|
+
raise ValueError(f"x={x} is out of bounds [{self.x_min}, {self.x_max}]")
|
|
81
|
+
|
|
82
|
+
@cache
|
|
83
|
+
def x_values(self) -> np.ndarray:
|
|
84
|
+
"""
|
|
85
|
+
Returns an array of x-values in [x_min, x_max] that we use to sample the function and infer its properties.
|
|
86
|
+
This is based on the multi_scale_samples function and does not include any other cached x-values resulting
|
|
87
|
+
from other calls to .f(.)
|
|
88
|
+
"""
|
|
89
|
+
return multi_scale_samples(
|
|
90
|
+
x_min=self.x_min,
|
|
91
|
+
x_max=self.x_max,
|
|
92
|
+
dx_min=self.dx,
|
|
93
|
+
n=self.n_fun_samples,
|
|
94
|
+
seed=self._seed,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
@cache
|
|
98
|
+
def fx_values(self) -> np.ndarray:
|
|
99
|
+
"""f(x) values corresponding to the x_values()."""
|
|
100
|
+
return np.array(self.f(list(self.x_values())), dtype=np.float64)
|
|
101
|
+
|
|
102
|
+
def function_cache(self) -> list[tuple[float, float]]:
|
|
103
|
+
"""
|
|
104
|
+
Returns contents of the function cache as a list of (x, f(x))-tuples.
|
|
105
|
+
Note this might return more information than .x_values() and .fx_values(), since those methods
|
|
106
|
+
only return information related to the initial multiscale sampling.
|
|
107
|
+
"""
|
|
108
|
+
return list(self._fun_cache.items())
|
|
109
|
+
|
|
110
|
+
def function_cache_size(self) -> int:
|
|
111
|
+
"""Return number of values in function cache."""
|
|
112
|
+
return len(self._fun_cache)
|
|
113
|
+
|
|
114
|
+
@cache
|
|
115
|
+
def fx_diff_values(self) -> np.ndarray:
|
|
116
|
+
return np.diff(self.fx_values())
|
|
117
|
+
|
|
118
|
+
@cache
|
|
119
|
+
def fx_quantile(self, q: float, absolute: bool) -> float:
|
|
120
|
+
"""
|
|
121
|
+
Returns the requested quantile f(x).
|
|
122
|
+
absolute==False --> quantile of f(x)
|
|
123
|
+
absolute==True --> quantile of abs(f(x))
|
|
124
|
+
"""
|
|
125
|
+
if absolute:
|
|
126
|
+
return float(np.quantile(abs(self.fx_values()), q))
|
|
127
|
+
else:
|
|
128
|
+
return float(np.quantile(self.fx_values(), q))
|
|
129
|
+
|
|
130
|
+
@cache
|
|
131
|
+
def robust_estimated_fx_max(self) -> float:
|
|
132
|
+
"""
|
|
133
|
+
Robust, approximate estimate of max(f(x)), without being susceptible to single-sample outliers, which might
|
|
134
|
+
arise in certain corner cases.
|
|
135
|
+
|
|
136
|
+
NOTE: this value is not guaranteed to be equal or larger than abs(f(x)), but should provide a reasonable
|
|
137
|
+
estimate under most regular circumstances.
|
|
138
|
+
"""
|
|
139
|
+
q = 1 - (1 / math.sqrt(self.n_fun_samples))
|
|
140
|
+
return (1 / q) * self.fx_quantile(q, absolute=True)
|
|
141
|
+
|
|
142
|
+
# -------------------------------------------------------------------------
|
|
143
|
+
# Specialized - Tolerances
|
|
144
|
+
# -------------------------------------------------------------------------
|
|
145
|
+
@cache
|
|
146
|
+
def tol_array_local(self) -> np.ndarray:
|
|
147
|
+
"""
|
|
148
|
+
Return (n_fun_samples, )-sized array with absolute tolerance values > 0, representing the LOCAL tolerance wrt
|
|
149
|
+
numerical rounding errors on a LOCAL per-sample basis, i.e. computed based on the magnitude of each f(x) sample.
|
|
150
|
+
"""
|
|
151
|
+
return self.rel_tol * abs(self.fx_values())
|
|
152
|
+
|
|
153
|
+
@cache
|
|
154
|
+
def tol_array_global(self) -> np.ndarray:
|
|
155
|
+
"""
|
|
156
|
+
Return (n_fun_samples, )-sized array with absolute tolerance values > 0, representing the GLOBAL tolerance wrt
|
|
157
|
+
numerical rounding errors on a GLOBAL basis, i.e. computed based on the overall (~maximum) magnitude of f(x).
|
|
158
|
+
This is a constant matrix.
|
|
159
|
+
"""
|
|
160
|
+
return np.full(self.n_fun_samples, self.rel_tol * self.robust_estimated_fx_max())
|
|
161
|
+
|
|
162
|
+
@cache
|
|
163
|
+
def fx_diff_smooth_sign(self) -> np.ndarray:
|
|
164
|
+
"""
|
|
165
|
+
Returns an array with elements in [-1,+1] representing a more nuanced np.sign(np.diff(fx_values())).
|
|
166
|
+
|
|
167
|
+
Local and global tolerances are used to determine the threshold around which differences transition
|
|
168
|
+
(smoothly) from 0 to 1 or 0 to -1.
|
|
169
|
+
|
|
170
|
+
See also smooth_sign().
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
# determine inner_tol, outer_tol
|
|
174
|
+
tol_global = self.tol_array_global()
|
|
175
|
+
tol_local = self.tol_array_local()
|
|
176
|
+
|
|
177
|
+
inner_tol = np.minimum(tol_local, tol_global) # make sure inner_tol[i] is the smallest of both tolerances
|
|
178
|
+
outer_tol = np.maximum(tol_local, tol_global) # make sure outer_tol[i] is the largest of both tolerances
|
|
179
|
+
|
|
180
|
+
# reduce to size n-1 from size n (take sum)
|
|
181
|
+
inner_tol = inner_tol[1:] + inner_tol[:-1] # take sum of both tolerances
|
|
182
|
+
outer_tol = outer_tol[1:] + outer_tol[:-1] # take sum of both tolerances
|
|
183
|
+
|
|
184
|
+
# compute smooth_sign
|
|
185
|
+
return smooth_sign_array(
|
|
186
|
+
x=self.fx_diff_values(),
|
|
187
|
+
inner_tol=inner_tol,
|
|
188
|
+
outer_tol=outer_tol,
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
# -------------------------------------------------------------------------
|
|
192
|
+
# Specialized - Roots
|
|
193
|
+
# -------------------------------------------------------------------------
|
|
194
|
+
@cache
|
|
195
|
+
def candidate_root_intervals(self) -> tuple[list[tuple[float, float]], list[tuple[float, float]]]:
|
|
196
|
+
"""
|
|
197
|
+
Return a list of 'root intervals' and 'non-root intervals', with the root intervals serving as candidates
|
|
198
|
+
(but potentially too many) for root finding.
|
|
199
|
+
:return: (root_intervals, non_root_intervals)-tuple
|
|
200
|
+
root_intervals : list of (x_left, x_right)-tuples WITH sign flip
|
|
201
|
+
non_root_intervals : list of (x_left, x_right)-tuples WITHOUT sign flip
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
# multi-scale samples as (x, fx)-tuples
|
|
205
|
+
samples = list(zip(self.x_values(), self.fx_values()))
|
|
206
|
+
|
|
207
|
+
# remove 0-valued samples, we are looking for strict sign flips
|
|
208
|
+
samples = [(x, fx) for i, (x, fx) in enumerate(samples) if (fx != 0.0)]
|
|
209
|
+
|
|
210
|
+
# split in root- and non-root-intervals
|
|
211
|
+
root_intervals = []
|
|
212
|
+
non_root_intervals = []
|
|
213
|
+
for (x_left, fx_left), (x_right, fx_right) in zip(samples[:-1], samples[1:]):
|
|
214
|
+
if np.sign(fx_left) != np.sign(fx_right):
|
|
215
|
+
# sign flip
|
|
216
|
+
root_intervals.append((x_left, x_right))
|
|
217
|
+
else:
|
|
218
|
+
# no sign flip
|
|
219
|
+
non_root_intervals.append((x_left, x_right))
|
|
220
|
+
|
|
221
|
+
# we're done
|
|
222
|
+
return root_intervals, non_root_intervals
|
|
223
|
+
|
|
224
|
+
@cache
|
|
225
|
+
def roots(self) -> list[Root]:
|
|
226
|
+
"""
|
|
227
|
+
Returns at most 'n_roots' root intervals [root_min, root_max] obtained using find_root_and_width().
|
|
228
|
+
We start from the candidate_root_intervals and - if needed - sample 'n_roots' intervals randomly
|
|
229
|
+
to if there are too many candidate intervals.
|
|
230
|
+
:return: list of Root objects, with deriv_sign != 0.
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
# get intervals
|
|
234
|
+
cand_intervals, _ = self.candidate_root_intervals()
|
|
235
|
+
|
|
236
|
+
# sample if needed
|
|
237
|
+
if len(cand_intervals) > self.n_roots:
|
|
238
|
+
cand_intervals = [
|
|
239
|
+
cand_intervals[i]
|
|
240
|
+
for i in sample_integers(
|
|
241
|
+
i_min=0,
|
|
242
|
+
i_max=len(cand_intervals),
|
|
243
|
+
n=self.n_roots,
|
|
244
|
+
seed=self._seed,
|
|
245
|
+
)
|
|
246
|
+
]
|
|
247
|
+
|
|
248
|
+
# compute roots & return
|
|
249
|
+
return [
|
|
250
|
+
find_odd_root(
|
|
251
|
+
fun=self.f,
|
|
252
|
+
x_min=x_min,
|
|
253
|
+
x_max=x_max,
|
|
254
|
+
dx_min=(EPS * EPS) * (self.x_max - self.x_min),
|
|
255
|
+
)
|
|
256
|
+
for x_min, x_max in cand_intervals
|
|
257
|
+
]
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from time import perf_counter_ns, time_ns
|
|
3
|
+
from typing import Generic, TypeVar
|
|
4
|
+
|
|
5
|
+
from snuffled._core.models import NamedArray, PropertyExtractionStats
|
|
6
|
+
|
|
7
|
+
from ._function_sampler import FunctionSampler
|
|
8
|
+
|
|
9
|
+
NA = TypeVar("NA", bound=NamedArray)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PropertyExtractor(ABC, Generic[NA]):
|
|
13
|
+
# =================================================================================================
|
|
14
|
+
# Main API
|
|
15
|
+
# =================================================================================================
|
|
16
|
+
def __init__(self, function_sampler: FunctionSampler):
|
|
17
|
+
self.function_sampler = function_sampler
|
|
18
|
+
self.__stats: dict[str, PropertyExtractionStats] = dict() # property -> stats
|
|
19
|
+
|
|
20
|
+
def supported_properties(self) -> list[str]:
|
|
21
|
+
"""Return list of all supported properties, in order in which they should be extracted by extract_all"""
|
|
22
|
+
return self._new_named_array().names()
|
|
23
|
+
|
|
24
|
+
def extract_all(self) -> NA:
|
|
25
|
+
"""Extract all properties and returned as specific NamedArray subclass."""
|
|
26
|
+
named_array = self._new_named_array()
|
|
27
|
+
for property_name in self.supported_properties():
|
|
28
|
+
named_array[property_name] = self.extract(property_name)
|
|
29
|
+
return named_array
|
|
30
|
+
|
|
31
|
+
def extract(self, prop: str) -> float:
|
|
32
|
+
"""Extract specific property, while tracking time and duration of extraction."""
|
|
33
|
+
|
|
34
|
+
# --- timed property extraction -------------------
|
|
35
|
+
t_start_ns_epoch = time_ns() # ns since epoch
|
|
36
|
+
t_start_ns = perf_counter_ns()
|
|
37
|
+
n_f_samples_before = self.function_sampler.function_cache_size()
|
|
38
|
+
result = self._extract(prop)
|
|
39
|
+
t_end_ns = perf_counter_ns()
|
|
40
|
+
n_f_samples_after = self.function_sampler.function_cache_size()
|
|
41
|
+
|
|
42
|
+
# --- store stats ---------------------------------
|
|
43
|
+
self.__stats[prop] = PropertyExtractionStats(
|
|
44
|
+
property=prop,
|
|
45
|
+
t_start_ns=t_start_ns_epoch,
|
|
46
|
+
t_duration_sec=(t_end_ns - t_start_ns) / 1e9,
|
|
47
|
+
n_f_samples=n_f_samples_after - n_f_samples_before,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# --- return result -------------------------------
|
|
51
|
+
return result
|
|
52
|
+
|
|
53
|
+
def statistics(self) -> dict[str, PropertyExtractionStats]:
|
|
54
|
+
"""
|
|
55
|
+
Return dictionary with property extraction stats by property name. Entries are sorted by
|
|
56
|
+
order of extraction.
|
|
57
|
+
"""
|
|
58
|
+
return dict(
|
|
59
|
+
sorted(
|
|
60
|
+
self.__stats.items(),
|
|
61
|
+
key=lambda prop_stat: prop_stat[1].t_start_ns,
|
|
62
|
+
)
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# =================================================================================================
|
|
66
|
+
# Abstract methods
|
|
67
|
+
# =================================================================================================
|
|
68
|
+
@abstractmethod
|
|
69
|
+
def _extract(self, prop: str) -> float:
|
|
70
|
+
"""Extract specific property."""
|
|
71
|
+
raise NotImplementedError()
|
|
72
|
+
|
|
73
|
+
@abstractmethod
|
|
74
|
+
def _new_named_array(self) -> NA:
|
|
75
|
+
raise NotImplementedError()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .diagnostic_analyser import DiagnosticAnalyser
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from snuffled._core.analysis._function_sampler import FunctionSampler
|
|
4
|
+
from snuffled._core.analysis._property_extractor import PropertyExtractor
|
|
5
|
+
from snuffled._core.models.properties import Diagnostic, SnuffledDiagnostics
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class DiagnosticAnalyser(PropertyExtractor[SnuffledDiagnostics]):
|
|
9
|
+
# -------------------------------------------------------------------------
|
|
10
|
+
# Constructor
|
|
11
|
+
# -------------------------------------------------------------------------
|
|
12
|
+
def __init__(self, function_sampler: FunctionSampler):
|
|
13
|
+
super().__init__(function_sampler)
|
|
14
|
+
|
|
15
|
+
# -------------------------------------------------------------------------
|
|
16
|
+
# Main Implementation
|
|
17
|
+
# -------------------------------------------------------------------------
|
|
18
|
+
def supported_properties(self) -> list[str]:
|
|
19
|
+
# return in order of increasing number of required function evals
|
|
20
|
+
return [
|
|
21
|
+
Diagnostic.INTERVAL_NOT_BRACKETING_READY,
|
|
22
|
+
Diagnostic.NO_ZEROS_DETECTED,
|
|
23
|
+
Diagnostic.MAX_ZERO_WIDTH,
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
def _new_named_array(self) -> SnuffledDiagnostics:
|
|
27
|
+
return SnuffledDiagnostics()
|
|
28
|
+
|
|
29
|
+
def _extract(self, prop: str) -> float:
|
|
30
|
+
match prop:
|
|
31
|
+
case Diagnostic.INTERVAL_NOT_BRACKETING_READY:
|
|
32
|
+
return self._extract_interval_not_bracketing_ready()
|
|
33
|
+
case Diagnostic.MAX_ZERO_WIDTH:
|
|
34
|
+
return self._extract_max_zero_width()
|
|
35
|
+
case Diagnostic.NO_ZEROS_DETECTED:
|
|
36
|
+
return self._extract_no_zeros_detected()
|
|
37
|
+
case _:
|
|
38
|
+
raise ValueError(f"Property {prop} not supported")
|
|
39
|
+
|
|
40
|
+
# -------------------------------------------------------------------------
|
|
41
|
+
# Internal methods
|
|
42
|
+
# -------------------------------------------------------------------------
|
|
43
|
+
def _extract_interval_not_bracketing_ready(self) -> float:
|
|
44
|
+
x_min, x_max = self.function_sampler.x_min, self.function_sampler.x_max
|
|
45
|
+
fx_min, fx_max = self.function_sampler.f(x_min), self.function_sampler.f(x_max)
|
|
46
|
+
fx_min_sign, fx_max_sign = np.sign(fx_min), np.sign(fx_max)
|
|
47
|
+
if fx_min_sign * fx_max_sign > 0:
|
|
48
|
+
# interval end-point f-values have same sign -> NOT READY
|
|
49
|
+
return 0.0
|
|
50
|
+
elif fx_min_sign * fx_max_sign == 0.0:
|
|
51
|
+
# one of the end-point f-values is 0 -> BORDERLINE
|
|
52
|
+
return 0.5
|
|
53
|
+
else:
|
|
54
|
+
# end-point f-values have opposite sign -> READY
|
|
55
|
+
return 1.0
|
|
56
|
+
|
|
57
|
+
def _extract_max_zero_width(self) -> float:
|
|
58
|
+
return max([root.width for root in self.function_sampler.roots()])
|
|
59
|
+
|
|
60
|
+
def _extract_no_zeros_detected(self) -> float:
|
|
61
|
+
root_intervals, no_root_intervals = self.function_sampler.candidate_root_intervals()
|
|
62
|
+
if len(root_intervals) == 0:
|
|
63
|
+
# no candidate intervals to find roots
|
|
64
|
+
return 1.0
|
|
65
|
+
else:
|
|
66
|
+
return 0.0
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .function_analyser import FunctionAnalyser
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from snuffled._core.analysis._function_sampler import FunctionSampler
|
|
6
|
+
from snuffled._core.analysis._property_extractor import PropertyExtractor
|
|
7
|
+
from snuffled._core.models import FunctionProperty, SnuffledFunctionProperties
|
|
8
|
+
from snuffled._core.utils.statistics import estimate_sign_flip_frequency
|
|
9
|
+
|
|
10
|
+
from .helpers_discontinuous import discontinuity_score
|
|
11
|
+
from .helpers_non_monotonic import non_monotonicity_score
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class FunctionAnalyser(PropertyExtractor[SnuffledFunctionProperties]):
|
|
15
|
+
# -------------------------------------------------------------------------
|
|
16
|
+
# Constructor
|
|
17
|
+
# -------------------------------------------------------------------------
|
|
18
|
+
def __init__(self, function_sampler: FunctionSampler):
|
|
19
|
+
super().__init__(function_sampler)
|
|
20
|
+
|
|
21
|
+
# -------------------------------------------------------------------------
|
|
22
|
+
# Main Implementation
|
|
23
|
+
# -------------------------------------------------------------------------
|
|
24
|
+
def supported_properties(self) -> list[str]:
|
|
25
|
+
return [
|
|
26
|
+
FunctionProperty.HIGH_DYNAMIC_RANGE,
|
|
27
|
+
FunctionProperty.MANY_ZEROES,
|
|
28
|
+
FunctionProperty.FLAT_INTERVALS,
|
|
29
|
+
FunctionProperty.NON_MONOTONIC,
|
|
30
|
+
FunctionProperty.DISCONTINUOUS, # this goes last to benefit from sampling of earlier properties
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
def _new_named_array(self) -> SnuffledFunctionProperties:
|
|
34
|
+
return SnuffledFunctionProperties()
|
|
35
|
+
|
|
36
|
+
def _extract(self, prop: str) -> float:
|
|
37
|
+
match prop:
|
|
38
|
+
case FunctionProperty.HIGH_DYNAMIC_RANGE:
|
|
39
|
+
return self._extract_high_dynamic_range()
|
|
40
|
+
case FunctionProperty.MANY_ZEROES:
|
|
41
|
+
return self._extract_many_zeroes()
|
|
42
|
+
case FunctionProperty.FLAT_INTERVALS:
|
|
43
|
+
return self._extract_flat_intervals()
|
|
44
|
+
case FunctionProperty.NON_MONOTONIC:
|
|
45
|
+
return self._extract_non_monotonic()
|
|
46
|
+
case FunctionProperty.DISCONTINUOUS:
|
|
47
|
+
return self._extract_discontinuous()
|
|
48
|
+
case _:
|
|
49
|
+
raise ValueError(f"Property {prop} not supported")
|
|
50
|
+
|
|
51
|
+
# -------------------------------------------------------------------------
|
|
52
|
+
# Internal methods
|
|
53
|
+
# -------------------------------------------------------------------------
|
|
54
|
+
def _extract_high_dynamic_range(self) -> float:
|
|
55
|
+
"""
|
|
56
|
+
Looks at q10, q90 percentiles of abs(f(x)) for x in [x_min, x_max] and
|
|
57
|
+
looks at the ratio q90/q10. High dynamic range score is calibrated as:
|
|
58
|
+
|
|
59
|
+
q90/q10 score
|
|
60
|
+
|
|
61
|
+
2^10 0.0 (most 'normal' functions will fall below)
|
|
62
|
+
2^52 0.5 (= accuracy of 64-bit float)
|
|
63
|
+
2^94 1.0 (extrapolated from the above)
|
|
64
|
+
|
|
65
|
+
:return: score in [0.0, 1.0] indicating to what extent this function exhibits a high dynamic range.
|
|
66
|
+
"""
|
|
67
|
+
q10 = self.function_sampler.fx_quantile(0.1, absolute=True)
|
|
68
|
+
q90 = self.function_sampler.fx_quantile(0.9, absolute=True)
|
|
69
|
+
return float(np.interp(np.log2(q90 / q10), [10.0, 94.0], [0.0, 1.0], left=0.0, right=1.0))
|
|
70
|
+
|
|
71
|
+
def _extract_many_zeroes(self) -> float:
|
|
72
|
+
"""
|
|
73
|
+
The MANY_ZEROES score indicates if we're 'suffering' from a large number of zeroes,
|
|
74
|
+
and is calibrated on a log scale as follows:
|
|
75
|
+
|
|
76
|
+
estimated # of zeroes score
|
|
77
|
+
|
|
78
|
+
1 0.0
|
|
79
|
+
(x_max-x_min)/dx 1.0
|
|
80
|
+
|
|
81
|
+
We estimate the # of zeroes by using the 'estimate_sign_flip_frequency' stats method.
|
|
82
|
+
|
|
83
|
+
:return: (float) score in [0,1]
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
# Estimate 'zero frequency' lambda = # of zeroes estimated to occur in a unit interval
|
|
87
|
+
|
|
88
|
+
# STEP 1: build list of observations (w, p) with w the interval width and p indicating if we have a sign flip
|
|
89
|
+
root_intervals, non_root_intervals = self.function_sampler.candidate_root_intervals()
|
|
90
|
+
observations = [(x_right - x_left, 1.0) for x_left, x_right in root_intervals]
|
|
91
|
+
observations += [(x_right - x_left, 0.0) for x_left, x_right in non_root_intervals]
|
|
92
|
+
w_values = np.array([w for w, p in observations])
|
|
93
|
+
p_values = np.array([p for w, p in observations])
|
|
94
|
+
|
|
95
|
+
# STEP 2: estimate lambda
|
|
96
|
+
# note that we use a factor of 1.1 in lambda_min to ensure we only give score>0.0 if we see some convincing
|
|
97
|
+
# evidence for multiple zeroes.
|
|
98
|
+
lambda_min = 1.1 / (self.function_sampler.x_max - self.function_sampler.x_min)
|
|
99
|
+
lambda_max = 1 / self.function_sampler.dx
|
|
100
|
+
zeroes_lambda = estimate_sign_flip_frequency(w_values, p_values, lambda_min, lambda_max)
|
|
101
|
+
|
|
102
|
+
# STEP 3: convert to score in [0,1]
|
|
103
|
+
score = (math.log2(zeroes_lambda) - math.log2(lambda_min)) / (math.log2(lambda_max) - math.log2(lambda_min))
|
|
104
|
+
score = min(max(score, 0.0), 1.0)
|
|
105
|
+
|
|
106
|
+
# done
|
|
107
|
+
return float(score)
|
|
108
|
+
|
|
109
|
+
def _extract_non_monotonic(self) -> float:
|
|
110
|
+
return non_monotonicity_score(
|
|
111
|
+
fx_diff=self.function_sampler.fx_diff_values(),
|
|
112
|
+
fx_diff_signs=self.function_sampler.fx_diff_smooth_sign(),
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
def _extract_flat_intervals(self) -> float:
|
|
116
|
+
fx_sign = self.function_sampler.fx_diff_smooth_sign()
|
|
117
|
+
return 1.0 - float(np.mean(abs(fx_sign)))
|
|
118
|
+
|
|
119
|
+
def _extract_discontinuous(self) -> float:
|
|
120
|
+
return discontinuity_score(
|
|
121
|
+
function_sampler=self.function_sampler,
|
|
122
|
+
n_samples=self.function_sampler.n_fun_samples,
|
|
123
|
+
)
|