def __init__(símismo, archivo, nombre='mds'): ext = os.path.splitext(archivo)[1] if ext == '.mdl': símismo.tipo = '.mdl' símismo.mod = pysd.read_vensim(archivo) elif ext in ['.xmile', '.xml']: símismo.tipo = '.xmile' símismo.mod = pysd.read_xmile(archivo) elif ext == '.py': # Modelos PySD ya traducidos símismo.tipo = '.py' símismo.mod = pysd.load(archivo) else: raise ValueError( _('PySD no sabe leer modelos del formato "{}". Debes darle un modelo ".mdl" o ".xmile".' ).format(ext)) símismo.tipo_mod = None símismo._conv_nombres = {} símismo.tiempo_final = None símismo.cont_simul = False símismo.paso_act = 0 símismo.vars_para_cambiar = {} símismo._res_recién = None # pd.DataFrame super().__init__(archivo, nombre=nombre)
def __init__(símismo, archivo, nombre='mds'): nmbr, ext = os.path.splitext(archivo) if ext == '.mdl': símismo.tipo = '.mdl' # Únicamente recrear el archivo .py si necesario if os.path.isfile(nmbr + '.py') and (os.path.getmtime(nmbr + '.py') > os.path.getmtime(archivo)): símismo.modelo = pysd.load(nmbr + '.py') else: símismo.modelo = pysd.read_vensim(archivo) elif ext in ['.xmile', '.xml']: símismo.tipo = '.xmile' símismo.modelo = pysd.read_xmile(archivo) elif ext == '.py': # Modelos PySD ya traducidos símismo.tipo = '.py' símismo.modelo = pysd.load(archivo) else: raise ValueError( _('PySD no sabe leer modelos del formato "{}". Debes darle un modelo ".mdl" o ".xmile".' ).format(ext)) símismo._conv_nombres = {} símismo.tiempo_final = None símismo.cont_simul = False símismo.paso_act = 0 símismo.vars_para_cambiar = {} símismo._res_recién = None # pd.DataFrame super().__init__(archivo, nombre=nombre)
def runner(model_file): directory = os.path.dirname(model_file) # load model if model_file.endswith('.mdl') or model_file.endswith('.MDL'): model = pysd.read_vensim(model_file) elif model_file.endswith(".xmile"): model = pysd.read_xmile(model_file) else: raise AttributeError('Modelfile should be *.mdl or *.xmile') # load canonical output try: encoding = detect_encoding(directory + '/output.csv') canon = pd.read_csv(directory + '/output.csv', encoding=encoding, index_col='Time') except IOError: try: encoding = detect_encoding(directory + '/output.tab') canon = pd.read_table(directory + '/output.tab', encoding=encoding, index_col='Time') except IOError: raise IOError('Canonical output file not found') # run model output = model.run(return_columns=canon.columns) return output, canon
def runner(model_file): directory = os.path.dirname(model_file) # load model if model_file.endswith('.mdl'): model = pysd.read_vensim(model_file) elif model_file.endswith(".xmile"): model = pysd.read_xmile(model_file) else: raise AttributeError('Modelfile should be *.mdl or *.xmile') # load canonical output try: encoding = detect_encoding(directory + '/output.csv') canon = pd.read_csv(directory + '/output.csv', encoding=encoding, index_col='Time') except IOError: try: encoding = detect_encoding(directory + '/output.tab') canon = pd.read_table(directory + '/output.tab', encoding=encoding, index_col='Time') except IOError: raise IOError('Canonical output file not found') # run model output = model.run(return_columns=canon.columns) return output, canon
def gen_mod_pysd(archivo): nmbr, ext = os.path.splitext(archivo) if ext == '.py': return pysd.load(archivo) arch_py = nmbr + '.py' if os.path.isfile(arch_py) and arch_más_recién(arch_py, archivo): return pysd.load(nmbr + '.py') else: return pysd.read_vensim(archivo) if ext == '.mdl' else pysd.read_xmile(archivo)
def load(model_file, data_files, missing_values, split_views, **kwargs): """ Translate and load model file. Paramters --------- model_file: str Vensim, Xmile or PySD model file. data_files: list If given the list of files where the necessary data to run the model is given. missing_values : str ("warning", "error", "ignore", "keep") What to do with missing values. If "warning" (default) shows a warning message and interpolates the values. If "raise" raises an error. If "ignore" interpolates the values without showing anything. If "keep" it will keep the missing values, this option may cause the integration to fail, but it may be used to check the quality of the data. split_views: bool (optional) If True, the sketch is parsed to detect model elements in each model view, and then translate each view in a separate python file. Setting this argument to True is recommended for large models split in many different views. Default is False. **kwargs: (optional) Additional keyword arguments. subview_sep:(str) Character used to separate views and subviews. If provided, and split_views=True, each submodule will be placed inside the folder of the parent view. Returns ------- pysd.model """ if model_file.lower().endswith(".mdl"): print("\nTranslating model file...\n") return pysd.read_vensim(model_file, initialize=False, data_files=data_files, missing_values=missing_values, split_views=split_views, **kwargs) elif model_file.lower().endswith(".xmile"): print("\nTranslating model file...\n") return pysd.read_xmile(model_file, initialize=False, data_files=data_files, missing_values=missing_values) else: return pysd.load(model_file, initialize=False, data_files=data_files, missing_values=missing_values)
def runner(model_file, canonical_file=None, transpose=False, data_files=None): """ Translates and runs a model and returns its output and the canonical output. Parameters ---------- model_file: str Name of the original model file. Must be '.mdl' or '.xmile'. canonical_file: str or None (optional) Canonical output file to read. If None, will search for 'output.csv' and 'output.tab' in the model directory. Default is None. transpose: bool (optional) If True reads transposed canonical file, i.e. one variable per row. Default is False. data_files: list (optional) List of the data files needed to run the model. Returns ------- output, canon: (pandas.DataFrame, pandas.DataFrame) pandas.DataFrame of the model output and the canonical output. """ directory = os.path.dirname(model_file) # load canonical output if not canonical_file: if os.path.isfile(os.path.join(directory, 'output.csv')): canonical_file = os.path.join(directory, 'output.csv') elif os.path.isfile(os.path.join(directory, 'output.tab')): canonical_file = os.path.join(directory, 'output.tab') else: raise FileNotFoundError('\nCanonical output file not found.') canon = load_outputs(canonical_file, transpose=transpose, encoding=detect_encoding(canonical_file)) # load model if model_file.lower().endswith('.mdl'): model = read_vensim(model_file, data_files) elif model_file.lower().endswith(".xmile"): model = read_xmile(model_file, data_files) else: raise ValueError('\nModelfile should be *.mdl or *.xmile') # run model and return the result return model.run(return_columns=canon.columns), canon
def simulationHandler(self): import pysd if self.filename != '': new_name = self.filename[:-5] + ".xmile" shutil.copy(self.filename, new_name) self.model_run = pysd.read_xmile(new_name) os.remove(new_name) # os.remove(new_name[:-6]+".py") self.results = self.model_run.run() print("Simulation Finished.") self.variablesInModel = self.results.columns.values.tolist() self.variablesInModel.remove("TIME") self.comboxlist["values"] = self.variablesInModel
def _generar_mod(símismo, archivo, **ops_mód): nmbr, ext = os.path.splitext(archivo) if ext == '.py': # Modelos PySD ya traducidos símismo.tipo_mod = '.py' return pysd.load(archivo) else: if ext == '.mdl': símismo.tipo_mod = '.mdl' elif ext in ['.xmile', '.xml']: símismo.tipo_mod = '.xmile' else: raise ValueError( _('PySD no sabe leer modelos del formato "{}". Debes darle un modelo ".py", ".mdl" o ".xmile".' ).format(ext)) # Únicamente recrear el archivo .py si necesario if os.path.isfile(nmbr + '.py') and (os.path.getmtime(nmbr + '.py') > os.path.getmtime(archivo)): return pysd.load(nmbr + '.py') else: return pysd.read_vensim( archivo) if ext == '.mdl' else pysd.read_xmile(archivo)
def test_teacup(self): model = pysd.read_xmile('tests/xmile/teacup.xmile') model.run()
print "Testing module at location: %s\n"%pysd.__file__ err_str = '\n\n' threshold = 1 success_count = 0 err_count = 0 fail_count = 0 for modelfile in testfiles: #print modelfile directory = os.path.dirname(modelfile) try: if modelfile[-3:] == "mdl": model = pysd.read_vensim(modelfile) elif modelfile[-5:] == "xmile": model = pysd.read_xmile(modelfile) canon = pd.read_csv(directory+'/output.csv', index_col='Time') canon.columns = [pysd.builder.make_python_identifier(x) for x in canon.columns.values] output = model.run(return_columns=list(canon.columns.values)) assert (canon-output).max().max() < 1 print '.', success_count += 1 except ParseError as e: print 'F', err_str += '='*60 + '\n'
def test_teacup(self): model = pysd.read_xmile("tests/old_tests/xmile/teacup.xmile") model.run()
print "Testing module at location: %s\n" % pysd.__file__ err_str = '\n\n' threshold = 1 success_count = 0 err_count = 0 fail_count = 0 for modelfile in testfiles: #print modelfile directory = os.path.dirname(modelfile) try: if modelfile[-3:] == "mdl": model = pysd.read_vensim(modelfile) elif modelfile[-5:] == "xmile": model = pysd.read_xmile(modelfile) canon = pd.read_csv(directory + '/output.csv', index_col='Time') canon.columns = [ pysd.builder.make_python_identifier(x) for x in canon.columns.values ] output = model.run(return_columns=list(canon.columns.values)) assert (canon - output).max().max() < 1 print '.', success_count += 1 except ParseError as e:
pandas.reset_option('display.max_rows') numpy.set_printoptions(threshold=sys.maxsize) if len(sys.argv) != 3: print("Error: wrong number of arguments. Expected 2 but got " + str(len(sys.argv) - 1)) exit() command = sys.argv[1] modelName = sys.argv[2] print('Command is ' + modelName) print('Model file name is ' + modelName) if command == 'compileMdl': model = pysd.read_vensim(modelName) elif command == 'compileAndRunMdl': model = pysd.read_vensim(modelName) result = model.run() print_full(json.dumps(result.to_dict()), modelName) elif command == 'compileXmile': model = pysd.read_xmile(modelName) elif command == 'compileAndRunXmile': model = pysd.read_xmile(modelName) result = model.run() print_full(json.dumps(result.to_dict()), modelName) exit()