def apply_irr(self): self.irr_dict = {} for rxn_name, rxn in self.reaction_dict.items(): if hasattr(self, 'irr'): try: self.irr_dict[rxn_name] = rxn * self.irr[rxn_name].view( ndarray) except ValueError as xxx_todo_changeme: (e) = xxx_todo_changeme self.irr_dict[rxn_name] = rxn * zeros(self.irr.shape, 'f') warn("IRR does not contain %s: skipped." % rxn_name) else: try: self.irr_dict[ rxn_name] = rxn * self.mrg.variables[rxn_name][:].view( type=PseudoNetCDFVariable).view(ndarray) except (KeyError, ValueError) as xxx_todo_changeme1: (e) = xxx_todo_changeme1 warn("IRR does not contain %s: skipped." % rxn_name) if self.__use_net_rxns and len(self.irr_dict) > 0: self.nreaction_dict = {} for nrxn_name, nrxn in self.net_reaction_dict.items(): try: self.nreaction_dict[nrxn_name] = eval( nrxn, None, self.irr_dict) except Exception as xxx_todo_changeme2: (e) = xxx_todo_changeme2 warn("Predefined net rxn %s is not available; %s" % (nrxn_name, str(e))) load_environ(self, self.variables)
def __init__(self, yaml_path): """ Initialization requires a yaml_path or a dictionary. The dictionary should have the following keys: species_list - a list of string names for chemical species (i.e. O3) reaction_list - a list of strings representing reactions (see ReactionGroup.ReactionFromString) net_reaction_list - a dictionary of reaction additions (i.e. NAME: RXN_01 + RXN_02) process_group_list - a dictionary of process additions (i.e. VertAdv = Top_Adv + Bottom_Adv) """ import os if isinstance(yaml_path, str): if os.path.exists(yaml_path): yaml_file = yaml.load(open(yaml_path)) else: yaml_file = yaml.load(yaml_path) elif isinstance(yaml_path, dict): yaml_file = yaml_path self.__yaml_file = yaml_file self.mechanism_comment = yaml_file.get('comment', '') self.species_dict = dict() for spc, spc_def in yaml_file.get('species_list', {}).items(): self.species_dict[spc] = Species("'" + spc + "': " + spc_def) self.reaction_dict = dict() reaction_species = [] for rxn_name, rxn_str in yaml_file.get('reaction_list', {}).items(): rxn = self.reaction_dict[rxn_name] = Reaction(rxn_str) reaction_species += rxn.species() reaction_species = set(reaction_species) for spc in [ spc for spc in reaction_species if spc not in self.species_dict ]: self.species_dict[spc] = Species(spc + ': IGNORE') for spc_grp_def in yaml_file.get('species_group_list', []): grp_name = spc_grp_def.split('=')[0].strip() if (spc_grp_def.count('+') + spc_grp_def.count('-')) > 4: spc_grp_def = '=species_sum(['.join( spc_grp_def.replace('+', ',').replace( '-', ',').split('=')) + '])' exec(spc_grp_def, None, self.species_dict) self.species_dict[grp_name].name = grp_name self.net_reaction_dict = yaml_file.get('net_reaction_list', {}) self.variables = {} load_environ(self, self.variables)
def add_rxn(self, rxn_key, rxn_str): """ Synopsis: add reaction with name rxn_key and definition rxns_str Requires: rxn_key - string to be used as key for reaction. rxn_str - string that defines the reaction (e.g., N2O + 2 H2O ->[k] HNO3 """ self.reaction_dict[rxn_key] = Reaction(rxn_str) if hasattr(self, 'irr_dict'): self.irr_dict[rxn_key] = Reaction(rxn_str) self.irr_dict[rxn_key] *= self.irr[rxn_key] load_environ(self, self.variables)
def subst_these_rxns(self, rxns, name=None): """ Synopsis Substitute net reaction for reactions in mechanism. 1. Create a net reactions from all reactions (rxns). 2. Remove all individual reactions (from e.g., irr_dict, reaction_dict, and variables) 3. Add net reaction from step 1 (to e.g., irr_dict, reaction_dict, and variables) Requires: rxns - iterable of reaction names name - key for new reaction Returns: None """ if all([isinstance(rxn, Reaction) for rxn in rxns]): irrs = rxns rxns = [] for irr in irrs: for rxnkey, crxn in self.irr_dict.items(): if irr is crxn: rxns.append(rxnkey) break else: raise KeyError('Could not match %s with a active reaction') elif all([isinstance(rxn, str) for rxn in rxns]): pass else: raise ValueError( 'Reactions must be all strings (i.e. keys) or objects') if len(rxns) > 1: eval_str = ' + '.join(rxns) if name is None: name = eval_str.replace(' + ', 'pl') nrxn = eval(eval_str, globals(), self.irr_dict) for rxn in rxns: del self.irr_dict[rxn] del self.reaction_dict[rxn] del self.variables[rxn] self.irr_dict[name] = nrxn self.reaction_dict[name] = nrxn.sum() load_environ(self, self.variables)
def set_mrg(self, mrg, use_net_rxns=True, use_irr=True, use_ipr=True): """ Add process analysis from a 1D merged IRR/IPR file """ self.mrg = mrg if use_irr: try: self.set_irr(mrg.variables['IRR'], mrg.Reactions.split(), use_net_rxns=use_net_rxns) except: self.set_irr() if use_ipr: try: self.set_ipr(mrg.variables['IPR']) except: self.set_ipr() load_environ(self, self.variables)
def subst_net_rxn(self, reactants=[], products=[], logical_and=True, reaction_type=None, name=None, netspc=False): """ Substitute net reaction for reaction in mechanism. 1. Find all matching reactions. 2. Create a net reactions from all matching reactions. 3. Remove all individual reactions (from e.g., irr_dict, reaction_dict, and variables) 4. Add net reaction from step 2 (to e.g., irr_dict, reaction_dict, and variables) Returns: None """ rxns = self.find_rxns(reactants=reactants, products=products, logical_and=logical_and, reaction_type=reaction_type) if len(rxns) > 1: eval_str = ' + '.join(rxns) if name is None: name = eval_str.replace(' + ', 'pl') nrxn = eval(eval_str, globals(), self.irr_dict) if netspc: nrxn = nrxn.net() for rxn in rxns: del self.irr_dict[rxn] del self.reaction_dict[rxn] del self.variables[rxn] self.irr_dict[name] = nrxn self.reaction_dict[name] = nrxn.sum() load_environ(self, self.variables)
except (IOError, RuntimeError), (e): warn( "\n-------------------------------------------------------\nFirst argument was not a data file.\nAttempting to continue with first argument as a script.\n-------------------------------------------------------" ) except ValueError, (e): warn( "\n-------------------------------------------\nAre you sure this is a %s data file?\n-------------------------------------------" % options.mechanism) raise e else: start_script = 1 from permm.Shell import PERMConsole console = PERMConsole() load_environ(mech, console.locals) for script in args[start_script:]: if os.path.isfile(script): execfile(script, globals(), console.locals) else: exec(script, globals(), console.locals) if options.graphical: console.runsource("from permm.GUI import StartGUI") console.runsource("StartGUI(mech)") if options.analysis is not None: if len(args) < 1: parser.error( msg=
def globalize(self, env): load_environ(self, env)
def parse_and_run(): import os from argparse import ArgumentParser from warnings import warn from permm import mechanism_dict, Mechanism from permm.analyses import __all__ as all_analyses all_mechs = '|'.join(list(mechanism_dict.keys())) all_analyses = '|'.join(all_analyses) from PseudoNetCDF.pncparse import getparser, pncparse parser = ArgumentParser( description= "permm (Python Environment for Reaction Mechanism Mathematics)") parser.add_argument("--gui", dest="graphical", \ action="store_true", default=False, \ help="open a graphical user interactive environment") parser.add_argument("--mechanism", dest="mechanism", \ default="cb05_camx", help="Chemical mechanisms (e.g., a custom path|%s)" % all_mechs) parser.add_argument("--analysis", dest="analysis", \ default=None, help="Stock analysis to perform (i.e., %s)" % all_analyses) parser.add_argument("--scripts", dest="scripts", action='append', default=[], help="Provide scripts to run") parser.add_argument("-i", "--interactive", dest="interactive", action='store_true', default=False, help="Run interactively") parser.add_argument( "--input-role", dest="inrole", action='append', default=[], help= "Is this a 'merge' file or a 'concentration' file or any other word indicating type?" ) parser.add_argument("pseudonetcdf", nargs='*') options = parser.parse_args() if len(options.pseudonetcdf) > 0: pncparser = getparser(has_ofile=False, interactive=True) ifiles, pncoptions = pncparse(has_ofile=False, interactive=True, parser=pncparser, args=args.pseudonetcdf) else: ifiles = [] pncoptions = {} from permm import netcdf from permm.Shell import load_environ try: mech = mechanism_dict[options.mechanism] except KeyError: mech = Mechanism(options.mechanism) start_script = 0 options.inrole += ['merge'] * (len(ifiles) - len(options.inrole)) for r, ifile in zip(options.inrole, ifiles): if r == 'merge': mech.set_mrg(ifile) else: vardict = dict([(k, v) for k, v in list(ifile.variables.items()) if k in mech.species_dict]) mech.set_process(r, vardict) from permm.Shell import PERMConsole console = PERMConsole() load_environ(mech, console.locals) for script in options.scripts: if os.path.isfile(script): exec(compile(open(script).read(), script, 'exec'), globals(), console.locals) else: exec(script, globals(), console.locals) if options.graphical: console.runsource("from permm.GUI import StartGUI") console.runsource("StartGUI(mech)") if options.analysis is not None: if len(args) < 1: parser.error( msg= "Requires a pyPA mrg file as an argument for analysis output. You can enter an interactive environment (-i), but will not have access to \"netted\" reactions" ) if options.analysis == "net_balance": console.runsource( "from permm.analyses.net_balance import net_balance") console.runsource("net_balance('%s', '%s', '%s')" % (options.mechanism, args[0], options.output)) elif options.analysis == "history": console.runsource("from permm.analyses.history import matrix") console.runsource( "history = matrix(mech, [C2O3], [HC+Radical-OH-HO2-O1D], [])") console.runsource("history.run()") else: raise "Unkown analysis" if options.interactive: load_environ(mech, console.locals) console.interact()
mrg_file = NetCDFFile(args[0]) mech.set_mrg(mrg_file) except (IOError, RuntimeError), (e): warn("\n-------------------------------------------------------\nFirst argument was not a data file.\nAttempting to continue with first argument as a script.\n-------------------------------------------------------") except ValueError, (e): warn("\n-------------------------------------------\nAre you sure this is a %s data file?\n-------------------------------------------" % options.mechanism) raise e else: start_script = 1 from permm.Shell import PERMConsole console = PERMConsole() load_environ(mech,console.locals) for script in args[start_script:]: if os.path.isfile(script): execfile(script, globals(), console.locals) else: exec(script, globals(), console.locals) if options.graphical: console.runsource("from permm.GUI import StartGUI") console.runsource("StartGUI(mech)") if options.analysis is not None: if len(args)<1: parser.error(msg="Requires a pyPA mrg file as an argument for analysis output. You can enter an interactive environment (-i), but will not have access to \"netted\" reactions")