Beispiel #1
0
def run_pfa(args, solution_object,error,past):

	if len(args.target) == 0: #If the target species are not specified, puke and die.
		print("Please specify a target species.")
		exit()
	done = [] #Singleton to hold wether or not any more species can be cut from the simulation.
	done.append(False)
	threshold = .1 #Starting threshold value
	threshold_i = .1
	n = 1
	error = [10.0] #Singleton to hold the error value of the previously ran simulation.

	#Check to make sure that conditions exist
	if args.conditions_file:
		conditions_array = readin_conditions(str(args.conditions_file))
	elif not args.conditions_file:
		print("Conditions file not found")
		exit()

	sim_array = helper.setup_simulations(conditions_array,solution_object) #Turn conditions array into unran simulation objects for the original solution
	ignition_delay_detailed = helper.simulate(sim_array) #Run simulations and process results
	rate_edge_data = get_rates_pfa(sim_array, solution_object) #Get edge weight calculation data.

	print("Testing for starting threshold value")
	pfa_loop_control(solution_object, args, error, threshold, done, rate_edge_data, ignition_delay_detailed, conditions_array) #Trim the solution at that threshold and find the error.
	while error[0] != 0: #While the error for trimming with that threshold value is greater than allowed.
		threshold = threshold / 10 #Reduce the starting threshold value and try again.
		threshold_i = threshold_i / 10
		n = n + 1
		pfa_loop_control(solution_object, args, error, threshold, done, rate_edge_data, ignition_delay_detailed, conditions_array)
		if error[0] <= .02:
			error[0] = 0

	print("Starting with a threshold value of " + str(threshold))
	sol_new = solution_object
	past[0] = 0 #An integer representing the error introduced in the past simulation.
	done[0] = False

	while not done[0] and error[0] < args.error: #Run the simulation until nothing else can be cut.
		sol_new = pfa_loop_control( solution_object, args, error, threshold, done, rate_edge_data, ignition_delay_detailed, conditions_array) #Trim at this threshold value and calculate error.
		if args.error > error[0]: #If a new max species cut without exceeding what is allowed is reached, save that threshold.
			max_t = threshold
		#if (past == error[0]): #If error wasn't increased, increase the threshold at a higher rate.
		#	threshold = threshold + (threshold_i * 4)
			past[0] = error[0]
		#if (threshold >= .01):
                #        threshold_i = .01
		threshold = threshold + threshold_i
		threshold = round(threshold, n)

	print("\nGreatest result: ")
	sol_new = pfa_loop_control( solution_object, args, error, max_t, done, rate_edge_data, ignition_delay_detailed, conditions_array)
	drgep_trimmed_file = soln2cti.write(sol_new) #Write the solution object with the greatest error that isn't over the allowed ammount.

	return sol_new[1]
Beispiel #2
0
def obtain_cti_file_nicely_named(chemkinfilepath,
                                 readComments=True,
                                 original_ck_file='chem_annotated.inp'):
    """
    Given a chemkin file path, this method reads in the chemkin file and species
    dictionary into RMG objects, renames the species more intuitively, and then
    saves the output as 'input_nicely_named.cti' to the same file path.
    """
    from rmgpy.chemkin import loadChemkinFile
    import os
    import soln2cti
    import cantera as ct

    chemkinPath = os.path.join(chemkinfilepath, original_ck_file)
    speciesDictPath = os.path.join(chemkinfilepath, 'species_dictionary.txt')
    species, reactions = loadChemkinFile(chemkinPath,
                                         speciesDictPath,
                                         readComments=readComments,
                                         useChemkinNames=False)
    make_string_labels_independent(species)
    for spec in species:
        if len(spec.molecule) == 0:
            print(spec)
    # convert species
    ct_species = [
        spec.toCantera(useChemkinIdentifier=False) for spec in species
    ]
    # convert reactions
    # since this can return a rxn or list of reactions, this allows to make a list based on the returned type
    ct_reactions = []
    for rxn in reactions:
        ct_rxn = rxn.toCantera(useChemkinIdentifier=False)
        if isinstance(ct_rxn, list):
            ct_reactions.extend(ct_rxn)
        else:
            ct_reactions.append(ct_rxn)

    # save new file
    gas = ct.Solution(thermo='IdealGas',
                      kinetics='GasKinetics',
                      species=ct_species,
                      reactions=ct_reactions)
    new_file = soln2cti.write(gas)
    # move the file to new location
    os.rename(new_file, os.path.join(chemkinfilepath,
                                     'input_nicely_named.cti'))
    # save species dictionary
    dictionary = ''
    for spec in species:
        dictionary += spec.toAdjacencyList() + '\n\n'
    f = open(
        os.path.join(chemkinfilepath, 'species_dictionary_nicely_named.txt'),
        'w')
    f.write(dictionary)
    f.close()
Beispiel #3
0
    print("Cleaning all species and reactions with " + element)
    clean_species = ()
    clean_reactions = ()
    #loop once over the species
    for i in mechanism_to_clean.species():
        if not element in i.name:
            clean_species += (i, )
    #loop once over the reactions
    for i in range(0, mechanism_to_clean.n_reactions):
        if not element in mechanism_to_clean.reaction_equation(i):
            reaction = mechanism_to_clean.reaction(i)
            if hasattr(reaction, 'efficiencies'):
                copy = {}
                for key in reaction.efficiencies.keys():
                    if not re.search(element, key):
                        copy.update({key: reaction.efficiencies[key]})
                reaction.efficiencies = copy
            clean_reactions += (mechanism_to_clean.reaction(i), )

    #print(mechanism_to_clean.element_names)
    clean_mechanism = ct.Solution(thermo='IdealGas',
                                  kinetics='GasKinetics',
                                  species=clean_species,
                                  reactions=clean_reactions)

    #print(clean_species)
    for x in clean_mechanism.reactions():
        print(x, '\n')
    print("writing cleaned file at ", cti_path_clean)
    soln2cti.write(clean_mechanism, cti_path_clean)
Beispiel #4
0
def pymars(model_file,
           conditions,
           error,
           method,
           target_species,
           retained_species=None,
           run_sensitivity_analysis=False,
           epsilon_star=0.1):
    """Driver function for pyMARS to reduce a model.

    Parameters
    ----------
    model_file : str
        Cantera-format model to be reduced (e.g., 'mech.cti').
    conditions : str
        File with list of autoignition initial conditions.
    error : float
        Maximum error % for the reduced model.
    method : {'DRG', 'DRGEP', 'PFA'}
        Skeletal reduction method to use.
    target_species: list of str
        List of target species for reduction.
    retained_species : list of str, optional
        List of non-target species to always retain.
    run_sensitivity_analysis : bool, optional
        Flag to run sensitivity analysis after completing another method.
    epsilon_star : float, optional
        Epsilon^* value used to determine species for sensitivity analysis.

    Returns
    -------
        Converted mechanism file
        Trimmed Solution Object
        Trimmed Mechanism file

    Examples
    --------
    >>> pymars('gri30.cti', conditions_file, 10.0, 'DRGEP', ['CH4', 'O2'], retained_species=['N2'])

    """

    solution_object = Solution(model_file)
    final_error = [0]

    if method == 'DRG':
        reduced_model = run_drg(solution_object, conditions, error,
                                target_species, retained_species, model_file,
                                final_error)
    elif method == 'PFA':
        reduced_model = run_pfa(solution_object, conditions, error,
                                target_species, retained_species, model_file,
                                final_error)
    elif method == 'DRGEP':
        reduced_model = run_drgep(solution_object, conditions, error,
                                  target_species, retained_species, model_file,
                                  final_error)

    if run_sensitivity_analysis:
        reduced_model = run_sa(solution_object, reduced_model, epsilon_star,
                               final_error, conditions, target_species,
                               retained_species, error)

    output_file = soln2cti.write(reduced_model)
Beispiel #5
0
for i in np.arange(len(phi)):
    for filename in np.arange(len(mechanisms)):
        for j in np.arange(len(fuels)):
            for t in np.arange(len(temps)):
                for p in np.arange(len(pressures)):
                    for truth in efficiency_manipulate:
                        conditionsTups.append([
                            mechanisms[filename], phi[i], fuels[j],
                            oxidizers[j], temps[t], pressures[p], truth
                        ])
if True in efficiency_manipulate:
    gas = ct.Solution(mechanisms[0])
    gas = em.efficiency_rate_swap(gas)
    gas.name = fuels[0] + '_' + mechanisms[0].rstrip('.cti').split('\\')[-1]
    import soln2cti as ctiw
    new_file = ctiw.write(gas)


#print(conditionsTups)
def solver(conditionsTup):
    try:
        if not conditionsTup[6]:
            fuels = conditionsTup[2]
            #oxidizer={'O2':0.5, 'N2':1.88}
            oxidizer = conditionsTup[3]
            gas = ct.Solution(conditionsTup[0])

            pressures = conditionsTup[5]
            #temps=[298]
            temps = conditionsTup[4]
            width = 0.03
Beispiel #6
0
def readin(args='none', **argv):
    """Main function for pyMARS

    Parameters
    ----------
    file:
        Input mechanism file (ex. file='gri30.cti')
    species:
        Species to eliminate (ex. species='H, OH')
    thermo:
        Thermo data file if Chemkin format (ex. thermo= 'thermo.dat')
    transport:
        Transport data file if Chemkin format
    plot:
        plot ignition curve (ex. plot='y')
    points:
        print ignition point and sample range (ex. points='y')
    writecsv:
        write data to csv (ex. writecsv='y')
    writehdf5:
        write data to hdf5 (ex. writehdf5='y')
    run_drg:
        Run DRG model reduction

    Returns
    -------
        Converted mechanism file
        Trimmed Solution Object
        Trimmed Mechanism file

    Examples
    --------
    readin(file='gri30.cti', plot='y', species='OH, H')
    """
    class args():

        #package from terminal use case
        if args is not 'none':
            plot = args.plot
            points = args.points
            writecsv = args.writecsv
            writehdf5 = args.writehdf5
            data_file = args.file
            thermo_file = args.thermo
            transport_file = args.transport
            run_drg = args.run_drg
            threshold_values = args.thresholds
            conditions_file = args.conditions
            convert = args.convert
            if args.species is None:
                exclusion_list = []
            else:
                exclusion_list = [
                    str(item) for item in args.species.split(',')
                ]
                #strip spaces
                for i, sp in enumerate(exclusion_list):
                    exclusion_list[i] = sp.strip()

    file_extension = os.path.splitext(args.data_file)[1]

    if file_extension == ".cti" or file_extension == ".xml":
        print("\nThis is an Cantera xml or cti file\n")
        solution_object = ct.Solution(args.data_file)
        if args.plot is True or args.writecsv is True or args.points is True or args.writehdf5 is True:
            print 'running sim'
            sim_result = autoignition_loop_control(solution_object, args)
        if args.run_drg is True:
            new_solution_objects = drg_loop_control(solution_object, args)
            os.system('rm production_rates.hdf5')
            os.system('rm mass_fractions.hdf5')
            drg_trimmed_file = soln2cti.write(new_solution_objects[1])
            try:
                os.system('rm production_rates.hdf5')
            except Exception:
                pass
        if args.convert is True:
            soln2ck.write(solution_object)

    elif file_extension == ".inp" or file_extension == ".dat" or file_extension == ".txt":
        print("\n\nThis is a Chemkin file")
        #convert file to cti
        converted_file_name = convert(args.data_file, args.thermo_file,
                                      args.transport_file)

    else:
        print("\n\nFile type not supported")
Beispiel #7
0
def cti_write(x={},original_cti='',master_rxns='',master_index=[]):
    if not original_cti:
        raise Exception('Please provide a name for the original mechanism file and try again.')
    if not master_rxns and np.any(master_index):
        raise Exception('Please provide a mechanism file for reactions analysed with master equation or leave master_index empty')
    if master_rxns and not np.any(master_index):
        raise Exception('Please provide master_index, a non-empty list of reaction numbers from original file which are analysed with master equation.')
        
    if not master_rxns and not master_index:
        master_index=np.ones(ct.Solution(original_cti).n_reactions,dtype=bool)
    elif master_rxns and np.any(master_index):
        temp=np.ones(ct.Solution(original_cti).n_reactions,dtype=bool)
        for j in np.arange(len(master_index)):
            
            temp[master_index[j]-1]=False        
        master_index=temp
    lineList=[]
    with open(original_cti) as f:
        lineList=f.readlines()        
    done=False
    count=0
    while not done or count<len(lineList):
        if 'Reaction data' in lineList[count] or 'Reaction Data' in lineList[count] or 'reaction data' in lineList[count]:
            done=True
            lineList=lineList[0:count-1]
        else:count+=1
    with open('tempcti.cti','w') as p:
        p.writelines(lineList)
        
    NewModel=ct.Solution('tempcti.cti')
    original_mechanism=ct.Solution(original_cti)
    master_count=0
    if master_rxns:
        master_reactions=ct.Solution(master_rxns)
    for i in np.arange(original_mechanism.n_reactions):
        if master_index[i]==True:
            NewModel.add_reaction(original_mechanism.reaction(i))
        elif master_index[i]==False:
            NewModel.add_reaction(master_reactions.reaction(master_count))
            master_count+=1   
    
    if x=={}:
        for j in np.arange(original_mechanism.n_reactions):
           
           if master_index[j]:
               if 'ThreeBodyReaction' in str(type(original_mechanism.reaction(j))):
                   NewModel.reaction(j).rate=original_mechanism.reaction(j).rate
               elif 'ElementaryReaction' in str(type(original_mechanism.reaction(j))):
                   NewModel.reaction(j).rate=original_mechanism.reaction(j).rate
               elif 'FalloffReaction' in str(type(original_mechanism.reaction(j))):
                   NewModel.reaction(j).high_rate=original_mechanism.reaction(j).high_rate
                   NewModel.reaction(j).low_rate=original_mechanism.reaction(j).low_rate
                   
                   if original_mechanism.reaction(j).falloff.type=='Troe':
                       NewModel.reaction(j).falloff=original_mechanism.reaction(j).falloff
                   if original_mechanism.reaction(j).falloff.type=='Sri':
                       NewModel.reaction(j).falloff=original_mechanism.reaction(j).falloff
               elif 'ChemicallyActivatedReaction' in str(type(original_mechanism.reaction(j))):
                   NewModel.reaction(j).high_rate=original_mechanism.reaction(j).high_rate
                   NewModel.reaction(j).low_rate=original_mechanism.reaction(j).low_rate
                   if original_mechanism.reaction(j).falloff.type=='Troe':
                       NewModel.reaction(j).falloff=original_mechanism.reaction(j).falloff
                   if original_mechanism.reaction(j).falloff.type=='Sri':
                       NewModel.reaction(j).falloff=original_mechanism.reaction(j).falloff
               elif 'PlogReaction' in str(type(original_mechanism.reaction(j))):
                   NewModel.reaction(j).rates=original_mechanism.reaction(j).rates
               elif 'ChebyshevReaction' in str(type(original_mechanism.reaction(j))):
                   NewModel.reaction(j).set_parameters(original_mechanism.reaction(j).Tmin,original_mechanism.reaction(j).Tmax,original_mechanism.reaction(j).Pmin,original_mechanism.reaction(j).Pmax,original_mechanism.reaction(j).coeffs)
    if x!={}:
        for j in np.arange(original_mechanism.n_reactions):
           if master_index[j]:
               try:
                   if 'ThreeBodyReaction' in str(type(original_mechanism.reaction(j))):
                       A=original_mechanism.reaction(j).rate.pre_exponential_factor
                       n=original_mechanism.reaction(j).rate.temperature_exponent
                       Ea=original_mechanism.reaction(j).rate.activation_energy
                       NewModel.reaction(j).rate=ct.Arrhenius(A*np.exp(x['r'+str(j)]['A']),n+x['r'+str(j)]['n'],Ea+x['r'+str(j)]['Ea'])
                   elif 'ElementaryReaction' in str(type(original_mechanism.reaction(j))):
                       A=original_mechanism.reaction(j).rate.pre_exponential_factor
                       n=original_mechanism.reaction(j).rate.temperature_exponent
                       Ea=original_mechanism.reaction(j).rate.activation_energy
                       NewModel.reaction(j).rate=ct.Arrhenius(A*np.exp(x['r'+str(j)]['A']),n+x['r'+str(j)]['n'],Ea+x['r'+str(j)]['Ea'])
                   elif 'FalloffReaction' in str(type(original_mechanism.reaction(j))):
                       A=original_mechanism.reaction(j).high_rate.pre_exponential_factor
                       n=original_mechanism.reaction(j).high_rate.temperature_exponent
                       Ea=original_mechanism.reaction(j).high_rate.activation_energy
                       NewModel.reaction(j).high_rate=ct.Arrhenius(A*np.exp(x['r'+str(j)]['A']),n+x['r'+str(j)]['n'],Ea+x['r'+str(j)]['Ea'])
                       A=original_mechanism.reaction(j).low_rate.pre_exponential_factor
                       n=original_mechanism.reaction(j).low_rate.temperature_exponent
                       Ea=original_mechanism.reaction(j).low_rate.activation_energy
                       NewModel.reaction(j).low_rate=ct.Arrhenius(A*np.exp(x['r'+str(j)]['A']),n+x['r'+str(j)]['n'],Ea+x['r'+str(j)]['Ea'])
                       if original_mechanism.reaction(j).falloff.type=='Troe':
                           NewModel.reaction(j).falloff=original_mechanism.reaction(j).falloff
                       if original_mechanism.reaction(j).falloff.type=='Sri':
                           NewModel.reaction(j).falloff=original_mechanism.reaction(j).falloff
                   elif 'ChemicallyActivatedReaction' in str(type(original_mechanism.reaction(j))):
                       A=original_mechanism.reaction(j).high_rate.pre_exponential_factor
                       n=original_mechanism.reaction(j).high_rate.temperature_exponent
                       Ea=original_mechanism.reaction(j).high_rate.activation_energy
                       NewModel.reaction(j).high_rate=ct.Arrhenius(A*np.exp(x['r'+str(j)]['A']),n+x['r'+str(j)]['n'],Ea+x['r'+str(j)]['Ea'])
                       A=original_mechanism.reaction(j).low_rate.pre_exponential_factor
                       n=original_mechanism.reaction(j).low_rate.temperature_exponent
                       Ea=original_mechanism.reaction(j).low_rate.activation_energy
                       NewModel.reaction(j).low_rate=ct.Arrhenius(A*np.exp(x['r'+str(j)]['A']),n+x['r'+str(j)]['n'],Ea+x['r'+str(j)]['Ea'])
                       if original_mechanism.reaction(j).falloff.type=='Troe':
                           NewModel.reaction(j).falloff=original_mechanism.reaction(j).falloff
                       if original_mechanism.reaction(j).falloff.type=='Sri':
                           NewModel.reaction(j).falloff=original_mechanism.reaction(j).falloff
                   elif 'PlogReaction' in str(type(original_mechanism.reaction(j))):
                       NewModel.reaction(j).rates=original_mechanism.reaction(j).rates
                   elif 'ChebyshevReaction' in str(type(original_mechanism.reaction(j))):
                       NewModel.reaction(j).set_parameters(original_mechanism.reaction(j).Tmin,original_mechanism.reaction(j).Tmax,original_mechanism.reaction(j).Pmin,original_mechanism.reaction(j).Pmax,original_mechanism.reaction(j).coeffs)
               except:
                   if 'ThreeBodyReaction' in str(type(original_mechanism.reaction(j))):
                       NewModel.reaction(j).rate=original_mechanism.reaction(j).rate
                   elif 'ElementaryReaction' in str(type(original_mechanism.reaction(j))):
                       NewModel.reaction(j).rate=original_mechanism.reaction(j).rate
                   elif 'FalloffReaction' in str(type(original_mechanism.reaction(j))):
                       NewModel.reaction(j).high_rate=original_mechanism.reaction(j).high_rate
                       NewModel.reaction(j).low_rate=original_mechanism.reaction(j).low_rate
                       if original_mechanism.reaction(j).falloff.type=='Troe':
                           NewModel.reaction(j).falloff=original_mechanism.reaction(j).falloff
                       if original_mechanism.reaction(j).falloff.type=='Sri':
                           NewModel.reaction(j).falloff=original_mechanism.reaction(j).falloff
                   elif 'ChemicallyActivatedReaction' in str(type(original_mechanism.reaction(j))):
                      NewModel.reaction(j).high_rate=original_mechanism.reaction(j).high_rate
                      NewModel.reaction(j).low_rate=original_mechanism.reaction(j).low_rate
                      if original_mechanism.reaction(j).falloff.type=='Troe':
                          NewModel.reaction(j).falloff=original_mechanism.reaction(j).falloff
                      if original_mechanism.reaction(j).falloff.type=='Sri':
                          NewModel.reaction(j).falloff=original_mechanism.reaction(j).falloff
                   elif 'PlogReaction' in str(type(original_mechanism.reaction(j))):
                      NewModel.reaction(j).rates=original_mechanism.reaction(j).rates
                   elif 'ChebyshevReaction' in str(type(original_mechanism.reaction(j))):
                      NewModel.reaction(j).set_parameters(original_mechanism.reaction(j).Tmin,original_mechanism.reaction(j).Tmax,original_mechanism.reaction(j).Pmin,original_mechanism.reaction(j).Pmax,original_mechanism.reaction(j).coeffs)
                   
               
    
    new_file=ctiw.write(NewModel)
    return new_file
coeffs = [[2.0, 1.5, 2.5]]
#coeffs=[[11.0]]
#coeffs=[[7.5]]
#coeffs=[[1.0]]
coeffs = [[
    2.0, 3.5, 3.0, 2.5, 5.0, 4.5, 4.0, 6.5, 6.5, 6.0, 6.0, 6.0, 5.5, 5.5, 5.5,
    5.5
]]
#coeffs=[[11.0],
#        [9.0]]
for i in nominal_models:
    gas = ct.Solution(i)
    gas.name = 'igDelayRateSwap_' + i.split('\\')[-1].rstrip('.cti')
    gas2 = em.efficiency_rate_swap(gas, [val])
    newfilename = ntpath.dirname(i) + '\\modified2_' + ntpath.basename(i)
    new_file = ctiw.write(gas2, newfilename)
    modified_models.append(new_file)

conditionsTup = []
for n in np.arange(len(nominal_models)):
    for p in np.arange(len(P)):
        for i in np.arange(len(T)):
            for subf in np.arange(len(fuels[n])):
                oxidizer = {}
                oxidizer = {
                    'O2': coeffs[n][subf],
                    'N2': 3.76 * coeffs[n][subf]
                }
                conditionsTup.append([
                    nominal_models[n], modified_models[n], P[p], phi,
                    fuels[n][subf], oxidizer, T[i]
Beispiel #9
0
def cti_write2(x={}, original_cti='', master_rxns='', master_index=[], MP={}):
    print(MP)
    if not original_cti:
        raise Exception(
            'Please provide a name for the original mechanism file and try again.'
        )
    if not master_rxns and np.any(master_index):
        raise Exception(
            'Please provide a mechanism file for reactions analysed with master equation or leave master_index empty'
        )
    if master_rxns and not np.any(master_index):
        raise Exception(
            'Please provide master_index, a non-empty list of reaction numbers from original file which are analysed with master equation.'
        )

    if not master_rxns and not master_index:
        master_index = np.ones(ct.Solution(original_cti).n_reactions,
                               dtype=bool)
    elif master_rxns and np.any(master_index):
        temp = np.ones(ct.Solution(original_cti).n_reactions, dtype=bool)
        for j in np.arange(len(master_index)):

            temp[master_index[j] - 1] = False
        master_index = temp
    lineList = []
    with open(original_cti) as f:
        lineList = f.readlines()
    done = False
    count = 0
    while not done or count < len(lineList):
        if 'Reaction data' in lineList[count] or 'Reaction Data' in lineList[
                count] or 'reaction data' in lineList[count]:
            done = True
            lineList = lineList[0:count - 1]
        else:
            count += 1
    with open('tempcti.cti', 'w') as p:
        p.writelines(lineList)

    NewModel = ct.Solution('tempcti.cti')
    original_mechanism = ct.Solution(original_cti)
    original_rxn_count = 0
    master_rxn_eqs = []
    if master_rxns:
        with open(master_rxns) as f:
            reactionsList = f.readlines()
        lineList = lineList + reactionsList
        with open('masterTemp.cti', 'w') as f:
            f.writelines(lineList)
        master_reactions = ct.Solution('masterTemp.cti')
        master_rxn_eqs = master_reactions.reaction_equations()
    original_rxn_eqs = []
    for i in np.arange(original_mechanism.n_reactions):
        if master_index[i]:
            NewModel.add_reaction(original_mechanism.reaction(i))
            original_rxn_count += 1
            original_rxn_eqs.append(original_mechanism.reaction_equation(i))
#            if 'FalloffReaction' in str(type(original_mechanism.reaction(i))):
#                print(original_mechanism.reaction(i).high_rate)
#                print(original_mechanism.reaction(i).low_rate)
    if master_rxns:
        for i in np.arange(master_reactions.n_reactions):
            print(master_reactions.reaction(i).rate)
            NewModel.add_reaction(master_reactions.reaction(i))

    #print(master_reactions.reaction(0).rate)

    if x == {}:

        for j in np.arange(original_rxn_count - 1):

            #if master_index[j]:
            #print(str(type(original_mechanism.reaction(j))),str(type(NewModel.reaction(j))))
            if 'ThreeBodyReaction' in str(type(NewModel.reaction(j))):
                NewModel.reaction(j).rate = NewModel.reaction(j).rate
            elif 'ElementaryReaction' in str(type(NewModel.reaction(j))):
                NewModel.reaction(j).rate = NewModel.reaction(j).rate
            elif 'FalloffReaction' in str(type(NewModel.reaction(j))):
                NewModel.reaction(j).high_rate = NewModel.reaction(j).high_rate
                NewModel.reaction(j).low_rate = NewModel.reaction(j).low_rate

                if NewModel.reaction(j).falloff.type == 'Troe':
                    NewModel.reaction(j).falloff = NewModel.reaction(j).falloff
                if NewModel.reaction(j).falloff.type == 'Sri':
                    NewModel.reaction(j).falloff = NewModel.reaction(j).falloff
            elif 'ChemicallyActivatedReaction' in str(
                    type(NewModel.reaction(j))):
                NewModel.reaction(j).high_rate = NewModel.reaction(j).high_rate
                NewModel.reaction(j).low_rate = NewModel.reaction(j).low_rate
                if NewModel.reaction(j).falloff.type == 'Troe':
                    NewModel.reaction(j).falloff = NewModel.reaction(j).falloff
                if NewModel.reaction(j).falloff.type == 'Sri':
                    NewModel.reaction(j).falloff = NewModel.reaction(j).falloff
            elif 'PlogReaction' in str(type(NewModel.reaction(j))):
                NewModel.reaction(j).rates = NewModel.reaction(j).rates
            elif 'ChebyshevReaction' in str(type(NewModel.reaction(j))):
                NewModel.reaction(j).set_parameters(
                    NewModel.reaction(j).Tmin,
                    NewModel.reaction(j).Tmax,
                    NewModel.reaction(j).Pmin,
                    NewModel.reaction(j).Pmax,
                    NewModel.reaction(j).coeffs)

    #Rinv = 1/R #cal/mol*K
    E = 1  #going test for energy
    T = 4.186e3
    if x != {}:

        for j in np.arange(original_rxn_count - 1):
            #if master_index[j]:
            try:
                if 'ThreeBodyReaction' in str(type(NewModel.reaction(j))):
                    A = NewModel.reaction(j).rate.pre_exponential_factor
                    n = NewModel.reaction(j).rate.temperature_exponent
                    Ea = NewModel.reaction(j).rate.activation_energy
                    NewModel.reaction(j).rate = ct.Arrhenius(
                        A * np.exp(x['r' + str(j)]['A']),
                        n + x['r' + str(j)]['n'],
                        Ea + x['r' + str(j)]['Ea'] * T)
                elif 'ElementaryReaction' in str(type(NewModel.reaction(j))):
                    A = NewModel.reaction(j).rate.pre_exponential_factor
                    n = NewModel.reaction(j).rate.temperature_exponent
                    Ea = NewModel.reaction(j).rate.activation_energy
                    NewModel.reaction(j).rate = ct.Arrhenius(
                        A * np.exp(x['r' + str(j)]['A']),
                        n + x['r' + str(j)]['n'],
                        Ea + x['r' + str(j)]['Ea'] * T)
                elif 'FalloffReaction' in str(type(NewModel.reaction(j))):
                    A = NewModel.reaction(j).high_rate.pre_exponential_factor
                    n = NewModel.reaction(j).high_rate.temperature_exponent
                    Ea = NewModel.reaction(j).high_rate.activation_energy

                    NewModel.reaction(j).high_rate = ct.Arrhenius(
                        A * np.exp(x['r' + str(j)]['A']),
                        n + x['r' + str(j)]['n'],
                        Ea + x['r' + str(j)]['Ea'] * T)
                    A = NewModel.reaction(j).low_rate.pre_exponential_factor
                    n = NewModel.reaction(j).low_rate.temperature_exponent
                    Ea = NewModel.reaction(j).low_rate.activation_energy
                    NewModel.reaction(j).low_rate = ct.Arrhenius(
                        A * np.exp(x['r' + str(j)]['A']),
                        n + x['r' + str(j)]['n'],
                        Ea + x['r' + str(j)]['Ea'] * T)
                    if NewModel.reaction(j).falloff.type == 'Troe':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                    if NewModel.reaction(j).falloff.type == 'Sri':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                elif 'ChemicallyActivatedReaction' in str(
                        type(NewModel.reaction(j))):
                    A = NewModel.reaction(j).high_rate.pre_exponential_factor
                    n = NewModel.reaction(j).high_rate.temperature_exponent
                    Ea = NewModel.reaction(j).high_rate.activation_energy
                    NewModel.reaction(j).high_rate = ct.Arrhenius(
                        A * np.exp(x['r' + str(j)]['A']),
                        n + x['r' + str(j)]['n'],
                        Ea + x['r' + str(j)]['Ea'] * T)
                    A = NewModel.reaction(j).low_rate.pre_exponential_factor
                    n = NewModel.reaction(j).low_rate.temperature_exponent
                    Ea = NewModel.reaction(j).low_rate.activation_energy
                    NewModel.reaction(j).low_rate = ct.Arrhenius(
                        A * np.exp(x['r' + str(j)]['A']),
                        n + x['r' + str(j)]['n'],
                        Ea + x['r' + str(j)]['Ea'] * T)
                    if NewModel.reaction(j).falloff.type == 'Troe':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                    if NewModel.reaction(j).falloff.type == 'Sri':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                elif 'PlogReaction' in str(type(NewModel.reaction(j))):
                    for number, reactions in enumerate(
                            NewModel.reaction(j).rates):
                        A = NewModel.reaction(
                            j)[number][1].pre_exponential_factor
                        n = NewModel.reaction(
                            j)[number][1].temperature_exponent
                        Ea = NewModel.reaction(j)[number][1].activation_energy
                        NewModel.reaction(j)[number][1] = ct.Arrhenius(
                            A * np.exp(x['r' + str(j)]['A']),
                            n + x['r' + str(j)]['n'],
                            Ea + x['r' + str(j)]['Ea'] * T)
                    NewModel.reaction(j).rates = NewModel.reaction(j).rates
                elif 'ChebyshevReaction' in str(
                        type(original_mechanism.reaction(j))):
                    NewModel.reaction(j).set_parameters(
                        NewModel.reaction(j).Tmin,
                        NewModel.reaction(j).Tmax,
                        NewModel.reaction(j).Pmin,
                        NewModel.reaction(j).Pmax,
                        NewModel.reaction(j).coeffs)

            except:
                print('we are in the except statment in marks code', j)
                if 'ThreeBodyReaction' in str(type(NewModel.reaction(j))):
                    NewModel.reaction(j).rate = NewModel.reaction(j).rate
                elif 'ElementaryReaction' in str(type(NewModel.reaction(j))):
                    NewModel.reaction(j).rate = NewModel.reaction(j).rate
                elif 'FalloffReaction' in str(type(NewModel.reaction(j))):
                    NewModel.reaction(j).high_rate = NewModel.reaction(
                        j).high_rate
                    NewModel.reaction(j).low_rate = NewModel.reaction(
                        j).low_rate
                    if NewModel.reaction(j).falloff.type == 'Troe':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                    if NewModel.reaction(j).falloff.type == 'Sri':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                elif 'ChemicallyActivatedReaction' in str(
                        type(NewModel.reaction(j))):
                    NewModel.reaction(j).high_rate = NewModel.reaction(
                        j).high_rate
                    NewModel.reaction(j).low_rate = NewModel.reaction(
                        j).low_rate
                    if NewModel.reaction(j).falloff.type == 'Troe':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                    if NewModel.reaction(j).falloff.type == 'Sri':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                elif 'PlogReaction' in str(type(NewModel.reaction(j))):
                    NewModel.reaction(j).rates = NewModel.reaction(j).rates
                elif 'ChebyshevReaction' in str(type(NewModel.reaction(j))):
                    NewModel.reaction(j).set_parameters(
                        NewModel.reaction(j).Tmin,
                        NewModel.reaction(j).Tmax,
                        NewModel.reaction(j).Pmin,
                        NewModel.reaction(j).Pmax,
                        NewModel.reaction(j).coeffs)
    if MP != {}:
        print('insdie the MP if statment')
        for j in np.arange(original_rxn_count, NewModel.n_reactions):

            try:
                if 'ThreeBodyReaction' in str(type(NewModel.reaction(j))):
                    A = NewModel.reaction(j).rate.pre_exponential_factor
                    n = NewModel.reaction(j).rate.temperature_exponent
                    Ea = NewModel.reaction(j).rate.activation_energy
                    NewModel.reaction(j).rate = ct.Arrhenius(
                        A * np.exp(MP['r' + str(j)]['A']),
                        n + MP['r' + str(j)]['n'],
                        Ea + MP['r' + str(j)]['Ea'] * E)
                elif 'ElementaryReaction' in str(type(NewModel.reaction(j))):
                    A = NewModel.reaction(j).rate.pre_exponential_factor
                    n = NewModel.reaction(j).rate.temperature_exponent
                    Ea = NewModel.reaction(j).rate.activation_energy
                    NewModel.reaction(j).rate = ct.Arrhenius(
                        A * np.exp(MP['r' + str(j)]['A']),
                        n + MP['r' + str(j)]['n'],
                        Ea + MP['r' + str(j)]['Ea'] * E)
                elif 'FalloffReaction' in str(type(NewModel.reaction(j))):
                    A = NewModel.reaction(j).high_rate.pre_exponential_factor
                    n = NewModel.reaction(j).high_rate.temperature_exponent
                    Ea = NewModel.reaction(j).high_rate.activation_energy

                    NewModel.reaction(j).high_rate = ct.Arrhenius(
                        A * np.exp(MP['r' + str(j)]['A']),
                        n + MP['r' + str(j)]['n'],
                        Ea + MP['r' + str(j)]['Ea'] * E)
                    A = NewModel.reaction(j).low_rate.pre_exponential_factor
                    n = NewModel.reaction(j).low_rate.temperature_exponent
                    Ea = NewModel.reaction(j).low_rate.activation_energy
                    NewModel.reaction(j).low_rate = ct.Arrhenius(
                        A * np.exp(MP['r' + str(j)]['A']),
                        n + MP['r' + str(j)]['n'],
                        Ea + MP['r' + str(j)]['Ea'] * E)
                    if NewModel.reaction(j).falloff.type == 'Troe':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                    if NewModel.reaction(j).falloff.type == 'Sri':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                elif 'ChemicallyActivatedReaction' in str(
                        type(NewModel.reaction(j))):
                    A = NewModel.reaction(j).high_rate.pre_exponential_factor
                    n = NewModel.reaction(j).high_rate.temperature_exponent
                    Ea = NewModel.reaction(j).high_rate.activation_energy
                    NewModel.reaction(j).high_rate = ct.Arrhenius(
                        A * np.exp(MP['r' + str(j)]['A']),
                        n + MP['r' + str(j)]['n'],
                        Ea + MP['r' + str(j)]['Ea'] * E)
                    A = NewModel.reaction(j).low_rate.pre_exponential_factor
                    n = NewModel.reaction(j).low_rate.temperature_exponent
                    Ea = NewModel.reaction(j).low_rate.activation_energy
                    NewModel.reaction(j).low_rate = ct.Arrhenius(
                        A * np.exp(MP['r' + str(j)]['A']),
                        n + MP['r' + str(j)]['n'],
                        Ea + MP['r' + str(j)]['Ea'] * E)
                    if NewModel.reaction(j).falloff.type == 'Troe':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                    if NewModel.reaction(j).falloff.type == 'Sri':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                elif 'PlogReaction' in str(type(NewModel.reaction(j))):
                    for number, reactions in enumerate(
                            NewModel.reaction(j).rates):
                        A = NewModel.reaction(
                            j)[number][1].pre_exponential_factor
                        n = NewModel.reaction(
                            j)[number][1].temperature_exponent
                        Ea = NewModel.reaction(j)[number][1].activation_energy
                        NewModel.reaction(j)[number][1] = ct.Arrhenius(
                            A * np.exp(MP['r' + str(j)]['A']),
                            n + MP['r' + str(j)]['n'],
                            Ea + MP['r' + str(j)]['Ea'] * E)
                    NewModel.reaction(j).rates = NewModel.reaction(j).rates
                elif 'ChebyshevReaction' in str(
                        type(original_mechanism.reaction(j))):
                    NewModel.reaction(j).set_parameters(
                        NewModel.reaction(j).Tmin,
                        NewModel.reaction(j).Tmax,
                        NewModel.reaction(j).Pmin,
                        NewModel.reaction(j).Pmax,
                        NewModel.reaction(j).coeffs)

            except:
                print('we are in the except statment in marks code', j)
                if 'ThreeBodyReaction' in str(type(NewModel.reaction(j))):
                    NewModel.reaction(j).rate = NewModel.reaction(j).rate
                elif 'ElementaryReaction' in str(type(NewModel.reaction(j))):
                    NewModel.reaction(j).rate = NewModel.reaction(j).rate
                elif 'FalloffReaction' in str(type(NewModel.reaction(j))):
                    NewModel.reaction(j).high_rate = NewModel.reaction(
                        j).high_rate
                    NewModel.reaction(j).low_rate = NewModel.reaction(
                        j).low_rate
                    if NewModel.reaction(j).falloff.type == 'Troe':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                    if NewModel.reaction(j).falloff.type == 'Sri':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                elif 'ChemicallyActivatedReaction' in str(
                        type(NewModel.reaction(j))):
                    NewModel.reaction(j).high_rate = NewModel.reaction(
                        j).high_rate
                    NewModel.reaction(j).low_rate = NewModel.reaction(
                        j).low_rate
                    if NewModel.reaction(j).falloff.type == 'Troe':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                    if NewModel.reaction(j).falloff.type == 'Sri':
                        NewModel.reaction(j).falloff = NewModel.reaction(
                            j).falloff
                elif 'PlogReaction' in str(type(NewModel.reaction(j))):
                    NewModel.reaction(j).rates = NewModel.reaction(j).rates
                elif 'ChebyshevReaction' in str(type(NewModel.reaction(j))):
                    NewModel.reaction(j).set_parameters(
                        NewModel.reaction(j).Tmin,
                        NewModel.reaction(j).Tmax,
                        NewModel.reaction(j).Pmin,
                        NewModel.reaction(j).Pmax,
                        NewModel.reaction(j).coeffs)

    new_file = ctiw.write(NewModel)
    return new_file, original_rxn_eqs, master_rxn_eqs
Beispiel #10
0
                                        OUTPUT_REACTONS_FILE_NAME)
        write_reactions.write_factors(best_factors, OUTPUT_FACTORS_FILE_NAME)

        # use solution to save ck or cti file
        if OUTPUT_CK:
            gas = ct.Solution(thermo='IdealGas',
                              kinetics='GasKinetics',
                              species=species,
                              reactions=best_reactions)
            soln2ck.write(gas)
        if OUTPUT_CTI:
            gas = ct.Solution(thermo='IdealGas',
                              kinetics='GasKinetics',
                              species=species,
                              reactions=best_reactions)
            soln2cti.write(gas)

    t_iteration_1 = time.time()
    #print('Counter: %d, Loss: %.5f, Time cost: %.2f s' % (counter, loss, (t_iteration_1 - t_iteration_0)))
    num_space = 5 - len(str(counter))
    print('Counter:%s%d, Loss: %.5f, Time cost: %.2f s' %
          (num_space * ' ', counter, loss, (t_iteration_1 - t_iteration_0)))

    # end metrics
    if loss <= MIN_LOSS or counter >= MAX_GAUSS:
        if loss == original_loss:
            print(
                'Did not find a better mech, please increase MAX_GAUSS and retry.'
            )
            exit()
        else:
Beispiel #11
0
def readin(args='none', **argv):
    """Main function for pyMARS

    Parameters
    ----------
    file:
        Input mechanism file (ex. file='gri30.cti')
    species:
        Species to eliminate (ex. species='H, OH')
    thermo:
        Thermo data file if Chemkin format (ex. thermo= 'thermo.dat')
    transport:
        Transport data file if Chemkin format
    plot:
        plot ignition curve (ex. plot='y')
    points:
        print ignition point and sample range (ex. points='y')
    writecsv:
        write data to csv (ex. writecsv='y')
    writehdf5:
        write data to hdf5 (ex. writehdf5='y')
    run_drg:
        Run DRG model reduction

    Returns
    -------
        Converted mechanism file
        Trimmed Solution Object
        Trimmed Mechanism file

    Examples
    --------
    readin(file='gri30.cti', plot='y', species='OH, H')
    """

    class args():

        #package from terminal use case
        if args is not 'none':
            plot = args.plot
            points = args.points
            writecsv = args.writecsv
            writehdf5 = args.writehdf5
            data_file= args.file
            thermo_file = args.thermo
            transport_file = args.transport
            run_drg = args.run_drg
            threshold_values = args.thresholds
            conditions_file = args.conditions
            convert = args.convert
            if args.species is None:
                exclusion_list = []
            else:
                exclusion_list = [str(item) for item in args.species.split(',')]
                #strip spaces
                for i, sp in enumerate(exclusion_list):
                    exclusion_list[i]=sp.strip()

    file_extension= os.path.splitext(args.data_file)[1]

    if file_extension == ".cti" or file_extension == ".xml":
        print("\nThis is an Cantera xml or cti file\n")
        solution_object = ct.Solution(args.data_file)
        if args.plot is True or args.writecsv is True or args.points is True or args.writehdf5 is True:
            print 'running sim'
            sim_result = autoignition_loop_control(solution_object, args)
        if args.run_drg is True:
            new_solution_objects = drg_loop_control(solution_object, args)
            os.system('rm production_rates.hdf5')
            os.system('rm mass_fractions.hdf5')
            drg_trimmed_file = soln2cti.write(new_solution_objects[1])
            try:
                os.system('rm production_rates.hdf5')
            except Exception:
                pass
        if args.convert is True:
            soln2ck.write(solution_object)


    elif file_extension == ".inp" or file_extension == ".dat" or file_extension == ".txt":
        print("\n\nThis is a Chemkin file")
        #convert file to cti
        converted_file_name = convert(args.data_file, args.thermo_file, args.transport_file)

    else:
        print("\n\nFile type not supported")
Beispiel #12
0
def run_drgep(args, solution_object):
    """
    Function to run the drgep method for model reduction

    Parameters
    ----------
    solution_object: ct._Solutuion object
	An object that represents the solution to be trimmed. 
    args: args object
	An object that contains the following:
    file:
        Input mechanism file (ex. file='gri30.cti')
    species:
        Species to eliminate (ex. species='H, OH')
    thermo:
        Thermo data file if Chemkin format (ex. thermo= 'thermo.dat')
    transport:
        Transport data file if Chemkin format
    plot:
        plot ignition curve (ex. plot='y')
    points:
        print ignition point and sample range (ex. points='y')
    writecsv:
        write data to csv (ex. writecsv='y')
    writehdf5:
        write data to hdf5 (ex. writehdf5='y')
    run_drg:
        Run DRG model reduction
    run_drgep:
	Run drgep model.
    error:
	Maximum ammount of error allowed. 
    keepers: list of strings
	The string names of the species that should be kept in the model no matter what.
    targets: list of strings
	The string names of the species that should be used as target species.

	"""

    #Set up variables
    if len(args.target
           ) == 0:  #If the target species are not specified, puke and die.
        print "Please specify a target species."
        exit()
    done = [
    ]  #Singleton to hold wether or not any more species can be cut from the simulation.
    done.append(False)
    threshold = .1  #Starting threshold value
    threshold_i = .1
    error = [
        10.0
    ]  #Singleton to hold the error value of the previously ran simulation.

    try:
        os.system('rm mass_fractions.hdf5')
    except Exception:
        pass

#Find overall interaction coefficients.
    detailed_result = autoignition_loop_control(
        solution_object, args
    )  #The simulation needs to be ran to make the mass_fractions file which has the info to calucalte edge weights I think?
    detailed_result.test.close()
    ignition_delay_detailed = np.array(detailed_result.tau_array)
    rate_edge_data = get_rates(
        'mass_fractions.hdf5',
        solution_object)  #Get edge weight calculation data.
    max_dic = make_dic_drgep(
        solution_object, rate_edge_data,
        args.target)  #Make a dictionary of overall interaction coefficients.

    print "Testing for starting threshold value"
    drgep_loop_control(
        solution_object, args, error, threshold, done,
        max_dic)  #Trim the solution at that threshold and find the error.
    while error[
            0] != 0:  #While the error for trimming with that threshold value is greater than allowed.
        threshold = threshold / 10  #Reduce the starting threshold value and try again.
        threshold_i = threshold_i / 10
        drgep_loop_control(solution_object, args, error, threshold, done,
                           max_dic)

    print("Starting with a threshold value of " + str(threshold))
    sol_new = solution_object
    past = 0  #An integer representing the error introduced in the past simulation.
    done[0] = False

    while not done[0] and error[
            0] < args.error:  #Run the simulation until nothing else can be cut.
        sol_new = drgep_loop_control(
            solution_object, args, error, threshold, done,
            max_dic)  #Trim at this threshold value and calculate error.
        if args.error > error[
                0]:  #If a new max species cut without exceeding what is allowed is reached, save that threshold.
            max_t = threshold

#if (past == error[0]): #If error wasn't increased, increase the threshold at a higher rate.
    #	threshold = threshold + (threshold_i * 4)
        past = error[0]
        #if (threshold >= .01):
        #        threshold_i = .01
        threshold = threshold + threshold_i

    print "\nGreatest result: "
    sol_new = drgep_loop_control(solution_object, args, error, max_t, done,
                                 max_dic)
    if os.path.exsists("production_rates.hdf5"):
        os.system('rm production_rates.hdf5')
    if os.path.exsists('mass_fractions.hdf5'):
        os.system('rm mass_fractions.hdf5')
    drgep_trimmed_file = soln2cti.write(
        sol_new
    )  #Write the solution object with the greatest error that isn't over the allowed ammount.

    try:
        os.system('rm production_rates.hdf5')
    except Exception:
        pass