bng_runner.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 pathlib
  29. import argparse
  30. import itertools
  31. import multiprocessing
  32. import re
  33. import subprocess
  34. from mcell4_runner import file_markers_start, file_markers_finish, generate_seeds
  35. TEST_BNGL = 'test.bngl'
  36. class Options:
  37. def __init__(self):
  38. self.seeds_str = None
  39. self.bng2pl_path = None
  40. self.max_cores = None
  41. self.main_model_file = None
  42. def create_argparse():
  43. parser = argparse.ArgumentParser(description='MCell4 Runner')
  44. parser.add_argument(
  45. '-s', '--seeds', type=str,
  46. help='seeds in the form first:last:step, e.g. 1:100:2 will use seeds 1 through 100 in steps of 2, '
  47. 'model must accept "-seed N" argument, '
  48. 'the output directories are different for different seeds, ODE model ignores this argument')
  49. parser.add_argument('-j', '--max-cores', type=int,
  50. help='sets maximum number of cores for running, default is all if -j is not used')
  51. parser.add_argument('-b', '--bng2pl', type=str,
  52. help='sets path to BNG2.pl')
  53. parser.add_argument('main_model_file',
  54. help='sets path to the BNGL model')
  55. return parser
  56. def process_opts():
  57. parser = create_argparse()
  58. args = parser.parse_args()
  59. opts = Options()
  60. if args.seeds:
  61. opts.seeds_str = args.seeds
  62. else:
  63. print("Error: argument -s/--seeds must be specified.")
  64. sys.exit(1)
  65. if args.bng2pl:
  66. if os.path.exists(args.bng2pl):
  67. opts.bng2pl_path = args.bng2pl
  68. else:
  69. print("Error: file " + args.bng2pl + " does not exist.")
  70. sys.exit(1)
  71. else:
  72. print("Error: argument -b/--bng2pl must be specified.")
  73. sys.exit(1)
  74. if args.max_cores:
  75. opts.max_cores = args.max_cores
  76. if args.main_model_file:
  77. if os.path.exists(args.main_model_file):
  78. opts.main_model_file = args.main_model_file
  79. else:
  80. print("Error: file " + args.main_model_file + " does not exist.")
  81. sys.exit(1)
  82. else:
  83. print("Error: main model file must be specified as a positional argument.")
  84. sys.exit(1)
  85. return opts
  86. def run_bng(abs_dir, opts):
  87. os.chdir(abs_dir)
  88. cmd_str = 'perl ' + opts.bng2pl_path + ' ' + TEST_BNGL
  89. print("Running " + cmd_str + " in " + abs_dir)
  90. log_name = opts.main_model_file + '_' + os.path.basename(abs_dir) + '.bng2pl.log'
  91. exit_code = 1
  92. with open(log_name, "w") as f:
  93. proc = subprocess.Popen(cmd_str, shell=True, cwd=os.getcwd(), stdout=f, stderr=subprocess.STDOUT)
  94. proc.communicate()
  95. exit_code = proc.returncode
  96. with open(log_name, "a") as f:
  97. f.write("DIR:" + os.getcwd() + "\n")
  98. f.write("CMD:" + cmd_str + "\n")
  99. if exit_code != 0:
  100. print("BNG2.pl failed, see '" + os.path.join(os.getcwd(), log_name) + "'.")
  101. return exit_code
  102. else:
  103. return 0
  104. def find_in_file(fname, search_for):
  105. lines = []
  106. with open(fname, "r") as infile:
  107. for line in infile:
  108. if search_for in line:
  109. return line
  110. return ''
  111. def replace_in_file(fname, search_for, replace_with):
  112. lines = []
  113. with open(fname, "r") as infile:
  114. for line in infile:
  115. line = line.replace(search_for, replace_with)
  116. lines.append(line)
  117. with open(fname, "w") as outfile:
  118. for line in lines:
  119. outfile.write(line)
  120. def run_bng_parallel(opts, seeds):
  121. # nfsim or ode?
  122. # does not handle comments
  123. line_nf = find_in_file(opts.main_model_file, 'method=>"nf"')
  124. line_ssa = find_in_file(opts.main_model_file, 'method=>"ssa"')
  125. if not line_nf and not line_ssa:
  126. # ODE
  127. dir = os.path.join('bng', 'ode')
  128. os.makedirs(dir)
  129. shutil.copy(TEST_BNGL, dir)
  130. run_bng(dir, opts)
  131. else:
  132. # NFSim - multiple runs are needed
  133. cwd = os.getcwd()
  134. dirs = []
  135. for s in seeds:
  136. dir = os.path.join('bng', 'nf_' + str(s).zfill(5))
  137. if not os.path.exists(dir):
  138. os.makedirs(dir)
  139. shutil.copy(opts.main_model_file, os.path.join(dir, TEST_BNGL))
  140. # copy also all other .bngl files from the main file's directory
  141. files = glob.iglob(os.path.join(os.path.dirname(opts.main_model_file), "*.bngl"))
  142. for file in files:
  143. if file != opts.main_model_file and os.path.isfile(file):
  144. shutil.copy2(file, dir)
  145. # update seed value
  146. replace_in_file(os.path.join(dir, TEST_BNGL), 'seed=>1', 'seed=>' + str(s))
  147. dirs.append(os.path.join(cwd, dir))
  148. if opts.max_cores:
  149. # maximum number of processes specified
  150. cpu_count = int(opts.max_cores)
  151. else:
  152. cpu_count = multiprocessing.cpu_count()
  153. pool = multiprocessing.Pool(processes=cpu_count)
  154. # run in parallel
  155. res_codes = pool.starmap(run_bng, zip(dirs, itertools.repeat(opts)), 1)
  156. num_total = 0
  157. num_failed = 0
  158. for i in range(len(res_codes)):
  159. c = res_codes[i]
  160. if c != 0:
  161. print("BNG run with seed '" + str(seeds[i]) + "' failed with exit code " + str(c) + ".")
  162. num_failed += 1
  163. if num_failed == 0:
  164. print("Finished, all runs passed.")
  165. return 0
  166. else:
  167. print("Finished with errors, " + str(num_failed) + "/" + str(num_total) + " runs failed.")
  168. return 1
  169. if __name__ == '__main__':
  170. file_markers_start()
  171. opts = process_opts()
  172. seeds = generate_seeds(opts.seeds_str)
  173. exit_code = run_bng_parallel(opts, seeds)
  174. file_markers_finish()
  175. sys.exit(exit_code)