# -*- coding: utf-8 -*- """Run objsim simulations from python. """ import os import subprocess import shutil class ObjsimRunner(object): """Run objsim simulations from python. """ def __init__(self, binary): self.binary = binary self.working_dir = os.path.dirname(self.binary) self.process = None def run(self, datadir, fname_default_settings, mod_settings): """Run objsim simulation. Args: datadir: dir for simulation data fname_default_settings: file name for .cfg file with default settings mod_settings: list with modifications to default settings (see example) Example: >>> from objsimpy.config import SIMDATA_BASE_DIR, OBJSIM_DIR >>> datadir = os.path.join(SIMDATA_BASE_DIR, 'csim', 'som02', 'tune_map_0') >>> changed_settings = ['--NTrials', '2', '--NSteps', '50', '--StimFileName', 'gauss20x20' ] >>> som02_binary = os.path.join(OBJSIM_DIR, 'install', 'bin', 'som02', 'som02') >>> som02 = ObjsimRunner(som02_binary) >>> som02.run(datadir, default_settings_file, changed_settings) """ if not os.path.isdir(datadir): os.mkdir(datadir) self.datadir = datadir fname_settings = os.path.join(self.working_dir, 'settings_' + os.path.basename(self.binary) + '.cfg') shutil.copy(fname_default_settings, fname_settings) fname_outfile = os.path.join(datadir, 'output.txt') fname_errfile = os.path.join(datadir, 'error.txt') with open(fname_outfile, 'w') as fout, open(fname_errfile, 'w') as ferr: cmd = [self.binary, '--DataDirectory', datadir] cmd += mod_settings self.process = subprocess.Popen(cmd, stdout=fout, stderr=ferr, cwd=self.working_dir) def is_running(self): return self.process.poll() is None def stop(self): """Kill simulation.""" self.process.kill()