GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Numerics/python/pynumerics/src/pynumerics/sampling.py at main · USACE-RMC/Numerics Expand file tree/ Copy pathsampling.pyMore file actions 1758 lines (1402 loc) · 62.7 KB / Copy pathsampling.pyFile metadata and controls1758 lines (1402 loc) · 62.7 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 """Sampling designs and resampling from ``Numerics.Sampling``. Stratification, Latin hypercube and Sobol designs, the Mersenne Twister, and the general bootstrap (:class:`Bootstrap`, ``Numerics.Sampling.Bootstrap<TData>``) with its confidence intervals. The MCMC samplers are in :mod:`pynumerics.mcmc`. Stratification bins come back as a :class:`StratificationBins` record of NumPy arrays holding the .NET bin list (``.net``), which can be passed back to Numerics members that take ``List<StratificationBin>``. """ from __future__ import annotations from collections.abc import Sequence from dataclasses import dataclass, field from typing import Any import numpy as np from pynumerics import callbacks from pynumerics._util import namespace, net_enum from pynumerics.enums import ImportanceDistribution, NetEnum from pynumerics.errors import translate_public from pynumerics.marshal import ( _numerics_matrix, _parameter_set_arrays, to_net_doubles, to_net_ints, to_net_matrix, to_numpy_doubles, to_numpy_ints, to_numpy_matrix, ) def _sampling() -> Any: """Return the ``Numerics.Sampling`` namespace after starting the runtime.""" return namespace("Numerics.Sampling") def _xelement(text: str) -> Any: """Parse XML text into a ``System.Xml.Linq.XElement``.""" _sampling() from System.Xml.Linq import XElement # noqa: PLC0415 - the runtime is running return XElement.Parse(str(text)) @dataclass(frozen=True) class StratificationBin: """One stratification bin as Numerics holds it (``StratificationBin``). Parameters ---------- lower_bound : float Lower edge. upper_bound : float Upper edge. weight : float Weight (probability mass); Numerics sets the bin width for value bins built without one. midpoint : float ``Midpoint`` as Numerics computes it, (lower + upper) / 2. """ lower_bound: float upper_bound: float weight: float midpoint: float def contains(self, x: float) -> bool: """Return whether ``lower_bound <= x < upper_bound``. Parameters ---------- x : float The value. Returns ------- bool True when the value lies in the half-open bin. """ return self.lower_bound <= x < self.upper_bound def to_net(self) -> Any: """Return the bin as a new .NET ``StratificationBin``. Returns ------- Numerics.Sampling.StratificationBin A bin with the same bounds and weight. """ return _sampling().StratificationBin(float(self.lower_bound), float(self.upper_bound), float(self.weight)) def compare_to(self, other: StratificationBin) -> int: """Order two non-overlapping bins (``CompareTo``). Parameters ---------- other : StratificationBin The other bin. Returns ------- int 1 when this bin lies above ``other``, -1 when below. Raises ------ ValueError If the bins overlap; Numerics counts a bin as overlapping itself. """ return int(self.to_net().CompareTo(other.to_net())) @dataclass(frozen=True) class StratificationBins: """Stratification bins as arrays. Parameters ---------- lower : numpy.ndarray Lower bound of each bin. upper : numpy.ndarray Upper bound of each bin. weight : numpy.ndarray Weight (probability mass) of each bin. net : System.Collections.Generic.List[Numerics.Sampling.StratificationBin] The .NET bin list the arrays were read from. """ lower: np.ndarray upper: np.ndarray weight: np.ndarray net: Any = field(repr=False, compare=False) @property def midpoint(self) -> np.ndarray: """Bin midpoints, (lower + upper) / 2 as Numerics computes them.""" return np.array([float(b.Midpoint) for b in self.net], dtype=np.float64) def __len__(self) -> int: return int(self.lower.size) @property def bins(self) -> tuple[StratificationBin, ...]: """The bins as :class:`StratificationBin` records (``LowerBound``, ``UpperBound``, ``Weight``, ``Midpoint``).""" return tuple(StratificationBin(float(b.LowerBound), float(b.UpperBound), float(b.Weight), float(b.Midpoint)) for b in self.net) @classmethod def from_net(cls, bins: Any) -> StratificationBins: """Read a .NET ``List<StratificationBin>``. Parameters ---------- bins : System.Collections.Generic.List[Numerics.Sampling.StratificationBin] The .NET bins. Returns ------- StratificationBins The arrays and the original list. """ lower = np.array([float(b.LowerBound) for b in bins], dtype=np.float64) upper = np.array([float(b.UpperBound) for b in bins], dtype=np.float64) weight = np.array([float(b.Weight) for b in bins], dtype=np.float64) return cls(lower, upper, weight, bins) def to_xml(self) -> str: """Serialize the bins (``StratificationBin.SaveToXElement(IList<StratificationBin>)``). Returns ------- str The ``StratificationBinList`` XML element, bounds and weights in G17. """ return str(_sampling().StratificationBin.SaveToXElement(self.net).ToString()) @classmethod def from_xml(cls, text: str) -> StratificationBins: """Read bins written by :meth:`to_xml` (``StratificationBin.XElementToStratificationBinList``). Parameters ---------- text : str A ``StratificationBinList`` XML element. Returns ------- StratificationBins The bins. """ return cls.from_net(_sampling().StratificationBin.XElementToStratificationBinList(_xelement(text))) class StratificationOptions: """The range and bin count of one stratification (``Numerics.Sampling.StratificationOptions``). Parameters ---------- lower_bound : float Lower end of the range. upper_bound : float Upper end of the range. number_of_bins : int Number of bins. is_probability : bool, optional Whether the range is a probability range; default False. Attributes ---------- net : Numerics.Sampling.StratificationOptions The wrapped .NET object. """ def __init__(self, lower_bound: float, upper_bound: float, number_of_bins: int, is_probability: bool = False) -> None: self.net = _sampling().StratificationOptions(float(lower_bound), float(upper_bound), int(number_of_bins), bool(is_probability)) @classmethod def _wrap(cls, net: Any) -> StratificationOptions: instance = cls.__new__(cls) instance.net = net return instance def __repr__(self) -> str: return (f"StratificationOptions({self.lower_bound!r}, {self.upper_bound!r}, {self.number_of_bins!r}, " f"is_probability={self.is_probability!r})") @property def lower_bound(self) -> float: """Lower end of the range (``LowerBound``).""" return float(self.net.LowerBound) @property def upper_bound(self) -> float: """Upper end of the range (``UpperBound``).""" return float(self.net.UpperBound) @property def number_of_bins(self) -> int: """Number of bins (``NumberOfBins``).""" return int(self.net.NumberOfBins) @property def is_probability(self) -> bool: """Whether the range is a probability range (``IsProbability``).""" return bool(self.net.IsProbability) @property def is_valid(self) -> bool: """Whether the options are valid (``IsValid``).""" return bool(self.net.IsValid) def get_errors(self) -> list[str]: """Return the validation messages (``GetErrors``). Returns ------- list of str Empty when the options are valid. """ return [str(e) for e in self.net.GetErrors()] def clone(self) -> StratificationOptions: """Return a copy (``Clone``). Returns ------- StratificationOptions The copy. """ return StratificationOptions._wrap(self.net.Clone()) def to_xml(self) -> str: """Serialize the options (``SaveToXElement``). Returns ------- str The ``StratificationOptions`` XML element. """ return str(self.net.SaveToXElement().ToString()) @classmethod def from_xml(cls, text: str) -> StratificationOptions: """Read options written by :meth:`to_xml` (``StratificationOptions(XElement)``). Parameters ---------- text : str A ``StratificationOptions`` XML element. Returns ------- StratificationOptions The options. """ return cls._wrap(_sampling().StratificationOptions(_xelement(text))) @staticmethod def list_to_xml(options: Sequence[StratificationOptions]) -> str: """Serialize several options (``StratificationOptions.SaveToXElement(IList<StratificationOptions>)``). Parameters ---------- options : sequence of StratificationOptions The options. Returns ------- str The XML element holding every option. """ return str(_sampling().StratificationOptions.SaveToXElement(_options_list(options)).ToString()) @staticmethod def list_from_xml(text: str) -> list[StratificationOptions]: """Read options written by :meth:`list_to_xml` (``XElementToStratificationOptions``). Parameters ---------- text : str The XML element. Returns ------- list of StratificationOptions The options. """ items = _sampling().StratificationOptions.XElementToStratificationOptions(_xelement(text)) return [StratificationOptions._wrap(o) for o in items] def _options(lower: float, upper: float, number_of_bins: int, is_probability: bool) -> Any: """Build ``StratificationOptions``.""" return _sampling().StratificationOptions(float(lower), float(upper), int(number_of_bins), bool(is_probability)) def _options_list(options: Any, is_probability: bool = False) -> Any: """Build ``List<StratificationOptions>`` from :class:`StratificationOptions` or ``(lower, upper, bins)`` triples.""" s = _sampling() from System.Collections.Generic import List # noqa: PLC0415 - the runtime is started by _sampling items = List[s.StratificationOptions]() for option in options: if isinstance(option, StratificationOptions): items.Add(option.net) else: lower, upper, number_of_bins = option items.Add(_options(lower, upper, number_of_bins, is_probability)) return items def stratify_x_values(lower: float, upper: float, number_of_bins: int, is_logarithmic: bool = False) -> StratificationBins: """Stratify a value range into equal-width bins (``Stratify.XValues``). Parameters ---------- lower, upper : float Range to stratify. number_of_bins : int Number of bins. is_logarithmic : bool, optional Equal widths in log10 space; default False. Returns ------- StratificationBins The bins; Numerics leaves their weights unset (−1) for value bins. """ s = _sampling() return StratificationBins.from_net(s.Stratify.XValues(_options(lower, upper, number_of_bins, False), bool(is_logarithmic))) def stratify_x_values_many(options: Any, is_logarithmic: bool = False) -> StratificationBins: """Stratify several value ranges into one bin list (``Stratify.XValues(List<StratificationOptions>)``). Parameters ---------- options : sequence of (float, float, int) or StratificationOptions One ``(lower, upper, number_of_bins)`` triple or options object per range. is_logarithmic : bool, optional Equal widths in log10 space; default False. Returns ------- StratificationBins The bins of every range, in the order Numerics returns them. """ s = _sampling() return StratificationBins.from_net(s.Stratify.XValues(_options_list(options), bool(is_logarithmic))) def stratify_probabilities(lower: float, upper: float, number_of_bins: int, importance: ImportanceDistribution | str = ImportanceDistribution.UNIFORM, is_exhaustive: bool = True) -> StratificationBins: """Stratify a non-exceedance probability range (``Stratify.Probabilities``). Parameters ---------- lower, upper : float Probability range in [0, 1]. number_of_bins : int Number of bins. importance : ImportanceDistribution or str, optional Space in which the bins are equally wide; default uniform. is_exhaustive : bool, optional Whether the end bins absorb the remaining probability; default True. Returns ------- StratificationBins The bins. """ s = _sampling() kind = net_enum(s.Stratify.ImportanceDistribution, importance) return StratificationBins.from_net(s.Stratify.Probabilities(_options(lower, upper, number_of_bins, True), kind, bool(is_exhaustive))) def stratify_probabilities_many(options: Any, importance: ImportanceDistribution | str = ImportanceDistribution.UNIFORM, is_exhaustive: bool = True) -> StratificationBins: """Stratify several probability ranges into one bin list (``Stratify.Probabilities(List<...>)``). Parameters ---------- options : sequence of (float, float, int) or StratificationOptions One ``(lower, upper, number_of_bins)`` probability range or options object per range. importance : ImportanceDistribution or str, optional Space in which the bins are equally wide; default uniform. is_exhaustive : bool, optional Whether the end bins absorb the remaining probability; default True. Returns ------- StratificationBins The bins of every range. """ s = _sampling() kind = net_enum(s.Stratify.ImportanceDistribution, importance) return StratificationBins.from_net(s.Stratify.Probabilities(_options_list(options, True), kind, bool(is_exhaustive))) def stratify_exceedance_probabilities(lower: float, upper: float, number_of_bins: int, importance: ImportanceDistribution | str = ImportanceDistribution.UNIFORM, is_exhaustive: bool = True) -> StratificationBins: """Stratify an exceedance probability range (``Stratify.ExceedanceProbabilities``). Parameters ---------- lower, upper : float Exceedance probability range in [0, 1]. number_of_bins : int Number of bins. importance : ImportanceDistribution or str, optional Space in which the bins are equally wide; default uniform. is_exhaustive : bool, optional Whether the end bins absorb the remaining probability; default True. Returns ------- StratificationBins The bins. """ s = _sampling() kind = net_enum(s.Stratify.ImportanceDistribution, importance) return StratificationBins.from_net(s.Stratify.ExceedanceProbabilities( _options(lower, upper, number_of_bins, True), kind, bool(is_exhaustive))) def stratify_exceedance_probabilities_many(options: Any, importance: ImportanceDistribution | str = ImportanceDistribution.UNIFORM, is_exhaustive: bool = True) -> StratificationBins: """Stratify several exceedance probability ranges (``Stratify.ExceedanceProbabilities(List<...>)``). Parameters ---------- options : sequence of (float, float, int) or StratificationOptions One ``(lower, upper, number_of_bins)`` range or options object per range. importance : ImportanceDistribution or str, optional Space in which the bins are equally wide; default uniform. is_exhaustive : bool, optional Whether the end bins absorb the remaining probability; default True. Returns ------- StratificationBins The bins of every range. """ s = _sampling() kind = net_enum(s.Stratify.ImportanceDistribution, importance) return StratificationBins.from_net(s.Stratify.ExceedanceProbabilities(_options_list(options, True), kind, bool(is_exhaustive))) def stratify_multivariate_probabilities(lower: float, upper: float, number_of_bins: int, importance: ImportanceDistribution | str = ImportanceDistribution.UNIFORM, is_exhaustive: bool = True, dimension: int = 1, seed: int = -1, correlation: Any = None) -> list[StratificationBins]: """Stratify a probability range in several dimensions (``Stratify.MultivariateProbabilities``). Parameters ---------- lower, upper : float Probability range in [0, 1]. number_of_bins : int Number of bins per dimension. importance : ImportanceDistribution or str, optional Space in which the bins are equally wide; default uniform. is_exhaustive : bool, optional Whether the end bins absorb the remaining probability; default True. dimension : int, optional Number of dimensions; default 1. seed : int, optional Seed of the random pairing; zero or negative seeds from the clock (not reproducible). correlation : array_like, optional Correlation matrix of shape ``(dimension, dimension)``; default independence. Returns ------- list of StratificationBins The bins of each dimension. """ s = _sampling() kind = net_enum(s.Stratify.ImportanceDistribution, importance) matrix = None if correlation is None else to_net_matrix(correlation) result = s.Stratify.MultivariateProbabilities(_options(lower, upper, number_of_bins, True), kind, bool(is_exhaustive), int(dimension), int(seed), matrix) return [StratificationBins.from_net(bins) for bins in result] def _bins(bins: Any) -> Any: """Return the .NET bin list of :class:`StratificationBins` or pass a .NET list through.""" return getattr(bins, "net", bins) def x_to_probability(x_bins: Any, transform: Any, is_exhaustive: bool = True) -> StratificationBins: """Map value bins to non-exceedance probability bins (``Stratify.XToProbability``). Parameters ---------- x_bins : StratificationBins Value bins. transform : callable, str or System.Delegate The CDF ``x -> p`` (``Func<double, double>``), for example ``Normal(0, 1).cdf``. is_exhaustive : bool, optional Whether the end bins absorb the remaining probability; default True. Returns ------- StratificationBins The probability bins. """ s = _sampling() return StratificationBins.from_net(s.Stratify.XToProbability(_bins(x_bins), callbacks.scalar_function(transform), bool(is_exhaustive))) def x_to_exceedance_probability(x_bins: Any, transform: Any, is_exhaustive: bool = True) -> StratificationBins: """Map value bins to exceedance probability bins (``Stratify.XToExceedanceProbability``). Parameters ---------- x_bins : StratificationBins Value bins. transform : callable, str or System.Delegate The survival function ``x -> 1 - F(x)`` (``Func<double, double>``). is_exhaustive : bool, optional Whether the end bins absorb the remaining probability; default True. Returns ------- StratificationBins The exceedance probability bins. """ s = _sampling() return StratificationBins.from_net(s.Stratify.XToExceedanceProbability( _bins(x_bins), callbacks.scalar_function(transform), bool(is_exhaustive))) def probability_to_x(probability_bins: Any, transform: Any) -> StratificationBins: """Map non-exceedance probability bins to value bins (``Stratify.ProbabilityToX``). Parameters ---------- probability_bins : StratificationBins Probability bins. transform : callable, str or System.Delegate The quantile function ``p -> x`` (``Func<double, double>``). Returns ------- StratificationBins The value bins; Numerics sets each weight to the bin width, as for value bins. """ s = _sampling() return StratificationBins.from_net(s.Stratify.ProbabilityToX(_bins(probability_bins), callbacks.scalar_function(transform))) def exceedance_probability_to_x(probability_bins: Any, transform: Any) -> StratificationBins: """Map exceedance probability bins to value bins (``Stratify.ExceedanceProbabilityToX``). Parameters ---------- probability_bins : StratificationBins Exceedance probability bins. transform : callable, str or System.Delegate The function ``q -> x`` (``Func<double, double>``), for example ``q -> F^-1(1 - q)``. Returns ------- StratificationBins The value bins, ascending in x; Numerics sets each weight to the bin width. """ s = _sampling() return StratificationBins.from_net(s.Stratify.ExceedanceProbabilityToX(_bins(probability_bins), callbacks.scalar_function(transform))) def latin_hypercube(sample_size: int, dimension: int = 1, seed: Any = -1, median: bool = False) -> np.ndarray: """Draw a Latin hypercube design on the unit cube (``LatinHypercube.Random``/``Median``). Parameters ---------- sample_size : int Number of rows. dimension : int, optional Number of columns; default 1. seed : int or MersenneTwister, optional Seed, or a generator to draw from (the ``Random`` overloads); zero or negative seeds from the clock (not reproducible). median : bool, optional Use bin midpoints instead of uniform positions within bins; default False. Returns ------- numpy.ndarray Array of shape ``(sample_size, dimension)``. """ lhs = _sampling().LatinHypercube method = lhs.Median if median else lhs.Random generator = seed.net if isinstance(seed, MersenneTwister) else seed if not isinstance(generator, int): return to_numpy_matrix(method(int(sample_size), int(dimension), generator)) return to_numpy_matrix(method(int(sample_size), int(dimension), int(generator))) class MersenneTwister: """The Numerics Mersenne Twister (``Numerics.Sampling.MersenneTwister``). Exposed for cross-checks of NumPy re-implementations against the .NET stream, and as the generator passed to Numerics members that take a ``System.Random``. Parameters ---------- seed : int or sequence of int, optional Seed, or an array of seeds (``init_by_array``); default the clock (not reproducible). Attributes ---------- net : Numerics.Sampling.MersenneTwister The wrapped .NET generator. """ def __init__(self, seed: Any = None) -> None: s = _sampling() if seed is None: self.net = s.MersenneTwister() elif isinstance(seed, (int, np.integer)): self.net = s.MersenneTwister(int(seed)) else: self.net = s.MersenneTwister(to_net_ints(seed)) def initialize(self, seed: int) -> None: """Reseed the generator with an unsigned 32-bit seed (``Initialize(uint)``). Parameters ---------- seed : int Seed in [0, 2**32). """ import System # noqa: PLC0415 - the runtime is running self.net.Initialize(System.UInt32(int(seed))) def next_double(self) -> float: """Return the next double in [0, 1) (``NextDouble``). Returns ------- float The draw. """ return float(self.net.NextDouble()) def next_doubles(self, length: int) -> np.ndarray: """Return the next doubles (``ExtensionMethods.NextDoubles``). Parameters ---------- length : int Number of draws. Returns ------- numpy.ndarray The draws. """ root = namespace("Numerics") return to_numpy_doubles(root.ExtensionMethods.NextDoubles(self.net, int(length))) def next_integers(self, length: int) -> np.ndarray: """Return the next non-negative integers (``ExtensionMethods.NextIntegers``). Parameters ---------- length : int Number of draws. Returns ------- numpy.ndarray The draws as int32. """ root = namespace("Numerics") return to_numpy_ints(root.ExtensionMethods.NextIntegers(self.net, int(length))) def gen_rand_int32(self) -> int: """Return the next raw 32-bit output (``GenRandInt32``). Returns ------- int An unsigned 32-bit integer. """ return int(self.net.GenRandInt32()) def gen_rand_int31(self) -> int: """Return the next 31-bit output (``GenRandInt31``). Returns ------- int An integer in [0, 2**31). """ return int(self.net.GenRandInt31()) def gen_rand_real1(self) -> float: """Return the next double in [0, 1] (``GenRandReal1``). Returns ------- float The draw. """ return float(self.net.GenRandReal1()) def gen_rand_real2(self) -> float: """Return the next double in [0, 1) (``GenRandReal2``). Returns ------- float The draw. """ return float(self.net.GenRandReal2()) def gen_rand_real3(self) -> float: """Return the next double in (0, 1) (``GenRandReal3``). Returns ------- float The draw. """ return float(self.net.GenRandReal3()) def gen_rand_res53(self) -> float: """Return the next double in [0, 1) with 53-bit resolution (``GenRandRes53``). Returns ------- float The draw. """ return float(self.net.GenRandRes53()) class SobolSequence: """The Sobol low-discrepancy sequence (``Numerics.Sampling.SobolSequence``). Parameters ---------- dimension : int, optional Space dimension; default 1. seed : int, optional Seed of the linear matrix scramble and digital shift; default None, the original unrandomized sequence. Attributes ---------- net : Numerics.Sampling.SobolSequence The wrapped .NET sequence. """ def __init__(self, dimension: int = 1, seed: int | None = None) -> None: s = _sampling() self.net = s.SobolSequence(int(dimension)) if seed is None else s.SobolSequence(int(dimension), int(seed)) @property def dimension(self) -> int: """The space dimension (``Dimension``).""" return int(self.net.Dimension) @property def seed(self) -> int | None: """The scramble seed, or None for the unrandomized sequence (``Seed``).""" value = self.net.Seed return None if value is None else int(value) def next_double(self) -> np.ndarray: """Return the next point of the sequence (``NextDouble``). Returns ------- numpy.ndarray A point in [0, 1)^dimension. """ return to_numpy_doubles(self.net.NextDouble()) def next_doubles(self, length: int) -> np.ndarray: """Return the next points, one ``NextDouble`` each. Parameters ---------- length : int Number of points. Returns ------- numpy.ndarray Array of shape ``(length, dimension)``. """ out = np.empty((int(length), self.dimension), dtype=np.float64) for row in range(int(length)): out[row] = to_numpy_doubles(self.net.NextDouble()) return out def skip_to(self, index: int) -> np.ndarray: """Move to a position of the sequence and return the point there (``SkipTo``). Indices count the origin as point 0, which Numerics never returns: ``skip_to(i)`` gives point ``i`` of ``scipy.stats.qmc.Sobol(d, scramble=False)`` for ``i >= 1``, ``skip_to(0)`` gives point 1, and :meth:`next_double` continues from there. Parameters ---------- index : int Position in the sequence. Returns ------- numpy.ndarray The point at ``index``. """ return to_numpy_doubles(self.net.SkipTo(int(index))) class BootstrapCIMethod(NetEnum): """Bootstrap confidence interval methods (``Numerics.Sampling.BootstrapCIMethod``).""" PERCENTILE = "Percentile" BIAS_CORRECTED = "BiasCorrected" BCA = "BCa" NORMAL = "Normal" BOOTSTRAP_T = "BootstrapT" class PivotalBootstrapInvalidDrawPolicy(NetEnum): """Handling of invalid pivotal draws (``Numerics.Sampling.PivotalBootstrapInvalidDrawPolicy``).""" DROP = "Drop" USE_RAW = "UseRaw" USE_PARENT = "UseParent" def _parameter_set(values: Any, fitness: float = float("nan")) -> Any: """Build a .NET ``ParameterSet`` from values, or pass a .NET one through.""" ps = namespace("Numerics.Mathematics.Optimization").ParameterSet if isinstance(values, ps): return values return ps(to_net_doubles(np.ravel(np.asarray(values, dtype=np.float64))), float(fitness)) class BootstrapFit: """A fitted parameter set with its covariance (``Numerics.Sampling.BootstrapFit``). Parameters ---------- parameters : array_like or Numerics.Sampling.BootstrapFit The fitted parameters, or a .NET fit to wrap. covariance : array_like, optional The parameter covariance, shape ``(p, p)``; required unless wrapping. Attributes ---------- net : Numerics.Sampling.BootstrapFit The wrapped .NET object. """ def __init__(self, parameters: Any, covariance: Any = None) -> None: s = _sampling() if isinstance(parameters, s.BootstrapFit): self.net = parameters return if covariance is None: raise ValueError("BootstrapFit needs a covariance matrix.") matrix = _numerics_matrix(np.atleast_2d(np.asarray(covariance, dtype=np.float64))) values = np.ravel(np.asarray(parameters, dtype=np.float64)) self.net = s.BootstrapFit(to_net_doubles(values), matrix) def __repr__(self) -> str: return f"BootstrapFit(parameters={self.parameters!r})" @property def parameters(self) -> np.ndarray: """The fitted parameter values (``Parameters.Values``).""" return to_numpy_doubles(self.net.Parameters.Values) @property def covariance(self) -> np.ndarray: """The parameter covariance (``Covariance``).""" return to_numpy_matrix(self.net.Covariance.ToArray()) @property def parameter_count(self) -> int: """The number of parameters (``ParameterCount``).""" return int(self.net.ParameterCount) class PivotalBootstrapContext: """The parent fit and raw fits a pivotal link factory sees (``Numerics.Sampling.PivotalBootstrapContext``). Parameters ---------- parent_fit : BootstrapFit or Numerics.Sampling.PivotalBootstrapContext The parent fit, or a .NET context to wrap. raw_bootstrap_fits : sequence of BootstrapFit, optional The accepted raw bootstrap fits; required unless wrapping. Attributes ---------- net : Numerics.Sampling.PivotalBootstrapContext The wrapped .NET object. """ def __init__(self, parent_fit: Any, raw_bootstrap_fits: Sequence[BootstrapFit] | None = None) -> None: s = _sampling() if isinstance(parent_fit, s.PivotalBootstrapContext): self.net = parent_fit return import System # noqa: PLC0415 - the runtime is running fits = System.Array[s.BootstrapFit]([f.net for f in (raw_bootstrap_fits or ())]) self.net = s.PivotalBootstrapContext(parent_fit.net, fits) @property def parent_fit(self) -> BootstrapFit: """The parent fit (``ParentFit``).""" return BootstrapFit(self.net.ParentFit) @property def raw_bootstrap_fits(self) -> list[BootstrapFit]: """The accepted raw bootstrap fits (``RawBootstrapFits``).""" return [BootstrapFit(f) for f in self.net.RawBootstrapFits] @property def parameter_count(self) -> int: """The number of parameters (``ParameterCount``).""" return int(self.net.ParameterCount) def get_raw_parameter_values(self, parameter_index: int) -> np.ndarray: """Return one parameter across the raw fits (``GetRawParameterValues``). Parameters ---------- parameter_index : int Zero-based parameter index. Returns ------- numpy.ndarray |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |