def computeConversion(targetLabel, reactionModel, reactionSystem, atol, rtol): """ Computes the conversion of a target molecule by - searching the index of the target species in the core species of the global reduction variable - resetting the reaction system, initialing with empty variables - fetching the initial moles variable y0 - running the simulation at the conditions stored in the reaction system - fetching the computed moles variable y - computing conversion """ targetIndex = searchTargetIndex(targetLabel, reactionModel) #reset reaction system variables: logging.info('No. of rxns in core reactions: {}'.format(len(reactionModel.core.reactions))) simulatorSettings = SimulatorSettings(atol,rtol) reactionSystem.initializeModel(\ reactionModel.core.species, reactionModel.core.reactions,\ reactionModel.edge.species, reactionModel.edge.reactions, \ [],[],[],atol=simulatorSettings.atol,rtol=simulatorSettings.rtol, sens_atol=simulatorSettings.sens_atol,sens_rtol=simulatorSettings.sens_rtol) #get the initial moles: y0 = reactionSystem.y.copy() #run the simulation: simulateOne(reactionModel, atol, rtol, reactionSystem) #compute conversion: conv = 1 - (reactionSystem.y[targetIndex] / y0[targetIndex]) return conv
def computeConversion(targetLabel, reactionModel, reactionSystem, atol, rtol): """ Computes the conversion of a target molecule by - searching the index of the target species in the core species of the global reduction variable - resetting the reaction system, initialing with empty variables - fetching the initial moles variable y0 - running the simulation at the conditions stored in the reaction system - fetching the computed moles variable y - computing conversion """ targetIndex = searchTargetIndex(targetLabel, reactionModel) #reset reaction system variables: logging.info('No. of rxns in core reactions: {}'.format(len(reactionModel.core.reactions))) reactionSystem.initializeModel(\ reactionModel.core.species, reactionModel.core.reactions,\ reactionModel.edge.species, reactionModel.edge.reactions, \ [], atol, rtol) #get the initial moles: y0 = reactionSystem.y.copy() #run the simulation: simulateOne(reactionModel, atol, rtol, reactionSystem) #compute conversion: conv = 1 - (reactionSystem.y[targetIndex] / y0[targetIndex]) return conv
def writeModel(rmg, chemkin_name='chem_reduced.inp'): """ Writes the reduced reaction model to a chemkin compatible files. """ logging.info('Writing reduced model to {}'.format(chemkin_name)) speciesList = rmg.reactionModel.core.species rxnList = rmg.reactionModel.core.reactions path = os.path.join(os.getcwd(), chemkin_name) saveChemkinFile(path, speciesList, rxnList, verbose = True, checkForDuplicates=True)
def evaluate(guess, targets, reactionModel, rmg, reactionSystemIndex): """ """ logging.info('Trial tolerance: {:.2E}'.format(10**guess)) observable, newImportantReactions = reduceModel(10**guess, targets, reactionModel, rmg, reactionSystemIndex) return observable, newImportantReactions
def bisect(low, high, error, targets, reactionModel, rmg, reactionSystemIndex, orig_observable): """ Bisect method in log space. Interrupt iterations when two consecutive, successful iterations differ less than a threshold value. """ THRESHOLD = 0.05 importantReactions = None final_devs = None old_trial = low while True: midpoint = (low + high) / 2.0 reduced_observable, newImportantReactions = evaluate( midpoint, targets, reactionModel, rmg, reactionSystemIndex) devs = computeDeviation(orig_observable, reduced_observable, targets) if isInvalid(devs, error): high = midpoint else: if len(newImportantReactions) == 0: logging.error( 'Model reduction resulted in a model with 0 reactions.') logging.error( 'Perhaps change reactor conditions to allow for more adequate reduction. Exiting...' ) break low = midpoint importantReactions = newImportantReactions final_devs = devs writeModel(rmg, chemkin_name='chem_reduced_{}.inp'.format( len(importantReactions))) if np.abs((midpoint - old_trial) / old_trial) < THRESHOLD: break old_trial = low if not importantReactions: logging.error("Could not find a good guess...") importantReactions = [] logging.info('Final deviations: '.format()) for dev, target in zip(final_devs, targets): logging.info('Final deviation for {}: {:.2f}%'.format( target, dev * 100)) return low, importantReactions
def writeModel(rmg, chemkin_name='chem_reduced.inp'): """ Writes the reduced reaction model to a chemkin compatible files. """ logging.info('Writing reduced model to {}'.format(chemkin_name)) speciesList = rmg.reactionModel.core.species rxnList = rmg.reactionModel.core.reactions path = os.path.join(os.getcwd(), chemkin_name) saveChemkinFile(path, speciesList, rxnList, verbose=True, checkForDuplicates=True)
def computeDeviation(original, reduced, targets): """ Computes the relative deviation between the observables of the original and reduced model. Assumes the observables are numpy arrays. """ devs = np.abs((reduced - original) / original) logging.info('Deviations: '.format()) for dev, target in zip(devs, targets): logging.info('Deviation for {}: {:.2f}%'.format(target, dev * 100)) return devs
def loadReductionInput(reductionFile): """ Load an reduction job from the input file located at `reductionFile` """ targets = None tolerance = -1 full_path = os.path.abspath(os.path.expandvars(reductionFile)) try: f = open(full_path) except IOError, e: logging.error('The input file "{0}" could not be opened.'.format(full_path)) logging.info('Check that the file exists and that you have read access.') raise e
def main(): args = parseCommandLineArguments() level = INFO if args.debug: level = 0 elif args.verbose: level = DEBUG elif args.quiet: level = WARNING initializeLog(level) inputFile, reductionFile, chemkinFile, spcDict = args.requiredFiles[-4:] for f in [inputFile, reductionFile, chemkinFile, spcDict]: assert os.path.isfile(f), 'Could not find {}'.format(f) inputDirectory = os.path.abspath(os.path.dirname(inputFile)) output_directory = inputDirectory rmg, targets, error = load(inputFile, reductionFile, chemkinFile, spcDict) logger.info('Allowed error in target observables: {0:.0f}%'.format(error * 100)) reactionModel = rmg.reactionModel initialize(rmg.outputDirectory, reactionModel.core.reactions) atol, rtol = rmg.absoluteTolerance, rmg.relativeTolerance index = 0 reactionSystem = rmg.reactionSystems[index] #compute original target observables observables = computeObservables(targets, reactionModel, reactionSystem, \ rmg.absoluteTolerance, rmg.relativeTolerance) logger.info('Observables of original model:') for target, observable in zip(targets, observables): logger.info('{}: {:.2f}%'.format(target, observable * 100)) # optimize reduction tolerance tol, importantReactions = optimize(targets, reactionModel, rmg, index, error, observables) logger.info('Optimized tolerance: {:.0E}'.format(10**tol)) logger.info('Number of reactions in optimized reduced model : {}'.format( len(importantReactions))) # plug the important reactions into the RMG object and write: rmg.reactionModel.core.reactions = importantReactions writeModel(rmg)
def bisect(low, high, error, targets, reactionModel, rmg, reactionSystemIndex, orig_observable): """ Bisect method in log space. Interrupt iterations when two consecutive, successful iterations differ less than a threshold value. """ THRESHOLD = 0.05 importantReactions = None final_devs = None old_trial = low while True: midpoint = (low + high) / 2.0 reduced_observable, newImportantReactions = evaluate(midpoint, targets, reactionModel, rmg, reactionSystemIndex) devs = computeDeviation(orig_observable, reduced_observable, targets) if isInvalid(devs, error): high = midpoint else: if len(newImportantReactions) == 0: logging.error('Model reduction resulted in a model with 0 reactions.') logging.error('Perhaps change reactor conditions to allow for more adequate reduction. Exiting...') break low = midpoint importantReactions = newImportantReactions final_devs = devs writeModel(rmg, chemkin_name='chem_reduced_{}.inp'.format(len(importantReactions))) if np.abs((midpoint - old_trial) / old_trial) < THRESHOLD: break old_trial = low if not importantReactions: logging.error("Could not find a good guess...") importantReactions = [] logging.info('Final deviations: '.format()) for dev, target in zip(final_devs, targets): logging.info('Final deviation for {}: {:.2f}%'.format(target, dev * 100)) return low, importantReactions
def loadReductionInput(reductionFile): """ Load an reduction job from the input file located at `reductionFile` """ targets = None tolerance = -1 full_path = os.path.abspath(os.path.expandvars(reductionFile)) try: f = open(full_path) except IOError: logging.error( 'The input file "{0}" could not be opened.'.format(full_path)) logging.info( 'Check that the file exists and that you have read access.') raise logging.info('Reading input file "{0}"...'.format(full_path)) global_context = {'__builtins__': None} local_context = { '__builtins__': None, 'targets': targets, 'tolerance': tolerance } try: exec f in global_context, local_context targets = local_context['targets'] tolerance = local_context['tolerance'] except (NameError, TypeError, SyntaxError) as e: logging.error('The input file "{0}" was invalid:'.format(full_path)) logging.exception(e) raise finally: f.close() assert targets is not None assert tolerance != -1 return targets, tolerance
def main(): args = parseCommandLineArguments() level = INFO if args.debug: level = 0 elif args.verbose: level = DEBUG elif args.quiet: level = WARNING initializeLog(level) inputFile, reductionFile, chemkinFile, spcDict = args.requiredFiles[-4:] for f in [inputFile, reductionFile, chemkinFile, spcDict]: assert os.path.isfile(f), 'Could not find {}'.format(f) inputDirectory = os.path.abspath(os.path.dirname(inputFile)) output_directory = inputDirectory rmg, targets, error = load(inputFile, reductionFile, chemkinFile, spcDict) logger.info('Allowed error in target observables: {0:.0f}%'.format(error * 100)) reactionModel = rmg.reactionModel initialize(rmg.outputDirectory, reactionModel.core.reactions) atol, rtol = rmg.absoluteTolerance, rmg.relativeTolerance index = 0 reactionSystem = rmg.reactionSystems[index] #compute original target observables observables = computeObservables(targets, reactionModel, reactionSystem, \ rmg.absoluteTolerance, rmg.relativeTolerance) logger.info('Observables of original model:') for target, observable in zip(targets, observables): logger.info('{}: {:.2f}%'.format(target, observable * 100)) # optimize reduction tolerance tol, importantReactions = optimize(targets, reactionModel, rmg, index, error, observables) logger.info('Optimized tolerance: {:.0E}'.format(10**tol)) logger.info('Number of reactions in optimized reduced model : {}'.format(len(importantReactions))) # plug the important reactions into the RMG object and write: rmg.reactionModel.core.reactions = importantReactions writeModel(rmg)
def loadReductionInput(reductionFile): """ Load an reduction job from the input file located at `reductionFile` """ targets = None tolerance = -1 full_path = os.path.abspath(os.path.expandvars(reductionFile)) try: f = open(full_path) except IOError: logging.error('The input file "{0}" could not be opened.'.format(full_path)) logging.info('Check that the file exists and that you have read access.') raise logging.info('Reading input file "{0}"...'.format(full_path)) global_context = { '__builtins__': None } local_context = { '__builtins__': None, 'targets': targets, 'tolerance': tolerance } try: exec f in global_context, local_context targets = local_context['targets'] tolerance = local_context['tolerance'] except (NameError, TypeError, SyntaxError) as e: logging.error('The input file "{0}" was invalid:'.format(full_path)) logging.exception(e) raise finally: f.close() assert targets is not None assert tolerance != -1 return targets, tolerance
def bisect(low, high, error, targets, reactionModel, rmg, reactionSystemIndex, orig_observable): """ Bisect method in log space. Interrupt iterations when two consecutive, successful iterations differ less than a threshold value. """ THRESHOLD = 0.05 importantReactions = None final_devs = None old_trial = low while True: midpoint = (low + high) / 2.0 reduced_observable, newImportantReactions = evaluate(midpoint, targets, reactionModel, rmg, reactionSystemIndex) devs = computeDeviation(orig_observable, reduced_observable, targets) if isInvalid(devs, error): high = midpoint else: low = midpoint importantReactions = newImportantReactions final_devs = devs if np.abs((midpoint - old_trial) / old_trial) < THRESHOLD: break old_trial = low if not importantReactions: logging.error("Could not find a good guess...") importantReactions = [] logging.info('Final deviations: '.format()) for dev, target in zip(final_devs, targets): logging.info('Final deviation for {}: {:.2f}%'.format(target, dev * 100)) return low, importantReactions
def reduceModel(tolerance, targets, reactionModel, rmg, reactionSystemIndex): """ Reduces the model for the given tolerance and evaluates the target observables. """ # reduce model with the tolerance specified earlier: importantReactions = findImportantReactions(rmg, tolerance) original_size = len(reactionModel.core.reactions) no_importantReactions = len(importantReactions) logging.info('No. of reactions in tested reduced model: {}'.format(no_importantReactions)) #set the core reactions to the reduced reaction set: originalReactions = reactionModel.core.reactions rmg.reactionModel.core.reactions = importantReactions #re-compute observables: observables = computeObservables(targets, rmg.reactionModel,\ rmg.reactionSystems[reactionSystemIndex],\ rmg.absoluteTolerance, rmg.relativeTolerance) #reset the reaction model to its original state: rmg.reactionModel.core.reactions = originalReactions logging.info('Observables of reduced model ({} rxns):'.format(no_importantReactions)) for target, observable in zip(targets, observables): logging.info('Observable in reduced model: {}: {:.2f}%'.format(target, observable * 100)) return observables, importantReactions
def reduceModel(tolerance, targets, reactionModel, rmg, reactionSystemIndex): """ Reduces the model for the given tolerance and evaluates the target observables. """ # reduce model with the tolerance specified earlier: importantReactions = findImportantReactions(rmg, tolerance) no_importantReactions = len(importantReactions) logging.info('No. of reactions in tested reduced model: {}'.format(no_importantReactions)) #set the core reactions to the reduced reaction set: originalReactions = reactionModel.core.reactions rmg.reactionModel.core.reactions = importantReactions #re-compute observables: observables = computeObservables(targets, rmg.reactionModel,\ rmg.reactionSystems[reactionSystemIndex],\ rmg.simulatorSettingsList[-1].atol, rmg.simulatorSettingsList[-1].rtol) #reset the reaction model to its original state: rmg.reactionModel.core.reactions = originalReactions logging.info('Observables of reduced model ({} rxns):'.format(no_importantReactions)) for target, observable in zip(targets, observables): logging.info('Observable in reduced model: {}: {:.2f}%'.format(target, observable * 100)) return observables, importantReactions
""" targets = None tolerance = -1 full_path = os.path.abspath(os.path.expandvars(reductionFile)) try: f = open(full_path) except IOError, e: logging.error( 'The input file "{0}" could not be opened.'.format(full_path)) logging.info( 'Check that the file exists and that you have read access.') raise e logging.info('Reading input file "{0}"...'.format(full_path)) global_context = {'__builtins__': None} local_context = { '__builtins__': None, 'targets': targets, 'tolerance': tolerance } try: exec f in global_context, local_context targets = local_context['targets'] tolerance = local_context['tolerance'] except (NameError, TypeError, SyntaxError), e:
""" Load an reduction job from the input file located at `reductionFile` """ targets = None tolerance = -1 full_path = os.path.abspath(os.path.expandvars(reductionFile)) try: f = open(full_path) except IOError, e: logging.error('The input file "{0}" could not be opened.'.format(full_path)) logging.info('Check that the file exists and that you have read access.') raise e logging.info('Reading input file "{0}"...'.format(full_path)) global_context = { '__builtins__': None } local_context = { '__builtins__': None, 'targets': targets, 'tolerance': tolerance } try: exec f in global_context, local_context targets = local_context['targets'] tolerance = local_context['tolerance'] except (NameError, TypeError, SyntaxError), e: