コード例 #1
0
 def __init__(self, runInfoDict):
     """
   Constructor
   @ In, runInfoDict, dict, the dictionary containing the runInfo (read in the XML input file)
   @ Out, None
 """
     Dummy.__init__(self, runInfoDict)
     self.sim = None
     self.modelVariableValues = {
     }  # dictionary of variable values for the external module imported at runtime
     self.modelVariableType = {
     }  # dictionary of variable types, used for consistency checks
     self.listOfRavenAwareVars = [
     ]  # list of variables RAVEN needs to be aware of
     self._availableVariableTypes = [
         'float', 'bool', 'int', 'ndarray', 'c1darray', 'float16',
         'float32', 'float64', 'float128', 'int16', 'int32', 'int64',
         'bool8'
     ]  # available data types
     self._availableVariableTypes = self._availableVariableTypes + [
         'numpy.' + item for item in self._availableVariableTypes
     ]  # as above
     self.printTag = 'EXTERNAL MODEL'
     self.initExtSelf = utils.Object()
     self.workingDir = runInfoDict['WorkingDir']
コード例 #2
0
 def _externalRun(self, Input, modelVariables):
     """
   Method that performs the actual run of the imported external model (separated from run method for parallelization purposes)
   @ In, Input, list, list of the inputs needed for running the model
   @ In, modelVariables, dict, the dictionary containing all the External Model variables
   @ Out, (outcomes,self), tuple, tuple containing the dictionary of the results (pos 0) and the self (pos 1)
 """
     externalSelf = utils.Object()
     #self.sim=__import__(self.ModuleToLoad)
     modelVariableValues = {}
     for key in self.modelVariableType.keys():
         modelVariableValues[key] = None
     for key, value in self.initExtSelf.__dict__.items():
         CustomCommandExecuter.execCommand(
             'self.' + key + ' = copy.copy(object)',
             self=externalSelf,
             object=value
         )  # exec('externalSelf.'+ key +' = copy.copy(value)')
         modelVariableValues[key] = copy.copy(value)
     for key in Input.keys():
         if key in modelVariableValues.keys():
             modelVariableValues[key] = copy.copy(Input[key])
     if 'createNewInput' not in dir(self.sim):
         InputDict = {}
     else:
         InputDict = Input
     #if 'createNewInput' not in dir(self.sim):
     for key in Input.keys():
         if key in modelVariables.keys():
             modelVariableValues[key] = copy.copy(Input[key])
     for key in self.modelVariableType.keys():
         CustomCommandExecuter.execCommand(
             'self.' + key + ' = copy.copy(object["' + key + '"])',
             self=externalSelf,
             object=modelVariableValues
         )  #exec('externalSelf.'+ key +' = copy.copy(modelVariableValues[key])')  #self.__uploadSolution()
     #else:
     #  InputDict = Input
     # only pass the variables and their values according to the model itself.
     for key in Input.keys():
         if key in self.modelVariableType.keys():
             InputDict[key] = Input[key]
     self.sim.run(externalSelf, InputDict)
     for key in self.modelVariableType.keys():
         CustomCommandExecuter.execCommand(
             'object["' + key + '"]  = copy.copy(self.' + key + ')',
             self=externalSelf,
             object=modelVariableValues
         )  #exec('modelVariableValues[key]  = copy.copy(externalSelf.'+key+')') #self.__pointSolution()
     for key in self.initExtSelf.__dict__.keys():
         CustomCommandExecuter.execCommand(
             'self.' + key + ' = copy.copy(object.' + key + ')',
             self=self.initExtSelf,
             object=externalSelf
         )  #exec('self.initExtSelf.' +key+' = copy.copy(externalSelf.'+key+')')
     if None in self.modelVariableType.values():
         errorFound = False
         for key in self.modelVariableType.keys():
             self.modelVariableType[key] = type(
                 modelVariableValues[key]).__name__
             if self.modelVariableType[
                     key] not in self._availableVariableTypes:
                 if not errorFound:
                     self.raiseADebug(
                         'Unsupported type found. Available ones are: ' +
                         str(self._availableVariableTypes).replace(
                             '[', '').replace(']', ''),
                         verbosity='silent')
                 errorFound = True
                 self.raiseADebug('variable ' + key +
                                  ' has an unsupported type -> ' +
                                  self.modelVariableType[key],
                                  verbosity='silent')
         if errorFound:
             self.raiseAnError(RuntimeError, 'Errors detected. See above!!')
     outcomes = dict(
         (k, modelVariableValues[k]) for k in self.listOfRavenAwareVars)
     # check type consistency... This is needed in order to keep under control the external model... In order to avoid problems in collecting the outputs in our internal structures
     for key in self.modelVariableType.keys():
         if not (utils.typeMatch(outcomes[key],
                                 self.modelVariableType[key])):
             self.raiseAnError(
                 RuntimeError, 'type of variable ' + key + ' is ' +
                 str(type(outcomes[key])) +
                 ' and mismatches with respect to the input ones (' +
                 self.modelVariableType[key] + ')!!!')
     self._replaceVariablesNamesWithAliasSystem(outcomes, 'inout', True)
     return outcomes, self
コード例 #3
0
ファイル: ExternalModel.py プロジェクト: dylanjm/raven
  def _externalRun(self, Input, modelVariables):
    """
      Method that performs the actual run of the imported external model (separated from run method for parallelization purposes)
      @ In, Input, list, list of the inputs needed for running the model
      @ In, modelVariables, dict, the dictionary containing all the External Model variables
      @ Out, (outcomes,self), tuple, tuple containing the dictionary of the results (pos 0) and the self (pos 1)
    """
    externalSelf        = utils.Object()
    #self.sim=__import__(self.ModuleToLoad)
    modelVariableValues = {}
    for key in self.modelVariableType.keys():
      modelVariableValues[key] = None
    for key, value in self.initExtSelf.__dict__.items():
      CustomCommandExecuter.execCommand('self.'+ key +' = copy.copy(object)',self=externalSelf,object=value)  # exec('externalSelf.'+ key +' = copy.copy(value)')
      modelVariableValues[key] = copy.copy(value)
    for key in Input.keys():
      if key in modelVariableValues.keys():
        modelVariableValues[key] = copy.copy(Input[key])
    if 'createNewInput' not in dir(self.sim):
      InputDict = {}
    else:
      InputDict = Input
    #if 'createNewInput' not in dir(self.sim):
    additionalKeys = []
    if '_indexMap' in Input.keys():
      additionalKeys.append('_indexMap')
    for key in Input.keys():
      if key in modelVariables.keys() or key in additionalKeys:
        modelVariableValues[key] = copy.copy(Input[key])
    for key in list(self.modelVariableType.keys()) + additionalKeys:
      # add the variable as a member of "self"
      try:
        CustomCommandExecuter.execCommand('self.'+ key +' = copy.copy(object["'+key+'"])',self=externalSelf,object=modelVariableValues) #exec('externalSelf.'+ key +' = copy.copy(modelVariableValues[key])')  #self.__uploadSolution()
      # if variable name is too strange to be a member of "self", then skip it
      except SyntaxError:
        self.raiseAWarning('Variable "{}" could not be added to "self" due to complex name.  Find it in "Inputs" dictionary instead.'.format(key))
    #else:
    #  InputDict = Input
    # only pass the variables and their values according to the model itself.
    for key in Input.keys():
      if key in self.modelVariableType.keys() or key in additionalKeys:
        InputDict[key] = Input[key]

    self.sim.run(externalSelf, InputDict)

    for key in self.modelVariableType:
      try:
        # Note, the following string can't be converted using {} formatting, at least as far as I can tell.
        CustomCommandExecuter.execCommand('object["'+key+'"]  = copy.copy(self.'+key+')', self=externalSelf,object=modelVariableValues) #exec('modelVariableValues[key]  = copy.copy(externalSelf.'+key+')') #self.__pointSolution()
      except (SyntaxError, AttributeError):
        self.raiseAWarning('Variable "{}" cannot be read from "self" due to complex name.  Retaining original value.'.format(key))
    for key in self.initExtSelf.__dict__.keys():
      # Note, the following string can't be converted using {} formatting, at least as far as I can tell.
      CustomCommandExecuter.execCommand('self.' +key+' = copy.copy(object.'+key+')', self=self.initExtSelf, object=externalSelf) #exec('self.initExtSelf.' +key+' = copy.copy(externalSelf.'+key+')')
    if None in self.modelVariableType.values():
      errorFound = False
      for key in self.modelVariableType:
        self.modelVariableType[key] = type(modelVariableValues[key]).__name__
        if self.modelVariableType[key] not in self._availableVariableTypes:
          if not errorFound:
            self.raiseADebug('Unsupported type found. Available ones are: '+ str(self._availableVariableTypes).replace('[','').replace(']', ''),verbosity='silent')
          errorFound = True
          self.raiseADebug('variable '+ key+' has an unsupported type -> '+ self.modelVariableType[key],verbosity='silent')
      if errorFound:
        self.raiseAnError(RuntimeError, 'Errors detected. See above!!')
    outcomes = dict((k, modelVariableValues[k]) for k in self.listOfRavenAwareVars)
    # check type consistency... This is needed in order to keep under control the external model... In order to avoid problems in collecting the outputs in our internal structures
    for key in self.modelVariableType:
      if not utils.typeMatch(outcomes[key], self.modelVariableType[key]):
        self.raiseAnError(RuntimeError, 'type of variable '+ key + ' is ' + str(type(outcomes[key]))+' and mismatches with respect to the input ones (' + self.modelVariableType[key] +')!!!')
    self._replaceVariablesNamesWithAliasSystem(outcomes, 'inout', True)
    # add the indexMap, if provided
    indexMap = getattr(externalSelf, '_indexMap', None)
    if indexMap:
      outcomes['_indexMap'] = indexMap
    # TODO slow conversion, but provides type consistency --> TODO this doesn't mach up well with other models!
    outcomes = dict((k, np.atleast_1d(val)) for k, val in outcomes.items())
    return outcomes, self