def findRelatedBySym( this, tol=1e-1 ): print "FIND ATOMS RELATED BY SYMMETRY" print "------------------------------" print " TOLERANCE = ", tol if( len( this.symmetryOperators ) == 0 ): print " ## ERROR ##: The molecule have not symmetry operators" return print "" symGrp = 0 for atom in this: if( atom.real ): atom.symGrp = symGrp print " ", "%5d"%atom.id, "--> [", for p in this.symmetryOperators: xyz = atom.xyzMatrix()*p.rotation.transpose()+numpy.matrix( p.translation ) proyectedAtom = Atom( xyz[0,0], xyz[0,1], xyz[0,2], label=atom.label, charge=atom.charge, id=atom.id ) for atom2 in this: r = numpy.sqrt( sum( (atom2.xyzArray()-proyectedAtom.xyzArray())**2 ) ) if( r < tol ): atom2.symGrp = symGrp print atom2.id, print "]" symGrp += 1 this.nSymGrp = symGrp print ""
def parse_list(t, p): """Takes a nested list that represents a chemical formula (returned by the function make_list()), makes an analogous list of atoms, and numbers the atoms in order. t: list of str p: Parser object Returns: list of Atoms """ res = [] for elem in t: if type(elem) == str: #res.append(elem + str(i)) #appends string if elem == 'C': res.append(Atom.Carbon(elem + str(p.i))) #appends atom if elem == 'N': res.append(Atom.Nitrogen(elem + str(p.i))) #appends atom if elem == 'O': res.append(Atom.Oxygen(elem + str(p.i))) #appends atom if elem == 'P': res.append(Atom.Phosphorus(elem + str(p.i))) #appends atom if elem == 'S': res.append(Atom.Sulfur(elem + str(p.i))) #appends atom p.incr() if type(elem) == list: res.append(parse_list(elem, p)) return res
def setAtomsAndConnections(self): ignore = [] atom_numbers = [] Hs = [] for line in self.lines: if line.split()[0].startswith("ATOM") and len(line.strip()) > 20: atom = Atom(line) atom_numbers.append(int(atom.id)) self.graph.add_node(atom.getID()) a = Atom(line) self.atoms[int(a.getID())] = a if a.atomname.__contains__("H"): self.atoms[int(a.getID())].atomtype = "HD" Hs.append(a) for key in self.atoms.keys(): atom = self.atoms[key] if atom.atomname == "O": for H in Hs: if distance(atom.getXYZ(), H.getXYZ()) < 1.5: print("or here") self.atoms[int(H.getID())].atomname = "HD" self.atoms[int(atom.getID())].atomname = "OA" if atom.atomname == "N": for H in Hs: if distance(atom.getXYZ(), H.getXYZ()) < 1.5: print("here") self.atoms[int(H.getID())].atomname = "HD"
def _open_sublist(self): """Appends an empty sublist to the current list. After completion, _this_atom will point to the sublist.""" # opening a sublist at top level if self._level == 1: next_atom = Atom.build_atom_from_cons(self._place_first_atom, Atom.NIL, self._this_atom) if self._this_atom: self._this_atom.data.second = next_atom # adding sublist below top level else: sublist = Atom.build_atom_from_cons(None, Atom.NIL, self._this_atom) if self._this_atom: if self._this_atom.data.first: self._this_atom.data.second = sublist else: self._this_atom.data.first = sublist # if the new sublist had to go into the second field, then we don't need to stick the next atom # inside another sublist if not self._this_atom.data.second == sublist: sublist.data.first = self._place_first_atom next_atom = sublist else: next_atom = Atom.build_atom_from_cons( self._place_first_atom, Atom.NIL, sublist) sublist.data.first = next_atom if not self._root: self._root = next_atom self._this_atom = next_atom
def _open_sublist(self): """Appends an empty sublist to the current list. After completion, _this_atom will point to the sublist.""" # opening a sublist at top level if self._level == 1: next_atom = Atom.build_atom_from_cons(self._place_first_atom, Atom.NIL, self._this_atom) if self._this_atom: self._this_atom.data.second = next_atom # adding sublist below top level else: sublist = Atom.build_atom_from_cons(None, Atom.NIL, self._this_atom) if self._this_atom: if self._this_atom.data.first: self._this_atom.data.second = sublist else: self._this_atom.data.first = sublist # if the new sublist had to go into the second field, then we don't need to stick the next atom # inside another sublist if not self._this_atom.data.second == sublist: sublist.data.first = self._place_first_atom next_atom = sublist else: next_atom = Atom.build_atom_from_cons(self._place_first_atom, Atom.NIL, sublist) sublist.data.first = next_atom if not self._root: self._root = next_atom self._this_atom = next_atom
def symbol_funcall(fun, args): fun_name = args[0] if fun_name.type == Atom.Atom.CONS: result = Atom.evaluate(fun_name, fun) return result.data(args[1:]) else: function = Atom.evaluate(fun_name, fun) return function.data(function.__str__(), args[1:])
def symbol_defun(fun, args): symbol_name = args[0].data function_args = Atom.cons_to_list(args[1].data) if function_args == [None]: function_args = [] results = args[2:] functions[symbol_name] = lambda fun_name, args: evaluate_function(fun_name, args, function_args, results) return Atom.make_symbol(symbol_name)
def worker(input_queue): while True: url = input_queue.get() if url is None: break path = vd.NSE_COMPANY_DATA_PATH df_ls = pd.read_csv(vd.NSE_ALL_COMPANY_LIST_URI) print("Requesting from {}".format(url)) data, timestamp = base.get_json_data(url) print("\nRequest acheived of {}\n".format(url)) print("Updating data of {}".format(url[url.rfind('/') + 1:])) for i in range(len(data)): d = data[i] ls = [] try: ls = df_ls[df_ls['Symbol'] == d['symbol']].values.tolist()[0] except IndexError as e: info_dict = base.get_info_companies(d['symbol']) ls.extend([0, '', '', '']) for key in info_dict: ls.append(info_dict[key]) logging.error(d['symbol'] + ' : ' + str(e)) d['Company Name'] = ls[2] d['Market Capitalization'] = ls[3] d['Date of Listing'] = ls[4] d['Face Value'] = ls[5] d['ISIN Code'] = ls[6] d['Industry'] = ls[7] d['timestamp'] = timestamp columns = [i for i in d] filename = path + '\\' + d['symbol'] + '.csv' if os.path.isfile(filename): with open(filename, 'r', newline='') as fp: reader = csv.DictReader(fp, fieldnames=columns) similar = isSimilar_ret(reader, d) fp.close() if not similar: with open(filename, '+a', newline='') as fp: writer = csv.DictWriter(fp, fieldnames=columns) writer.writerow(d) fp.close() else: with open(filename, 'w', newline='') as fp: writer = csv.DictWriter(fp, fieldnames=columns) writer.writeheader() writer.writerow(d) fp.close() print('Data stored of {}'.format(url[url.rfind('/') + 1:])) print('-' * 50)
def AddAtomTo(self, to_atom): if not to_atom: return newatom = Atom(graph=self) # new atom b = Bond(newatom, to_atom) # new bond # add to both bonds edge lists to_atom.AddBond(b) newatom.AddBond(b) self.atoms.append(newatom) self.bonds.append(b)
def eval(args, called_from): if not isinstance(args, Atom.Atom) and not isinstance(args, Cons.Cons): return args if isinstance(args, Cons.Cons): args = args.first atom = Atom.evaluate(args, called_from) if isinstance(atom, Atom.Atom): if atom.type == Atom.Atom.SYMBOL: return eval(Environment.get_symbol_value(atom.data), called_from) atom = Atom.evaluate(atom, called_from) return atom
def test_disp100(nq, ne): """Calculates the scattering intensity for phonon dispersions for B2 FeAl along q // [100]. nq = number of q points to calculate. ne = number of e points to calculate.""" uc = UnitCell() at1 = Atom(symbol='Fe', mass=57) pos1 = (0.0, 0.0, 0.0) at2 = Atom(symbol='Al') pos2 = (0.5, 0.5, 0.5) site1 = Site(pos1, at1) site2 = Site(pos2, at2) uc.addAtom(at1, pos1, "Fe1") uc.addAtom(at2, pos2, "Al1") print uc kptlist = uc.getMonkhorstPackGrid((20, 20, 20)).reshape(8000, 3) sqecalc = AbInitio.kernelGenerator.SqeCalculator.SqeCalculator( uc, kpoints=kptlist) sqecalc.readIDFeigenvectors(filename='pols_FeAl222.idf') sqecalc.readEigenvaluesFromIDFomega2(filename='omega2_FeAl222.idf') sqecalc._DebyeWallerCalculator._energies = sqecalc._energies sqecalc._DebyeWallerCalculator._polvecs = sqecalc._polvecs estart = 0.0 deltae = 50.0 / ne sqecalc._etransferTol = deltae deltaqx = 3.0 / nq sqecalc._qtransferTolRadius = deltaqx qstart = numpy.array([0.0, 0.0, 0.0]) deltaq = numpy.array([deltaqx, 0.0, 0.0]) sqe = numpy.zeros((nq, ne), dtype='float') for iq in range(nq): for ie in range(ne): qtransfer = qstart + iq * deltaq etransfer = estart + ie * deltae sqe[iq, ie] = sqecalc.calcSqeCohCreateAllmodes(qtransfer, etransfer) print iq, ie, sqe[iq, ie] pylab.imshow(sqe) pylab.show() end = raw_input() return
def symbol_let(fun, args): Environment.enter_frame() params = Atom.cons_to_list(args[0].data) result = args[1] for pair in params: pair = pair.data symbol_name = pair.first.data symbol_value = Atom.evaluate(pair.second.data.first, fun) Environment.set_dynamic_symbol(symbol_name, symbol_value) result = Atom.evaluate(result, fun) Environment.leave_frame() return result
def symbol_while(fun, args): # condition = args[0] #statements = args[1:] result = Atom.NIL while True: #if not eval(condition, fun): # return result for s in args: result = Atom.evaluate(s, fun) if isinstance(result, Atom.Atom) and result.type == Atom.Atom.CONS and result.data.first.data == "RETURN": if result.data.second != Atom.NIL: return Atom.evaluate(result.data.second.data.first) else: return Atom.NIL
def symbol_format(fun, args): newline = Atom.evaluate(args[0], fun) #control = eval(args[1], fun) control = re.sub("\\{\\}", "%s", eval(args[1], fun)) args = args[2:] for i in range(len(args)): args[i] = Atom.evaluate(args[i]) if not isinstance(args[i], Atom.Atom): args[i] = Atom.make_atom(args[i]) elif args[i].type == Atom.Atom.STRING: args[i] = args[i].data args = tuple(args) print(control % args, end="") if newline: print("")
def AddAtomTo(self, to_atom): if not to_atom: return newatom = Atom(graph=self) # luodaan uusi solmu b = Bond(newatom, to_atom) # luodaan kaari 'newnode' -> 'to_node' # lisätään molempien solmujen kaarilistaan to_atom.AddBond(b) newatom.AddBond(b) # lisätään verkon listoihin uusi solmu ja kaari self.atoms.append(newatom) self.bonds.append(b)
def orphan(cons): """Creates a list with no parent from a list. All atoms are kept in place, but a new root cons object with no parent is created to contain the first atom of the list.""" new_atom = Atom.build_atom_from_cons(cons.data.first, cons.data.second) new_atom.quote = cons.quote return new_atom
def fill(t, p): """Takes a flattened list of Atom objects and adds hydrogen atoms to them where appropriate. t: list of Atom objects p: Parser object""" res = copy.copy(t) for j in range(len(t)): atom = t[j] if isinstance(atom, Atom.Atom): num_h = 4 - len( atom.bonds ) #Since Atom objects cannot have more than 4 bonds, the only spaces that remain must belong to hydrogens. # print num_h if num_h > 0: for n in range( num_h ): #for every space that remains in atom.bonds, append a Hydrogen object to the bonds list. hyd = Atom.Hydrogen('H' + str(p.i)) res.append(hyd) final_atom = res[j] final_atom.bonds.append(hyd) p.i += 1 else: fill(t[j], p) return res
def read_PQR_into_atomList(arg_pqrFile): """ Read lines from a PQR file and creates instances of Class Atom for each of them. Make a list of these instances and return it. """ atomSerial = 0 atomList = [] with open(arg_pqrFile, 'r') as fPQR: for line in fPQR: line = line.strip() if line.startswith("ATOM") or line.startswith("HETATM"): atomSerial += 1 atomArgs = { 'header' : line[0:6].strip(), 'index' : int(line[6:11]), 'atomName' : line[12:16].strip(), 'resName' : line[17:20].strip(), 'x' : float(line[30:38]), 'y' : float(line[38:46]), 'z' : float(line[46:54]), 'charge' : float(line[54:62]), 'radius' : float(line[62:69]) } newAtom = Atom.Atom(arg_serial = atomSerial, **atomArgs) atomList.append(newAtom) return atomList
def create_atom(self, path="atom", weight=1.0, \ label_type = Events.AbstractLabel, contents_type=Events.AbstractContents, event_type=Events.AbstractEvent, \ activity_type = ActivityPatterns.ClassicActivityPattern, memory_type = MemorySpaces.NGramMemorySpace, memory_file = None): '''creating an atom at required path''' atom = None if ":" in path: head, tail = Tools.parse_path(path) # if atom in a sub-streamview atom = self.atoms[head].add_atom(tail, weight, label_type, contents_type, event_type, activity_type, memory_type) print "[ERROR] Could not add atom {0} in streamview {1}".format( path, self.name) else: # if atom is directly in current streamview if path in self.atoms: print "[ERROR] Atom {0} already existing in {1}".format( path, self.name) else: atom = Atom.Atom(path, weight, label_type, contents_type, event_type, activity_type, memory_type, memory_file) self.atoms[path] = atom return atom
def symbol_setf(fun, args): """Sets the value of an atom ref A reference to an atom value The value to be evaluated and copied into ref""" ref = Atom.evaluate(args[0], fun, True) value = Atom.evaluate(args[1], fun, True) if not isinstance(value, Atom.Atom): new_atom = Atom.make_atom(value) else: new_atom = value ref.type = new_atom.type ref.data = new_atom.data return new_atom
def symbol_dolist(fun, args): pair = Atom.cons_to_list(args[0].data) symbol_name = pair[0].data list = Atom.cons_to_list(Atom.evaluate(pair[1]).data) Environment.enter_frame() body = args[1:] result = None for x in list: Environment.set_dynamic_symbol(symbol_name, x) for s in body: result = Atom.evaluate(s) Environment.leave_frame() return result
def symbol_null(fun, args): result = Atom.evaluate(args[0], fun) if ((result.type == Atom.Atom.BOOLEAN and result.data is False) or (not result and type(result) is bool)): return Atom.T else: return Atom.NIL
def symbol_while(fun, args): # condition = args[0] #statements = args[1:] result = Atom.NIL while True: #if not eval(condition, fun): # return result for s in args: result = Atom.evaluate(s, fun) if isinstance( result, Atom.Atom ) and result.type == Atom.Atom.CONS and result.data.first.data == "RETURN": if result.data.second != Atom.NIL: return Atom.evaluate(result.data.second.data.first) else: return Atom.NIL
def symbol_defvar(fun, args): """Sets a variable in the current stack frame""" symbol_name = args[0].data result = Atom.evaluate(args[1], fun) Environment.set_dynamic_symbol(symbol_name.upper(), result) return result
def fill_hydrogens(t): """Takes a flattened list of Atom objects (from the function flatten()) and fills in all the missing hydrogen Atoms such that each Atom object has four bonds. t: list of Atom objects Returns: list of Atom objects. """ i = 0 res = copy.copy(t) #for debugging/testing purposes -- can delete later! This variable will keep count of the number of hydrogens added at a given point in time. c = 0 for j in range(len(t)): atom = t[j] num_h = 4 - len( atom.bonds ) #Since Atom objects cannot have more than 4 bonds, the only spaces that remain must belong to hydrogens. # print num_h if num_h > 0: #Again, these two lines are for debugging purposes only. Delete them if you do not want extra output. c += num_h print c for n in range( num_h ): #for every space that remains in atom.bonds, append a Hydrogen object to the bonds list. print('Adding a Hydrogen') hyd = Atom.Hydrogen('H' + str(i)) res.append(hyd) final_atom = res[j] final_atom.bonds.append(hyd) i += 1 return res
def symbol_read_char(fun, args): handle = eval(args[0], fun) if handle not in file_handles: raise LispError("READ-CHAR: File handle not active") ch = file_handles[handle].read(1) if not ch: return Atom.make_symbol("EOF") return "\"%s\"" % ch
def evaluate_function(fun_name, args, params, results): Environment.enter_frame() # initialize parameters for i, arg in enumerate(args): param_name = params[i].data param_value = Atom.evaluate(arg, fun_name) # eval(arg, fun_name) Environment.set_dynamic_symbol(param_name, param_value if isinstance(param_value, Atom.Atom) else Atom.make_atom(param_value)) result = None for x in results: # evaluate result of function given current stack frame result = eval(x, fun_name) Environment.leave_frame() return result
def newAtom(self): """ function newAtom: creates and returns an atom in the current residue """ myatom = Atom() self.addAtom(myatom) return myatom
def setAtomsAndConnections(self): ignore = [] atom_numbers = [] for line in self.lines: if (line.split()[0].startswith("ATOM") or line.split()[0].startswith("HETATM")) and len( line.strip()) > 20: atom = Atom(line) atom_numbers.append(atom.id) if not atom.atom_type.__contains__("H"): self.graph.add_node(atom.getID()) a = Atom(line) self.atoms[int(a.getID())] = a else: ignore.append(int(atom.getID())) elif line.startswith("CONECT"): split = line.split() if int(split[1]) in atom_numbers: for connection in split[2:]: if int(connection) not in ignore and int( split[1]) not in ignore: self.atoms[int(line.split()[1])].add_connection( int(connection)) self.graph.add_edge(int(split[1]), int(connection))
def symbol_read(fun, args): handle = eval(args[0], fun) if handle not in file_handles: raise LispError("READ: File handle not active") try: parser = LispParser.LispParser(file_handles[handle]) return parser.read_object() except StopIteration: return Atom.make_symbol("EOF")
def __init__(self, index, nAtoms, atomic_type): self.index = index self.nAtoms = nAtoms self.atomic_type = atomic_type assert self.nAtoms == len(self.atomic_type) self.atoms = [] for i in range(self.nAtoms): self.atoms.append(Atom.Atom(index, self.atomic_type[i]))
def symbol_do(fun, args): condition = args[0] body = args[1:] result = Atom.NIL while True: if not eval(condition, fun): return result for s in body: result = Atom.evaluate(s, fun) return result
def readstring(self, lines): lines = lines.split(os.linesep) numAtoms = string.atoi(lines[0]) lines = lines[2:] for i in range(numAtoms): element, x, y, z = lines[i].split() x, y, z = map(string.atof, (x, y, z)) a = Atom.Atom() a.fromXyz(element, x, y, z) self.atoms.append(a)
def _process_token(self): if self._finish_token: # just completed token # encapsulate the token inside an atom of the proper type next_atom = Atom.detect_type(self._finish_token) self._finish_token = "" # quote closed list if self._level == self._quote_level: self._quote_level = None # next_atom = Atom.make_quote(next_atom) next_atom.quote += 1 # return completed atom outside of list if self._level == 0: return next_atom # append atom to current list if self._this_atom.data.first: # if we've already filled the current cons, place the current atom in a new cons and link to that next_cons = Atom.build_atom_from_cons(next_atom, Atom.NIL, self._this_atom) self._this_atom.data.second = next_cons self._this_atom = next_cons else: # otherwise just place it into the current cons self._this_atom.data.first = next_atom if self._open_paren: self._open_sublist() self._place_first_atom = None self._open_paren = False if self._close_paren: self._close_paren = False self._close_sublist() if self._level == 0: return self._root
def checkSymmetry( this, tol=1e-1, force=False ): print "SYMMETRY CHECKING" print "-----------------" print " TOLERANCE = ", tol print " FORCE SYMMETRY = ", force if( len( this.symmetryOperators ) == 0 ): print " Skipping check, because the molecule have not symmetry operators" return isSymmetric = True for atom in this: for p in this.symmetryOperators: xyz = atom.xyzMatrix()*p.rotation.transpose()+numpy.matrix( p.translation ) proyectedAtom = Atom( xyz[0,0], xyz[0,1], xyz[0,2], label=atom.label, charge=atom.charge, id=atom.id ) for atom2 in this: r = numpy.sqrt( sum( (atom2.xyzArray()-proyectedAtom.xyzArray())**2 ) ) if( r < tol and r > Atom.xyzThresholdComparison ): print " Is possible that this atoms are equivalent:" print " "+str(atom2) print " "+str(proyectedAtom) isSymmetric = False if( force ): print " Forced to satisfy the symmetry !!!" atom2.set( x=proyectedAtom.x, y=proyectedAtom.y, z=proyectedAtom.z ) if( force ): print " The molecule now is according with the symmetry operators" else: if( isSymmetric ): print " The molecule is according with the symmetry operators" else: print " The molecule is not according with the symmetry operators"
def symbol_if(fun, args): condition = eval(args[0], fun) if condition: return Atom.evaluate(args[1], fun) option2 = Atom.evaluate(args[2], fun) if len(args) > 2 else Atom.NIL return option2
file = ReadaheadBuffer(sys.stdin) show_prompt = True parser = LispParser.LispParser(file) while True: if show_prompt: print("> ", end="") try: atom = parser.read_object() except StopIteration: break except LispError as err: print("Parser error: %s\n" % err) continue except KeyboardInterrupt: print("<<keyboard interrupt>>") continue try: result = Atom.evaluate(atom, True) if show_prompt: #if result != None: print(result) print() except LispError as err: print("Error: %s\n" % err) except KeyboardInterrupt: print("<<keyboard interrupt>>") #except Exception as err: # print("Python exception: %s" % err)
def _process_character(self, ch): if self._in_comment: if ch == "\n": # end comment self._in_comment = False elif self._in_quotation or self._in_character_quote: if self._in_escape: self._in_escape = False if ch == "\\": self._token += "\\" elif ch == "\r": self._token += "\r" elif ch == "\n": self._token += "\n" elif ch == "\t": self._token += "\t" elif ch == '"': self._token += '"' else: raise LispError("Unknown escape sequence \\%s" % ch) elif ch == "\\": self._in_escape = True return else: self._token += ch if ch == '"' and not self._in_character_quote: self._in_quotation = False self._finish_token = self._token self._token = "" self._in_character_quote = False elif ch == ";": # begin comment self._in_comment = True elif ch == "'": # quoted object begins here self._quote_level = self._level # self._quote_atom = self._this_atom elif ch.isspace() or ch == ",": # token delimiter if self._last and not self._last.isspace(): self._finish_token = self._token self._token = "" elif ch == "(": if self._last == "#": self._token = "#(" while True: peek = self._input.read(1) self._token += peek if peek == ")": break self._finish_token = self._token self._token = "" else: # open s-expression self._level += 1 self._open_paren = True elif ch == "[": # open m-expression self._place_first_atom = Atom.detect_type(self._token) self._token = "" self._level += 1 self._open_paren = True elif ch == ")" or ch == "]": if self._level: # close s- or m-expression self._close_paren = True self._finish_token = self._token self._token = "" else: self._finish_token = self._token self._token = "" self._input.putback(")") elif ch == '"': # open/close string self._token += ch self._in_quotation = True else: # add to token self._token += ch if self._token == "#\\": self._in_character_quote = True self._last = ch
def input(self, fname): f = open(fname) lines = map(str.strip, f.readlines()) f.close() # set # - self.atoms # - self.bonds # - self.reactions # - self.compoundatoms # - self.compoundbonds for line in lines: data = line.split()[1:] # print line if line.startswith("ATOM"): i = int(data[0]) s = data[1] coords = {} for xystr in data[2].split(","): c = xystr.split(":")[0] x,y = xystr.split(":")[1].split("|") coords[c] = Point() coords[c].x = float(x) coords[c].y = float(y) a = Atom(id=i,symbol=s) a.coords = coords self.AddAtom(a) elif line.startswith("BOND"): i = int(data[0]) srcid = int(data[1]) tgtid = int(data[2]) t = int(data[3]) source = self.atoms[srcid-1] target = self.atoms[tgtid-1] b = Bond(id=i,source=source,target=target,type=t) b.reactions = {} self.AddBond(b) elif line.startswith("COMPOUND"): c = data[0] atoms = data[1][1:-1] bonds = data[2][1:-1] # first compoundptr if c not in self.compoundatoms: self.compoundatoms[c] = [[]] self.compoundbonds[c] = [[]] for aid in atoms.split(","): self.compoundatoms[c][-1].append( self.atoms[int(aid)-1]) for bid in bonds.split(","): if bid: self.compoundbonds[c][-1].append(self.bonds[int(bid)-1]) else: self.compoundatoms[c].append([]) self.compoundbonds[c].append([]) for aid in atoms.split(","): self.compoundatoms[c][-1].append( self.atoms[int(aid)-1]) for bid in bonds.split(","): if bid: self.compoundbonds[c][-1].append(self.bonds[int(bid)-1]) elif line.startswith("REACTIONCHANGE"): bid = int(data[0]) ligand = data[1].split(":")[0] type = int(data[1].split(":")[1]) self.bonds[bid-1].reactions[ligand] = type elif line.startswith("REACTION"): ligand = data[0] atoms = data[1][1:-1] bonds = data[2][1:-1] self.reactions[ligand] = [] for aid in atoms.split(","): self.reactions[ligand].append(self.atoms[int(aid)-1]) for bid in bonds.split(","): bid = int(bid) self.bonds[bid-1].reactions[ligand] = 0
def read(self, mapfile = None): # print self.reaction.ligand # read mappings self.reaction.read_mapping("ASTAR", mapfile) if not self.reaction.mappings[0].mapping: # print "no mappings" self = None return # get sub/prod atoms, mapping both ways, compound list subatoms = [a for sub in self.reaction.subs if sub.graph for a in sub.graph.atoms ] prodatoms = [a for prod in self.reaction.prods if prod.graph for a in prod.graph.atoms] mapping = self.reaction.mappings[-1].mapping revmapping = dict( [(rhs,lhs) for lhs,rhs in mapping.items()] ) newatoms = {} aids = 1 # atom id counter bids = 1 # for k,v in mapping.items(): # print k,v # print # for k,v in revmapping.items(): # print k,v # go through subs and prods and create new atoms based on these for a in subatoms: newatom = Atom(a.symbol, id=aids, graph=self) aids += 1 newatom.x = a.x newatom.y = a.y self.AddAtom(newatom) newatoms[a] = newatom # # the self.compoundatoms and self.compoundbonds contain { "C00031":[[atoms],[atoms],...] } # if there are multiple same reactant (eg. 2 C00031 <=> C00634 + C03259), we need to map both # C00031's into indices in compoundatoms-list of atoms # this id done with 'molindex{}' # # TODO: change .compoundatoms and .compoundbonds to have [[atoms],[atoms]...] structure!!! # here change so that we have multiple compounds when eg. 2 C00031 <=> C00634 + C03259 # molindex = {} for a in subatoms: mol = a.graph.molecule reac = a.graph.molecule.reaction newatom = newatoms[a] # here for "2 C00031 <=> ******", put "C00031":[[atoms],[atoms]] self.compoundatoms.setdefault(mol.ligand, []) self.compoundbonds.setdefault(mol.ligand, []) self.reactions.setdefault(reac.ligand, []) # if mol is not seen before, add new atomlist and save its index in the outer list if mol not in molindex: molindex[mol] = len(self.compoundatoms[mol.ligand]) self.compoundatoms[mol.ligand].append( [newatom] ) self.compoundbonds[mol.ligand].append( [] ) # mol is seen before, simply append else: index = molindex[mol] self.compoundatoms[mol.ligand][index].append(newatom) self.origatoms.setdefault(newatom, []).append( a ) if newatom not in self.reactions[reac.ligand]: self.reactions[reac.ligand].append( newatom ) for a in prodatoms: # print a mol = a.graph.molecule newatom = newatoms[revmapping[a]] self.compoundatoms.setdefault(mol.ligand, []) self.compoundbonds.setdefault(mol.ligand, []) # if mol is not seen before, add new atomlist and save its index in the outer list if mol not in molindex: molindex[mol] = len(self.compoundatoms[mol.ligand]) self.compoundatoms[mol.ligand].append( [newatom] ) self.compoundbonds[mol.ligand].append( [] ) # mol is seen before, simply append else: index = molindex[mol] self.compoundatoms[mol.ligand][index].append(newatom) self.origatoms.setdefault(newatom, []).append( a ) # go through pairs of atoms, add bonds to reaction graph for ind1,a1 in enumerate(subatoms[:-1]): for a2 in subatoms[ind1+1:]: atom1mol = a1.graph.molecule.ligand mappedatom1mol = mapping[a1].graph.molecule.ligand index = molindex[a1.graph.molecule] mappedindex = molindex[mapping[a1].graph.molecule] # intact bond if a1 in a2.GetAtomNeighbors() and mapping[a1] in mapping[a2].GetAtomNeighbors(): b = a1.GetBond(a2) source = newatoms[b.source] target = newatoms[b.target] newbond = Bond(source, target, b.type, bids, self) bids += 1 newbond.reactions = { self.reaction : 0 } # set a new field self.AddBond( newbond ) self.origbonds.setdefault(newbond, []).append(b) self.compoundbonds[atom1mol][index].append( newbond ) self.compoundbonds[mappedatom1mol][mappedindex].append( newbond ) # cleaved bond elif a1 in a2.GetAtomNeighbors() and mapping[a1] not in mapping[a2].GetAtomNeighbors(): b = a1.GetBond(a2) source = newatoms[b.source] target = newatoms[b.target] newbond = Bond(source, target, b.type, bids, self) bids += 1 newbond.reactions = { self.reaction : -1 } # set a new field self.AddBond(newbond) self.origbonds.setdefault(newbond, []).append(b) self.compoundbonds[atom1mol][index].append( newbond ) # new bond elif a1 not in a2.GetAtomNeighbors() and mapping[a1] in mapping[a2].GetAtomNeighbors(): b = mapping[a1].GetBond(mapping[a2]) source = newatoms[a1] target = newatoms[a2] newbond = Bond(source, target, b.type, bids, self) bids += 1 newbond.reactions = { self.reaction : 1 } # set a new field self.AddBond(newbond) self.origbonds.setdefault(newbond, []).append(b) self.compoundbonds[mappedatom1mol][mappedindex].append( newbond )
def symbol_lambda(fun, args): function_args = Atom.cons_to_list(args[0].data) results = args[1:] return Atom.Atom(Atom.Atom.FUNCTION, lambda fun_name, fun_params: evaluate_function("<lambda>", fun_params, function_args, results))
def symbol_print(fun, args): for x in args: item = Atom.evaluate(x, fun) print(item, end="\n")
def symbol_eval(fun, args): return Atom.evaluate(args[0], "EVAL")