def grab_cinder_dat(build_dir="", datapath=''): """Grabs the cinder.dat file from the DATAPATH directory if not already present.""" build_filename = os.path.join(build_dir, 'cinder.dat') if os.path.exists(build_filename): return True if isinstance(datapath, basestring) and 0 < len(datapath): pass elif 'DATAPATH' in os.environ: datapath = os.environ['DATAPATH'] else: print failure( "DATAPATH not defined in environment; cinder.dat not found - skipping." ) return False local_filename = os.path.join(datapath, "[Cc][Ii][Nn][Dd][Ee][Rr].[Dd][Aa][Tt]") local_filename = glob(local_filename) if 0 < len(local_filename): print "Grabbing cinder.dat from " + datapath shutil.copy(local_filename[0], build_filename) rtn = True else: print failure("cinder.dat file not found in DATAPATH dir - skipping.") rtn = False return rtn
def pid(self): """Finds the process id for a currently running char instance.""" if self.env['options'].LOCAL: rflag = '' spout = subprocess.check_output("ps ux | grep {0}".format(self.n_code.run_str), shell=True) else: rflag = 'Remote ' try: spout = subprocess.check_output("ssh {rc.user}@{rc.url} 'ps ux | grep {0}'".format( self.n_code.run_str, rc=self.env.remote_connection), shell=True) except NameError: if 0 < self.env['verbosity']: print(failure(remote_err_msg)) spout = spout.split('\n')[:-1] if len(spout) < 1: if 0 < self.env['verbosity']: print(message("{0}Process Not Running.".format(rflag))) raise SystemExit self.pid = spout[0].split()[1] self.prt = spout[0].split()[9] if 0 < self.env['verbosity']: print(message("{0}Process ID: {1}".format(rflag, self.pid))) print(message("{0}Process Runtime: {1} min.".format(rflag, self.prt))) raise SystemExit
def run_remotely(self): """Runs the transport calculation on a remote machine""" if 0 < self.env['verbosity']: print(message("Copying files to remote server.")) rs = self.env['run_script'] rc = self.env['remote_connection'] try: # Make remote directory, if it isn't already there rc.run("mkdir -p {rc.dir}".format(rc=rc)) # Remove the current contents of the remote directory rc.run("rm -r {rc.dir}*".format(rc=rc)) # Put all appropriate files in reomte dir rc.put(rs, rc.dir + rs) for inputfile in self.n_code.place_remote_files: print(inputfile) rc.put(inputfile, rc.dir + inputfile) # Run char rc.run("source /etc/profile; cd {rc.dir}; ./{rs} > run.log 2>&1 &".format(rc=rc, rs=rs)) if 0 < self.env['verbosity']: print(message("Running transport code remotely.")) except NameError: if 0 < self.env['verbosity']: print(failure(remote_err_msg)) # My work here is done raise SystemExit
def pid(self): """Finds the process id for a currently running char instance.""" if self.env['options'].LOCAL: rflag = '' spout = subprocess.check_output("qstat -u {0}| grep {1}".format(os.getlogin(), self.n_code.run_str), shell=True) else: rflag = 'Remote ' try: spout = subprocess.check_output("ssh {rc.user}@{rc.url} 'qstat -u {rc.user}'".format(rc=rc), shell=True) except NameError: if 0 < self.env['verbosity']: print(failure(remote_err_msg)) spout = spout.split('\n') if len(spout) < 2: if 0 < self.env['verbosity']: print(message("{0}Process Not Running.".format(rflag))) raise SystemExit spout = spout[-2].split() self.pid = spout[0].partition('.')[0] self.prt = spout[-1] if 0 < self.env['verbosity']: print(message("{0}Process ID: {1}".format(rflag, self.pid))) print(message("{0}Process Runtime: {1} min.".format(rflag, self.prt))) raise SystemExit
def fetch(self): """Fetches files from remote server.""" if 0 < self.env['verbosity']: print(message("Fetching files from remote server.")) try: for outputfile in self.n_code.fetch_remote_files: self.env['remote_connection'].get(self.env.remote_connection.dir + outputfile, ".") except NameError: if 0 < self.env['verbosity']: print(failure(remote_err_msg)) raise SystemExit
def run_ui(): """Runs the cross section user interface.""" # Test to see if ui library is installed try: from bright.xsgen.ui import app except ImportError: sys.exit(failure("Please install the Enthought Tool Suite (ETS) for CHAR UI.")) # Open UI application = app.Application() application.configure_traits() # Clean-up UI if application.rx_h5 is not None: application.rx_h5.close() sys.exit()
def grab_cinder_dat(build_dir="", datapath=''): """Grabs the cinder.dat file from the DATAPATH directory if not already present.""" build_filename = os.path.join(build_dir, 'cinder.dat') if os.path.exists(build_filename): return True if isinstance(datapath, basestring) and 0 < len(datapath): pass elif 'DATAPATH' in os.environ: datapath = os.environ['DATAPATH'] else: print failure("DATAPATH not defined in environment; cinder.dat not found - skipping.") return False local_filename = os.path.join(datapath, "[Cc][Ii][Nn][Dd][Ee][Rr].[Dd][Aa][Tt]") local_filename = glob(local_filename) if 0 < len(local_filename): print "Grabing cinder.dat from " + datapath shutil.copy(local_filename[0], build_filename) rtn = True else: print failure("cinder.dat file not found in DATAPATH dir - skipping.") rtn = False return rtn
def _ensure_inp(self, rc): "Grab the initial nuclide perturbation." max_mass = 0.0 initial_nuc_keys = [] for key in rc: m = INITIAL_NUC_RE.match(key) if m is None: continue rc_initial_nuc = getattr(rc, key) rc_initial_nuc = np.atleast_1d(rc_initial_nuc) setattr(rc, key, rc_initial_nuc) initial_nuc_keys.append(key) max_mass += np.max(rc_initial_nuc) initial_nuc_keys.sort() rc.initial_nuc_keys = initial_nuc_keys if 1.0 < max_mass: msg = "The maxium mass of initial heavy metal perturbations exceeds 1.0 kg!" sys.exit(failure(msg))
def test_failure(): if os.name is 'posix': assert_equal('\033[1;31mWorld\033[0m', utils.failure('World')) else: assert_equal('*** FAILURE ***: World', utils.failure('World'))
def main(): ########################### ### Command Line Parser ### ########################### usage = "usage: %prog [options] confchar" parser = OptionParser(usage) parser.add_option("-v", "--verbose", action="store_true", dest="VERBOSE", default=False, help="Gives extra info while running.") parser.add_option("-i", "--input", action="store_true", dest="MAKE_INPUT", help="Makes the transport calculation input deck.") parser.add_option("-r", "--run", action="store_true", dest="RUN_TRANSPORT", default=False, help="Run the transport calculation.") parser.add_option("-d", "--dry-run", action="store_false", dest="RUN_TRANSPORT", help="Dry Run. Do NOT run the transport calculation.") parser.add_option("-a", "--analyze", action="store_true", dest="RUN_ANALYSIS", default=False, help="Run analysis on database.") parser.add_option("-b", "--burnup", action="store_true", dest="RUN_BURNUP", default=False, help="Run the burnup calculation.") parser.add_option("-x", "--xs", action="store_true", dest="RUN_XS_GEN", default=False, help="Run the cross-section generation calculation.") parser.add_option("-m", "--delta-mass", action="store_true", dest="RUN_DELTAM", default=False, help="Run the initial nuclide sensitivity calculation.") parser.add_option("-N", action="store", dest="NPERT", default='', help="Pertubation indices to calculate, in Python slice syntax.") parser.add_option("-I", action="store", dest="ISOS", default='', help="Nuclides to calculate.") parser.add_option("-S", action="store", dest="NSENS", default='', help="Sensitivity indices to calculate, in Python slice syntax.") parser.add_option("-c", "--clean", action="store_true", dest="CLEAN", help="Cleans the reactor direactory of current files.") parser.add_option("-C", "--cache", action="store_true", dest="CACHE", default=False, help="Uses the current files in the reactor direactory.") parser.add_option("-l", "--local", action="store_true", dest="LOCAL", default=True, help="Run or Fetch files locally.") parser.add_option("-s", "--server", action="store_false", dest="LOCAL", help="Run or Fetch files from a remote server.") parser.add_option("-f", "--fetch", action="store_true", dest="FETCH_FILES", default=False, help="Fetches files from the remote server. Does not run transport, even if -r is set. Automatically sets -s.") parser.add_option("-p", "--pid", action="store_true", dest="PID", default=False, help="Finds the process identification number of a current transport run. Sets -d.") parser.add_option("-k", "--kill", action="store_true", dest="KILL_TRANSPORT", default=False, help="Kills the current transport run. Sets -p.") parser.add_option("--cwd", action="store_true", dest="CWD", default=False, help="Run char in the current working directory.") parser.add_option("--ui", action="store_true", dest="UI", default=False, help="Launches the char ui.") parser.add_option("-t", "--test", action="store_true", dest="TEST", default=False, help="Tests an existing library for soundness.") (options, args) = parser.parse_args() # Try launching ui before anything else if options.UI: # Test to see if ui library is installed try: from bright.xsgen.ui import app except ImportError: print(failure("Please install the Enthought Tool Suite (ETS) for CHAR UI.")) raise SystemExit # Open UI application = app.Application() #application.rx_h5_path = "/home/scopatz/MultiGroupPaper/DataXS/lwr/lwr.h5" application.configure_traits() # Clean-up UI if application.rx_h5 is not None: application.rx_h5.close() raise SystemExit # Make sure we have a configureation file before proceeding if len(args) == 0: print(failure("Please specify a file for char.")) raise SystemExit absolute_path = os.path.abspath(args[0]) # Run tests on a db file if options.TEST: _run_tests(absolute_path) raise SystemExit # Load the CHAR definition file into its own env namespace env = {} execfile(absolute_path, {}, env) # Add command line arguments to env env['options'] = options env['args'] = args # Update defchar adding more useful values. env = envchar.update_env(env) #intial command-line options protocol. if options.KILL_TRANSPORT: options.PID = True #Ensures that the PID is found in order that it mak be killed. if options.PID: options.RUN_XS_GEN = False options.RUN_DELTAM = False options.RUN_TRANSPORT = False #Ensures that transport calculation is not initiated while fetching files. if options.FETCH_FILES: options.RUN_XS_GEN = False options.RUN_DELTAM = False options.RUN_TRANSPORT = False #Ensures that transport calculation is not initiated while fetching files. options.LOCAL = False #Ensures that ssh package is loaded. ################ #### Script #### ################ # Prep work if not options.CWD: if env['options'].CLEAN: remove(env['reactor']) if env['reactor'] not in os.listdir('.'): os.mkdir(env['reactor']) os.chdir(env['reactor']) shutil.copyfile(absolute_path, 'defchar.py') # Start up logger logger = logging.getLogger('char') hdlr = logging.FileHandler('char.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) env['logger'] = logger # Set the neutronics code n_coder = n_code_switch[env['transporter']] n_code = n_coder(env) env['n_code'] = n_code # Get the run controller runner = run_switch[env['scheduler']] runchar = runner(n_code, env) # Get the inputs indeces idx = parse_slice(options.NPERT, n_code.nperturbations) nucs = parse_nucs(options.ISOS) if len(nucs) == 0: nucs = set(env['core_transmute']) else: nucs = (nucs & set(env['core_transmute'])) ihm_nucs = (nucs & set(env['ihm_mat'].comp.keys())) if 'deltam' in env: sidx = parse_slice(options.NSENS, len(env['deltam'])) # Make the input file unless otherwise specified. if (options.MAKE_INPUT) and (not options.FETCH_FILES) and (not options.PID): runchar.init_h5() # Check a bunch of run conditions if options.RUN_TRANSPORT: # Run Transport code runchar.make_run_script() if options.LOCAL: runchar.run_locally() else: runchar.run_remotely() elif options.RUN_ANALYSIS: n_code.analyze_deltam() elif options.RUN_BURNUP or options.RUN_XS_GEN or options.RUN_DELTAM: # Make tranumatrion libraries by executing the as a separate step from # the cross-section generation if options.RUN_BURNUP: runchar.burnup(idx) # Make Cross-sections as a separate step from the burnup calculation if options.RUN_XS_GEN: runchar.xs_gen(idx, nucs) # Run initial nuclide sensitivity calculation if options.RUN_DELTAM: n_code.run_deltam_pert(idx, ihm_isos, sidx) elif options.FETCH_FILES: # Fetches files from remote server runchar.fetch() elif options.PID: # Finds and prints the PID of CHAR runchar.pid() elif options.KILL_TRANSPORT: # Finds and kills CHAR runchar.kill() # Clean up if not options.CWD: os.chdir('..')
def test_failure(): if os.name is "posix": assert_equal("\033[1;31mWorld\033[0m", utils.failure("World")) else: assert_equal("*** FAILURE ***: World", utils.failure("World"))