Пример #1
0
def randomSeed(value, seedBoth=False, engine=None):
    """
    Function to get a random seed
    @ In, value, float, the seed
    @ In, engine, instance, optional, random number generator
    @ In, seedBoth, bool, optional, if True then seed both random environments
    @ Out, None
  """
    # we need a flag to tell us  if the global numpy stochastic environment is needed to be changed
    replaceGlobalEnv = False
    ## choose an engine if it is none
    if engine is None:
        if stochasticEnv == 'crow':
            distStochEnv.seedRandom(value)
            engine = crowStochEnv
        elif stochasticEnv == 'numpy':
            replaceGlobalEnv = True
            global npStochEnv
            # global npStochEvn is needed in numpy environment here
            # to prevent referenced before assignment in local loop
            engine = npStochEnv

    if isinstance(engine, np.random.RandomState):
        engine = np.random.RandomState(value)
    elif isinstance(engine, findCrowModule('randomENG').RandomClass):
        engine.seed(value)
        if seedBoth:
            np.random.seed(value + 1)  # +1 just to prevent identical seed sets
    if stochasticEnv == 'numpy' and replaceGlobalEnv:
        npStochEnv = engine
    if replaceGlobalEnv:
        print('randomUtils: Global random number seed has been changed to',
              value)
Пример #2
0
def newRNG(env=None):
    """
    Provides a new instance of the random number generator.
    @ In, env, string, optional, type of random number generator.  Defaults to global option stored in "stochasticEnv".
    @ Out, engine, object, RNG producer
  """
    if env is None:
        env = stochasticEnv
    if env == 'crow':
        engine = findCrowModule('randomENG').RandomClass()
    elif env == 'numpy':
        engine = np.random.RandomState()
    return engine
Пример #3
0
def getEngine(eng):
    """
   Choose an engine if it is none and raise error if engine type not recognized
   @ In, engine, instance, random number generator
   @ Out, engine, instance, random number generator
  """
    if eng is None:
        if stochasticEnv == 'numpy':
            eng = npStochEnv
        elif stochasticEnv == 'crow':
            eng = crowStochEnv
    if not isinstance(eng, np.random.RandomState) and not isinstance(
            eng,
            findCrowModule('randomENG').RandomClass):
        raise TypeError('Engine type not recognized! {}'.format(type(eng)))
    return eng
Пример #4
0
def randomPermutation(l, caller, engine=None):
    """
    Function to get a random permutation
    @ In, l, list, list to be permuted
    @ In, caller, instance, the caller
    @ In, engine, instance, optional, random number generator
    @ Out, newList, list, randomly permuted list
  """
    engine = getEngine(engine)
    if isinstance(engine, np.random.RandomState):
        return engine.permutation(l)
    elif isinstance(engine, findCrowModule('randomENG').RandomClass):
        newList = []
        oldList = l[:]
        while len(oldList) > 0:
            newList.append(
                oldList.pop(
                    randomIntegers(0, len(oldList) - 1, caller,
                                   engine=engine)))
        return newList
Пример #5
0
def randomIntegers(low, high, caller, engine=None):
    """
    Function to get a random integer
    @ In, low, int, low boundary
    @ In, high, int, upper boundary
    @ In, caller, instance, object requesting the random integers
    @ In, engine, instance, optional, random number generator
    @ Out, rawInt, int, random int
  """
    engine = getEngine(engine)
    if isinstance(engine, np.random.RandomState):
        return engine.randint(low, high=high + 1)
    elif isinstance(engine, findCrowModule('randomENG').RandomClass):
        intRange = high - low
        rawNum = low + random(engine=engine) * intRange
        rawInt = int(round(rawNum))
        if rawInt < low or rawInt > high:
            caller.raiseAMessage("Random int out of range")
            rawInt = max(low, min(rawInt, high))
        return rawInt
    else:
        raise TypeError('Engine type not recognized! {}'.format(type(engine)))
Пример #6
0
def randomNormal(dim=1, samples=1, keepMatrix=False, engine=None):
    """
    Function to get a single random value, an array of random values, or a matrix of random values, normally distributed
    @ In, dim, int, optional, dimensionality of samples
    @ In, samples, int, optional, number of arrays to deliver
    @ In, keepMatrix, bool, optional, if True then will always return np.array(np.array(float))
    @ In, engine, instance, optional, random number generator
    @ Out, vals, float, random normal number (or np.array with size [n] if n>1, or np.array with size [n,samples] if sampels>1)
  """
    engine = getEngine(engine)
    dim = int(dim)
    samples = int(samples)
    if isinstance(engine, np.random.RandomState):
        vals = engine.randn(samples, dim)
    elif isinstance(engine, findCrowModule('randomENG').RandomClass):
        vals = np.zeros([samples, dim])
        for i in range(len(vals)):
            for j in range(len(vals[0])):
                vals[i, j] = boxMullerGen.generate(engine=engine)
    if keepMatrix:
        return vals
    else:
        return _reduceRedundantListing(vals, dim, samples)
Пример #7
0
def randomNormal(size=(1, ), keepMatrix=False, engine=None):
    """
    Function to get a single random value, an array of random values, or a matrix of random values, normally distributed
    @ In, size, int or tuple, optional, shape of the samples to return
      (if int, an array of samples will be returned if size>1, otherwise a float if keepMatrix is false)
    @ In, keepMatrix, bool, optional, if True then will always return np.array(np.array(float))
    @ In, engine, instance, optional, random number generator
    @ Out, vals, float, random normal number (or np.array with size [n] if n>1, or np.array with size [n,samples] if sampels>1)
  """
    engine = getEngine(engine)
    if isinstance(size, int):
        size = (size, )
    if isinstance(engine, np.random.RandomState):
        vals = engine.randn(*size)
    elif isinstance(engine, findCrowModule('randomENG').RandomClass):
        vals = np.zeros(np.prod(size))
        for i in range(len(vals)):
            vals[i] = boxMullerGen.generate(engine=engine)
        vals.shape = size
    if keepMatrix:
        return vals
    else:
        return _reduceRedundantListing(vals, size)
Пример #8
0
    """
      Tests distribution of samples over a large number.
      @ In, n, int, optional, number of samples to test with
      @ Out, mean, float, mean of sample set
      @ Out, stdev, float, standard deviation of sample set
    """
    n = int(n)
    samples = np.array([self.generate() for _ in range(n)])
    mean = np.average(samples)
    stdev = np.std(samples)
    return mean,stdev

if stochasticEnv == 'numpy':
  npStochEnv = np.random.RandomState()
else:
  crowStochEnv = findCrowModule('randomENG').RandomClass()
  # this is needed for now since we need to split the stoch enviroments
  distStochEnv = findCrowModule('distribution1D').DistributionContainer.instance()
  boxMullerGen = BoxMullerGenerator()

def randomSeed(value):
  """
    Function to get a random seed
    @ In, value, float, the seed
    @ Out, None
  """
  if stochasticEnv == 'numpy':
    global npStochEnv
    npStochEnv = np.random.RandomState(value)
  else:
    crowStochEnv.seed(value)
Пример #9
0
# limitations under the License.
"""
  This Module performs Unit Tests for the frontUtils methods
"""

import os, sys
import numpy as np
frameworkDir = os.path.normpath(
    os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), os.pardir,
                 os.pardir, os.pardir, os.pardir, 'framework'))
sys.path.append(frameworkDir)
from utils import utils
utils.find_crow(frameworkDir)
from utils import frontUtils

randomENG = utils.findCrowModule("randomENG")

print(frontUtils)

results = {"pass": 0, "fail": 0}


def checkAnswer(comment, value, expected, tol=1e-7, updateResults=True):
    """
    This method is aimed to compare two floats given a certain tolerance
    @ In, comment, string, a comment printed out if it fails
    @ In, value, float, the value to compare
    @ In, expected, float, the expected value
    @ In, tol, float, optional, the tolerance
    @ In, updateResults, bool, optional, if True updates global results
    @ Out, None
Пример #10
0
  @author: talbpaul
  Originally from SupervisedLearning.py, split in PR #650 in July 2018
  Specific ROM implementation for NDinterpolatorRom
"""
#for future compatibility with Python 3--------------------------------------------------------------
from __future__ import division, print_function, unicode_literals, absolute_import
#End compatibility block for Python 3----------------------------------------------------------------

#External Modules------------------------------------------------------------------------------------
import numpy as np
#External Modules End--------------------------------------------------------------------------------

#Internal Modules------------------------------------------------------------------------------------
from utils import utils
interpolationND = utils.findCrowModule("interpolationND")
from .SupervisedLearning import supervisedLearning
#Internal Modules End--------------------------------------------------------------------------------



class NDinterpolatorRom(supervisedLearning):
  """
  A Reduced Order Model for interpolating N-dimensional data
  """
  def __init__(self, **kwargs):
    """
      A constructor that will appropriately intialize a supervised learning object
      @ In, kwargs, dict, an arbitrary dictionary of keywords and values
      @ Out, None
    """
Пример #11
0
if sys.version_info.major > 2:
  from crow_modules.distribution1Dpy3 import CDF
else:
  from crow_modules.distribution1Dpy2 import CDF

#External Modules------------------------------------------------------------------------------------
import numpy as np
import abc
import copy
#External Modules End--------------------------------------------------------------------------------

#Internal Modules------------------------------------------------------------------------------------
from utils import utils, mathUtils, xmlUtils
import MessageHandler

interpolationND = utils.findCrowModule('interpolationND')
#Internal Modules End--------------------------------------------------------------------------------

class supervisedLearning(utils.metaclass_insert(abc.ABCMeta),MessageHandler.MessageUser):
  """
    This is the general interface to any supervisedLearning learning method.
    Essentially it contains a train method and an evaluate method
  """
  returnType       = ''    # this describe the type of information generated the possibility are 'boolean', 'integer', 'float'
  qualityEstType   = []    # this describe the type of estimator returned known type are 'distance', 'probability'. The values are returned by the self.__confidenceLocal__(Features)
  ROMtype          = ''    # the broad class of the interpolator
  ROMmultiTarget   = False #
  ROMtimeDependent = False # is this ROM able to treat time-like (any monotonic variable) explicitly in its formulation?

  @staticmethod
  def checkArrayConsistency(arrayIn,isDynamic=False):