pynumerics 2.3.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.
- pynumerics/__init__.py +73 -0
- pynumerics/_bin/Microsoft.CodeAnalysis.CSharp.dll +0 -0
- pynumerics/_bin/Microsoft.CodeAnalysis.LICENSE.txt +27 -0
- pynumerics/_bin/Microsoft.CodeAnalysis.dll +0 -0
- pynumerics/_bin/Numerics.dll +0 -0
- pynumerics/_bin/pynumerics.runtimeconfig.json +15 -0
- pynumerics/_coverage.py +3825 -0
- pynumerics/_util.py +237 -0
- pynumerics/_version.py +40 -0
- pynumerics/bootstrap.py +593 -0
- pynumerics/callbacks.py +791 -0
- pynumerics/copulas.py +910 -0
- pynumerics/data.py +2233 -0
- pynumerics/differentiation.py +348 -0
- pynumerics/distributions.py +4043 -0
- pynumerics/download.py +623 -0
- pynumerics/enums.py +119 -0
- pynumerics/errors.py +245 -0
- pynumerics/functions.py +1142 -0
- pynumerics/goodness_of_fit.py +699 -0
- pynumerics/graphs.py +556 -0
- pynumerics/hypothesis_tests.py +445 -0
- pynumerics/identity.py +144 -0
- pynumerics/integration.py +677 -0
- pynumerics/linalg.py +1408 -0
- pynumerics/machine_learning.py +1335 -0
- pynumerics/marshal.py +733 -0
- pynumerics/mathematics.py +1053 -0
- pynumerics/mcmc.py +1406 -0
- pynumerics/multivariate.py +1539 -0
- pynumerics/ode.py +156 -0
- pynumerics/optimization.py +1736 -0
- pynumerics/probability.py +966 -0
- pynumerics/py.typed +0 -0
- pynumerics/regional.py +522 -0
- pynumerics/roots.py +274 -0
- pynumerics/runtime.py +384 -0
- pynumerics/sampling.py +1758 -0
- pynumerics/special.py +1079 -0
- pynumerics/statistics.py +1958 -0
- pynumerics/timeseries.py +1326 -0
- pynumerics-2.3.0.dist-info/METADATA +142 -0
- pynumerics-2.3.0.dist-info/RECORD +46 -0
- pynumerics-2.3.0.dist-info/WHEEL +5 -0
- pynumerics-2.3.0.dist-info/licenses/LICENSE +10 -0
- pynumerics-2.3.0.dist-info/top_level.txt +1 -0
pynumerics/sampling.py
ADDED
|
@@ -0,0 +1,1758 @@
|
|
|
1
|
+
"""Sampling designs and resampling from ``Numerics.Sampling``.
|
|
2
|
+
|
|
3
|
+
Stratification, Latin hypercube and Sobol designs, the Mersenne Twister, and the general
|
|
4
|
+
bootstrap (:class:`Bootstrap`, ``Numerics.Sampling.Bootstrap<TData>``) with its confidence
|
|
5
|
+
intervals. The MCMC samplers are in :mod:`pynumerics.mcmc`.
|
|
6
|
+
|
|
7
|
+
Stratification bins come back as a :class:`StratificationBins` record of NumPy arrays
|
|
8
|
+
holding the .NET bin list (``.net``), which can be passed back to Numerics members that
|
|
9
|
+
take ``List<StratificationBin>``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from collections.abc import Sequence
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from pynumerics import callbacks
|
|
21
|
+
from pynumerics._util import namespace, net_enum
|
|
22
|
+
from pynumerics.enums import ImportanceDistribution, NetEnum
|
|
23
|
+
from pynumerics.errors import translate_public
|
|
24
|
+
from pynumerics.marshal import (
|
|
25
|
+
_numerics_matrix,
|
|
26
|
+
_parameter_set_arrays,
|
|
27
|
+
to_net_doubles,
|
|
28
|
+
to_net_ints,
|
|
29
|
+
to_net_matrix,
|
|
30
|
+
to_numpy_doubles,
|
|
31
|
+
to_numpy_ints,
|
|
32
|
+
to_numpy_matrix,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _sampling() -> Any:
|
|
37
|
+
"""Return the ``Numerics.Sampling`` namespace after starting the runtime."""
|
|
38
|
+
return namespace("Numerics.Sampling")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _xelement(text: str) -> Any:
|
|
42
|
+
"""Parse XML text into a ``System.Xml.Linq.XElement``."""
|
|
43
|
+
_sampling()
|
|
44
|
+
from System.Xml.Linq import XElement # noqa: PLC0415 - the runtime is running
|
|
45
|
+
|
|
46
|
+
return XElement.Parse(str(text))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class StratificationBin:
|
|
51
|
+
"""One stratification bin as Numerics holds it (``StratificationBin``).
|
|
52
|
+
|
|
53
|
+
Parameters
|
|
54
|
+
----------
|
|
55
|
+
lower_bound : float
|
|
56
|
+
Lower edge.
|
|
57
|
+
upper_bound : float
|
|
58
|
+
Upper edge.
|
|
59
|
+
weight : float
|
|
60
|
+
Weight (probability mass); Numerics sets the bin width for value bins built
|
|
61
|
+
without one.
|
|
62
|
+
midpoint : float
|
|
63
|
+
``Midpoint`` as Numerics computes it, (lower + upper) / 2.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
lower_bound: float
|
|
67
|
+
upper_bound: float
|
|
68
|
+
weight: float
|
|
69
|
+
midpoint: float
|
|
70
|
+
|
|
71
|
+
def contains(self, x: float) -> bool:
|
|
72
|
+
"""Return whether ``lower_bound <= x < upper_bound``.
|
|
73
|
+
|
|
74
|
+
Parameters
|
|
75
|
+
----------
|
|
76
|
+
x : float
|
|
77
|
+
The value.
|
|
78
|
+
|
|
79
|
+
Returns
|
|
80
|
+
-------
|
|
81
|
+
bool
|
|
82
|
+
True when the value lies in the half-open bin.
|
|
83
|
+
"""
|
|
84
|
+
return self.lower_bound <= x < self.upper_bound
|
|
85
|
+
|
|
86
|
+
def to_net(self) -> Any:
|
|
87
|
+
"""Return the bin as a new .NET ``StratificationBin``.
|
|
88
|
+
|
|
89
|
+
Returns
|
|
90
|
+
-------
|
|
91
|
+
Numerics.Sampling.StratificationBin
|
|
92
|
+
A bin with the same bounds and weight.
|
|
93
|
+
"""
|
|
94
|
+
return _sampling().StratificationBin(float(self.lower_bound), float(self.upper_bound), float(self.weight))
|
|
95
|
+
|
|
96
|
+
def compare_to(self, other: StratificationBin) -> int:
|
|
97
|
+
"""Order two non-overlapping bins (``CompareTo``).
|
|
98
|
+
|
|
99
|
+
Parameters
|
|
100
|
+
----------
|
|
101
|
+
other : StratificationBin
|
|
102
|
+
The other bin.
|
|
103
|
+
|
|
104
|
+
Returns
|
|
105
|
+
-------
|
|
106
|
+
int
|
|
107
|
+
1 when this bin lies above ``other``, -1 when below.
|
|
108
|
+
|
|
109
|
+
Raises
|
|
110
|
+
------
|
|
111
|
+
ValueError
|
|
112
|
+
If the bins overlap; Numerics counts a bin as overlapping itself.
|
|
113
|
+
"""
|
|
114
|
+
return int(self.to_net().CompareTo(other.to_net()))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True)
|
|
118
|
+
class StratificationBins:
|
|
119
|
+
"""Stratification bins as arrays.
|
|
120
|
+
|
|
121
|
+
Parameters
|
|
122
|
+
----------
|
|
123
|
+
lower : numpy.ndarray
|
|
124
|
+
Lower bound of each bin.
|
|
125
|
+
upper : numpy.ndarray
|
|
126
|
+
Upper bound of each bin.
|
|
127
|
+
weight : numpy.ndarray
|
|
128
|
+
Weight (probability mass) of each bin.
|
|
129
|
+
net : System.Collections.Generic.List[Numerics.Sampling.StratificationBin]
|
|
130
|
+
The .NET bin list the arrays were read from.
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
lower: np.ndarray
|
|
134
|
+
upper: np.ndarray
|
|
135
|
+
weight: np.ndarray
|
|
136
|
+
net: Any = field(repr=False, compare=False)
|
|
137
|
+
|
|
138
|
+
@property
|
|
139
|
+
def midpoint(self) -> np.ndarray:
|
|
140
|
+
"""Bin midpoints, (lower + upper) / 2 as Numerics computes them."""
|
|
141
|
+
return np.array([float(b.Midpoint) for b in self.net], dtype=np.float64)
|
|
142
|
+
|
|
143
|
+
def __len__(self) -> int:
|
|
144
|
+
return int(self.lower.size)
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
def bins(self) -> tuple[StratificationBin, ...]:
|
|
148
|
+
"""The bins as :class:`StratificationBin` records (``LowerBound``, ``UpperBound``, ``Weight``, ``Midpoint``)."""
|
|
149
|
+
return tuple(StratificationBin(float(b.LowerBound), float(b.UpperBound), float(b.Weight), float(b.Midpoint))
|
|
150
|
+
for b in self.net)
|
|
151
|
+
|
|
152
|
+
@classmethod
|
|
153
|
+
def from_net(cls, bins: Any) -> StratificationBins:
|
|
154
|
+
"""Read a .NET ``List<StratificationBin>``.
|
|
155
|
+
|
|
156
|
+
Parameters
|
|
157
|
+
----------
|
|
158
|
+
bins : System.Collections.Generic.List[Numerics.Sampling.StratificationBin]
|
|
159
|
+
The .NET bins.
|
|
160
|
+
|
|
161
|
+
Returns
|
|
162
|
+
-------
|
|
163
|
+
StratificationBins
|
|
164
|
+
The arrays and the original list.
|
|
165
|
+
"""
|
|
166
|
+
lower = np.array([float(b.LowerBound) for b in bins], dtype=np.float64)
|
|
167
|
+
upper = np.array([float(b.UpperBound) for b in bins], dtype=np.float64)
|
|
168
|
+
weight = np.array([float(b.Weight) for b in bins], dtype=np.float64)
|
|
169
|
+
return cls(lower, upper, weight, bins)
|
|
170
|
+
|
|
171
|
+
def to_xml(self) -> str:
|
|
172
|
+
"""Serialize the bins (``StratificationBin.SaveToXElement(IList<StratificationBin>)``).
|
|
173
|
+
|
|
174
|
+
Returns
|
|
175
|
+
-------
|
|
176
|
+
str
|
|
177
|
+
The ``StratificationBinList`` XML element, bounds and weights in G17.
|
|
178
|
+
"""
|
|
179
|
+
return str(_sampling().StratificationBin.SaveToXElement(self.net).ToString())
|
|
180
|
+
|
|
181
|
+
@classmethod
|
|
182
|
+
def from_xml(cls, text: str) -> StratificationBins:
|
|
183
|
+
"""Read bins written by :meth:`to_xml` (``StratificationBin.XElementToStratificationBinList``).
|
|
184
|
+
|
|
185
|
+
Parameters
|
|
186
|
+
----------
|
|
187
|
+
text : str
|
|
188
|
+
A ``StratificationBinList`` XML element.
|
|
189
|
+
|
|
190
|
+
Returns
|
|
191
|
+
-------
|
|
192
|
+
StratificationBins
|
|
193
|
+
The bins.
|
|
194
|
+
"""
|
|
195
|
+
return cls.from_net(_sampling().StratificationBin.XElementToStratificationBinList(_xelement(text)))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class StratificationOptions:
|
|
199
|
+
"""The range and bin count of one stratification (``Numerics.Sampling.StratificationOptions``).
|
|
200
|
+
|
|
201
|
+
Parameters
|
|
202
|
+
----------
|
|
203
|
+
lower_bound : float
|
|
204
|
+
Lower end of the range.
|
|
205
|
+
upper_bound : float
|
|
206
|
+
Upper end of the range.
|
|
207
|
+
number_of_bins : int
|
|
208
|
+
Number of bins.
|
|
209
|
+
is_probability : bool, optional
|
|
210
|
+
Whether the range is a probability range; default False.
|
|
211
|
+
|
|
212
|
+
Attributes
|
|
213
|
+
----------
|
|
214
|
+
net : Numerics.Sampling.StratificationOptions
|
|
215
|
+
The wrapped .NET object.
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
def __init__(self, lower_bound: float, upper_bound: float, number_of_bins: int,
|
|
219
|
+
is_probability: bool = False) -> None:
|
|
220
|
+
self.net = _sampling().StratificationOptions(float(lower_bound), float(upper_bound), int(number_of_bins),
|
|
221
|
+
bool(is_probability))
|
|
222
|
+
|
|
223
|
+
@classmethod
|
|
224
|
+
def _wrap(cls, net: Any) -> StratificationOptions:
|
|
225
|
+
instance = cls.__new__(cls)
|
|
226
|
+
instance.net = net
|
|
227
|
+
return instance
|
|
228
|
+
|
|
229
|
+
def __repr__(self) -> str:
|
|
230
|
+
return (f"StratificationOptions({self.lower_bound!r}, {self.upper_bound!r}, {self.number_of_bins!r}, "
|
|
231
|
+
f"is_probability={self.is_probability!r})")
|
|
232
|
+
|
|
233
|
+
@property
|
|
234
|
+
def lower_bound(self) -> float:
|
|
235
|
+
"""Lower end of the range (``LowerBound``)."""
|
|
236
|
+
return float(self.net.LowerBound)
|
|
237
|
+
|
|
238
|
+
@property
|
|
239
|
+
def upper_bound(self) -> float:
|
|
240
|
+
"""Upper end of the range (``UpperBound``)."""
|
|
241
|
+
return float(self.net.UpperBound)
|
|
242
|
+
|
|
243
|
+
@property
|
|
244
|
+
def number_of_bins(self) -> int:
|
|
245
|
+
"""Number of bins (``NumberOfBins``)."""
|
|
246
|
+
return int(self.net.NumberOfBins)
|
|
247
|
+
|
|
248
|
+
@property
|
|
249
|
+
def is_probability(self) -> bool:
|
|
250
|
+
"""Whether the range is a probability range (``IsProbability``)."""
|
|
251
|
+
return bool(self.net.IsProbability)
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def is_valid(self) -> bool:
|
|
255
|
+
"""Whether the options are valid (``IsValid``)."""
|
|
256
|
+
return bool(self.net.IsValid)
|
|
257
|
+
|
|
258
|
+
def get_errors(self) -> list[str]:
|
|
259
|
+
"""Return the validation messages (``GetErrors``).
|
|
260
|
+
|
|
261
|
+
Returns
|
|
262
|
+
-------
|
|
263
|
+
list of str
|
|
264
|
+
Empty when the options are valid.
|
|
265
|
+
"""
|
|
266
|
+
return [str(e) for e in self.net.GetErrors()]
|
|
267
|
+
|
|
268
|
+
def clone(self) -> StratificationOptions:
|
|
269
|
+
"""Return a copy (``Clone``).
|
|
270
|
+
|
|
271
|
+
Returns
|
|
272
|
+
-------
|
|
273
|
+
StratificationOptions
|
|
274
|
+
The copy.
|
|
275
|
+
"""
|
|
276
|
+
return StratificationOptions._wrap(self.net.Clone())
|
|
277
|
+
|
|
278
|
+
def to_xml(self) -> str:
|
|
279
|
+
"""Serialize the options (``SaveToXElement``).
|
|
280
|
+
|
|
281
|
+
Returns
|
|
282
|
+
-------
|
|
283
|
+
str
|
|
284
|
+
The ``StratificationOptions`` XML element.
|
|
285
|
+
"""
|
|
286
|
+
return str(self.net.SaveToXElement().ToString())
|
|
287
|
+
|
|
288
|
+
@classmethod
|
|
289
|
+
def from_xml(cls, text: str) -> StratificationOptions:
|
|
290
|
+
"""Read options written by :meth:`to_xml` (``StratificationOptions(XElement)``).
|
|
291
|
+
|
|
292
|
+
Parameters
|
|
293
|
+
----------
|
|
294
|
+
text : str
|
|
295
|
+
A ``StratificationOptions`` XML element.
|
|
296
|
+
|
|
297
|
+
Returns
|
|
298
|
+
-------
|
|
299
|
+
StratificationOptions
|
|
300
|
+
The options.
|
|
301
|
+
"""
|
|
302
|
+
return cls._wrap(_sampling().StratificationOptions(_xelement(text)))
|
|
303
|
+
|
|
304
|
+
@staticmethod
|
|
305
|
+
def list_to_xml(options: Sequence[StratificationOptions]) -> str:
|
|
306
|
+
"""Serialize several options (``StratificationOptions.SaveToXElement(IList<StratificationOptions>)``).
|
|
307
|
+
|
|
308
|
+
Parameters
|
|
309
|
+
----------
|
|
310
|
+
options : sequence of StratificationOptions
|
|
311
|
+
The options.
|
|
312
|
+
|
|
313
|
+
Returns
|
|
314
|
+
-------
|
|
315
|
+
str
|
|
316
|
+
The XML element holding every option.
|
|
317
|
+
"""
|
|
318
|
+
return str(_sampling().StratificationOptions.SaveToXElement(_options_list(options)).ToString())
|
|
319
|
+
|
|
320
|
+
@staticmethod
|
|
321
|
+
def list_from_xml(text: str) -> list[StratificationOptions]:
|
|
322
|
+
"""Read options written by :meth:`list_to_xml` (``XElementToStratificationOptions``).
|
|
323
|
+
|
|
324
|
+
Parameters
|
|
325
|
+
----------
|
|
326
|
+
text : str
|
|
327
|
+
The XML element.
|
|
328
|
+
|
|
329
|
+
Returns
|
|
330
|
+
-------
|
|
331
|
+
list of StratificationOptions
|
|
332
|
+
The options.
|
|
333
|
+
"""
|
|
334
|
+
items = _sampling().StratificationOptions.XElementToStratificationOptions(_xelement(text))
|
|
335
|
+
return [StratificationOptions._wrap(o) for o in items]
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _options(lower: float, upper: float, number_of_bins: int, is_probability: bool) -> Any:
|
|
339
|
+
"""Build ``StratificationOptions``."""
|
|
340
|
+
return _sampling().StratificationOptions(float(lower), float(upper), int(number_of_bins), bool(is_probability))
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _options_list(options: Any, is_probability: bool = False) -> Any:
|
|
344
|
+
"""Build ``List<StratificationOptions>`` from :class:`StratificationOptions` or ``(lower, upper, bins)`` triples."""
|
|
345
|
+
s = _sampling()
|
|
346
|
+
from System.Collections.Generic import List # noqa: PLC0415 - the runtime is started by _sampling
|
|
347
|
+
|
|
348
|
+
items = List[s.StratificationOptions]()
|
|
349
|
+
for option in options:
|
|
350
|
+
if isinstance(option, StratificationOptions):
|
|
351
|
+
items.Add(option.net)
|
|
352
|
+
else:
|
|
353
|
+
lower, upper, number_of_bins = option
|
|
354
|
+
items.Add(_options(lower, upper, number_of_bins, is_probability))
|
|
355
|
+
return items
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def stratify_x_values(lower: float, upper: float, number_of_bins: int,
|
|
359
|
+
is_logarithmic: bool = False) -> StratificationBins:
|
|
360
|
+
"""Stratify a value range into equal-width bins (``Stratify.XValues``).
|
|
361
|
+
|
|
362
|
+
Parameters
|
|
363
|
+
----------
|
|
364
|
+
lower, upper : float
|
|
365
|
+
Range to stratify.
|
|
366
|
+
number_of_bins : int
|
|
367
|
+
Number of bins.
|
|
368
|
+
is_logarithmic : bool, optional
|
|
369
|
+
Equal widths in log10 space; default False.
|
|
370
|
+
|
|
371
|
+
Returns
|
|
372
|
+
-------
|
|
373
|
+
StratificationBins
|
|
374
|
+
The bins; Numerics leaves their weights unset (−1) for value bins.
|
|
375
|
+
"""
|
|
376
|
+
s = _sampling()
|
|
377
|
+
return StratificationBins.from_net(s.Stratify.XValues(_options(lower, upper, number_of_bins, False),
|
|
378
|
+
bool(is_logarithmic)))
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def stratify_x_values_many(options: Any, is_logarithmic: bool = False) -> StratificationBins:
|
|
382
|
+
"""Stratify several value ranges into one bin list (``Stratify.XValues(List<StratificationOptions>)``).
|
|
383
|
+
|
|
384
|
+
Parameters
|
|
385
|
+
----------
|
|
386
|
+
options : sequence of (float, float, int) or StratificationOptions
|
|
387
|
+
One ``(lower, upper, number_of_bins)`` triple or options object per range.
|
|
388
|
+
is_logarithmic : bool, optional
|
|
389
|
+
Equal widths in log10 space; default False.
|
|
390
|
+
|
|
391
|
+
Returns
|
|
392
|
+
-------
|
|
393
|
+
StratificationBins
|
|
394
|
+
The bins of every range, in the order Numerics returns them.
|
|
395
|
+
"""
|
|
396
|
+
s = _sampling()
|
|
397
|
+
return StratificationBins.from_net(s.Stratify.XValues(_options_list(options), bool(is_logarithmic)))
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def stratify_probabilities(lower: float, upper: float, number_of_bins: int,
|
|
401
|
+
importance: ImportanceDistribution | str = ImportanceDistribution.UNIFORM,
|
|
402
|
+
is_exhaustive: bool = True) -> StratificationBins:
|
|
403
|
+
"""Stratify a non-exceedance probability range (``Stratify.Probabilities``).
|
|
404
|
+
|
|
405
|
+
Parameters
|
|
406
|
+
----------
|
|
407
|
+
lower, upper : float
|
|
408
|
+
Probability range in [0, 1].
|
|
409
|
+
number_of_bins : int
|
|
410
|
+
Number of bins.
|
|
411
|
+
importance : ImportanceDistribution or str, optional
|
|
412
|
+
Space in which the bins are equally wide; default uniform.
|
|
413
|
+
is_exhaustive : bool, optional
|
|
414
|
+
Whether the end bins absorb the remaining probability; default True.
|
|
415
|
+
|
|
416
|
+
Returns
|
|
417
|
+
-------
|
|
418
|
+
StratificationBins
|
|
419
|
+
The bins.
|
|
420
|
+
"""
|
|
421
|
+
s = _sampling()
|
|
422
|
+
kind = net_enum(s.Stratify.ImportanceDistribution, importance)
|
|
423
|
+
return StratificationBins.from_net(s.Stratify.Probabilities(_options(lower, upper, number_of_bins, True), kind,
|
|
424
|
+
bool(is_exhaustive)))
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def stratify_probabilities_many(options: Any, importance: ImportanceDistribution | str = ImportanceDistribution.UNIFORM,
|
|
428
|
+
is_exhaustive: bool = True) -> StratificationBins:
|
|
429
|
+
"""Stratify several probability ranges into one bin list (``Stratify.Probabilities(List<...>)``).
|
|
430
|
+
|
|
431
|
+
Parameters
|
|
432
|
+
----------
|
|
433
|
+
options : sequence of (float, float, int) or StratificationOptions
|
|
434
|
+
One ``(lower, upper, number_of_bins)`` probability range or options object per range.
|
|
435
|
+
importance : ImportanceDistribution or str, optional
|
|
436
|
+
Space in which the bins are equally wide; default uniform.
|
|
437
|
+
is_exhaustive : bool, optional
|
|
438
|
+
Whether the end bins absorb the remaining probability; default True.
|
|
439
|
+
|
|
440
|
+
Returns
|
|
441
|
+
-------
|
|
442
|
+
StratificationBins
|
|
443
|
+
The bins of every range.
|
|
444
|
+
"""
|
|
445
|
+
s = _sampling()
|
|
446
|
+
kind = net_enum(s.Stratify.ImportanceDistribution, importance)
|
|
447
|
+
return StratificationBins.from_net(s.Stratify.Probabilities(_options_list(options, True), kind,
|
|
448
|
+
bool(is_exhaustive)))
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def stratify_exceedance_probabilities(lower: float, upper: float, number_of_bins: int,
|
|
452
|
+
importance: ImportanceDistribution | str = ImportanceDistribution.UNIFORM,
|
|
453
|
+
is_exhaustive: bool = True) -> StratificationBins:
|
|
454
|
+
"""Stratify an exceedance probability range (``Stratify.ExceedanceProbabilities``).
|
|
455
|
+
|
|
456
|
+
Parameters
|
|
457
|
+
----------
|
|
458
|
+
lower, upper : float
|
|
459
|
+
Exceedance probability range in [0, 1].
|
|
460
|
+
number_of_bins : int
|
|
461
|
+
Number of bins.
|
|
462
|
+
importance : ImportanceDistribution or str, optional
|
|
463
|
+
Space in which the bins are equally wide; default uniform.
|
|
464
|
+
is_exhaustive : bool, optional
|
|
465
|
+
Whether the end bins absorb the remaining probability; default True.
|
|
466
|
+
|
|
467
|
+
Returns
|
|
468
|
+
-------
|
|
469
|
+
StratificationBins
|
|
470
|
+
The bins.
|
|
471
|
+
"""
|
|
472
|
+
s = _sampling()
|
|
473
|
+
kind = net_enum(s.Stratify.ImportanceDistribution, importance)
|
|
474
|
+
return StratificationBins.from_net(s.Stratify.ExceedanceProbabilities(
|
|
475
|
+
_options(lower, upper, number_of_bins, True), kind, bool(is_exhaustive)))
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def stratify_exceedance_probabilities_many(options: Any,
|
|
479
|
+
importance: ImportanceDistribution | str = ImportanceDistribution.UNIFORM,
|
|
480
|
+
is_exhaustive: bool = True) -> StratificationBins:
|
|
481
|
+
"""Stratify several exceedance probability ranges (``Stratify.ExceedanceProbabilities(List<...>)``).
|
|
482
|
+
|
|
483
|
+
Parameters
|
|
484
|
+
----------
|
|
485
|
+
options : sequence of (float, float, int) or StratificationOptions
|
|
486
|
+
One ``(lower, upper, number_of_bins)`` range or options object per range.
|
|
487
|
+
importance : ImportanceDistribution or str, optional
|
|
488
|
+
Space in which the bins are equally wide; default uniform.
|
|
489
|
+
is_exhaustive : bool, optional
|
|
490
|
+
Whether the end bins absorb the remaining probability; default True.
|
|
491
|
+
|
|
492
|
+
Returns
|
|
493
|
+
-------
|
|
494
|
+
StratificationBins
|
|
495
|
+
The bins of every range.
|
|
496
|
+
"""
|
|
497
|
+
s = _sampling()
|
|
498
|
+
kind = net_enum(s.Stratify.ImportanceDistribution, importance)
|
|
499
|
+
return StratificationBins.from_net(s.Stratify.ExceedanceProbabilities(_options_list(options, True), kind,
|
|
500
|
+
bool(is_exhaustive)))
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def stratify_multivariate_probabilities(lower: float, upper: float, number_of_bins: int,
|
|
504
|
+
importance: ImportanceDistribution | str = ImportanceDistribution.UNIFORM,
|
|
505
|
+
is_exhaustive: bool = True, dimension: int = 1, seed: int = -1,
|
|
506
|
+
correlation: Any = None) -> list[StratificationBins]:
|
|
507
|
+
"""Stratify a probability range in several dimensions (``Stratify.MultivariateProbabilities``).
|
|
508
|
+
|
|
509
|
+
Parameters
|
|
510
|
+
----------
|
|
511
|
+
lower, upper : float
|
|
512
|
+
Probability range in [0, 1].
|
|
513
|
+
number_of_bins : int
|
|
514
|
+
Number of bins per dimension.
|
|
515
|
+
importance : ImportanceDistribution or str, optional
|
|
516
|
+
Space in which the bins are equally wide; default uniform.
|
|
517
|
+
is_exhaustive : bool, optional
|
|
518
|
+
Whether the end bins absorb the remaining probability; default True.
|
|
519
|
+
dimension : int, optional
|
|
520
|
+
Number of dimensions; default 1.
|
|
521
|
+
seed : int, optional
|
|
522
|
+
Seed of the random pairing; zero or negative seeds from the clock (not reproducible).
|
|
523
|
+
correlation : array_like, optional
|
|
524
|
+
Correlation matrix of shape ``(dimension, dimension)``; default independence.
|
|
525
|
+
|
|
526
|
+
Returns
|
|
527
|
+
-------
|
|
528
|
+
list of StratificationBins
|
|
529
|
+
The bins of each dimension.
|
|
530
|
+
"""
|
|
531
|
+
s = _sampling()
|
|
532
|
+
kind = net_enum(s.Stratify.ImportanceDistribution, importance)
|
|
533
|
+
matrix = None if correlation is None else to_net_matrix(correlation)
|
|
534
|
+
result = s.Stratify.MultivariateProbabilities(_options(lower, upper, number_of_bins, True), kind,
|
|
535
|
+
bool(is_exhaustive), int(dimension), int(seed), matrix)
|
|
536
|
+
return [StratificationBins.from_net(bins) for bins in result]
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _bins(bins: Any) -> Any:
|
|
540
|
+
"""Return the .NET bin list of :class:`StratificationBins` or pass a .NET list through."""
|
|
541
|
+
return getattr(bins, "net", bins)
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def x_to_probability(x_bins: Any, transform: Any, is_exhaustive: bool = True) -> StratificationBins:
|
|
545
|
+
"""Map value bins to non-exceedance probability bins (``Stratify.XToProbability``).
|
|
546
|
+
|
|
547
|
+
Parameters
|
|
548
|
+
----------
|
|
549
|
+
x_bins : StratificationBins
|
|
550
|
+
Value bins.
|
|
551
|
+
transform : callable, str or System.Delegate
|
|
552
|
+
The CDF ``x -> p`` (``Func<double, double>``), for example ``Normal(0, 1).cdf``.
|
|
553
|
+
is_exhaustive : bool, optional
|
|
554
|
+
Whether the end bins absorb the remaining probability; default True.
|
|
555
|
+
|
|
556
|
+
Returns
|
|
557
|
+
-------
|
|
558
|
+
StratificationBins
|
|
559
|
+
The probability bins.
|
|
560
|
+
"""
|
|
561
|
+
s = _sampling()
|
|
562
|
+
return StratificationBins.from_net(s.Stratify.XToProbability(_bins(x_bins), callbacks.scalar_function(transform),
|
|
563
|
+
bool(is_exhaustive)))
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def x_to_exceedance_probability(x_bins: Any, transform: Any, is_exhaustive: bool = True) -> StratificationBins:
|
|
567
|
+
"""Map value bins to exceedance probability bins (``Stratify.XToExceedanceProbability``).
|
|
568
|
+
|
|
569
|
+
Parameters
|
|
570
|
+
----------
|
|
571
|
+
x_bins : StratificationBins
|
|
572
|
+
Value bins.
|
|
573
|
+
transform : callable, str or System.Delegate
|
|
574
|
+
The survival function ``x -> 1 - F(x)`` (``Func<double, double>``).
|
|
575
|
+
is_exhaustive : bool, optional
|
|
576
|
+
Whether the end bins absorb the remaining probability; default True.
|
|
577
|
+
|
|
578
|
+
Returns
|
|
579
|
+
-------
|
|
580
|
+
StratificationBins
|
|
581
|
+
The exceedance probability bins.
|
|
582
|
+
"""
|
|
583
|
+
s = _sampling()
|
|
584
|
+
return StratificationBins.from_net(s.Stratify.XToExceedanceProbability(
|
|
585
|
+
_bins(x_bins), callbacks.scalar_function(transform), bool(is_exhaustive)))
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def probability_to_x(probability_bins: Any, transform: Any) -> StratificationBins:
|
|
589
|
+
"""Map non-exceedance probability bins to value bins (``Stratify.ProbabilityToX``).
|
|
590
|
+
|
|
591
|
+
Parameters
|
|
592
|
+
----------
|
|
593
|
+
probability_bins : StratificationBins
|
|
594
|
+
Probability bins.
|
|
595
|
+
transform : callable, str or System.Delegate
|
|
596
|
+
The quantile function ``p -> x`` (``Func<double, double>``).
|
|
597
|
+
|
|
598
|
+
Returns
|
|
599
|
+
-------
|
|
600
|
+
StratificationBins
|
|
601
|
+
The value bins; Numerics sets each weight to the bin width, as for value bins.
|
|
602
|
+
"""
|
|
603
|
+
s = _sampling()
|
|
604
|
+
return StratificationBins.from_net(s.Stratify.ProbabilityToX(_bins(probability_bins),
|
|
605
|
+
callbacks.scalar_function(transform)))
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def exceedance_probability_to_x(probability_bins: Any, transform: Any) -> StratificationBins:
|
|
609
|
+
"""Map exceedance probability bins to value bins (``Stratify.ExceedanceProbabilityToX``).
|
|
610
|
+
|
|
611
|
+
Parameters
|
|
612
|
+
----------
|
|
613
|
+
probability_bins : StratificationBins
|
|
614
|
+
Exceedance probability bins.
|
|
615
|
+
transform : callable, str or System.Delegate
|
|
616
|
+
The function ``q -> x`` (``Func<double, double>``), for example ``q -> F^-1(1 - q)``.
|
|
617
|
+
|
|
618
|
+
Returns
|
|
619
|
+
-------
|
|
620
|
+
StratificationBins
|
|
621
|
+
The value bins, ascending in x; Numerics sets each weight to the bin width.
|
|
622
|
+
"""
|
|
623
|
+
s = _sampling()
|
|
624
|
+
return StratificationBins.from_net(s.Stratify.ExceedanceProbabilityToX(_bins(probability_bins),
|
|
625
|
+
callbacks.scalar_function(transform)))
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def latin_hypercube(sample_size: int, dimension: int = 1, seed: Any = -1, median: bool = False) -> np.ndarray:
|
|
629
|
+
"""Draw a Latin hypercube design on the unit cube (``LatinHypercube.Random``/``Median``).
|
|
630
|
+
|
|
631
|
+
Parameters
|
|
632
|
+
----------
|
|
633
|
+
sample_size : int
|
|
634
|
+
Number of rows.
|
|
635
|
+
dimension : int, optional
|
|
636
|
+
Number of columns; default 1.
|
|
637
|
+
seed : int or MersenneTwister, optional
|
|
638
|
+
Seed, or a generator to draw from (the ``Random`` overloads); zero or negative seeds
|
|
639
|
+
from the clock (not reproducible).
|
|
640
|
+
median : bool, optional
|
|
641
|
+
Use bin midpoints instead of uniform positions within bins; default False.
|
|
642
|
+
|
|
643
|
+
Returns
|
|
644
|
+
-------
|
|
645
|
+
numpy.ndarray
|
|
646
|
+
Array of shape ``(sample_size, dimension)``.
|
|
647
|
+
"""
|
|
648
|
+
lhs = _sampling().LatinHypercube
|
|
649
|
+
method = lhs.Median if median else lhs.Random
|
|
650
|
+
generator = seed.net if isinstance(seed, MersenneTwister) else seed
|
|
651
|
+
if not isinstance(generator, int):
|
|
652
|
+
return to_numpy_matrix(method(int(sample_size), int(dimension), generator))
|
|
653
|
+
return to_numpy_matrix(method(int(sample_size), int(dimension), int(generator)))
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
class MersenneTwister:
|
|
657
|
+
"""The Numerics Mersenne Twister (``Numerics.Sampling.MersenneTwister``).
|
|
658
|
+
|
|
659
|
+
Exposed for cross-checks of NumPy re-implementations against the .NET stream, and as the
|
|
660
|
+
generator passed to Numerics members that take a ``System.Random``.
|
|
661
|
+
|
|
662
|
+
Parameters
|
|
663
|
+
----------
|
|
664
|
+
seed : int or sequence of int, optional
|
|
665
|
+
Seed, or an array of seeds (``init_by_array``); default the clock (not reproducible).
|
|
666
|
+
|
|
667
|
+
Attributes
|
|
668
|
+
----------
|
|
669
|
+
net : Numerics.Sampling.MersenneTwister
|
|
670
|
+
The wrapped .NET generator.
|
|
671
|
+
"""
|
|
672
|
+
|
|
673
|
+
def __init__(self, seed: Any = None) -> None:
|
|
674
|
+
s = _sampling()
|
|
675
|
+
if seed is None:
|
|
676
|
+
self.net = s.MersenneTwister()
|
|
677
|
+
elif isinstance(seed, (int, np.integer)):
|
|
678
|
+
self.net = s.MersenneTwister(int(seed))
|
|
679
|
+
else:
|
|
680
|
+
self.net = s.MersenneTwister(to_net_ints(seed))
|
|
681
|
+
|
|
682
|
+
def initialize(self, seed: int) -> None:
|
|
683
|
+
"""Reseed the generator with an unsigned 32-bit seed (``Initialize(uint)``).
|
|
684
|
+
|
|
685
|
+
Parameters
|
|
686
|
+
----------
|
|
687
|
+
seed : int
|
|
688
|
+
Seed in [0, 2**32).
|
|
689
|
+
"""
|
|
690
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
691
|
+
|
|
692
|
+
self.net.Initialize(System.UInt32(int(seed)))
|
|
693
|
+
|
|
694
|
+
def next_double(self) -> float:
|
|
695
|
+
"""Return the next double in [0, 1) (``NextDouble``).
|
|
696
|
+
|
|
697
|
+
Returns
|
|
698
|
+
-------
|
|
699
|
+
float
|
|
700
|
+
The draw.
|
|
701
|
+
"""
|
|
702
|
+
return float(self.net.NextDouble())
|
|
703
|
+
|
|
704
|
+
def next_doubles(self, length: int) -> np.ndarray:
|
|
705
|
+
"""Return the next doubles (``ExtensionMethods.NextDoubles``).
|
|
706
|
+
|
|
707
|
+
Parameters
|
|
708
|
+
----------
|
|
709
|
+
length : int
|
|
710
|
+
Number of draws.
|
|
711
|
+
|
|
712
|
+
Returns
|
|
713
|
+
-------
|
|
714
|
+
numpy.ndarray
|
|
715
|
+
The draws.
|
|
716
|
+
"""
|
|
717
|
+
root = namespace("Numerics")
|
|
718
|
+
return to_numpy_doubles(root.ExtensionMethods.NextDoubles(self.net, int(length)))
|
|
719
|
+
|
|
720
|
+
def next_integers(self, length: int) -> np.ndarray:
|
|
721
|
+
"""Return the next non-negative integers (``ExtensionMethods.NextIntegers``).
|
|
722
|
+
|
|
723
|
+
Parameters
|
|
724
|
+
----------
|
|
725
|
+
length : int
|
|
726
|
+
Number of draws.
|
|
727
|
+
|
|
728
|
+
Returns
|
|
729
|
+
-------
|
|
730
|
+
numpy.ndarray
|
|
731
|
+
The draws as int32.
|
|
732
|
+
"""
|
|
733
|
+
root = namespace("Numerics")
|
|
734
|
+
return to_numpy_ints(root.ExtensionMethods.NextIntegers(self.net, int(length)))
|
|
735
|
+
|
|
736
|
+
def gen_rand_int32(self) -> int:
|
|
737
|
+
"""Return the next raw 32-bit output (``GenRandInt32``).
|
|
738
|
+
|
|
739
|
+
Returns
|
|
740
|
+
-------
|
|
741
|
+
int
|
|
742
|
+
An unsigned 32-bit integer.
|
|
743
|
+
"""
|
|
744
|
+
return int(self.net.GenRandInt32())
|
|
745
|
+
|
|
746
|
+
def gen_rand_int31(self) -> int:
|
|
747
|
+
"""Return the next 31-bit output (``GenRandInt31``).
|
|
748
|
+
|
|
749
|
+
Returns
|
|
750
|
+
-------
|
|
751
|
+
int
|
|
752
|
+
An integer in [0, 2**31).
|
|
753
|
+
"""
|
|
754
|
+
return int(self.net.GenRandInt31())
|
|
755
|
+
|
|
756
|
+
def gen_rand_real1(self) -> float:
|
|
757
|
+
"""Return the next double in [0, 1] (``GenRandReal1``).
|
|
758
|
+
|
|
759
|
+
Returns
|
|
760
|
+
-------
|
|
761
|
+
float
|
|
762
|
+
The draw.
|
|
763
|
+
"""
|
|
764
|
+
return float(self.net.GenRandReal1())
|
|
765
|
+
|
|
766
|
+
def gen_rand_real2(self) -> float:
|
|
767
|
+
"""Return the next double in [0, 1) (``GenRandReal2``).
|
|
768
|
+
|
|
769
|
+
Returns
|
|
770
|
+
-------
|
|
771
|
+
float
|
|
772
|
+
The draw.
|
|
773
|
+
"""
|
|
774
|
+
return float(self.net.GenRandReal2())
|
|
775
|
+
|
|
776
|
+
def gen_rand_real3(self) -> float:
|
|
777
|
+
"""Return the next double in (0, 1) (``GenRandReal3``).
|
|
778
|
+
|
|
779
|
+
Returns
|
|
780
|
+
-------
|
|
781
|
+
float
|
|
782
|
+
The draw.
|
|
783
|
+
"""
|
|
784
|
+
return float(self.net.GenRandReal3())
|
|
785
|
+
|
|
786
|
+
def gen_rand_res53(self) -> float:
|
|
787
|
+
"""Return the next double in [0, 1) with 53-bit resolution (``GenRandRes53``).
|
|
788
|
+
|
|
789
|
+
Returns
|
|
790
|
+
-------
|
|
791
|
+
float
|
|
792
|
+
The draw.
|
|
793
|
+
"""
|
|
794
|
+
return float(self.net.GenRandRes53())
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
class SobolSequence:
|
|
798
|
+
"""The Sobol low-discrepancy sequence (``Numerics.Sampling.SobolSequence``).
|
|
799
|
+
|
|
800
|
+
Parameters
|
|
801
|
+
----------
|
|
802
|
+
dimension : int, optional
|
|
803
|
+
Space dimension; default 1.
|
|
804
|
+
seed : int, optional
|
|
805
|
+
Seed of the linear matrix scramble and digital shift; default None, the original
|
|
806
|
+
unrandomized sequence.
|
|
807
|
+
|
|
808
|
+
Attributes
|
|
809
|
+
----------
|
|
810
|
+
net : Numerics.Sampling.SobolSequence
|
|
811
|
+
The wrapped .NET sequence.
|
|
812
|
+
"""
|
|
813
|
+
|
|
814
|
+
def __init__(self, dimension: int = 1, seed: int | None = None) -> None:
|
|
815
|
+
s = _sampling()
|
|
816
|
+
self.net = s.SobolSequence(int(dimension)) if seed is None else s.SobolSequence(int(dimension), int(seed))
|
|
817
|
+
|
|
818
|
+
@property
|
|
819
|
+
def dimension(self) -> int:
|
|
820
|
+
"""The space dimension (``Dimension``)."""
|
|
821
|
+
return int(self.net.Dimension)
|
|
822
|
+
|
|
823
|
+
@property
|
|
824
|
+
def seed(self) -> int | None:
|
|
825
|
+
"""The scramble seed, or None for the unrandomized sequence (``Seed``)."""
|
|
826
|
+
value = self.net.Seed
|
|
827
|
+
return None if value is None else int(value)
|
|
828
|
+
|
|
829
|
+
def next_double(self) -> np.ndarray:
|
|
830
|
+
"""Return the next point of the sequence (``NextDouble``).
|
|
831
|
+
|
|
832
|
+
Returns
|
|
833
|
+
-------
|
|
834
|
+
numpy.ndarray
|
|
835
|
+
A point in [0, 1)^dimension.
|
|
836
|
+
"""
|
|
837
|
+
return to_numpy_doubles(self.net.NextDouble())
|
|
838
|
+
|
|
839
|
+
def next_doubles(self, length: int) -> np.ndarray:
|
|
840
|
+
"""Return the next points, one ``NextDouble`` each.
|
|
841
|
+
|
|
842
|
+
Parameters
|
|
843
|
+
----------
|
|
844
|
+
length : int
|
|
845
|
+
Number of points.
|
|
846
|
+
|
|
847
|
+
Returns
|
|
848
|
+
-------
|
|
849
|
+
numpy.ndarray
|
|
850
|
+
Array of shape ``(length, dimension)``.
|
|
851
|
+
"""
|
|
852
|
+
out = np.empty((int(length), self.dimension), dtype=np.float64)
|
|
853
|
+
for row in range(int(length)):
|
|
854
|
+
out[row] = to_numpy_doubles(self.net.NextDouble())
|
|
855
|
+
return out
|
|
856
|
+
|
|
857
|
+
def skip_to(self, index: int) -> np.ndarray:
|
|
858
|
+
"""Move to a position of the sequence and return the point there (``SkipTo``).
|
|
859
|
+
|
|
860
|
+
Indices count the origin as point 0, which Numerics never returns: ``skip_to(i)`` gives
|
|
861
|
+
point ``i`` of ``scipy.stats.qmc.Sobol(d, scramble=False)`` for ``i >= 1``, ``skip_to(0)``
|
|
862
|
+
gives point 1, and :meth:`next_double` continues from there.
|
|
863
|
+
|
|
864
|
+
Parameters
|
|
865
|
+
----------
|
|
866
|
+
index : int
|
|
867
|
+
Position in the sequence.
|
|
868
|
+
|
|
869
|
+
Returns
|
|
870
|
+
-------
|
|
871
|
+
numpy.ndarray
|
|
872
|
+
The point at ``index``.
|
|
873
|
+
"""
|
|
874
|
+
return to_numpy_doubles(self.net.SkipTo(int(index)))
|
|
875
|
+
|
|
876
|
+
|
|
877
|
+
class BootstrapCIMethod(NetEnum):
|
|
878
|
+
"""Bootstrap confidence interval methods (``Numerics.Sampling.BootstrapCIMethod``)."""
|
|
879
|
+
|
|
880
|
+
PERCENTILE = "Percentile"
|
|
881
|
+
BIAS_CORRECTED = "BiasCorrected"
|
|
882
|
+
BCA = "BCa"
|
|
883
|
+
NORMAL = "Normal"
|
|
884
|
+
BOOTSTRAP_T = "BootstrapT"
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
class PivotalBootstrapInvalidDrawPolicy(NetEnum):
|
|
888
|
+
"""Handling of invalid pivotal draws (``Numerics.Sampling.PivotalBootstrapInvalidDrawPolicy``)."""
|
|
889
|
+
|
|
890
|
+
DROP = "Drop"
|
|
891
|
+
USE_RAW = "UseRaw"
|
|
892
|
+
USE_PARENT = "UseParent"
|
|
893
|
+
|
|
894
|
+
|
|
895
|
+
def _parameter_set(values: Any, fitness: float = float("nan")) -> Any:
|
|
896
|
+
"""Build a .NET ``ParameterSet`` from values, or pass a .NET one through."""
|
|
897
|
+
ps = namespace("Numerics.Mathematics.Optimization").ParameterSet
|
|
898
|
+
if isinstance(values, ps):
|
|
899
|
+
return values
|
|
900
|
+
return ps(to_net_doubles(np.ravel(np.asarray(values, dtype=np.float64))), float(fitness))
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
class BootstrapFit:
|
|
904
|
+
"""A fitted parameter set with its covariance (``Numerics.Sampling.BootstrapFit``).
|
|
905
|
+
|
|
906
|
+
Parameters
|
|
907
|
+
----------
|
|
908
|
+
parameters : array_like or Numerics.Sampling.BootstrapFit
|
|
909
|
+
The fitted parameters, or a .NET fit to wrap.
|
|
910
|
+
covariance : array_like, optional
|
|
911
|
+
The parameter covariance, shape ``(p, p)``; required unless wrapping.
|
|
912
|
+
|
|
913
|
+
Attributes
|
|
914
|
+
----------
|
|
915
|
+
net : Numerics.Sampling.BootstrapFit
|
|
916
|
+
The wrapped .NET object.
|
|
917
|
+
"""
|
|
918
|
+
|
|
919
|
+
def __init__(self, parameters: Any, covariance: Any = None) -> None:
|
|
920
|
+
s = _sampling()
|
|
921
|
+
if isinstance(parameters, s.BootstrapFit):
|
|
922
|
+
self.net = parameters
|
|
923
|
+
return
|
|
924
|
+
if covariance is None:
|
|
925
|
+
raise ValueError("BootstrapFit needs a covariance matrix.")
|
|
926
|
+
matrix = _numerics_matrix(np.atleast_2d(np.asarray(covariance, dtype=np.float64)))
|
|
927
|
+
values = np.ravel(np.asarray(parameters, dtype=np.float64))
|
|
928
|
+
self.net = s.BootstrapFit(to_net_doubles(values), matrix)
|
|
929
|
+
|
|
930
|
+
def __repr__(self) -> str:
|
|
931
|
+
return f"BootstrapFit(parameters={self.parameters!r})"
|
|
932
|
+
|
|
933
|
+
@property
|
|
934
|
+
def parameters(self) -> np.ndarray:
|
|
935
|
+
"""The fitted parameter values (``Parameters.Values``)."""
|
|
936
|
+
return to_numpy_doubles(self.net.Parameters.Values)
|
|
937
|
+
|
|
938
|
+
@property
|
|
939
|
+
def covariance(self) -> np.ndarray:
|
|
940
|
+
"""The parameter covariance (``Covariance``)."""
|
|
941
|
+
return to_numpy_matrix(self.net.Covariance.ToArray())
|
|
942
|
+
|
|
943
|
+
@property
|
|
944
|
+
def parameter_count(self) -> int:
|
|
945
|
+
"""The number of parameters (``ParameterCount``)."""
|
|
946
|
+
return int(self.net.ParameterCount)
|
|
947
|
+
|
|
948
|
+
|
|
949
|
+
class PivotalBootstrapContext:
|
|
950
|
+
"""The parent fit and raw fits a pivotal link factory sees (``Numerics.Sampling.PivotalBootstrapContext``).
|
|
951
|
+
|
|
952
|
+
Parameters
|
|
953
|
+
----------
|
|
954
|
+
parent_fit : BootstrapFit or Numerics.Sampling.PivotalBootstrapContext
|
|
955
|
+
The parent fit, or a .NET context to wrap.
|
|
956
|
+
raw_bootstrap_fits : sequence of BootstrapFit, optional
|
|
957
|
+
The accepted raw bootstrap fits; required unless wrapping.
|
|
958
|
+
|
|
959
|
+
Attributes
|
|
960
|
+
----------
|
|
961
|
+
net : Numerics.Sampling.PivotalBootstrapContext
|
|
962
|
+
The wrapped .NET object.
|
|
963
|
+
"""
|
|
964
|
+
|
|
965
|
+
def __init__(self, parent_fit: Any, raw_bootstrap_fits: Sequence[BootstrapFit] | None = None) -> None:
|
|
966
|
+
s = _sampling()
|
|
967
|
+
if isinstance(parent_fit, s.PivotalBootstrapContext):
|
|
968
|
+
self.net = parent_fit
|
|
969
|
+
return
|
|
970
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
971
|
+
|
|
972
|
+
fits = System.Array[s.BootstrapFit]([f.net for f in (raw_bootstrap_fits or ())])
|
|
973
|
+
self.net = s.PivotalBootstrapContext(parent_fit.net, fits)
|
|
974
|
+
|
|
975
|
+
@property
|
|
976
|
+
def parent_fit(self) -> BootstrapFit:
|
|
977
|
+
"""The parent fit (``ParentFit``)."""
|
|
978
|
+
return BootstrapFit(self.net.ParentFit)
|
|
979
|
+
|
|
980
|
+
@property
|
|
981
|
+
def raw_bootstrap_fits(self) -> list[BootstrapFit]:
|
|
982
|
+
"""The accepted raw bootstrap fits (``RawBootstrapFits``)."""
|
|
983
|
+
return [BootstrapFit(f) for f in self.net.RawBootstrapFits]
|
|
984
|
+
|
|
985
|
+
@property
|
|
986
|
+
def parameter_count(self) -> int:
|
|
987
|
+
"""The number of parameters (``ParameterCount``)."""
|
|
988
|
+
return int(self.net.ParameterCount)
|
|
989
|
+
|
|
990
|
+
def get_raw_parameter_values(self, parameter_index: int) -> np.ndarray:
|
|
991
|
+
"""Return one parameter across the raw fits (``GetRawParameterValues``).
|
|
992
|
+
|
|
993
|
+
Parameters
|
|
994
|
+
----------
|
|
995
|
+
parameter_index : int
|
|
996
|
+
Zero-based parameter index.
|
|
997
|
+
|
|
998
|
+
Returns
|
|
999
|
+
-------
|
|
1000
|
+
numpy.ndarray
|
|
1001
|
+
The values, one per raw fit.
|
|
1002
|
+
"""
|
|
1003
|
+
return to_numpy_doubles(self.net.GetRawParameterValues(int(parameter_index)))
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
class PivotalBootstrapDiagnostics:
|
|
1007
|
+
"""Counts and timings of a pivotal bootstrap run (``Numerics.Sampling.PivotalBootstrapDiagnostics``).
|
|
1008
|
+
|
|
1009
|
+
Parameters
|
|
1010
|
+
----------
|
|
1011
|
+
net : Numerics.Sampling.PivotalBootstrapDiagnostics, optional
|
|
1012
|
+
The .NET object to wrap; default a new empty one.
|
|
1013
|
+
|
|
1014
|
+
Attributes
|
|
1015
|
+
----------
|
|
1016
|
+
net : Numerics.Sampling.PivotalBootstrapDiagnostics
|
|
1017
|
+
The wrapped .NET object.
|
|
1018
|
+
"""
|
|
1019
|
+
|
|
1020
|
+
def __init__(self, net: Any = None) -> None:
|
|
1021
|
+
self.net = _sampling().PivotalBootstrapDiagnostics() if net is None else net
|
|
1022
|
+
|
|
1023
|
+
@property
|
|
1024
|
+
def requested_replicates(self) -> int:
|
|
1025
|
+
"""Replicates requested (``RequestedReplicates``)."""
|
|
1026
|
+
return int(self.net.RequestedReplicates)
|
|
1027
|
+
|
|
1028
|
+
@property
|
|
1029
|
+
def rejected_raw_replicates(self) -> int:
|
|
1030
|
+
"""Raw fits rejected by the filter (``RejectedRawReplicates``)."""
|
|
1031
|
+
return int(self.net.RejectedRawReplicates)
|
|
1032
|
+
|
|
1033
|
+
@property
|
|
1034
|
+
def failed_raw_replicates(self) -> int:
|
|
1035
|
+
"""Raw fits that failed (``FailedRawReplicates``)."""
|
|
1036
|
+
return int(self.net.FailedRawReplicates)
|
|
1037
|
+
|
|
1038
|
+
@property
|
|
1039
|
+
def accepted_raw_replicates(self) -> int:
|
|
1040
|
+
"""Raw fits accepted (``AcceptedRawReplicates``)."""
|
|
1041
|
+
return int(self.net.AcceptedRawReplicates)
|
|
1042
|
+
|
|
1043
|
+
@property
|
|
1044
|
+
def invalid_pivotal_replicates(self) -> int:
|
|
1045
|
+
"""Pivotal draws found invalid (``InvalidPivotalReplicates``)."""
|
|
1046
|
+
return int(self.net.InvalidPivotalReplicates)
|
|
1047
|
+
|
|
1048
|
+
@property
|
|
1049
|
+
def retained_pivotal_replicates(self) -> int:
|
|
1050
|
+
"""Pivotal draws retained (``RetainedPivotalReplicates``)."""
|
|
1051
|
+
return int(self.net.RetainedPivotalReplicates)
|
|
1052
|
+
|
|
1053
|
+
@property
|
|
1054
|
+
def resampling_time(self) -> float:
|
|
1055
|
+
"""Seconds spent resampling and fitting (``ResamplingTime``)."""
|
|
1056
|
+
return float(self.net.ResamplingTime.TotalSeconds)
|
|
1057
|
+
|
|
1058
|
+
@property
|
|
1059
|
+
def transformation_time(self) -> float:
|
|
1060
|
+
"""Seconds spent on the pivotal transformation (``TransformationTime``)."""
|
|
1061
|
+
return float(self.net.TransformationTime.TotalSeconds)
|
|
1062
|
+
|
|
1063
|
+
|
|
1064
|
+
class BootstrapStatisticResult:
|
|
1065
|
+
"""The interval of one statistic or parameter (``Numerics.Sampling.BootstrapStatisticResult``).
|
|
1066
|
+
|
|
1067
|
+
Parameters
|
|
1068
|
+
----------
|
|
1069
|
+
net : Numerics.Sampling.BootstrapStatisticResult, optional
|
|
1070
|
+
The .NET object to wrap; default a new empty one.
|
|
1071
|
+
|
|
1072
|
+
Attributes
|
|
1073
|
+
----------
|
|
1074
|
+
net : Numerics.Sampling.BootstrapStatisticResult
|
|
1075
|
+
The wrapped .NET object.
|
|
1076
|
+
"""
|
|
1077
|
+
|
|
1078
|
+
def __init__(self, net: Any = None) -> None:
|
|
1079
|
+
self.net = _sampling().BootstrapStatisticResult() if net is None else net
|
|
1080
|
+
|
|
1081
|
+
def __repr__(self) -> str:
|
|
1082
|
+
return (f"BootstrapStatisticResult(estimate={self.population_estimate!r}, lower_ci={self.lower_ci!r}, "
|
|
1083
|
+
f"upper_ci={self.upper_ci!r}, standard_error={self.standard_error!r})")
|
|
1084
|
+
|
|
1085
|
+
@property
|
|
1086
|
+
def population_estimate(self) -> float:
|
|
1087
|
+
"""The estimate from the original data (``PopulationEstimate``)."""
|
|
1088
|
+
return float(self.net.PopulationEstimate)
|
|
1089
|
+
|
|
1090
|
+
@property
|
|
1091
|
+
def lower_ci(self) -> float:
|
|
1092
|
+
"""Lower confidence bound (``LowerCI``)."""
|
|
1093
|
+
return float(self.net.LowerCI)
|
|
1094
|
+
|
|
1095
|
+
@property
|
|
1096
|
+
def upper_ci(self) -> float:
|
|
1097
|
+
"""Upper confidence bound (``UpperCI``)."""
|
|
1098
|
+
return float(self.net.UpperCI)
|
|
1099
|
+
|
|
1100
|
+
@property
|
|
1101
|
+
def valid_count(self) -> int:
|
|
1102
|
+
"""Replicates with a finite value (``ValidCount``)."""
|
|
1103
|
+
return int(self.net.ValidCount)
|
|
1104
|
+
|
|
1105
|
+
@property
|
|
1106
|
+
def total_count(self) -> int:
|
|
1107
|
+
"""Replicates requested (``TotalCount``)."""
|
|
1108
|
+
return int(self.net.TotalCount)
|
|
1109
|
+
|
|
1110
|
+
@property
|
|
1111
|
+
def standard_error(self) -> float:
|
|
1112
|
+
"""Bootstrap standard error (``StandardError``)."""
|
|
1113
|
+
return float(self.net.StandardError)
|
|
1114
|
+
|
|
1115
|
+
@property
|
|
1116
|
+
def mean(self) -> float:
|
|
1117
|
+
"""Mean of the bootstrap replicates (``Mean``)."""
|
|
1118
|
+
return float(self.net.Mean)
|
|
1119
|
+
|
|
1120
|
+
|
|
1121
|
+
class BootstrapResults:
|
|
1122
|
+
"""Confidence intervals of a bootstrap run (``Numerics.Sampling.BootstrapResults``).
|
|
1123
|
+
|
|
1124
|
+
Parameters
|
|
1125
|
+
----------
|
|
1126
|
+
net : Numerics.Sampling.BootstrapResults, optional
|
|
1127
|
+
The .NET object to wrap; default a new empty one.
|
|
1128
|
+
|
|
1129
|
+
Attributes
|
|
1130
|
+
----------
|
|
1131
|
+
net : Numerics.Sampling.BootstrapResults
|
|
1132
|
+
The wrapped .NET object.
|
|
1133
|
+
"""
|
|
1134
|
+
|
|
1135
|
+
def __init__(self, net: Any = None) -> None:
|
|
1136
|
+
self.net = _sampling().BootstrapResults() if net is None else net
|
|
1137
|
+
|
|
1138
|
+
@property
|
|
1139
|
+
def method(self) -> BootstrapCIMethod:
|
|
1140
|
+
"""The interval method (``Method``)."""
|
|
1141
|
+
return BootstrapCIMethod(str(self.net.Method))
|
|
1142
|
+
|
|
1143
|
+
@property
|
|
1144
|
+
def alpha(self) -> float:
|
|
1145
|
+
"""The two-sided level (``Alpha``)."""
|
|
1146
|
+
return float(self.net.Alpha)
|
|
1147
|
+
|
|
1148
|
+
@property
|
|
1149
|
+
def statistic_results(self) -> list[BootstrapStatisticResult]:
|
|
1150
|
+
"""The interval of each statistic by the requested method (``StatisticResults``)."""
|
|
1151
|
+
return [BootstrapStatisticResult(r) for r in self.net.StatisticResults]
|
|
1152
|
+
|
|
1153
|
+
@property
|
|
1154
|
+
def parameter_results(self) -> list[BootstrapStatisticResult]:
|
|
1155
|
+
"""The percentile interval of each parameter, whatever the method (``ParameterResults``)."""
|
|
1156
|
+
return [BootstrapStatisticResult(r) for r in self.net.ParameterResults]
|
|
1157
|
+
|
|
1158
|
+
@property
|
|
1159
|
+
def failed_replicates(self) -> int:
|
|
1160
|
+
"""Replicates that failed after every retry (``FailedReplicates``)."""
|
|
1161
|
+
return int(self.net.FailedReplicates)
|
|
1162
|
+
|
|
1163
|
+
|
|
1164
|
+
_PROGRESS: list[Any] = []
|
|
1165
|
+
|
|
1166
|
+
|
|
1167
|
+
def _progress_type() -> Any:
|
|
1168
|
+
"""Return a .NET ``IProgress<int>`` implementation that forwards ``Report`` to a Python callable, built once."""
|
|
1169
|
+
if not _PROGRESS:
|
|
1170
|
+
_sampling()
|
|
1171
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1172
|
+
|
|
1173
|
+
class CallableProgress(System.IProgress[System.Int32]):
|
|
1174
|
+
__namespace__ = "Pynumerics.Sampling"
|
|
1175
|
+
|
|
1176
|
+
def __init__(self, fn: Any) -> None:
|
|
1177
|
+
self.fn = fn
|
|
1178
|
+
|
|
1179
|
+
def Report(self, value: Any) -> None: # noqa: N802 - the .NET interface member
|
|
1180
|
+
self.fn(int(value))
|
|
1181
|
+
|
|
1182
|
+
_PROGRESS.append(CallableProgress)
|
|
1183
|
+
return _PROGRESS[0]
|
|
1184
|
+
|
|
1185
|
+
|
|
1186
|
+
def _is_python(fn: Any) -> bool:
|
|
1187
|
+
"""Return whether ``fn`` is a Python callable (not C# source or a .NET delegate)."""
|
|
1188
|
+
return not isinstance(fn, str) and callbacks.uses_python_callback(fn) and not _is_net_delegate(fn)
|
|
1189
|
+
|
|
1190
|
+
|
|
1191
|
+
def _is_net_delegate(fn: Any) -> bool:
|
|
1192
|
+
"""Return whether ``fn`` is a .NET delegate."""
|
|
1193
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1194
|
+
|
|
1195
|
+
return isinstance(fn, System.Delegate)
|
|
1196
|
+
|
|
1197
|
+
|
|
1198
|
+
class Bootstrap:
|
|
1199
|
+
"""The general bootstrap (``Numerics.Sampling.Bootstrap<TData>``).
|
|
1200
|
+
|
|
1201
|
+
The analysis is defined by functions: ``resample`` draws a data set, ``fit`` fits the model
|
|
1202
|
+
and ``statistic`` derives the quantities of interest, replicated ``replicates`` times. Each
|
|
1203
|
+
function is a Python callable, C# source compiled with Roslyn or a .NET delegate of the
|
|
1204
|
+
``Func`` type named below. Python callables see NumPy arrays: a ``ParameterSet`` argument
|
|
1205
|
+
arrives as its values, and ``fit`` may return parameter values (built into a ``ParameterSet``
|
|
1206
|
+
with NaN fitness). C# source and delegates use the .NET types directly.
|
|
1207
|
+
|
|
1208
|
+
Runs are reproducible: replicate i draws from its own Mersenne Twister seeded from ``seed``
|
|
1209
|
+
(``PRNGSeed``), whatever the thread order. Numerics runs the replicates with ``Parallel.For``
|
|
1210
|
+
while :attr:`use_parallel` is True. A Python callable sets it to False (the callback policy of
|
|
1211
|
+
:mod:`pynumerics.callbacks`), so the replicates run in order on the calling thread with the same
|
|
1212
|
+
bits; C# source and .NET delegates keep the replicates parallel. The leave-one-out jackknife of
|
|
1213
|
+
the BCa intervals follows :attr:`use_parallel` too, with the same bits either way. An exception
|
|
1214
|
+
in a function fails the attempt, which is retried up to ``max_retries`` times (see
|
|
1215
|
+
:attr:`failed_attempts`).
|
|
1216
|
+
|
|
1217
|
+
Parameters
|
|
1218
|
+
----------
|
|
1219
|
+
data : array_like or .NET object
|
|
1220
|
+
The original data. A NumPy-convertible 1-D array makes ``TData`` ``double[]``; a .NET
|
|
1221
|
+
object makes ``TData`` its type (or ``data_type``).
|
|
1222
|
+
original_parameters : array_like or BootstrapFit
|
|
1223
|
+
The fit to the original data, or a :class:`BootstrapFit` with covariance for the pivotal
|
|
1224
|
+
bootstrap.
|
|
1225
|
+
resample : callable, str or System.Delegate, optional
|
|
1226
|
+
``Func<TData, ParameterSet, Random, TData>``: ``resample(data, parameters, prng)``.
|
|
1227
|
+
fit : callable, str or System.Delegate, optional
|
|
1228
|
+
``Func<TData, ParameterSet>``: ``fit(data)``.
|
|
1229
|
+
statistic : callable, str or System.Delegate, optional
|
|
1230
|
+
``Func<ParameterSet, double[]>``: ``statistic(parameters)``.
|
|
1231
|
+
fit_with_covariance : callable, str or System.Delegate, optional
|
|
1232
|
+
``Func<TData, BootstrapFit>`` for the pivotal bootstrap; a Python callable returns a
|
|
1233
|
+
:class:`BootstrapFit` or ``(parameters, covariance)``.
|
|
1234
|
+
jackknife : callable, str or System.Delegate, optional
|
|
1235
|
+
``Func<TData, int, TData>``: the data without observation i (for BCa).
|
|
1236
|
+
sample_size : callable, str or System.Delegate, optional
|
|
1237
|
+
``Func<TData, int>``: the number of observations (for BCa).
|
|
1238
|
+
replicates : int, optional
|
|
1239
|
+
Number of replicates; default 10000.
|
|
1240
|
+
seed : int, optional
|
|
1241
|
+
``PRNGSeed``; default 12345.
|
|
1242
|
+
data_type : type, optional
|
|
1243
|
+
The .NET type ``TData`` for .NET data.
|
|
1244
|
+
|
|
1245
|
+
Attributes
|
|
1246
|
+
----------
|
|
1247
|
+
net : Numerics.Sampling.Bootstrap
|
|
1248
|
+
The wrapped .NET bootstrap.
|
|
1249
|
+
"""
|
|
1250
|
+
|
|
1251
|
+
def __init__(self, data: Any, original_parameters: Any, *, resample: Any = None, fit: Any = None,
|
|
1252
|
+
statistic: Any = None, fit_with_covariance: Any = None, jackknife: Any = None,
|
|
1253
|
+
sample_size: Any = None, replicates: int | None = None, seed: int | None = None,
|
|
1254
|
+
data_type: Any = None) -> None:
|
|
1255
|
+
s = _sampling()
|
|
1256
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1257
|
+
|
|
1258
|
+
if data_type is None and isinstance(data, System.Object) and not isinstance(data, System.Array[System.Double]):
|
|
1259
|
+
data_type = type(data)
|
|
1260
|
+
if data_type is None:
|
|
1261
|
+
self._data_type = System.Array[System.Double]
|
|
1262
|
+
net_data = data if isinstance(data, System.Array[System.Double]) else to_net_doubles(
|
|
1263
|
+
np.ravel(np.asarray(data, dtype=np.float64)))
|
|
1264
|
+
else:
|
|
1265
|
+
self._data_type, net_data = data_type, data
|
|
1266
|
+
self._is_array = self._data_type is System.Array[System.Double]
|
|
1267
|
+
boot = s.Bootstrap[self._data_type]
|
|
1268
|
+
if isinstance(original_parameters, BootstrapFit):
|
|
1269
|
+
self.net = boot(net_data, original_parameters.net)
|
|
1270
|
+
else:
|
|
1271
|
+
self.net = boot(net_data, _parameter_set(original_parameters))
|
|
1272
|
+
for name, value in (("resample_function", resample), ("fit_function", fit), ("statistic_function", statistic),
|
|
1273
|
+
("fit_with_covariance_function", fit_with_covariance),
|
|
1274
|
+
("jackknife_function", jackknife), ("sample_size_function", sample_size)):
|
|
1275
|
+
if value is not None:
|
|
1276
|
+
setattr(self, name, value)
|
|
1277
|
+
if replicates is not None:
|
|
1278
|
+
self.replicates = replicates
|
|
1279
|
+
if seed is not None:
|
|
1280
|
+
self.seed = seed
|
|
1281
|
+
|
|
1282
|
+
def _data_in(self, value: Any) -> Any:
|
|
1283
|
+
"""Return a data argument as Python sees it."""
|
|
1284
|
+
return to_numpy_doubles(value) if self._is_array else value
|
|
1285
|
+
|
|
1286
|
+
def _data_out(self, value: Any) -> Any:
|
|
1287
|
+
"""Return a Python data result as .NET ``TData``."""
|
|
1288
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1289
|
+
|
|
1290
|
+
if self._is_array and not isinstance(value, System.Array[System.Double]):
|
|
1291
|
+
return to_net_doubles(np.ravel(np.asarray(value, dtype=np.float64)))
|
|
1292
|
+
return value
|
|
1293
|
+
|
|
1294
|
+
def _func(self, *types: Any) -> Any:
|
|
1295
|
+
"""Return the ``System.Func`` delegate type of the given argument and result types."""
|
|
1296
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1297
|
+
|
|
1298
|
+
return System.Func[types]
|
|
1299
|
+
|
|
1300
|
+
def _types(self) -> tuple[Any, Any, Any, Any]:
|
|
1301
|
+
"""Return ``TData``, ``ParameterSet``, ``BootstrapFit`` and ``System.Random``."""
|
|
1302
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1303
|
+
|
|
1304
|
+
ps = namespace("Numerics.Mathematics.Optimization").ParameterSet
|
|
1305
|
+
return self._data_type, ps, _sampling().BootstrapFit, System.Random
|
|
1306
|
+
|
|
1307
|
+
def _set(self, prop: str, fn: Any, dtype: Any, adapter: Any) -> None:
|
|
1308
|
+
"""Set a delegate property from a Python callable (through ``adapter``), C# source or delegate."""
|
|
1309
|
+
if fn is None:
|
|
1310
|
+
setattr(self.net, prop, None)
|
|
1311
|
+
return
|
|
1312
|
+
setattr(self.net, prop, dtype(adapter(fn)) if _is_python(fn) else callbacks.to_delegate(fn, dtype))
|
|
1313
|
+
callbacks.apply_parallel_policy(self.net, fn)
|
|
1314
|
+
|
|
1315
|
+
@property
|
|
1316
|
+
def resample_function(self) -> Any:
|
|
1317
|
+
"""``resample(data, parameters, prng) -> data`` (``ResampleFunction``)."""
|
|
1318
|
+
return self.net.ResampleFunction
|
|
1319
|
+
|
|
1320
|
+
@resample_function.setter
|
|
1321
|
+
def resample_function(self, fn: Any) -> None:
|
|
1322
|
+
data, ps, _, rnd = self._types()
|
|
1323
|
+
self._set("ResampleFunction", fn, self._func(data, ps, rnd, data),
|
|
1324
|
+
lambda f: lambda d, p, r: self._data_out(f(self._data_in(d), to_numpy_doubles(p.Values), r)))
|
|
1325
|
+
|
|
1326
|
+
@property
|
|
1327
|
+
def fit_function(self) -> Any:
|
|
1328
|
+
"""``fit(data) -> parameters`` (``FitFunction``)."""
|
|
1329
|
+
return self.net.FitFunction
|
|
1330
|
+
|
|
1331
|
+
@fit_function.setter
|
|
1332
|
+
def fit_function(self, fn: Any) -> None:
|
|
1333
|
+
data, ps, _, _ = self._types()
|
|
1334
|
+
self._set("FitFunction", fn, self._func(data, ps), lambda f: lambda d: _parameter_set(f(self._data_in(d))))
|
|
1335
|
+
|
|
1336
|
+
@property
|
|
1337
|
+
def fit_with_covariance_function(self) -> Any:
|
|
1338
|
+
"""``fit_with_covariance(data) -> BootstrapFit`` (``FitWithCovarianceFunction``)."""
|
|
1339
|
+
return self.net.FitWithCovarianceFunction
|
|
1340
|
+
|
|
1341
|
+
@fit_with_covariance_function.setter
|
|
1342
|
+
def fit_with_covariance_function(self, fn: Any) -> None:
|
|
1343
|
+
data, _, bf, _ = self._types()
|
|
1344
|
+
|
|
1345
|
+
def adapt(f: Any) -> Any:
|
|
1346
|
+
def call(d: Any) -> Any:
|
|
1347
|
+
value = f(self._data_in(d))
|
|
1348
|
+
return value.net if isinstance(value, BootstrapFit) else BootstrapFit(*value).net
|
|
1349
|
+
return call
|
|
1350
|
+
|
|
1351
|
+
self._set("FitWithCovarianceFunction", fn, self._func(data, bf), adapt)
|
|
1352
|
+
|
|
1353
|
+
@property
|
|
1354
|
+
def statistic_function(self) -> Any:
|
|
1355
|
+
"""``statistic(parameters) -> values`` (``StatisticFunction``)."""
|
|
1356
|
+
return self.net.StatisticFunction
|
|
1357
|
+
|
|
1358
|
+
@statistic_function.setter
|
|
1359
|
+
def statistic_function(self, fn: Any) -> None:
|
|
1360
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1361
|
+
|
|
1362
|
+
_, ps, _, _ = self._types()
|
|
1363
|
+
self._set("StatisticFunction", fn, self._func(ps, System.Array[System.Double]),
|
|
1364
|
+
lambda f: lambda p: to_net_doubles(np.ravel(np.asarray(f(to_numpy_doubles(p.Values)),
|
|
1365
|
+
dtype=np.float64))))
|
|
1366
|
+
|
|
1367
|
+
@property
|
|
1368
|
+
def jackknife_function(self) -> Any:
|
|
1369
|
+
"""``jackknife(data, index) -> data`` without observation ``index`` (``JackknifeFunction``)."""
|
|
1370
|
+
return self.net.JackknifeFunction
|
|
1371
|
+
|
|
1372
|
+
@jackknife_function.setter
|
|
1373
|
+
def jackknife_function(self, fn: Any) -> None:
|
|
1374
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1375
|
+
|
|
1376
|
+
data = self._data_type
|
|
1377
|
+
self._set("JackknifeFunction", fn, self._func(data, System.Int32, data),
|
|
1378
|
+
lambda f: lambda d, i: self._data_out(f(self._data_in(d), int(i))))
|
|
1379
|
+
|
|
1380
|
+
@property
|
|
1381
|
+
def sample_size_function(self) -> Any:
|
|
1382
|
+
"""``sample_size(data) -> int`` (``SampleSizeFunction``)."""
|
|
1383
|
+
return self.net.SampleSizeFunction
|
|
1384
|
+
|
|
1385
|
+
@sample_size_function.setter
|
|
1386
|
+
def sample_size_function(self, fn: Any) -> None:
|
|
1387
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1388
|
+
|
|
1389
|
+
self._set("SampleSizeFunction", fn, self._func(self._data_type, System.Int32),
|
|
1390
|
+
lambda f: lambda d: int(f(self._data_in(d))))
|
|
1391
|
+
|
|
1392
|
+
@property
|
|
1393
|
+
def transform(self) -> Any:
|
|
1394
|
+
"""Transform applied before the Normal and Bootstrap-t intervals (``Transform``); default cube root."""
|
|
1395
|
+
return self.net.Transform
|
|
1396
|
+
|
|
1397
|
+
@transform.setter
|
|
1398
|
+
def transform(self, fn: Any) -> None:
|
|
1399
|
+
self.net.Transform = callbacks.scalar_function(fn)
|
|
1400
|
+
|
|
1401
|
+
@property
|
|
1402
|
+
def inverse_transform(self) -> Any:
|
|
1403
|
+
"""Inverse of :attr:`transform` (``InverseTransform``); default cube."""
|
|
1404
|
+
return self.net.InverseTransform
|
|
1405
|
+
|
|
1406
|
+
@inverse_transform.setter
|
|
1407
|
+
def inverse_transform(self, fn: Any) -> None:
|
|
1408
|
+
self.net.InverseTransform = callbacks.scalar_function(fn)
|
|
1409
|
+
|
|
1410
|
+
@property
|
|
1411
|
+
def pivotal_link_factory(self) -> Any:
|
|
1412
|
+
"""``factory(context) -> links``, one ``ILinkFunction`` or None per parameter (``PivotalLinkFactory``)."""
|
|
1413
|
+
return self.net.PivotalLinkFactory
|
|
1414
|
+
|
|
1415
|
+
@pivotal_link_factory.setter
|
|
1416
|
+
def pivotal_link_factory(self, fn: Any) -> None:
|
|
1417
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1418
|
+
|
|
1419
|
+
link = namespace("Numerics.Functions").ILinkFunction
|
|
1420
|
+
s = _sampling()
|
|
1421
|
+
|
|
1422
|
+
def adapt(f: Any) -> Any:
|
|
1423
|
+
return lambda context: System.Array[link](list(f(PivotalBootstrapContext(context))))
|
|
1424
|
+
|
|
1425
|
+
self._set("PivotalLinkFactory", fn, self._func(s.PivotalBootstrapContext, System.Array[link]), adapt)
|
|
1426
|
+
|
|
1427
|
+
@property
|
|
1428
|
+
def pivotal_replicate_filter(self) -> Any:
|
|
1429
|
+
"""``filter(fit) -> bool`` applied to valid raw fits (``PivotalReplicateFilter``)."""
|
|
1430
|
+
return self.net.PivotalReplicateFilter
|
|
1431
|
+
|
|
1432
|
+
@pivotal_replicate_filter.setter
|
|
1433
|
+
def pivotal_replicate_filter(self, fn: Any) -> None:
|
|
1434
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1435
|
+
|
|
1436
|
+
self._set("PivotalReplicateFilter", fn, self._func(_sampling().BootstrapFit, System.Boolean),
|
|
1437
|
+
lambda f: lambda fit: bool(f(BootstrapFit(fit))))
|
|
1438
|
+
|
|
1439
|
+
@property
|
|
1440
|
+
def pivotal_parameter_validator(self) -> Any:
|
|
1441
|
+
"""``validator(values) -> bool`` applied to pivotal draws (``PivotalParameterValidator``)."""
|
|
1442
|
+
return self.net.PivotalParameterValidator
|
|
1443
|
+
|
|
1444
|
+
@pivotal_parameter_validator.setter
|
|
1445
|
+
def pivotal_parameter_validator(self, fn: Any) -> None:
|
|
1446
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1447
|
+
|
|
1448
|
+
self._set("PivotalParameterValidator", fn, self._func(System.Array[System.Double], System.Boolean),
|
|
1449
|
+
lambda f: lambda v: bool(f(to_numpy_doubles(v))))
|
|
1450
|
+
|
|
1451
|
+
@property
|
|
1452
|
+
def replicates(self) -> int:
|
|
1453
|
+
"""Number of replicates (``Replicates``)."""
|
|
1454
|
+
return int(self.net.Replicates)
|
|
1455
|
+
|
|
1456
|
+
@replicates.setter
|
|
1457
|
+
def replicates(self, value: int) -> None:
|
|
1458
|
+
self.net.Replicates = int(value)
|
|
1459
|
+
|
|
1460
|
+
@property
|
|
1461
|
+
def seed(self) -> int:
|
|
1462
|
+
"""The PRNG seed (``PRNGSeed``)."""
|
|
1463
|
+
return int(self.net.PRNGSeed)
|
|
1464
|
+
|
|
1465
|
+
@seed.setter
|
|
1466
|
+
def seed(self, value: int) -> None:
|
|
1467
|
+
self.net.PRNGSeed = int(value)
|
|
1468
|
+
|
|
1469
|
+
@property
|
|
1470
|
+
def max_retries(self) -> int:
|
|
1471
|
+
"""Attempts per replicate before it counts as failed (``MaxRetries``)."""
|
|
1472
|
+
return int(self.net.MaxRetries)
|
|
1473
|
+
|
|
1474
|
+
@max_retries.setter
|
|
1475
|
+
def max_retries(self, value: int) -> None:
|
|
1476
|
+
self.net.MaxRetries = int(value)
|
|
1477
|
+
|
|
1478
|
+
@property
|
|
1479
|
+
def inner_replicates(self) -> int:
|
|
1480
|
+
"""Inner replicates of the Bootstrap-t standard errors (``InnerReplicates``)."""
|
|
1481
|
+
return int(self.net.InnerReplicates)
|
|
1482
|
+
|
|
1483
|
+
@inner_replicates.setter
|
|
1484
|
+
def inner_replicates(self, value: int) -> None:
|
|
1485
|
+
self.net.InnerReplicates = int(value)
|
|
1486
|
+
|
|
1487
|
+
@property
|
|
1488
|
+
def use_parallel(self) -> bool:
|
|
1489
|
+
"""Whether the outer replicates run on several threads (``UseParallel``).
|
|
1490
|
+
|
|
1491
|
+
Numerics defaults to True; giving a Python callable turns it off. False runs the replicates
|
|
1492
|
+
in order on the calling thread, with the same per-replicate seeds and bit-identical results.
|
|
1493
|
+
"""
|
|
1494
|
+
return bool(self.net.UseParallel)
|
|
1495
|
+
|
|
1496
|
+
@use_parallel.setter
|
|
1497
|
+
def use_parallel(self, value: bool) -> None:
|
|
1498
|
+
self.net.UseParallel = bool(value)
|
|
1499
|
+
|
|
1500
|
+
@property
|
|
1501
|
+
def progress(self) -> Any:
|
|
1502
|
+
"""The ``IProgress<int>`` receiving completed outer replicates, or None (``Progress``).
|
|
1503
|
+
|
|
1504
|
+
A Python callable ``progress(count)`` is wrapped in an ``IProgress<int>`` whose ``Report``
|
|
1505
|
+
calls it synchronously from the worker threads, as Numerics reports (counts can arrive out
|
|
1506
|
+
of order); an exception it raises fails the run.
|
|
1507
|
+
"""
|
|
1508
|
+
return self.net.Progress
|
|
1509
|
+
|
|
1510
|
+
@progress.setter
|
|
1511
|
+
def progress(self, value: Any) -> None:
|
|
1512
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1513
|
+
|
|
1514
|
+
if value is not None and callable(value) and not isinstance(value, System.Object):
|
|
1515
|
+
value = _progress_type()(value)
|
|
1516
|
+
self.net.Progress = value
|
|
1517
|
+
|
|
1518
|
+
@property
|
|
1519
|
+
def cancellation_token(self) -> Any:
|
|
1520
|
+
"""A ``System.Threading.CancellationToken`` that stops the run (``CancellationToken``)."""
|
|
1521
|
+
return self.net.CancellationToken
|
|
1522
|
+
|
|
1523
|
+
@cancellation_token.setter
|
|
1524
|
+
def cancellation_token(self, value: Any) -> None:
|
|
1525
|
+
self.net.CancellationToken = value
|
|
1526
|
+
|
|
1527
|
+
@property
|
|
1528
|
+
def original_covariance(self) -> np.ndarray | None:
|
|
1529
|
+
"""The covariance of the original fit for the pivotal bootstrap (``OriginalCovariance``)."""
|
|
1530
|
+
value = self.net.OriginalCovariance
|
|
1531
|
+
return None if value is None else to_numpy_matrix(value.ToArray())
|
|
1532
|
+
|
|
1533
|
+
@original_covariance.setter
|
|
1534
|
+
def original_covariance(self, value: Any) -> None:
|
|
1535
|
+
self.net.OriginalCovariance = None if value is None else _numerics_matrix(
|
|
1536
|
+
np.atleast_2d(np.asarray(value, dtype=np.float64)))
|
|
1537
|
+
|
|
1538
|
+
@property
|
|
1539
|
+
def pivotal_invalid_draw_policy(self) -> PivotalBootstrapInvalidDrawPolicy:
|
|
1540
|
+
"""Handling of invalid pivotal draws (``PivotalInvalidDrawPolicy``)."""
|
|
1541
|
+
return PivotalBootstrapInvalidDrawPolicy(str(self.net.PivotalInvalidDrawPolicy))
|
|
1542
|
+
|
|
1543
|
+
@pivotal_invalid_draw_policy.setter
|
|
1544
|
+
def pivotal_invalid_draw_policy(self, value: PivotalBootstrapInvalidDrawPolicy | str) -> None:
|
|
1545
|
+
self.net.PivotalInvalidDrawPolicy = net_enum(_sampling().PivotalBootstrapInvalidDrawPolicy, value)
|
|
1546
|
+
|
|
1547
|
+
@property
|
|
1548
|
+
def regularize_pivotal_covariances(self) -> bool:
|
|
1549
|
+
"""Whether pivotal covariances are regularized before Cholesky (``RegularizePivotalCovariances``)."""
|
|
1550
|
+
return bool(self.net.RegularizePivotalCovariances)
|
|
1551
|
+
|
|
1552
|
+
@regularize_pivotal_covariances.setter
|
|
1553
|
+
def regularize_pivotal_covariances(self, value: bool) -> None:
|
|
1554
|
+
self.net.RegularizePivotalCovariances = bool(value)
|
|
1555
|
+
|
|
1556
|
+
@property
|
|
1557
|
+
def pivotal_z_limit(self) -> float | None:
|
|
1558
|
+
"""Absolute limit of the standardized pivotal components, or None (``PivotalZLimit``)."""
|
|
1559
|
+
value = self.net.PivotalZLimit
|
|
1560
|
+
return None if value is None else float(value)
|
|
1561
|
+
|
|
1562
|
+
@pivotal_z_limit.setter
|
|
1563
|
+
def pivotal_z_limit(self, value: float | None) -> None:
|
|
1564
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1565
|
+
|
|
1566
|
+
self.net.PivotalZLimit = None if value is None else System.Nullable[System.Double](float(value))
|
|
1567
|
+
|
|
1568
|
+
@property
|
|
1569
|
+
def add_pivotal_jitter(self) -> bool:
|
|
1570
|
+
"""Whether Gaussian jitter is added to pivotal vectors (``AddPivotalJitter``)."""
|
|
1571
|
+
return bool(self.net.AddPivotalJitter)
|
|
1572
|
+
|
|
1573
|
+
@add_pivotal_jitter.setter
|
|
1574
|
+
def add_pivotal_jitter(self, value: bool) -> None:
|
|
1575
|
+
self.net.AddPivotalJitter = bool(value)
|
|
1576
|
+
|
|
1577
|
+
@property
|
|
1578
|
+
def pivotal_jitter_scale(self) -> float:
|
|
1579
|
+
"""Base jitter standard deviation, divided by sqrt(p) when applied (``PivotalJitterScale``)."""
|
|
1580
|
+
return float(self.net.PivotalJitterScale)
|
|
1581
|
+
|
|
1582
|
+
@pivotal_jitter_scale.setter
|
|
1583
|
+
def pivotal_jitter_scale(self, value: float) -> None:
|
|
1584
|
+
self.net.PivotalJitterScale = float(value)
|
|
1585
|
+
|
|
1586
|
+
@property
|
|
1587
|
+
def bootstrap_parameter_sets(self) -> np.ndarray:
|
|
1588
|
+
"""Replicate parameters, shape ``(replicates, parameters)`` (``BootstrapParameterSets``).
|
|
1589
|
+
|
|
1590
|
+
There are as many columns as the longest parameter set. A shorter set is padded with NaN, and a
|
|
1591
|
+
failed replicate, which Numerics fills with NaN values of the full length, reads as NaN throughout.
|
|
1592
|
+
"""
|
|
1593
|
+
return _parameter_set_arrays(self.net.BootstrapParameterSets)[0]
|
|
1594
|
+
|
|
1595
|
+
@property
|
|
1596
|
+
def bootstrap_statistics(self) -> np.ndarray:
|
|
1597
|
+
"""The replicate statistics, shape ``(replicates, statistics)`` (``BootstrapStatistics``)."""
|
|
1598
|
+
return to_numpy_matrix(self.net.BootstrapStatistics)
|
|
1599
|
+
|
|
1600
|
+
@property
|
|
1601
|
+
def raw_bootstrap_fits(self) -> list[BootstrapFit]:
|
|
1602
|
+
"""The accepted raw fits of the last pivotal run (``RawBootstrapFits``)."""
|
|
1603
|
+
return [BootstrapFit(f) for f in self.net.RawBootstrapFits]
|
|
1604
|
+
|
|
1605
|
+
@property
|
|
1606
|
+
def raw_bootstrap_parameter_sets(self) -> np.ndarray:
|
|
1607
|
+
"""The accepted raw parameters of the last pivotal run (``RawBootstrapParameterSets``).
|
|
1608
|
+
|
|
1609
|
+
There are as many columns as the longest parameter set; a shorter set is padded with NaN.
|
|
1610
|
+
"""
|
|
1611
|
+
return _parameter_set_arrays(self.net.RawBootstrapParameterSets)[0]
|
|
1612
|
+
|
|
1613
|
+
@property
|
|
1614
|
+
def raw_bootstrap_statistics(self) -> np.ndarray | None:
|
|
1615
|
+
"""The raw statistics of the last pivotal run, or None (``RawBootstrapStatistics``)."""
|
|
1616
|
+
value = self.net.RawBootstrapStatistics
|
|
1617
|
+
return None if value is None else to_numpy_matrix(value)
|
|
1618
|
+
|
|
1619
|
+
@property
|
|
1620
|
+
def pivotal_links(self) -> list[Any]:
|
|
1621
|
+
"""The link functions of the last pivotal run (``PivotalLinks``)."""
|
|
1622
|
+
return list(self.net.PivotalLinks)
|
|
1623
|
+
|
|
1624
|
+
@property
|
|
1625
|
+
def pivotal_diagnostics(self) -> PivotalBootstrapDiagnostics | None:
|
|
1626
|
+
"""Diagnostics of the last pivotal run, or None (``PivotalDiagnostics``)."""
|
|
1627
|
+
value = self.net.PivotalDiagnostics
|
|
1628
|
+
return None if value is None else PivotalBootstrapDiagnostics(value)
|
|
1629
|
+
|
|
1630
|
+
@property
|
|
1631
|
+
def failed_replicates(self) -> int:
|
|
1632
|
+
"""Replicates that failed after every retry (``FailedReplicates``)."""
|
|
1633
|
+
return int(self.net.FailedReplicates)
|
|
1634
|
+
|
|
1635
|
+
@property
|
|
1636
|
+
def failed_attempts(self) -> int:
|
|
1637
|
+
"""Attempts that raised in the last run (``FailedAttempts``)."""
|
|
1638
|
+
return int(self.net.FailedAttempts)
|
|
1639
|
+
|
|
1640
|
+
@property
|
|
1641
|
+
def failed_jackknife_replicates(self) -> int:
|
|
1642
|
+
"""Leave-one-out replicates that failed in the last BCa request (``FailedJackknifeReplicates``)."""
|
|
1643
|
+
return int(self.net.FailedJackknifeReplicates)
|
|
1644
|
+
|
|
1645
|
+
def run(self) -> Bootstrap:
|
|
1646
|
+
"""Run the regular bootstrap (``Run``).
|
|
1647
|
+
|
|
1648
|
+
Returns
|
|
1649
|
+
-------
|
|
1650
|
+
Bootstrap
|
|
1651
|
+
This object, for chaining :meth:`get_confidence_intervals`.
|
|
1652
|
+
"""
|
|
1653
|
+
self.net.Run()
|
|
1654
|
+
return self
|
|
1655
|
+
|
|
1656
|
+
def run_double_bootstrap(self, inner_replicates: int = 300) -> Bootstrap:
|
|
1657
|
+
"""Run the double bootstrap with bias correction (``RunDoubleBootstrap``).
|
|
1658
|
+
|
|
1659
|
+
Parameters
|
|
1660
|
+
----------
|
|
1661
|
+
inner_replicates : int, optional
|
|
1662
|
+
Inner replicates per outer replicate; default 300.
|
|
1663
|
+
|
|
1664
|
+
Returns
|
|
1665
|
+
-------
|
|
1666
|
+
Bootstrap
|
|
1667
|
+
This object.
|
|
1668
|
+
"""
|
|
1669
|
+
self.net.RunDoubleBootstrap(int(inner_replicates))
|
|
1670
|
+
return self
|
|
1671
|
+
|
|
1672
|
+
def run_with_studentized_bootstrap(self) -> Bootstrap:
|
|
1673
|
+
"""Run the bootstrap with inner standard errors for Bootstrap-t (``RunWithStudentizedBootstrap``).
|
|
1674
|
+
|
|
1675
|
+
Returns
|
|
1676
|
+
-------
|
|
1677
|
+
Bootstrap
|
|
1678
|
+
This object.
|
|
1679
|
+
"""
|
|
1680
|
+
self.net.RunWithStudentizedBootstrap()
|
|
1681
|
+
return self
|
|
1682
|
+
|
|
1683
|
+
def run_pivotal_bootstrap(self) -> Bootstrap:
|
|
1684
|
+
"""Run the covariance-aware pivotal bootstrap (``RunPivotalBootstrap``).
|
|
1685
|
+
|
|
1686
|
+
Returns
|
|
1687
|
+
-------
|
|
1688
|
+
Bootstrap
|
|
1689
|
+
This object.
|
|
1690
|
+
"""
|
|
1691
|
+
self.net.RunPivotalBootstrap()
|
|
1692
|
+
return self
|
|
1693
|
+
|
|
1694
|
+
def transform_pivotal_bootstrap(self, raw_fits: Sequence[BootstrapFit]) -> Bootstrap:
|
|
1695
|
+
"""Apply the pivotal transformation to given raw fits (``TransformPivotalBootstrap``).
|
|
1696
|
+
|
|
1697
|
+
Parameters
|
|
1698
|
+
----------
|
|
1699
|
+
raw_fits : sequence of BootstrapFit
|
|
1700
|
+
Raw covariance-aware bootstrap fits.
|
|
1701
|
+
|
|
1702
|
+
Returns
|
|
1703
|
+
-------
|
|
1704
|
+
Bootstrap
|
|
1705
|
+
This object.
|
|
1706
|
+
"""
|
|
1707
|
+
import System # noqa: PLC0415 - the runtime is running
|
|
1708
|
+
|
|
1709
|
+
fits = System.Array[_sampling().BootstrapFit]([getattr(f, "net", f) for f in raw_fits])
|
|
1710
|
+
self.net.TransformPivotalBootstrap(fits)
|
|
1711
|
+
return self
|
|
1712
|
+
|
|
1713
|
+
def get_confidence_intervals(self, method: BootstrapCIMethod | str = BootstrapCIMethod.PERCENTILE,
|
|
1714
|
+
alpha: float = 0.1) -> BootstrapResults:
|
|
1715
|
+
"""Return confidence intervals of the last run (``GetConfidenceIntervals``).
|
|
1716
|
+
|
|
1717
|
+
Parameters
|
|
1718
|
+
----------
|
|
1719
|
+
method : BootstrapCIMethod or str, optional
|
|
1720
|
+
The interval method; default percentile.
|
|
1721
|
+
alpha : float, optional
|
|
1722
|
+
Two-sided level; default 0.1 (90 percent intervals).
|
|
1723
|
+
|
|
1724
|
+
Returns
|
|
1725
|
+
-------
|
|
1726
|
+
BootstrapResults
|
|
1727
|
+
Intervals of every parameter and statistic.
|
|
1728
|
+
"""
|
|
1729
|
+
kind = net_enum(_sampling().BootstrapCIMethod, method)
|
|
1730
|
+
return BootstrapResults(self.net.GetConfidenceIntervals(kind, float(alpha)))
|
|
1731
|
+
|
|
1732
|
+
def get_raw_pivotal_confidence_intervals(self, alpha: float = 0.1) -> BootstrapResults:
|
|
1733
|
+
"""Return percentile intervals of the raw fits of the last pivotal run (``GetRawPivotalConfidenceIntervals``).
|
|
1734
|
+
|
|
1735
|
+
Parameters
|
|
1736
|
+
----------
|
|
1737
|
+
alpha : float, optional
|
|
1738
|
+
Two-sided level; default 0.1.
|
|
1739
|
+
|
|
1740
|
+
Returns
|
|
1741
|
+
-------
|
|
1742
|
+
BootstrapResults
|
|
1743
|
+
The intervals.
|
|
1744
|
+
"""
|
|
1745
|
+
return BootstrapResults(self.net.GetRawPivotalConfidenceIntervals(float(alpha)))
|
|
1746
|
+
|
|
1747
|
+
|
|
1748
|
+
__all__ = [
|
|
1749
|
+
"Bootstrap", "BootstrapCIMethod", "BootstrapFit", "BootstrapResults", "BootstrapStatisticResult",
|
|
1750
|
+
"MersenneTwister", "PivotalBootstrapContext", "PivotalBootstrapDiagnostics", "PivotalBootstrapInvalidDrawPolicy",
|
|
1751
|
+
"SobolSequence", "StratificationBin", "StratificationBins", "StratificationOptions",
|
|
1752
|
+
"exceedance_probability_to_x", "latin_hypercube", "probability_to_x", "stratify_exceedance_probabilities",
|
|
1753
|
+
"stratify_exceedance_probabilities_many", "stratify_multivariate_probabilities", "stratify_probabilities",
|
|
1754
|
+
"stratify_probabilities_many", "stratify_x_values", "stratify_x_values_many", "x_to_exceedance_probability",
|
|
1755
|
+
"x_to_probability",
|
|
1756
|
+
]
|
|
1757
|
+
|
|
1758
|
+
translate_public(globals())
|