def read_block_Surface_Secondary (list_datablock_surfsec): # initialization of variables to return names_sorption_secondary_species = [] List_Sorption_secondary_species = [] List_sorption_reactions = [] # variables for loop line_counter = 0 while line_counter < len(list_datablock_surfsec): temp = list_datablock_surfsec[line_counter].strip() if temp == '' or temp[0] == '#' or temp == 'Surface_Secondary': line_counter += 1 else: words_line = temp.split() words_line = remove_coments(words_line) # Remove the parts that contain comments "#" if words_line[0] == '-log_k': R.set_log_k(float(words_line[1])) List_sorption_reactions.append(R) line_counter +=1 else: R = Reaction() dic_reaction = {} for i in range(0, len(words_line), 2): if i == 0: dic_reaction[words_line[i]] = int(1) else: dic_reaction[words_line[i]] = int(words_line[i+1]) R.set_reaction(dic_reaction) S = Surf_species(words_line[0]) S.set_surface_charge (int(words_line[1])) names_sorption_secondary_species.append(words_line[0]) List_Sorption_secondary_species.append(S) line_counter += 1 return names_sorption_secondary_species, List_Sorption_secondary_species, List_sorption_reactions
def read_reactions(self): f = open(Kegg.REACTION_FILE) data = f.read() f.close() print "reaction file read into memory" blocks = data.split("\n///\n") blocks = [b.split("\n") for b in blocks] blocks = [[x for x in b if x.strip() != ""] for b in blocks] blocks = [b for b in blocks if b] print "reactions digested into blocks" blocks = blocks[0:100] for block in blocks: # print block[0] reac_id = None try: reac_id = re.findall(r'(R\d{5})', block[0])[0] except: print block, "failed" reac = Reaction(reac_id, block) if reac: self.reactions.append(reac) else: print "reaction failed" if len(self.reactions) % 100 == 0: print len(self.reactions), "reactions processed"
def parse_line(self, line): """ parse string containing chemical reaction """ line2 = line.split('#') # skip comments line = line2[0] try: if line.find(',') < 0: reactstr = line k = 1.0 else: (reactstr, kstr) = line.split(',', 2) reactstr = reactstr.strip() (kstr, kvar) = kstr.split('=', 2) if (kstr.strip() != 'k'): raise ValueError k = float(kvar) (educts, products) = reactstr.split('-->', 2) edlist = educts.split('+') prlist = products.split('+') edmset = ReactionParser.parse_molecules(self, edlist) prmset = ReactionParser.parse_molecules(self, prlist) except ValueError: print >> sys.stderr, "syntax error on line=", line exit(-1) if (edmset.empty() and prmset.empty()): return newreaction = Reaction(edmset, prmset, k) return newreaction
def getSimulator(xmlFile): tree = ET.parse(xmlFile) crn_tag = tree.getroot() crn = ReactionNetwork() reactions_tag = crn_tag.find('reactions') init_tag = crn_tag.find('init') for reaction_tag in reactions_tag: # Traverse over all reactions rate_constant = int(reaction_tag.attrib.get('rate_constant', 1)) reaction = Reaction(rate_constant) for reaction_chemical_tag in reaction_tag: chemical_name = reaction_chemical_tag.attrib.get('name') chemical_coeff = int(reaction_chemical_tag.attrib.get('coeff')) absense_name = reaction_chemical_tag.attrib.get('absense_name') recChemical = ReactionChemical(chemical_name, chemical_coeff, absense_name) if reaction_chemical_tag.tag == 'reactant': reaction.addReactant(recChemical) else: reaction.addProduct(recChemical) crn.addReaction(reaction) for chemical_tag in init_tag: chemical_name = chemical_tag.attrib.get('name') init_conc = int(chemical_tag.attrib.get('val')) crn.addInitConcentration(chemical_name, init_conc) return Simulator(crn)
def read_block_Secondary_Species (list_datablock_secondary): # initialization of variables to return names_secondary_species = [] List_Aq_classes_secondary_species = [] List_aq_reactions = [] # variables for loop line_counter = 0 while line_counter < len(list_datablock_secondary): temp = list_datablock_secondary[line_counter].strip() if temp == '' or temp[0] == '#' or temp == 'Secondary_Species': line_counter += 1 else: words_line = temp.split() words_line = remove_coments(words_line) # Remove the parts that contain comments "#" if words_line[0] == '-log_k': R.set_log_k(float(words_line[1])) List_aq_reactions.append(R) line_counter +=1 elif words_line[0] == '-a': S.set_ionsizeparameter(float(words_line[1])) line_counter += 1 elif words_line[0] == '-b': S.set_deviationionsizeparameter(float(words_line[1])) line_counter += 1 else: R = Reaction() dic_reaction = {} for i in range(0, len(words_line), 2): if i == 0: dic_reaction[words_line[i]] = int(1) else: dic_reaction[words_line[i]] = int(words_line[i+1]) R.set_reaction(dic_reaction) S = Aq_Species(words_line[0]) names_secondary_species.append(words_line[0]) S.set_charge (int(words_line[1])) List_Aq_classes_secondary_species.append(S) line_counter += 1 return names_secondary_species,List_Aq_classes_secondary_species, List_aq_reactions
from case import DiscordTestCase, Reaction class SkileBot(DiscordTestCase): target_channel = "274134846216077314" target_user = "******" skile = SkileBot() skile.append_interaction("히익", Reaction(reply="힉")) def setup(tester): tester.add_case(skile)
def rr(model): re = Reaction(model) re.setParC('nom', ['Benzene']) re.setParC('Co', ones((1, 1)) * 13.) re.setParC('nC', 1) re.setParC('mm', [78.]) re.setParC('ne', ones((4, 1)) * 30.) re.setParC('k', ones((4, 1)) * 100.) re.setParC('Rf', [1.]) re.setParC('typ', ones((4, 1)) * 2) re.setParM('Co', [8., 0., 0., 0.]) return re
def getReactions(self, mols): listOfReactions = self.__model.getListOfReactions() reactions = [] for i in xrange(len(listOfReactions) ): r = Reaction() r.setName("React_" + str(i + 1)) # +1 for consistence with SBML ordering # Reactants reacts = [] lhsList = [] # Left side STEPS reactants = listOfReactions[i].getListOfReactants() for reactant in reactants: sto = reactant.getStoichiometry() for j in xrange(int(sto)): if(reactant.getSpecies() != "Empty"): reacts.append(reactant.getSpecies()) # Adding the mol Obj from STEPS lhsList.append(mols[reactant.getSpecies()]) r.setReacts(reacts) r.setLhs(lhsList) # Products prods = [] rhsList = [] # Right side STEPS products = listOfReactions[i].getListOfProducts() for product in products: sto = product.getStoichiometry() for j in xrange(int(sto)): if(product.getSpecies() != "Empty"): prods.append(product.getSpecies()) rhsList.append(mols[product.getSpecies()]) r.setProds(prods) r.setRhs(rhsList) # Kinetik constants params = {} kLaw = listOfReactions[i].getKineticLaw() ## Getting the math # math = kLaw.getMath() # numc = math.getNumChildren() # if (numc > 1): # child = math.getLeftChild() # if (child.isOperator() == False) and (child.isNumber() == False): # print child.getName() # i = 1 # for i in xrange(numc -1): # print math.getChild(i).getName() parameters = kLaw.getListOfParameters() for p in parameters: r.setKName(p.getId()) if p.getId() in self.__globalParameters: # Overwrite the local # with the global params[p.getId()] = self.__globalParameters[p.getId()] r.setKValue(self.__globalParameters[p.getId()]) else: params[p.getId()] = p.getValue() r.setKValue(p.getValue()) reactions.append(r) return reactions
def run(glo): # Get path to current directory path = os.getcwd() #Check whether there is a directory for putting calcuation data in. If not create it if not os.path.exists(path + '/Raw'): os.mkdir(path + '/Raw') #Set restart bool for now glo.restart = True # Add system name to path syspath = path + '/' + glo.dirName #Make working directories for each core for i in range(0, glo.cores): if not os.path.exists(path + '/Raw/' + str(i)): os.mkdir(path + '/Raw/' + str(i)) #Start counter which tracks the kinetic timescale mechanismRunTime = 0.0 #Set reaction instance reacs = dict( ("reac_" + str(i), rxn.Reaction(glo.cartesians, glo.species, i, glo)) for i in range(glo.cores)) #Initialise Master Equation object me = MasterEq.MasterEq() # Open files for saving summary mainsumfile = open(('mainSummary.txt'), "a") while mechanismRunTime < glo.maxSimulationTime: # Minimise starting Geom and write summary xml for channel if reacs['reac_0'].have_reactant == False: outputs = [] if __name__ == 'Main': arguments = [] for i in range(0, glo.cores): name = 'reac_' + str(i) arguments.append(reacs[name]) p = multiprocessing.Pool(glo.cores) results = p.map(minReac, arguments) outputs = [result for result in results] for i in range(0, glo.cores): name = 'reac_' + str(i) reacs[name] = outputs[i] else: for i in range(0, glo.cores): name = 'reac_' + str(i) reacs[name].have_reactant = False # Update path for new minima minpath = syspath + '/' + reacs['reac_0'].ReacName # Get smiles name for initial geom and create directory for first minimum if not os.path.exists(minpath): os.makedirs(minpath) #Copy MESMER file from mes folder MESpath = syspath + '/MESMER/' symb = "".join(reacs[name].CombReac.get_chemical_symbols()) if reacs['reac_0'].energyDictionary[symb] == 0.0: for i in range(0, glo.cores): name = 'reac_' + str(i) d = {symb: reacs[name].reactantEnergy} reacs[name].energyDictionary.update(d) # If a MESMER file has not been created for the current minima then create one if not os.path.exists(MESpath): os.makedirs(MESpath) copyfile('mestemplate.xml', MESpath + 'mestemplate.xml') copyfile('mestemplate.xml', MESpath + 'mestemplateFull.xml') MESFullPath = MESpath + 'mestemplateFull.xml' MESpath = MESpath + 'mestemplate.xml' io.writeMinXML(reacs['reac_0'], MESpath, True, False) io.writeMinXML(reacs['reac_0'], MESFullPath, True, False) if reacs['reac_0'].is_bimol_reac == True: io.writeMinXML(reacs['reac_0'], MESpath, True, True) io.writeMinXML(reacs['reac_0'], MESFullPath, True, True) glo.restart = False else: MESFullPath = MESpath + 'mestemplateFull.xml' MESpath = MESpath + 'mestemplate.xml' # If this is a restart then need to find the next new product from the ME, otherwise start trajectories if glo.restart == False: # Open files for saving summary sumfile = open((minpath + '/summary.txt'), "w") reacs['reac_0'].printReac(minpath) for r in range(0, glo.ReactIters): tempPaths = dict(("tempPath_" + str(i), minpath + '/temp' + str(i) + '_' + str(r)) for i in range(glo.cores)) # Now set up tmp directory for each thread for i in range(0, glo.cores): if not os.path.exists(tempPaths[('tempPath_' + str(i))]): os.makedirs(tempPaths[('tempPath_' + str(i))]) if r % 2 == 0: glo.trajMethod = glo.trajMethod1 glo.trajLevel = glo.trajLevel1 else: glo.trajMethod = glo.trajMethod2 glo.trajLevel = glo.trajLevel2 # If this is the first species and it is a bimolecular channel, then initialise a bimolecular trajectory # Otherwise initialise unimolecular trajectory at minima if glo.InitialBi == True: trajs = dict( ("traj_" + str(i), Trajectory.Trajectory( reacs[('reac_' + str(i))].CombReac, glo, tempPaths[( 'tempPath_' + str(i))], str(i), True)) for i in range(glo.cores)) else: trajs = dict( ("traj_" + str(i), Trajectory.Trajectory( reacs[('reac_' + str(i))].CombReac, glo, tempPaths[( 'tempPath_' + str(i))], str(i), False)) for i in range(glo.cores)) results2 = [] outputs2 = [] if __name__ == "Main": arguments1 = [] arguments2 = [] for i in range(0, glo.cores): name = 'reac_' + str(i) name2 = 'traj_' + str(i) arguments1.append(reacs[name]) arguments2.append(trajs[name2]) arguments = list( zip(arguments1, arguments2, [minpath] * glo.cores, [MESpath] * glo.cores, range(glo.cores), [glo] * glo.cores)) p = multiprocessing.Pool(glo.cores) results2 = p.map(runNormal, arguments) outputs2 = [result for result in results2] for i in range(0, glo.cores): name = 'reac_' + str(i) reacs[name] = outputs2[i][0] sumfile.write( str(reacs[name].ProdName) + '_' + str(reacs[name].biProdName) + '\t' + str(reacs[name].forwardBarrier) + '\t' + str(outputs2[i][1].numberOfSteps)) sumfile.flush() # run a master eqution to estimate the lifetime of the current species me.runTillReac(MESpath) me.newSpeciesFound = False # check whether there is a possible bimolecular rection for current intermediate if len(glo.BiList) > 0 and glo.InitialBi == False: for i in range(0, len(glo.BiList)): baseXYZ = reacs['reac_0'].CombReac.get_chemical_symbols() if me.time > (1 / float(glo.BiRates[i])): print( "assessing whether or not to look for bimolecular channel. Rate = " + str(float(glo.BiRates[i])) + "Mesmer reaction time = " + str(me.time)) glo.InitialBi = True xyz = CT.get_bi_xyz(reacs['reac_0'].ReacName, glo.BiList[i]) spec = np.append( baseXYZ, np.array(glo.BiList[i].get_chemical_symbols())) combinedMol = Atoms(symbols=spec, positions=xyz) #Set reaction instance for j in range(0, glo.cores): name = 'reac_' + str(j) d = {symb: reacs[name].reactantEnergy} reacs[name].re_init_bi(xyz, spec) biTrajs = dict( ("traj_" + str(k), Trajectory.Trajectory( combinedMol, glo, tempPaths[( 'tempPath_' + str(k))], str(k), True)) for k in range(glo.cores)) biTempPaths = dict(("tempPath_" + str(k), minpath + '/temp' + str(j)) for k in range(glo.cores)) if __name__ == "Main": arguments1 = [] arguments2 = [] for j in range(0, glo.cores): name = 'reac_' + str(j) name2 = 'traj_' + str(j) biTrajs[name2].fragIdx = (len(baseXYZ), len(xyz)) arguments1.append(reacs[name]) arguments2.append(biTrajs[name2]) arguments = list( zip(arguments1, arguments2, [minpath] * glo.cores, [MESpath] * glo.cores, range(glo.cores), [glo] * glo.cores, [glo.BiList[i]] * glo.cores)) p = multiprocessing.Pool(glo.cores) p.map(runNormal, arguments) glo.InitialBi = False # Run ME from the given minimum. While loop until species formed is new sumfile.close() glo.restart = False glo.InitialBi = False while me.newSpeciesFound == False: me.runTillReac(MESpath) mechanismRunTime += me.time out = me.prodName + ' ' + str(mechanismRunTime) + '\n' me.visitedList.append(me.prodName) mainsumfile.write(out) mainsumfile.flush() if not os.path.exists(syspath + '/' + me.prodName): os.makedirs(syspath + '/' + me.prodName) for i in range(0, glo.cores): if os.path.exists(syspath + '/' + reacs[('reac_' + str(i))].ReacName + '/' + me.prodName): reacs[('reac_' + str(i))].newReac( syspath + '/' + reacs[('reac_' + str(i))].ReacName + '/' + me.prodName, me.prodName, False) else: print("cant find path " + str(syspath + '/' + reacs[ ('reac_' + str(i))].ReacName + '/' + me.prodName)) try: reacs[('reac_' + str(i))].newReac( syspath + '/' + me.prodName, me.prodName, True) except: reacs[('reac_' + str(i))].newReacFromSMILE( me.prodName) io.update_me_start(me.prodName, me.ene, MESpath) me.newSpeciesFound = True else: if me.repeated() == True: me.equilCount += 1 if me.equilCount >= 20: mainsumfile.write('lumping' + ' ' + str(reacs['reac_0'].ReacName) + ' ' + str(me.prodName) + '\n') me.prodName = io.lumpSpecies(reacs['reac_0'].ReacName, me.prodName, MESpath, MESpath) mainsumfile.flush() me.equilCount = 1 minpath = syspath + '/' + me.prodName for i in range(0, glo.cores): if os.path.exists(syspath + '/' + reacs[('reac_' + str(i))].ReacName + '/' + me.prodName): reacs[('reac_' + str(i))].newReac( syspath + '/' + reacs[('reac_' + str(i))].ReacName + '/' + me.prodName, me.prodName, False) else: try: reacs[('reac_' + str(i))].newReac( syspath + '/' + me.prodName, me.prodName, True) except: reacs[('reac_' + str(i))].newReacFromSMILE( me.prodName) io.update_me_start(me.prodName, me.ene, MESpath) me.newspeciesFound = False glo.restart = False mainsumfile.close()
def rr(model): re = Reaction(model); re.setParC('nom',['Benzene']);re.setParC('Co',ones((1,1))*13.) re.setParC('nC',1);re.setParC('mm',[78.]);re.setParC('ne',ones((4,1))*30.) re.setParC('k',ones((4,1))*100.);re.setParC('Rf',[1.]);re.setParC('typ',ones((4,1))*2) re.setParM('Co',[8.,0.,0.,0.]) return re