runner.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. """Run objsim simulations from python.
  3. """
  4. import os
  5. import subprocess
  6. import shutil
  7. class ObjsimRunner(object):
  8. """Run objsim simulations from python.
  9. """
  10. def __init__(self, binary):
  11. self.binary = binary
  12. self.working_dir = os.path.dirname(self.binary)
  13. self.process = None
  14. def run(self, datadir, fname_default_settings, mod_settings):
  15. """Run objsim simulation.
  16. Args:
  17. datadir: dir for simulation data
  18. fname_default_settings: file name for .cfg file with default settings
  19. mod_settings: list with modifications to default settings (see example)
  20. Example:
  21. >>> from objsimpy.config import SIMDATA_BASE_DIR, OBJSIM_DIR
  22. >>> datadir = os.path.join(SIMDATA_BASE_DIR, 'csim', 'som02', 'tune_map_0')
  23. >>> changed_settings = ['--NTrials', '2',
  24. '--NSteps', '50',
  25. '--StimFileName', 'gauss20x20'
  26. ]
  27. >>> som02_binary = os.path.join(OBJSIM_DIR, 'install', 'bin', 'som02', 'som02')
  28. >>> som02 = ObjsimRunner(som02_binary)
  29. >>> som02.run(datadir, default_settings_file, changed_settings)
  30. """
  31. if not os.path.isdir(datadir):
  32. os.mkdir(datadir)
  33. self.datadir = datadir
  34. fname_settings = os.path.join(self.working_dir, 'settings_' + os.path.basename(self.binary) + '.cfg')
  35. shutil.copy(fname_default_settings, fname_settings)
  36. fname_outfile = os.path.join(datadir, 'output.txt')
  37. fname_errfile = os.path.join(datadir, 'error.txt')
  38. with open(fname_outfile, 'w') as fout, open(fname_errfile, 'w') as ferr:
  39. cmd = [self.binary,
  40. '--DataDirectory', datadir]
  41. cmd += mod_settings
  42. self.process = subprocess.Popen(cmd, stdout=fout, stderr=ferr, cwd=self.working_dir)
  43. def is_running(self):
  44. return self.process.poll() is None
  45. def stop(self):
  46. """Kill simulation."""
  47. self.process.kill()