Example #1
0
def load_model(file):
    """
    load the model 
    
    :param file: the location of the .vpm file to be loaded.
    :exception: raises a :class:`~EMAExceptions.VensimError` if the model 
                cannot be loaded.
    
    .. note: only works for .vpm files
    
    """
    EMAlogging.debug("executing COMMAND: SIMULATE>SPECIAL>LOADMODEL|" + file)
    try:
        command(r"SPECIAL>LOADMODEL|" + file)
    except VensimWarning as w:
        EMAlogging.warning(str(w))
        raise VensimError("vensim file not found")
Example #2
0
def get_data(filename, varname, step=1):
    """ 
    Retrieves data from simulation runs or imported data sets. 
    
    
    :param filename: the name of the .vdf file that contains the data
    :param varname: the name of the variable to retrieve data on
    :param step: steps used in slicing. Defaults to 1, meaning the full
                 recored time series is returned.
    :return: an array with the values for varname over the simulation
    
    """

    vval = []
    try:
        vval, tval = vensimDLLwrapper.get_data(filename, varname)
    except VensimWarning as w:
        EMAlogging.warning(str(w))

    return vval
Example #3
0
def run_simulation(file):
    """ 
    Convenient function to run a model and store the results of the run in 
    the specified .vdf file. The specified output file will be overwritten 
    by default

    :param file: the location of the outputfile
    :exception: raises a :class:`~EMAExceptions.VensimError` if running 
                the model failed in some way. 
                
    """

    try:
        EMAlogging.debug(" executing COMMAND: SIMULATE>RUNNAME|" + file + "|O")
        command("SIMULATE>RUNNAME|" + file + "|O")
        EMAlogging.debug(r"MENU>RUN|o")
        command(r"MENU>RUN|o")
    except VensimWarning as w:
        EMAlogging.warning((str(w)))
        raise VensimError(str(w))
Example #4
0
def set_value(variable, value):
    """
    set the value of a variable to value
    
    current implementation only works for lookups and normal values. In case
    of a list, a lookup is assumed, else a normal value is assumed. 
    See the DSS reference supplement, p. 58 for details.

    
    :param variable: name of the variable to set.
    :param value: the value for the variable. 
                  **note**: the value can be either a list, or an float/integer. 
                  If it is a list, it is assumed the variable is a lookup.
    """

    if type(value) == types.ListType:
        command(r"SIMULATE>SETVAL|" + variable + "(" + str(value)[1:-1] + ")")
    else:
        try:
            command(r"SIMULATE>SETVAL|" + variable + "=" + str(value))
        except VensimWarning:
            EMAlogging.warning("variable: '" + variable + "' not found")
Example #5
0
    def run_model(self, case):
        """
        Method for running an instantiated model structures. This 
        implementation assumes that the names of the uncertainties correspond
        to the name of the cells in Excel. See e.g. `this site <http://spreadsheets.about.com/od/exceltips/qt/named_range.htm>`_ 
        for details or use Google and search on 'named range'. One of the 
        requirements on the names is that the cannot contains spaces. 

        For the extraction of results, the same approach is used. That is, 
        this implementation assumes that the name of a :class:`~outcomes.Outcome`
        instance corresponds to the name of a cell, or set of cells.

        :param case:    dictionary with arguments for running the model
        
        """
        #find right sheet
        try:
            sheet = self.wb.Sheets(self.sheet)
        except Exception as e:
            EMAlogging.warning("com error: sheet not found")
            self.cleanup()
            raise
        
        #set values on sheet
        for key, value in case.items():
            try:
                sheet.Range(key).Value = value 
            except com_error:
                EMAlogging.warning("com error: no cell(s) named %s found" % key,)

        #get results
        results = {}
        for outcome in self.outcomes:
            try:
                output = sheet.Range(outcome.name).Value
                try:
                    output = [value[0] for value in output]
                    output = np.array(output)
                except TypeError:
                    output = np.array(output)
                results[outcome.name] = output
            except com_error:
                EMAlogging.warning("com error: no cell(s) named %s found" % outcome.name,)
        self.output = results
Example #6
0
def worker(inqueue, 
           outqueue, 
           modelInterfaces, 
           modelInitKwargs=None):
    #
    # Code run by worker processes
    #    
        
    debug("worker started")
    
    put = outqueue.put
    get = inqueue.get
    if hasattr(inqueue, '_writer'):
        inqueue._writer.close()
        outqueue._reader.close()
    
    def cleanup(modelInterfaces):
        for msi in modelInterfaces:
            msi.cleanup()
            del msi
    

    oldPolicy = {}
    modelInitialized = False
    while 1:
        try:
            task = get()
        except (EOFError, IOError):
            debug('worker got EOFError or IOError -- exiting')
            break
        if task is None:
            debug('worker got sentinel -- exiting')
            cleanup(modelInterfaces)
            break

        job, i, case, policy = task
        for modelInterface in modelInterfaces:
            if policy != oldPolicy:
                modelInitialized = False
                try:
                    debug("invoking model init")
                    modelInterface.model_init(policy, modelInitKwargs)
                    debug("model initialized successfully")
                    modelInitialized = True
                except EMAError as e:
                    exception("init not implemented")
                    raise
                except Exception:
                    exception("some exception occurred when invoking the init")
            if modelInitialized:
                try:
                    try:
                        debug("trying to run model")
                        modelInterface.run_model(copy.deepcopy(case))
                    except CaseError as e:
                        EMAlogging.warning(e)
                    debug("trying to retrieve output")
                    result = modelInterface.retrieve_output()
                    
                    debug("trying to reset model")
                    modelInterface.reset_model()
                    result = (True, (case, policy, modelInterface.name, result))
                except Exception as e:
                    result = (False, e)
            else:
                result = (False, EMAParallelError("failure to initialize"))
            put((job, i, result))
            oldPolicy = policy