Page MenuHomec4science

random_sampler.py
No OneTemporary

File Metadata

Created
Tue, May 14, 23:43

random_sampler.py

# Copyright (C) 2018 by the RROMPy authors
#
# This file is part of RROMPy.
#
# RROMPy is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RROMPy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with RROMPy. If not, see <http://www.gnu.org/licenses/>.
#
import numpy as np
from rrompy.utilities.base.sobol import sobolGenerate
from rrompy.utilities.parameter_sampling.generic_sampler import GenericSampler
from rrompy.utilities.base.types import Np1D, Tuple, List
__all__ = ['RandomSampler']
class RandomSampler(GenericSampler):
"""Generator of quadrature sample points."""
allowedKinds = ["UNIFORM", "SOBOL"]
def __init__(self, lims:Tuple[Np1D, Np1D], kind : str = "UNIFORM",
scaling : callable = None, scalingInv : callable = None):
super().__init__(lims = lims, scaling = scaling,
scalingInv = scalingInv)
self.kind = kind
def __str__(self) -> str:
return "{}_{}".format(super().__str__(), self.kind)
def __repr__(self) -> str:
return self.__str__() + " at " + hex(id(self))
@property
def kind(self):
"""Value of kind."""
return self._kind
@kind.setter
def kind(self, kind):
if kind.upper() not in self.allowedKinds:
raise Exception("Generator kind not recognized.")
self._kind = kind.upper()
def generatePoints(self, n:int, seed : int = 0) -> Tuple[List[Np1D], Np1D]:
"""Array of quadrature points and array of weights."""
super().generatePoints(n)
d = len(self.lims[0])
if self.kind == "UNIFORM":
np.random.seed(seed)
x = np.random.uniform(size = (n, d))
else:
x = sobolGenerate(d, n, seed)
for j in range(d):
a, b = self.lims[0][j], self.lims[1][j]
if self.scaling is not None:
a, b = self.scaling[j](a), self.scaling[j](b)
x[:, j] = a + (b - a) * x[:, j]
if self.scalingInv is not None:
x[:, j] = self.scalingInv[j](x[:, j])
return [y.flatten() for y in np.split(x, n)], np.ones(n)
def refine(self, n:int, seed : int = 420) -> Tuple[List[Np1D], Np1D]:
"""
Apply refinement. If points are not nested, equivalent to
generatePoints([2 * x - 1 for x in n]).
"""
try:
len(n)
except:
n = np.array([n])
return self.generatePoints([nj - 1 for nj in n], seed)

Event Timeline