Exemple #1
0
  def localInitialize(self):
    """
      Will perform all initialization specific to this Sampler. For instance,
      creating an empty container to hold the identified surface points, error
      checking the optionally provided solution export and other preset values,
      and initializing the limit surface Post-Processor used by this sampler.
      @ In, None
      @ Out, None
    """
    Grid.localInitialize(self)
    self.limit = (self.pointByVar-1)
    # For the multivariate normal distribtuion, if the user generates the grids on the transformed space, the user needs to provide the grid for each variables, no globalGrid is needed
    if self.variablesTransformationDict:
      tempFillingCheck = [[None]*(self.pointByVar-1)]*len(self.gridEntity.returnParameter("dimensionNames")) #for all variables
      self.sampledCoordinate = [[None]*len(self.axisName)]*(self.pointByVar-1)
      for i in range(len(tempFillingCheck)):
        tempFillingCheck[i]  = randomUtils.randomPermutation(list(range(self.pointByVar-1)),self) #pick a random interval sequence
      mappingIdVarName = {}
      for cnt, varName in enumerate(self.axisName):
        mappingIdVarName[varName] = cnt
    # For the multivariate normal, if the user wants to generate the grids based on joint distribution, the user needs to provide the globalGrid for all corresponding variables
    else:
      globGridsCount = {}
      dimInfo = self.gridEntity.returnParameter("dimInfo")
      for val in dimInfo.values():
        if val[-1] is not None and val[-1] not in globGridsCount.keys():
          globGridsCount[val[-1]] = 0
        globGridsCount[val[-1]] += 1
      diff = -sum(globGridsCount.values())+len(globGridsCount.keys())
      tempFillingCheck = [[None]*(self.pointByVar-1)]*(len(self.gridEntity.returnParameter("dimensionNames"))+diff) #for all variables
      self.sampledCoordinate = [[None]*len(self.axisName)]*(self.pointByVar-1)
      for i in range(len(tempFillingCheck)):
        tempFillingCheck[i]  = randomUtils.randomPermutation(list(range(self.pointByVar-1)),self) #pick a random interval sequence
      cnt = 0
      mappingIdVarName = {}
      for varName in self.axisName:
        if varName not in dimInfo.keys():
          mappingIdVarName[varName] = cnt
        else:
          for addKey,value in dimInfo.items():
            if value[1] == dimInfo[varName][1] and addKey not in mappingIdVarName.keys():
              mappingIdVarName[addKey] = cnt
        if len(mappingIdVarName.keys()) == len(self.axisName):
          break
        cnt +=1

    for nPoint in range(self.pointByVar-1):
      self.sampledCoordinate[nPoint]= [tempFillingCheck[mappingIdVarName[varName]][nPoint] for varName in self.axisName]
Exemple #2
0
def scrambleMutator(offSprings, **kwargs):
    """
    This method performs the scramble mutator. For each child, a subset of genes is chosen
    and their values are shuffled randomly.
    @ In, offSprings, xr.DataArray, offsprings after crossover
    @ In, kwargs, dict, dictionary of parameters for this mutation method:
          chromosome, numpy.array, the chromosome that will mutate to the new child
          locs, list, the locations of the genes to be randomly scrambled
          mutationProb, float, probability that governs the mutation process, i.e., if prob < random number, then the mutation will occur
          variables, list, variables names.
    @ Out, child, np.array, the mutated chromosome, i.e., the child.
  """
    locs = kwargs['locs']
    if locs == None:
        nLocs = randomUtils.randomIntegers(0, offSprings.sizes['Gene'] - 1,
                                           None)
        locs = []
        for i in range(nLocs):
            l = randomUtils.randomIntegers(0, offSprings.sizes['Gene'] - 1,
                                           None)
            locs.append(l)
        locs = list(set(locs))
    nMutable = len(locs)
    # initializing children
    children = xr.DataArray(np.zeros((np.shape(offSprings))),
                            dims=['chromosome', 'Gene'],
                            coords={
                                'chromosome':
                                np.arange(np.shape(offSprings)[0]),
                                'Gene': kwargs['variables']
                            })
    for i in range(np.shape(offSprings)[0]):
        children[i] = copy.deepcopy(offSprings[i])
        new = list(itemgetter(*locs)(offSprings[i].values))
        for ind, element in enumerate(locs):
            if randomUtils.random(dim=1, samples=1) < kwargs['mutationProb']:
                children[i,
                         locs[0]:locs[-1] + 1] = randomUtils.randomPermutation(
                             list(offSprings.data[i, locs[0]:locs[-1] + 1]),
                             None)
    return children
Exemple #3
0
### randomIntegers(), sampling integers in a range
randomUtils.randomSeed(42,engine=None)
randomUtils.randomSeed(42,engine=eng)
right = [14,18,20,12,17]
for i in range(5):
  n = randomUtils.randomIntegers(10,20,None,engine=None) #no message handler, error handling will error out
  checkAnswer('random integer, {} sample for engine not provided'.format(i),n,right[i])

for i in range(5):
  n = randomUtils.randomIntegers(10,20,None,engine=eng) #no message handler, error handling will error out
  checkAnswer('random integer, {} sample for local engine provided'.format(i),n,right[i])
### randomPermutation(), rearranging lists
randomUtils.randomSeed(42,engine=None)
randomUtils.randomSeed(42,engine=eng)
l = [1,2,3,4,5]
l2 = randomUtils.randomPermutation(l,None,engine=None)
checkArray('random permutation for engine not provided',l2,[2,4,5,1,3])
l2 = randomUtils.randomPermutation(l,None,engine=eng)
checkArray('random permutation for local engine provided',l2,[2,4,5,1,3])
### randPointsOnHypersphere(), unit hypersphere surface sampling (aka random direction)
randomUtils.randomSeed(42,engine=None)
randomUtils.randomSeed(42,engine=eng)
## check the radius is always 1 (if not specified)
for i in range(1,6):
  pt = randomUtils.randPointsOnHypersphere(i,engine=None)
  checkAnswer('Random {}D hypersphere surface for engine not provided'.format(i),np.sum(pt*pt),1.0)
for i in range(1,6):
  pt = randomUtils.randPointsOnHypersphere(i,engine=eng)
  checkAnswer('Random {}D hypersphere surface for local engine provided'.format(i),np.sum(pt*pt),1.0)
## check the sum of the squares is always the square of the radius
randomUtils.randomSeed(42,engine=None)
vals = randomUtils.randomNormal(3, 5)
checkAnswer('randomNormal number of samples', len(vals), 5)
checkAnswer('randomNormal size of sample', len(vals[0]), 3)

### randomIntegers(), sampling integers in a range
randomUtils.randomSeed(42)
right = [14, 18, 20, 12, 17]
for i in range(5):
    n = randomUtils.randomIntegers(
        10, 20, None)  #no message handler, error handling will error out
    checkAnswer('random integer, {} sample'.format(i), n, right[i])

### randomPermutation(), rearranging lists
randomUtils.randomSeed(42)
l = [1, 2, 3, 4, 5]
l2 = randomUtils.randomPermutation(l, None)
checkArray('random permutation', l2, [2, 4, 5, 1, 3])

### randPointsOnHypersphere(), unit hypersphere surface sampling (aka random direction)
randomUtils.randomSeed(42)
## check the radius is always 1 (if not specified)
for i in range(1, 6):
    pt = randomUtils.randPointsOnHypersphere(i)
    checkAnswer('Random {}D hypersphere surface'.format(i), np.sum(pt * pt),
                1.0)
## check the sum of the squares is always the square of the radius
randomUtils.randomSeed(42)
for i in [0.2, 0.7, 1.5, 10.0, 100.0]:
    pt = randomUtils.randPointsOnHypersphere(4, r=i)
    checkAnswer('Random 4D hypersphere surface with {} radius'.format(i),
                np.sum(pt * pt), i * i)