def test_falloff(self): r = ct.FalloffReaction('OH:2', 'H2O2:1') r.high_rate = ct.Arrhenius(7.4e10, -0.37, 0.0) r.low_rate = ct.Arrhenius(2.3e12, -0.9, -1700 * 1000 * 4.184) r.falloff = ct.TroeFalloff((0.7346, 94, 1756, 5182)) r.efficiencies = {'AR': 0.7, 'H2': 2.0, 'H2O': 6.0} gas2 = ct.Solution(thermo='IdealGas', kinetics='GasKinetics', species=self.species, reactions=[r]) gas2.TPX = self.gas.TPX self.assertNear(gas2.forward_rate_constants[0], self.gas.forward_rate_constants[20]) self.assertNear(gas2.net_rates_of_progress[0], self.gas.net_rates_of_progress[20])
def remove(seed, num, exclude): np.random.seed(seed) reactions = gas.reactions() removed = [] rcandidates = range(0, len(reactions)) rcandidates = [item for item in rcandidates if item not in exclude] removed = np.random.choice(rcandidates, size=num, replace=False) for ind in removed: if (gas.reaction_type(ind) == 1): newreac = ct.ElementaryReaction(reactants=reactions[ind].reactants, products=reactions[ind].products) gas.modify_reaction(ind, newreac) if (gas.reaction_type(ind) == 2): newreac = ct.ThreeBodyReaction(reactants=reactions[ind].reactants, products=reactions[ind].products) gas.modify_reaction(ind, newreac) if (gas.reaction_type(ind) == 4): newreac = ct.FalloffReaction(reactants=reactions[ind].reactants, products=reactions[ind].products) gas.modify_reaction(ind, newreac) return removed
def perturb_parameter_thisisthecomplicatedonethatdoesntwork( self, parameter, new_value): param_info = self.model_parameter_info[parameter] reaction_number = param_info['reaction_number'] parameter_type = param_info['parameter_type'] print(parameter) print(param_info) reaction = self.gas.reaction(reaction_number) print(reaction.rate) rate = None efficiencies = None reactants = reaction.reactant_string products = reaction.product_string rtype = reaction.reaction_type pressurestring = 'pressure' HasFalloff = False if pressurestring in parameter_type: HasFalloff = True if HasFalloff: highrate = reaction.high_rate lowrate = reaction.low_rate if rtype == 4: newreaction = ct.FalloffReaction(reactants=reactants, products=products) if rtype == 8: newreaction = ct.ChemicallyActivatedReaction( reactants=reactants, products=products) else: rate = reaction.rate if rtype == 2: newreaction = ct.ThreeBodyReaction(reactants=reactants, products=products) else: newreaction = ct.ElementaryReaction(reactants=reactants, products=products) if parameter_type == 'A_factor': old_A = rate.pre_exponential_factor old_b = rate.temperature_exponent old_E = rate.activation_energy new_A = new_value newreaction.rate = ct.Arrhenius(A=new_A, b=old_b, E=old_E) if parameter_type == 'Energy': old_A = rate.pre_exponential_factor old_b = rate.temperature_exponent old_E = rate.activation_energy new_E = new_value newreaction.rate = ct.Arrhenius(A=old_A, b=old_b, E=new_E) if parameter_type == 'High_pressure_A': rate = highrate old_A = rate.pre_exponential_factor old_b = rate.temperature_exponent old_E = rate.activation_energy new_A = new_value newreaction.high_rate = ct.Arrhenius(A=new_A, b=old_b, E=old_E) if parameter_type == 'High_pressure_E': rate = highrate old_A = rate.pre_exponential_factor old_b = rate.temperature_exponent old_E = rate.activation_energy new_E = new_value newreaction.high_rate = ct.Arrhenius(A=old_A, b=old_b, E=new_E) if parameter_type == 'Low_pressure_A': rate = lowrate old_A = rate.pre_exponential_factor old_b = rate.temperature_exponent old_E = rate.activation_energy new_A = new_value newreaction.low_rate = ct.Arrhenius(A=new_A, b=old_b, E=old_E) if parameter_type == 'Low_pressure_E': rate = lowrate old_A = rate.pre_exponential_factor old_b = rate.temperature_exponent old_E = rate.activation_energy new_E = new_value newreaction.low_rate = ct.Arrhenius(A=old_A, b=old_b, E=new_E) self.gas.modify_reaction(reaction_number, newreaction) if parameter_type == 'Efficiency': efficiencies = copy.deepcopy(reaction.efficiencies) species = param_info['species'] efficiencies[species] = new_value reaction.efficiencies = efficiencies return
def residual(eta, k0, observations, measure_ind, tmaxes, temperatures, pressures, initials, maxes, yields): rstart = timeit.default_timer() ret = 0 reactions = gas.reaction_equations() k = k0 * 10**eta if (gas.reaction_type(measure_ind) == 1): newrate = ct.ElementaryReaction(gas.reactions()[measure_ind].reactants, gas.reactions()[measure_ind].products) newrate.rate = ct.Arrhenius( k, gas.reactions()[measure_ind].rate.temperature_exponent, gas.reactions()[measure_ind].rate.activation_energy) gas.modify_reaction(measure_ind, newrate) if (gas.reaction_type(measure_ind) == 2): newrate = ct.ThreeBodyReaction( reactants=gas.reactions()[measure_ind].reactants, products=gas.reactions()[measure_ind].products) newrate.efficiencies = gas.reactions()[measure_ind].efficiencies newrate.rate = ct.Arrhenius( k, gas.reactions()[measure_ind].rate.temperature_exponent, gas.reactions()[measure_ind].rate.activation_energy) gas.modify_reaction(measure_ind, newrate) if (gas.reaction_type(measure_ind) == 4): newrate = ct.FalloffReaction( reactants=gas.reactions()[measure_ind].reactants, products=gas.reactions()[measure_ind].products) newrate.efficiencies = gas.reactions()[measure_ind].efficiencies newrate.falloff = gas.reactions()[measure_ind].falloff newrate.low_rate = ct.Arrhenius( k, gas.reactions()[measure_ind].low_rate.temperature_exponent, gas.reactions()[measure_ind].low_rate.temperature_exponent, gas.reactions()[measure_ind].low_rate.activation_energy) newrate.high_rate = gas.reactions()[measure_ind].high_rate gas.modify_reaction(measure_ind, newrate) sys.stdout.flush() for i in range(0, nmeasure): states = runsim_nosense(tmaxes[i], temperatures[i], pressures[i], initials[i]) for n in maxes: lst1 = observations[i].X[:, n] lst2 = states.X[:, n] ind1 = np.array(np.where(np.sign(np.diff(lst1)) == -1))[0, 0] if np.any(np.sign(np.diff(lst2)) == -1): ind2 = np.array(np.where(np.sign(np.diff(lst2)) == -1))[0, 0] else: ind2 = len(lst2) - 1 ret += ((1.0 * ind2 / ind1 - 1)**2 + (lst2[ind2] / lst1[ind1] - 1)**2) / nmeasure if (outflag == 1): print(temperatures[i], tmaxes[i], pressures[i] / ct.one_atm, (1.0 * ind2 / ind1 - 1), (lst2[ind2] / lst1[ind1] - 1)) sys.stdout.flush() for n in yields: lst1 = observations[i].X[:, n] lst2 = states.X[:, n] ret += ((lst2[-1] / lst1[-1] - 1)**2) / nmeasure if (outflag == 1): print(temperatures[i], tmaxes[i], pressures[i] / ct.one_atm, (lst2[-1] / lst1[-1] - 1)) sys.stdout.flush() if (outflag == 1): rstop = timeit.default_timer() print('iter time: %f' % (rstop - rstart)) print('residual: ', ret) print('x: ', eta) sys.stdout.flush() return np.sqrt(ret)
gas.reactions()[measure_ind].rate.temperature_exponent, gas.reactions()[measure_ind].rate.activation_energy) gas.modify_reaction(measure_ind, newrate) if (gas.reaction_type(measure_ind) == 2): newrate = ct.ThreeBodyReaction( reactants=gas.reactions()[measure_ind].reactants, products=gas.reactions()[measure_ind].products) newrate.efficiencies = gas.reactions()[measure_ind].efficiencies newrate.rate = ct.Arrhenius( k, gas.reactions()[measure_ind].rate.temperature_exponent, gas.reactions()[measure_ind].rate.activation_energy) gas.modify_reaction(measure_ind, newrate) if (gas.reaction_type(measure_ind) == 4): newrate = ct.FalloffReaction( reactants=gas.reactions()[measure_ind].reactants, products=gas.reactions()[measure_ind].products) newrate.efficiencies = gas.reactions()[measure_ind].efficiencies newrate.falloff = gas.reactions()[measure_ind].falloff newrate.low_rate = ct.Arrhenius( k, gas.reactions()[measure_ind].low_rate.temperature_exponent, gas.reactions()[measure_ind].low_rate.temperature_exponent, gas.reactions()[measure_ind].low_rate.activation_energy) newrate.high_rate = gas.reactions()[measure_ind].high_rate gas.modify_reaction(measure_ind, newrate) print(measure_ind, reactions[measure_ind]) for n in range(0, nmeasure): states = runsim_nosense(tmaxes[n], temperatures[n], pressures[n], initials[n])
def _build_cantera_solution(cls, gdata): p_ref = gdata['ref_pressure'] species_list = list() for s in gdata['species']: spec = gdata['species'][s] ctspec = ct.Species( s, ','.join( [f'{k}:{spec["atom_map"][k]}' for k in spec['atom_map']])) if spec['cp'][0] == 'constant': Tmin, Tmax, T0, h0, s0, cp = spec['cp'][1:] ctspec.thermo = ct.ConstantCp(Tmin, Tmax, p_ref, list([T0, h0, s0, cp])) elif spec['cp'][0] == 'NASA7': Tmin, Tmid, Tmax, low_coeffs, high_coeffs = spec['cp'][1:] coeffs = [Tmid] + high_coeffs + low_coeffs ctspec.thermo = ct.NasaPoly2(Tmin, Tmax, p_ref, coeffs) species_list.append(ctspec) reaction_list = list() for rxn in gdata['reactions']: type, reactants_stoich, products_stoich, reversible = rxn[:4] fwd_pre_exp_value, fwd_temp_exponent, fwd_act_energy = rxn[4:7] fwd_rate = ct.Arrhenius(fwd_pre_exp_value, fwd_temp_exponent, fwd_act_energy) if type == 'simple' or type == 'simple-special': ctrxn = ct.ElementaryReaction(reactants_stoich, products_stoich) ctrxn.rate = fwd_rate elif type == 'three-body' or type == 'three-body-special': ctrxn = ct.ThreeBodyReaction(reactants_stoich, products_stoich) ctrxn.rate = fwd_rate ctrxn.efficiencies = rxn[7] ctrxn.default_efficiency = rxn[8] elif type == 'Lindemann' or type == 'Lindemann-special': ctrxn = ct.FalloffReaction(reactants_stoich, products_stoich) ctrxn.efficiencies = rxn[7] ctrxn.default_efficiency = rxn[8] flf_pre_exp_value, flf_temp_exponent, flf_act_energy = rxn[ 9:12] ctrxn.high_rate = fwd_rate ctrxn.low_rate = ct.Arrhenius(flf_pre_exp_value, flf_temp_exponent, flf_act_energy) ctrxn.falloff = ct.Falloff() elif type == 'Troe' or type == 'Troe-special': ctrxn = ct.FalloffReaction(reactants_stoich, products_stoich) ctrxn.efficiencies = rxn[7] ctrxn.default_efficiency = rxn[8] flf_pre_exp_value, flf_temp_exponent, flf_act_energy = rxn[ 9:12] troe_params = rxn[12] ctrxn.high_rate = fwd_rate ctrxn.low_rate = ct.Arrhenius(flf_pre_exp_value, flf_temp_exponent, flf_act_energy) if len(troe_params) == 4 and abs(troe_params[3]) < 1e-300: ctrxn.falloff = ct.TroeFalloff(troe_params[:3]) else: ctrxn.falloff = ct.TroeFalloff(troe_params) if 'special' in type: ctrxn.orders = rxn[-1] ctrxn.reversible = reversible reaction_list.append(ctrxn) return ct.Solution(thermo='IdealGas', kinetics='GasKinetics', species=species_list, reactions=reaction_list)
def set_mechanism(self, mech_dict, species_dict={}, bnds=[]): def get_Arrhenius_parameters(entry): A = entry['pre_exponential_factor'] b = entry['temperature_exponent'] Ea = entry['activation_energy'] return A, b, Ea if len(species_dict) == 0: species = self.gas.species() else: species = [] for n in range(len(species_dict)): s_dict = species_dict[n] s = ct.Species(name=s_dict['name'], composition=s_dict['composition'], charge=s_dict['charge'], size=s_dict['size']) thermo = s_dict['type'](s_dict['T_low'], s_dict['T_high'], s_dict['P_ref'], s_dict['coeffs']) s.thermo = thermo species.append(s) # Set kinetics data rxns = [] for rxnIdx in range(len(mech_dict)): if 'ElementaryReaction' == mech_dict[rxnIdx]['rxnType']: rxn = ct.ElementaryReaction(mech_dict[rxnIdx]['reactants'], mech_dict[rxnIdx]['products']) rxn.allow_negative_pre_exponential_factor = True A, b, Ea = get_Arrhenius_parameters( mech_dict[rxnIdx]['rxnCoeffs'][0]) rxn.rate = ct.Arrhenius(A, b, Ea) elif 'ThreeBodyReaction' == mech_dict[rxnIdx]['rxnType']: rxn = ct.ThreeBodyReaction(mech_dict[rxnIdx]['reactants'], mech_dict[rxnIdx]['products']) A, b, Ea = get_Arrhenius_parameters( mech_dict[rxnIdx]['rxnCoeffs'][0]) rxn.rate = ct.Arrhenius(A, b, Ea) rxn.efficiencies = mech_dict[rxnIdx]['rxnCoeffs'][0][ 'efficiencies'] elif 'PlogReaction' == mech_dict[rxnIdx]['rxnType']: rxn = ct.PlogReaction(mech_dict[rxnIdx]['reactants'], mech_dict[rxnIdx]['products']) rates = [] for plog in mech_dict[rxnIdx]['rxnCoeffs']: pressure = plog['Pressure'] A, b, Ea = get_Arrhenius_parameters(plog) rates.append((pressure, ct.Arrhenius(A, b, Ea))) rxn.rates = rates elif 'FalloffReaction' == mech_dict[rxnIdx]['rxnType']: rxn = ct.FalloffReaction(mech_dict[rxnIdx]['reactants'], mech_dict[rxnIdx]['products']) # high pressure limit A, b, Ea = get_Arrhenius_parameters( mech_dict[rxnIdx]['rxnCoeffs']['high_rate']) rxn.high_rate = ct.Arrhenius(A, b, Ea) # low pressure limit A, b, Ea = get_Arrhenius_parameters( mech_dict[rxnIdx]['rxnCoeffs']['low_rate']) rxn.low_rate = ct.Arrhenius(A, b, Ea) # falloff parameters if mech_dict[rxnIdx]['rxnCoeffs']['falloff_type'] == 'Troe': falloff_param = mech_dict[rxnIdx]['rxnCoeffs'][ 'falloff_parameters'] if falloff_param[-1] == 0.0: falloff_param = falloff_param[0:-1] rxn.falloff = ct.TroeFalloff(falloff_param) else: rxn.falloff = ct.SriFalloff( mech_dict[rxnIdx]['rxnCoeffs']['falloff_parameters']) rxn.efficiencies = mech_dict[rxnIdx]['rxnCoeffs'][ 'efficiencies'] elif 'ChebyshevReaction' == mech_dict[rxnIdx]['rxnType']: rxn = ct.ChebyshevReaction(mech_dict[rxnIdx]['reactants'], mech_dict[rxnIdx]['products']) rxn.set_parameters(Tmin=mech_dict['Tmin'], Tmax=mech_dict['Tmax'], Pmin=mech_dict['Pmin'], Pmax=mech_dict['Pmax'], coeffs=mech_dict['coeffs']) rxn.duplicate = mech_dict[rxnIdx]['duplicate'] rxn.reversible = mech_dict[rxnIdx]['reversible'] rxn.allow_negative_orders = True rxn.allow_nonreactant_orders = True rxns.append(rxn) self.gas = ct.Solution(thermo='IdealGas', kinetics='GasKinetics', species=species, reactions=rxns) self.set_rate_expression_coeffs(bnds) # set copy of coeffs self.set_thermo_expression_coeffs() # set copy of thermo coeffs
def toCantera(self, speciesList=None, useChemkinIdentifier = False): """ Converts the RMG Reaction object to a Cantera Reaction object with the appropriate reaction class. If useChemkinIdentifier is set to False, the species label is used instead. Be sure that species' labels are unique when setting it False. """ from rmgpy.kinetics import Arrhenius, ArrheniusEP, MultiArrhenius, PDepArrhenius, MultiPDepArrhenius, Chebyshev, ThirdBody, Lindemann, Troe import cantera as ct if speciesList is None: speciesList = [] # Create the dictionaries containing species strings and their stoichiometries # for initializing the cantera reaction object ctReactants = {} for reactant in self.reactants: if useChemkinIdentifier: reactantName = reactant.toChemkin() else: reactantName = reactant.label if reactantName in ctReactants: ctReactants[reactantName] += 1 else: ctReactants[reactantName] = 1 ctProducts = {} for product in self.products: if useChemkinIdentifier: productName = product.toChemkin() else: productName = product.label if productName in ctProducts: ctProducts[productName] += 1 else: ctProducts[productName] = 1 if self.kinetics: if isinstance(self.kinetics, Arrhenius): # Create an Elementary Reaction ctReaction = ct.ElementaryReaction(reactants=ctReactants, products=ctProducts) elif isinstance(self.kinetics, MultiArrhenius): # Return a list of elementary reactions which are duplicates ctReaction = [ct.ElementaryReaction(reactants=ctReactants, products=ctProducts) for arr in self.kinetics.arrhenius] elif isinstance(self.kinetics, PDepArrhenius): ctReaction = ct.PlogReaction(reactants=ctReactants, products=ctProducts) elif isinstance(self.kinetics, MultiPDepArrhenius): ctReaction = [ct.PlogReaction(reactants=ctReactants, products=ctProducts) for arr in self.kinetics.arrhenius] elif isinstance(self.kinetics, Chebyshev): ctReaction = ct.ChebyshevReaction(reactants=ctReactants, products=ctProducts) elif isinstance(self.kinetics, ThirdBody): ctReaction = ct.ThreeBodyReaction(reactants=ctReactants, products=ctProducts) elif isinstance(self.kinetics, Lindemann) or isinstance(self.kinetics, Troe): ctReaction = ct.FalloffReaction(reactants=ctReactants, products=ctProducts) else: raise NotImplementedError('Not able to set cantera kinetics for {0}'.format(self.kinetics)) # Set reversibility, duplicate, and ID attributes if isinstance(ctReaction,list): for rxn in ctReaction: rxn.reversible = self.reversible # Set the duplicate flag to true since this reaction comes from multiarrhenius or multipdeparrhenius rxn.duplicate = True # Set the ID flag to the original rmg index rxn.ID = str(self.index) else: ctReaction.reversible = self.reversible ctReaction.duplicate = self.duplicate ctReaction.ID = str(self.index) self.kinetics.setCanteraKinetics(ctReaction, speciesList) return ctReaction else: raise Exception('Cantera reaction cannot be created because there was no kinetics.')