snuffled 0.1.0__tar.gz

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.
Files changed (57) hide show
  1. snuffled-0.1.0/.gitignore +33 -0
  2. snuffled-0.1.0/LICENSE +201 -0
  3. snuffled-0.1.0/PKG-INFO +25 -0
  4. snuffled-0.1.0/README.md +9 -0
  5. snuffled-0.1.0/pyproject.toml +51 -0
  6. snuffled-0.1.0/snuffled/__init__.py +12 -0
  7. snuffled-0.1.0/snuffled/_core/__init__.py +12 -0
  8. snuffled-0.1.0/snuffled/_core/analysis/__init__.py +2 -0
  9. snuffled-0.1.0/snuffled/_core/analysis/_function_sampler.py +257 -0
  10. snuffled-0.1.0/snuffled/_core/analysis/_property_extractor.py +75 -0
  11. snuffled-0.1.0/snuffled/_core/analysis/diagnostic/__init__.py +1 -0
  12. snuffled-0.1.0/snuffled/_core/analysis/diagnostic/diagnostic_analyser.py +66 -0
  13. snuffled-0.1.0/snuffled/_core/analysis/function/__init__.py +1 -0
  14. snuffled-0.1.0/snuffled/_core/analysis/function/function_analyser.py +123 -0
  15. snuffled-0.1.0/snuffled/_core/analysis/function/helpers_discontinuous.py +219 -0
  16. snuffled-0.1.0/snuffled/_core/analysis/function/helpers_non_monotonic.py +88 -0
  17. snuffled-0.1.0/snuffled/_core/analysis/roots/__init__.py +1 -0
  18. snuffled-0.1.0/snuffled/_core/analysis/roots/curve_fitting/__init__.py +3 -0
  19. snuffled-0.1.0/snuffled/_core/analysis/roots/curve_fitting/brute_force/__init__.py +7 -0
  20. snuffled-0.1.0/snuffled/_core/analysis/roots/curve_fitting/brute_force/_fit_optimal_with_uncertainty.py +97 -0
  21. snuffled-0.1.0/snuffled/_core/analysis/roots/curve_fitting/shared/__init__.py +2 -0
  22. snuffled-0.1.0/snuffled/_core/analysis/roots/curve_fitting/shared/_curves_and_costs.py +63 -0
  23. snuffled-0.1.0/snuffled/_core/analysis/roots/curve_fitting/shared/_function_sampling.py +78 -0
  24. snuffled-0.1.0/snuffled/_core/analysis/roots/curve_fitting/specialized/__init__.py +4 -0
  25. snuffled-0.1.0/snuffled/_core/analysis/roots/curve_fitting/specialized/_explore_uncertainty.py +97 -0
  26. snuffled-0.1.0/snuffled/_core/analysis/roots/curve_fitting/specialized/_fit_exact.py +58 -0
  27. snuffled-0.1.0/snuffled/_core/analysis/roots/curve_fitting/specialized/_fit_optimal.py +199 -0
  28. snuffled-0.1.0/snuffled/_core/analysis/roots/curve_fitting/specialized/_fit_optimal_with_uncertainty.py +119 -0
  29. snuffled-0.1.0/snuffled/_core/analysis/roots/curve_fitting/specialized/_helpers.py +119 -0
  30. snuffled-0.1.0/snuffled/_core/analysis/roots/roots_analyser.py +58 -0
  31. snuffled-0.1.0/snuffled/_core/analysis/roots/single_root_one_side_analyser.py +244 -0
  32. snuffled-0.1.0/snuffled/_core/analysis/roots/single_root_two_side_analyser.py +141 -0
  33. snuffled-0.1.0/snuffled/_core/analysis/snuffler.py +68 -0
  34. snuffled-0.1.0/snuffled/_core/compatibility/__init__.py +2 -0
  35. snuffled-0.1.0/snuffled/_core/compatibility/_numba.py +26 -0
  36. snuffled-0.1.0/snuffled/_core/compatibility/_strenum.py +6 -0
  37. snuffled-0.1.0/snuffled/_core/models/__init__.py +11 -0
  38. snuffled-0.1.0/snuffled/_core/models/base/__init__.py +1 -0
  39. snuffled-0.1.0/snuffled/_core/models/base/_named_array.py +68 -0
  40. snuffled-0.1.0/snuffled/_core/models/properties/__init__.py +5 -0
  41. snuffled-0.1.0/snuffled/_core/models/properties/_all.py +61 -0
  42. snuffled-0.1.0/snuffled/_core/models/properties/_diagnostic.py +17 -0
  43. snuffled-0.1.0/snuffled/_core/models/properties/_function.py +19 -0
  44. snuffled-0.1.0/snuffled/_core/models/properties/_property_extraction_stats.py +9 -0
  45. snuffled-0.1.0/snuffled/_core/models/properties/_root.py +19 -0
  46. snuffled-0.1.0/snuffled/_core/models/root_analysis/__init__.py +1 -0
  47. snuffled-0.1.0/snuffled/_core/models/root_analysis/_root.py +66 -0
  48. snuffled-0.1.0/snuffled/_core/utils/__init__.py +0 -0
  49. snuffled-0.1.0/snuffled/_core/utils/constants.py +23 -0
  50. snuffled-0.1.0/snuffled/_core/utils/math.py +97 -0
  51. snuffled-0.1.0/snuffled/_core/utils/noise.py +23 -0
  52. snuffled-0.1.0/snuffled/_core/utils/numba.py +35 -0
  53. snuffled-0.1.0/snuffled/_core/utils/root_finding.py +186 -0
  54. snuffled-0.1.0/snuffled/_core/utils/sampling.py +188 -0
  55. snuffled-0.1.0/snuffled/_core/utils/signs.py +16 -0
  56. snuffled-0.1.0/snuffled/_core/utils/statistics/__init__.py +1 -0
  57. snuffled-0.1.0/snuffled/_core/utils/statistics/_estimate_sign_flip_frequency.py +127 -0
@@ -0,0 +1,33 @@
1
+ # build files
2
+ dist
3
+ *.tar.gz
4
+ *.whl
5
+
6
+ # no need to track uv.lock for a Python package (where deps are not pinned)
7
+ uv.lock
8
+
9
+ # Python cache files
10
+ __pycache__
11
+ *.pyc
12
+
13
+ # Coverage reports
14
+ .coverage
15
+ htmlcov
16
+
17
+ # Jupyter Notebook checkpoints
18
+ .ipynb_checkpoints
19
+
20
+ # Virtual environment directories
21
+ venv
22
+ .env
23
+
24
+ # Pytest cache
25
+ .cache
26
+
27
+ # OS thumbnail files
28
+ .DS_Store
29
+ Thumbs.db
30
+
31
+ # IDE files
32
+ .idea
33
+ .vscode
snuffled-0.1.0/LICENSE ADDED
@@ -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.
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: snuffled
3
+ Version: 0.1.0
4
+ Summary: Systematic Numerical Univariate Full Function anaLysis for Establishing Root-finding difficulty
5
+ Project-URL: Source, https://github.com/bertpl/snuffled
6
+ Project-URL: Issues, https://github.com/bertpl/snuffled/issues
7
+ Project-URL: Roadmap, https://github.com/bertpl/snuffled/milestones
8
+ Author-email: Bert Pluymers <bert.pluymers@gmail.com>
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.10
11
+ Requires-Dist: backports-strenum>=1.3.1
12
+ Requires-Dist: numpy>=1.20
13
+ Provides-Extra: numba
14
+ Requires-Dist: numba>=0.50; extra == 'numba'
15
+ Description-Content-Type: text/markdown
16
+
17
+ <!--START_SECTION:images-->
18
+ ![shields.io-python-versions](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)
19
+ ![genbadge-test-count](https://bertpl.github.io/snuffled/version_artifacts/v0.1.0/badge-test-count.svg)
20
+ ![genbadge-test-coverage](https://bertpl.github.io/snuffled/version_artifacts/v0.1.0/badge-coverage.svg)
21
+ ![snuffled logo](https://bertpl.github.io/snuffled/version_artifacts/v0.1.0/splash.webp)
22
+ <!--END_SECTION:images-->
23
+
24
+ # SNUFFLED
25
+ **S**ystematic **N**umerical **U**nivariate **F**unction ana**L**ysis for **E**stablishing **D**ifficulty of root-finding.
@@ -0,0 +1,9 @@
1
+ <!--START_SECTION:images-->
2
+ ![shields.io-python-versions](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)
3
+ ![genbadge-test-count](https://bertpl.github.io/snuffled/version_artifacts/v0.1.0/badge-test-count.svg)
4
+ ![genbadge-test-coverage](https://bertpl.github.io/snuffled/version_artifacts/v0.1.0/badge-coverage.svg)
5
+ ![snuffled logo](https://bertpl.github.io/snuffled/version_artifacts/v0.1.0/splash.webp)
6
+ <!--END_SECTION:images-->
7
+
8
+ # SNUFFLED
9
+ **S**ystematic **N**umerical **U**nivariate **F**unction ana**L**ysis for **E**stablishing **D**ifficulty of root-finding.
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "snuffled"
3
+ version = "0.1.0"
4
+ description = "Systematic Numerical Univariate Full Function anaLysis for Establishing Root-finding difficulty"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Bert Pluymers", email = "bert.pluymers@gmail.com" }
8
+ ]
9
+ requires-python = ">=3.10"
10
+ dependencies = [
11
+ "backports-strenum>=1.3.1",
12
+ "numpy>=1.20",
13
+ ]
14
+
15
+ [project.urls]
16
+ Source = "https://github.com/bertpl/snuffled"
17
+ Issues = "https://github.com/bertpl/snuffled/issues"
18
+ Roadmap = "https://github.com/bertpl/snuffled/milestones"
19
+
20
+
21
+ [project.optional-dependencies]
22
+ numba = [
23
+ "numba>=0.50",
24
+ ]
25
+
26
+ [build-system]
27
+ requires = ["hatchling"]
28
+ build-backend = "hatchling.build"
29
+
30
+ [tool.hatch.build.targets.sdist]
31
+ packages = ["snuffled"]
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["snuffled"]
35
+
36
+ [tool.ruff]
37
+ line-length = 120
38
+ target-version = "py310"
39
+
40
+ [tool.ruff.lint]
41
+ select = ["I"]
42
+
43
+ [dependency-groups]
44
+ dev = [
45
+ "genbadge[all]>=1.1.2",
46
+ "jupyterlab>=4.4.6",
47
+ "matplotlib>=3.10.5",
48
+ "notebook>=7.4.5",
49
+ "pytest>=8.0",
50
+ "pytest-cov>=6.0",
51
+ ]
@@ -0,0 +1,12 @@
1
+ from ._core import (
2
+ Diagnostic,
3
+ FunctionProperty,
4
+ NamedArray,
5
+ PropertyExtractionStats,
6
+ RootProperty,
7
+ SnuffledDiagnostics,
8
+ SnuffledFunctionProperties,
9
+ SnuffledProperties,
10
+ SnuffledRootProperties,
11
+ Snuffler,
12
+ )
@@ -0,0 +1,12 @@
1
+ from .analysis import Snuffler
2
+ from .models import (
3
+ Diagnostic,
4
+ FunctionProperty,
5
+ NamedArray,
6
+ PropertyExtractionStats,
7
+ RootProperty,
8
+ SnuffledDiagnostics,
9
+ SnuffledFunctionProperties,
10
+ SnuffledProperties,
11
+ SnuffledRootProperties,
12
+ )
@@ -0,0 +1,2 @@
1
+ from ._function_sampler import FunctionSampler
2
+ from .snuffler import Snuffler
@@ -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
+ ]