mcell4_runner.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #!/usr/bin/env python
  2. """
  3. This is free and unencumbered software released into the public domain.
  4. Anyone is free to copy, modify, publish, use, compile, sell, or
  5. distribute this software, either in source code form or as a compiled
  6. binary, for any purpose, commercial or non-commercial, and by any
  7. means.
  8. In jurisdictions that recognize copyright laws, the author or authors
  9. of this software dedicate any and all copyright interest in the
  10. software to the public domain. We make this dedication for the benefit
  11. of the public at large and to the detriment of our heirs and
  12. successors. We intend this dedication to be an overt act of
  13. relinquishment in perpetuity of all present and future rights to this
  14. software under copyright law.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  19. OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  20. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  21. OTHER DEALINGS IN THE SOFTWARE.
  22. For more information, please refer to [http://unlicense.org]
  23. """
  24. import os
  25. import sys
  26. import shutil
  27. import glob
  28. import argparse
  29. import itertools
  30. import multiprocessing
  31. import re
  32. import subprocess
  33. MCELL_PATH = ''
  34. RUNNING_MARKER = 'running.marker'
  35. FINISHED_MARKER = 'finished.marker'
  36. LOGS_DIR = 'logs'
  37. class Options:
  38. def __init__(self):
  39. self.seeds_str = None
  40. self.extra_arg = ''
  41. self.args_file = None
  42. self.max_cores = None
  43. self.main_model_file = None
  44. def create_argparse(name):
  45. parser = argparse.ArgumentParser(description=name + ' Runner')
  46. parser.add_argument(
  47. '-s', '--seeds', type=str,
  48. help='seeds in the form first:last:step, e.g. 1:100:2 will use seeds 1 through 100 in steps of 2, '
  49. 'model must accept "-seed N" argument, '
  50. 'model must make sure that the output directories are different for different seeds, '
  51. 'can be used with argument -x')
  52. parser.add_argument(
  53. '-x', '--extra-arg', type=str,
  54. help='optional extra argument to be passed when -s is used')
  55. parser.add_argument(
  56. '-a', '--args-file', type=str,
  57. help='arguments file where each line contains arguments passed to the main model file, '
  58. 'model must make sure that the output directories are different for different arguments')
  59. parser.add_argument('-j', '--max-cores', type=int,
  60. help='sets maximum number of cores for running, default is all if -j is not used')
  61. parser.add_argument('main_model_file',
  62. help='sets path to the MCell4 model')
  63. return parser
  64. def process_opts(name = 'MCell4'):
  65. parser = create_argparse(name)
  66. args = parser.parse_args()
  67. opts = Options()
  68. if args.seeds and args.args_file:
  69. sys.exit("Error: only one argument -s/--seeds or -a/--args-file must be specified, not both.")
  70. if not args.seeds and not args.args_file:
  71. sys.exit("Error: one of arguments -s/--seeds or -a/--args-file must be specified.")
  72. if args.seeds:
  73. opts.seeds_str = args.seeds
  74. if args.extra_arg:
  75. opts.extra_arg = args.extra_arg
  76. if args.args_file:
  77. if os.path.exists(args.args_file):
  78. opts.args_file = args.args_file
  79. else:
  80. sys.exit("Error: file " + args.args_file + " does not exist.")
  81. if args.extra_arg:
  82. sys.exit("Error: argument -x/-extra-args cannot be used with -a/--args-file.")
  83. if args.max_cores:
  84. opts.max_cores = args.max_cores
  85. if args.main_model_file:
  86. if os.path.exists(args.main_model_file):
  87. opts.main_model_file = args.main_model_file
  88. else:
  89. sys.exit("Error: file " + args.main_model_file + " does not exist.")
  90. else:
  91. sys.exit("Error: main model file must be specified as a positional argument.")
  92. return opts
  93. def check_prerequisites():
  94. global MCELL_PATH
  95. MCELL_PATH = os.environ.get('MCELL_PATH', '')
  96. if MCELL_PATH:
  97. sys.path.append(os.path.join(MCELL_PATH, 'lib'))
  98. else:
  99. sys.exit("Error: system variable MCELL_PATH that is used to find the mcell library was not set.")
  100. if os.name == 'nt':
  101. ext = '.pyd'
  102. else:
  103. ext = '.so'
  104. mcell_so_path = os.path.join(MCELL_PATH, 'lib', 'mcell' + ext)
  105. if not os.path.exists(mcell_so_path):
  106. sys.exit("Could not find library '" + mcell_so_path + ".")
  107. def generate_seeds(seeds_str):
  108. seeds_info = seeds_str.split(':')
  109. if len(seeds_info) != 3 or \
  110. not seeds_info[0].isdigit() or \
  111. not seeds_info[1].isdigit() or \
  112. not seeds_info[2].isdigit():
  113. sys.exit("Error: invalid seed string, must be in for form min:max:step, given '" + seeds_str + "'.")
  114. res = []
  115. for i in range(int(seeds_info[0]), int(seeds_info[1]) + 1, int(seeds_info[2])):
  116. res.append(i)
  117. return res
  118. def prepare_args(opts):
  119. if opts.seeds_str:
  120. seeds = generate_seeds(opts.seeds_str)
  121. return ['-seed ' + str(i) + ' ' + opts.extra_arg for i in seeds ]
  122. elif opts.args_file:
  123. res = []
  124. with open(opts.args_file, 'r') as f:
  125. for line in f:
  126. if not line.isspace():
  127. if line.endswith('\n'):
  128. res.append(line[:-1])
  129. else:
  130. res.append(line[:-1])
  131. return res
  132. def run_mcell4(args_str_w_opts):
  133. args_str = args_str_w_opts[0]
  134. opts = args_str_w_opts[1]
  135. cmd_str = sys.executable + ' ' + opts.main_model_file + ' '
  136. cmd_str += args_str
  137. print("Running " + cmd_str)
  138. args_log = args_str.replace(' ', '_').replace('-', '_').replace('\\', '_').replace('/', '_')
  139. log_name = os.path.join(
  140. LOGS_DIR,
  141. os.path.splitext(os.path.basename(opts.main_model_file))[0] + '_' + args_log + '.mcell4.log')
  142. with open(log_name, "w") as f:
  143. f.write("DIR:" + os.getcwd() + "\n")
  144. f.write("CMD:" + cmd_str + "\n")
  145. exit_code = 1
  146. with open(log_name, "a") as f:
  147. proc = subprocess.Popen(cmd_str, shell=True, cwd=os.getcwd(), stdout=f, stderr=subprocess.STDOUT)
  148. proc.communicate()
  149. exit_code = proc.returncode
  150. if exit_code != 0:
  151. print("MCell4 failed, see '" + os.path.join(os.getcwd(), log_name) + "'.")
  152. return exit_code
  153. else:
  154. return 0
  155. def run_mcell4_parallel(opts, args):
  156. # set up the parallel task pool to use all available processors ot the
  157. # maximum specified
  158. if opts.max_cores:
  159. cpu_count = int(opts.max_cores)
  160. else:
  161. cpu_count = multiprocessing.cpu_count()
  162. # create logs directory
  163. if not os.path.exists(LOGS_DIR):
  164. os.mkdir(LOGS_DIR)
  165. # run the jobs
  166. pool = multiprocessing.Pool(processes=cpu_count)
  167. args_str_w_opts = zip(args, itertools.repeat(opts))
  168. res_codes = pool.map(run_mcell4, args_str_w_opts, 1)
  169. num_total = 0
  170. num_failed = 0
  171. for i in range(len(res_codes)):
  172. c = res_codes[i]
  173. if c != 0:
  174. print("MCell run with args '" + args[i] + "' failed with exit code " + str(c) + ".")
  175. num_failed += 1
  176. num_total += 1
  177. if num_failed == 0:
  178. print("Finished, all runs passed.")
  179. return 0
  180. else:
  181. print("Finished with errors, " + str(num_failed) + "/" + str(num_total) + " runs failed.")
  182. return 1
  183. def my_touch(fname):
  184. # emulates 'touch', pathlib.Path(FINISHED_MARKER).touch() may not be available
  185. try:
  186. if os.path.exists(fname):
  187. os.utime(fname, None)
  188. else:
  189. open(fname, 'a').close()
  190. except:
  191. print("Warning: could not 'touch' file " + fname + ".")
  192. def file_markers_start():
  193. if (os.path.exists(FINISHED_MARKER)):
  194. os.remove(FINISHED_MARKER)
  195. my_touch(RUNNING_MARKER)
  196. def file_markers_finish():
  197. if (os.path.exists(RUNNING_MARKER)):
  198. os.remove(RUNNING_MARKER)
  199. my_touch(FINISHED_MARKER)
  200. if __name__ == '__main__':
  201. file_markers_start()
  202. check_prerequisites()
  203. opts = process_opts()
  204. args = prepare_args(opts)
  205. exit_code = run_mcell4_parallel(opts, args)
  206. file_markers_finish()
  207. sys.exit(exit_code)