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 """ if len(self.hybridStrategyToApply.keys()) > 0: hybridlistoflist = [] for cnt, preckey in enumerate(self.hybridStrategyToApply.keys()): hybridsampler = self.hybridStrategyToApply[preckey] hybridlistoflist.append([]) hybridsampler.initialize() self.hybridNumberSamplers *= hybridsampler.limit while hybridsampler.amIreadyToProvideAnInput(): hybridsampler.counter +=1 hybridsampler.localGenerateInput(None,None) hybridsampler.inputInfo['prefix'] = hybridsampler.counter hybridlistoflist[cnt].append(copy.deepcopy(hybridsampler.inputInfo)) if self.hybridNumberSamplers > 0: self.raiseAMessage('Number of Hybrid Samples are ' + str(self.hybridNumberSamplers) + '!') hybridNumber = self.hybridNumberSamplers combinations = list(itertools.product(*hybridlistoflist)) else: hybridNumber = 1 self.TreeInfo = {} for precSample in range(hybridNumber): elm = ETS.HierarchicalNode(self.messageHandler,self.name + '_' + str(precSample+1)) elm.add('name', self.name + '_'+ str(precSample+1)) elm.add('startTime', str(0.0)) # Initialize the endTime to be equal to the start one... # It will modified at the end of each branch elm.add('endTime', str(0.0)) elm.add('runEnded',False) elm.add('running',True) elm.add('queue',False) # if preconditioned DET, add the sampled from hybridsampler samplers if self.hybridNumberSamplers > 0: elm.add('hybridsamplerCoordinate', combinations[precSample]) for point in combinations[precSample]: for epistVar, val in point['SampledVars'].items(): self.epistemicVariables[epistVar][elm.get('name')] = val # The dictionary branchedLevel is stored in the xml tree too. That's because # the advancement of the thresholds must follow the tree structure elm.add('branchedLevel', self.branchedLevel[0]) # Here it is stored all the info regarding the DET => we create the info for all the # branchings and we store them self.TreeInfo[self.name + '_' + str(precSample+1)] = ETS.HierarchicalTree(self.messageHandler,elm) for key in self.branchProbabilities.keys(): #kk = self.toBeSampled.values().index(key) #self.branchValues[key] = [self.distDict[self.toBeSampled.keys()[self.toBeSampled.values().index(key)]].ppf(float(self.branchProbabilities[key][index])) for index in range(len(self.branchProbabilities[key]))] self.branchValues[key] = [self.distDict[key].ppf(float(self.branchProbabilities[key][index])) for index in range(len(self.branchProbabilities[key]))] for key in self.branchValues.keys(): #kk = self.toBeSampled.values().index(key) #self.branchProbabilities[key] = [self.distDict[self.toBeSampled.keys()[self.toBeSampled.values().index(key)]].cdf(float(self.branchValues[key][index])) for index in range(len(self.branchValues[key]))] self.branchProbabilities[key] = [self.distDict[key].cdf(float(self.branchValues[key][index])) for index in range(len(self.branchValues[key]))] self.limit = sys.maxsize
def localGenerateInput(self, model, myInput): """ Function to select the next most informative point for refining the limit surface search. After this method is called, the self.inputInfo should be ready to be sent to the model @ In, model, model instance, an instance of a model @ In, myInput, list, a list of the original needed inputs for the model (e.g. list of files, etc.) @ Out, None """ if self.startAdaptive == True and self.adaptiveReady == True: LimitSurfaceSearch.localGenerateInput(self, model, myInput) #the adaptive sampler created the next point sampled vars #find the closest branch if self.hybridDETstrategy is not None: closestBranch, cdfValues, treer = self._checkClosestBranch() else: closestBranch, cdfValues = self._checkClosestBranch() if closestBranch is None: self.raiseADebug( 'An usable branch for next candidate has not been found => create a parallel branch!' ) # add pbthresholds in the grid investigatedPoint = {} for key, value in cdfValues.items(): try: ind = utils.first( np.atleast_1d( np.asarray(self.branchProbabilities[key]) <= value ).nonzero())[-1] except (IndexError, ValueError): ind = 0 if value not in self.branchProbabilities[key]: self.branchProbabilities[key].insert(ind, value) self.branchValues[key].insert( ind, self.distDict[key].ppf(value)) investigatedPoint[key] = value # collect investigated point self.investigatedPoints.append(investigatedPoint) if closestBranch: info = self._retrieveBranchInfo(closestBranch) self._constructEndInfoFromBranch(model, myInput, info, cdfValues) else: # create a new tree, since there are no branches that are close enough to the adaptive request elm = ETS.HierarchicalNode( self.messageHandler, self.name + '_' + str(len(self.TreeInfo.keys()) + 1)) elm.add('name', self.name + '_' + str(len(self.TreeInfo.keys()) + 1)) elm.add('startTime', 0.0) # Initialize the endTime to be equal to the start one... # It will modified at the end of each branch elm.add('endTime', 0.0) elm.add('runEnded', False) elm.add('running', True) elm.add('queue', False) elm.add('completedHistory', False) branchedLevel = {} for key, value in cdfValues.items(): branchedLevel[key] = utils.first( np.atleast_1d( np.asarray(self.branchProbabilities[key]) == value).nonzero())[-1] # The dictionary branchedLevel is stored in the xml tree too. That's because # the advancement of the thresholds must follow the tree structure elm.add('branchedLevel', branchedLevel) if self.hybridDETstrategy is not None and not self.foundEpistemicTree: # adaptive hybrid DET and not found a tree in the epistemic space # take the first tree and modify the hybridsamplerCoordinate hybridSampled = copy.deepcopy( utils.first(self.TreeInfo.values()).getrootnode().get( 'hybridsamplerCoordinate')) for hybridStrategy in hybridSampled: for key in self.epistemicVariables.keys(): if key in hybridStrategy['SampledVars'].keys(): self.raiseADebug("epistemic var " + str(key) + " value = " + str(self.values[key])) hybridStrategy['SampledVars'][key] = copy.copy( self.values[key]) hybridStrategy['SampledVarsPb'][ key] = self.distDict[key].pdf( self.values[key]) hybridStrategy['prefix'] = len( self.TreeInfo.values()) + 1 # TODO: find a strategy to recompute the probability weight here (for now == PointProbability) hybridStrategy['PointProbability'] = reduce( mul, self.inputInfo['SampledVarsPb'].values()) hybridStrategy['ProbabilityWeight'] = reduce( mul, self.inputInfo['SampledVarsPb'].values()) elm.add('hybridsamplerCoordinate', hybridSampled) self.inputInfo.update({ 'ProbabilityWeight-' + key.strip(): value for key, value in self.inputInfo['SampledVarsPb'].items() }) # Here it is stored all the info regarding the DET => we create the info for all the branchings and we store them self.TreeInfo[self.name + '_' + str(len(self.TreeInfo.keys()) + 1)] = ETS.HierarchicalTree( self.messageHandler, elm) self._createRunningQueueBeginOne( self.TreeInfo[self.name + '_' + str(len(self.TreeInfo.keys()))], branchedLevel, model, myInput) return DynamicEventTree.localGenerateInput(self, model, myInput)