def AddBondTo(self, source, target): if not source or not target: return b = Bond(source, target) # lisätään kaari molempien solmujen kaarilistaan source.AddBond(b) target.AddBond(b) # lisätään verkon listaan uusi kaari self.bonds.append(b)
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 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 AddMoleculeGraph(self, mg, mapping): # we have to take care of: # - atoms # - bonds # - compoundatoms # - compoundbonds # - origatoms # - origbonds aidcounter = max([x.id for x in self.atoms]) + 1 if self.atoms else 0 bidcounter = max([x.id for x in self.bonds]) + 1 if self.atoms else 0 self.compoundatoms[mg.molecule.ligand] = [] self.compoundbonds[mg.molecule.ligand] = [] # go through atoms on the rhs side for a in mg.atoms: if a in mapping: self.origatoms.setdefault(mapping[a], []).append(a) self.compoundatoms.setdefault(mg.molecule.ligand, []).append(a) else: newatom = Atom(symbol=a.symbol, id=aidcounter, graph=self) self.AddAtom(newatom) aidcounter += 1 mapping[a] = newatom self.origatoms.setdefault(newatom, []).append(a) self.compoundatoms.setdefault(mg.molecule.ligand, []).append(newatom) for b in mg.bonds: newsrc = mapping[b.source] newtgt = mapping[b.target] mbond = newsrc.GetBond(newtgt) if mbond: self.origbonds.setdefault(mbond, []).append(b) self.compoundbonds.setdefault(mg.molecule.ligand, []).append(mbond) mapping[b] = mbond else: newbond = Bond(newsrc, newtgt, b.type, bidcounter, self) self.AddBond(newbond) bidcounter += 1 mapping[b] = newbond self.origbonds.setdefault(newbond, []).append(b) self.compoundbonds.setdefault(mg.molecule.ligand, []).append(newbond)
(math.pow(1.0 + self.spot_rates[i + 1] / 100.0 / 2.0, (i + 2) / 2.0) / math.pow(1.0 + self.spot_rates[i] / 100.0 / 2.0, (i + 1) / 2.0)), 1.0 / 0.5) - 1.0) * 100.0 * 2.0 if __name__ == "__main__": bonds = [] name = "6m" coupon = 4.0 issue_date = 20130301 maturity_date = 20130901 compounding_frequency_per_annum = 2 price = 100.0 bond = Bond(name, coupon, issue_date, maturity_date, compounding_frequency_per_annum) bond.set_price(price) bonds.append(bond) name = "1y" coupon = 5.0 issue_date = 20130301 maturity_date = 20140301 compounding_frequency_per_annum = 2 price = 100.0 bond = Bond(name, coupon, issue_date, maturity_date, compounding_frequency_per_annum) bond.set_price(price) bonds.append(bond) name = "2y"
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 AddReactionGraph(self, rg, mappings=None): # self = current reaction graph # rg = reaction graph to be merged # # for the mapped regions, add to those atoms the mapped atom's molecules and reactions # the remaining unmapped regions atoms should be transferred to this graph # the mapped bonds should be added to mcs parts (reactions) # the unmapped bonds should be transferred # for svg the coordinates have to be calibrated, # basically just overlay the two reaction graphs on top of each other # causes collisions, need aritas layout algorithm? # if not mappings: mappings = self.optimal_atom_mappings(rg) aidcounter = max([x.id for x in self.atoms]) + 1 bidcounter = max([x.id for x in self.bonds]) + 1 newidstart = aidcounter # optimal mappings, basically iso/automorphic mapping = mappings[0] # we need to handle: # - reactions # - compounds # - origatoms # - origbonds # - bond.reactions # first add atoms not yet on 'self' for a in rg.atoms: if mapping[a] is None: newatom = Atom(symbol=a.symbol, id=aidcounter, graph=self) mapping[a] = newatom self.AddAtom(newatom) aidcounter += 1 # next add bonds # now we have all atoms mapped from rg to self # we have created all new atoms # we have all atom information updated # next we go through all bonds in rg and map them to self and create all new bonds # for b in rg.bonds: src = b.source tgt = b.target msrc = mapping[src] # can be none mtgt = mapping[tgt] mb = msrc.GetBond(mtgt) # bond exists if msrc and mtgt and mb: mb.reactions.update(b.reactions) mapping[b] = mb # new bond else: newbond = Bond(msrc, mtgt, b.type, bidcounter, self) newbond.reactions = b.reactions # if the new bond attaches new atom to old atom, set the bond as +1 # if (newbond.source.id < newidstart) != (newbond.target.id < newidstart): # newbond.reactions[rg.reaction] = +1 if newbond.source.id < newidstart or newbond.target.id < newidstart: newbond.reactions[rg.reaction] = +1 bidcounter += 1 self.AddBond(newbond) mapping[b] = newbond # next update information on the atoms for rhs in rg.atoms: lhs = mapping[rhs] # origatoms ( newatom -> [origatoms] ) try: self.origatoms[lhs] += rg.origatoms[rhs] except: self.origatoms[lhs] = rg.origatoms[rhs] # finally update information on all rg bonds mapped to self # origbonds ( newbond -> [origbonds] ) for rhs in rg.bonds: lhs = mapping[rhs] try: self.origbonds[lhs] += rg.origbonds[rhs] except: self.origbonds[lhs] = rg.origbonds[rhs] # TODO: a compound can exist in numerous places, the compoundatoms should be { mol: [[atoms],[atoms],..] } for c, pieces in rg.compoundatoms.items(): for atoms in pieces: if c in self.compoundatoms: indices = {} for i in range(len(self.compoundatoms[c])): Alist = self.compoundatoms[c][i] for a in atoms: if mapping[a] in Alist: indices[a] = i components = len(set(indices.values())) if c not in self.compoundatoms or components != 1: self.compoundatoms.setdefault(c, []).append([]) for a in atoms: self.compoundatoms[c][-1].append(mapping[a]) for c, pieces in rg.compoundbonds.items(): for bonds in pieces: if c in self.compoundbonds: # matching_areas = list(dict([ (B,b) for B in self.compoundbonds[c] for b in bonds if mapping[b] in B])) indices = {} for i in range(len(self.compoundbonds[c])): Blist = self.compoundbonds[c][i] for b in bonds: if mapping[b] in Blist: indices[b] = i components = len(set(indices.values())) if c not in self.compoundbonds or components != 1: self.compoundbonds.setdefault(c, []).append([]) for b in bonds: self.compoundbonds[c][-1].append(mapping[b]) for r, ats in rg.reactions.items(): if r not in self.reactions: self.reactions[r] = [] for a in ats: self.reactions[r].append(mapping[a])
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 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 main(): req = requests.get(TARGET_URL) match = re.search('defjson:\{pages:.*?,data:(\[.*?\])', req.text).group(1) js = json.loads(match) today_bond = [] shangshi_bond = [] for item in js: if item['STARTDATE'] != '-': start_date = item['STARTDATE'].split('T')[0].split('-') year = start_date[0] month = start_date[1] day = start_date[2] if int(year) == time.localtime().tm_year and int( month) == time.localtime().tm_mon and int( day) == time.localtime().tm_mday: today_bond.append( Bond.Bond(item["SNAME"], item["BONDCODE"], item["ZGJ"], item["SWAPPRICE"])) if item['LISTDATE'] != '-': list_date = item['LISTDATE'].split('T')[0].split('-') year = list_date[0] month = list_date[1] day = list_date[2] if int(year) == time.localtime().tm_year and int( month) == time.localtime().tm_mon and int( day) == time.localtime().tm_mday: shangshi_bond.append( Bond.Bond(item["SNAME"], item["BONDCODE"], item["ZGJ"], item["SWAPPRICE"])) wx_msg = '\n' wx_msg += '今日发售:\n\n' if len(today_bond) > 0: for bond in today_bond: if bond.price != "-" and bond.price != "-": wx_msg += '- 债券代码:%s,债券简称:%s,正股价:%s,转股价:%s, 转股价值:%.2f' % ( bond.code, bond.name, bond.price, bond.swap_price, bond.swap_value) if bond.swap_value > 90: wx_msg += ' 推荐✅' else: wx_msg += '- 债券代码:%s,债券简称:%s,正股价:%s,转股价:%s, 转股价值:%s' % ( bond.code, bond.name, bond.price, bond.swap_price, bond.swap_value) wx_msg += '\n\n' else: wx_msg += '- 无\n\n' wx_msg += '今日上市:\n\n' if len(shangshi_bond) > 0: for bond in shangshi_bond: wx_msg += '- 债券代码:% s,债券简称:% s\n\n' % (bond.code, bond.name) else: wx_msg += '- 无\n\n' if '今日发售' in wx_msg or '今日上市' in wx_msg: wx_msg += '<a href="%s">点击查看一览表</a>' % TARGET_URL log(wx_msg) wx_send.wx_send(title='每日可转债', content=wx_msg) else: log("今日无可转债发行或上市")
## SET YILED CURVE T = np.arange(0.5, 31, 0.5) DF = poly_model.fit(T) fitCurve = yc.YieldCurve() fitCurve.setCurve(T, DF) # GET THE PARYIELD T_par, parYield = fitCurve.getParYield(); MacDuration = [] ModDuration = [] DV01 = [] for t, py in zip(T_par, parYield): myBond = Bond.Bond(100, py, t) MacDuration.append(myBond.getMacDuration(fitCurve)) ModDuration.append(myBond.getModDuration(fitCurve)) DV01.append(myBond.getDV01(fitCurve)) plt.figure(1) plt.subplot(1,2,1) plt.plot(T_par,MacDuration, label="Mac Duration") plt.plot(T_par,ModDuration, label="Mod Duration") plt.ylabel('Duration (years)') plt.xlabel('Time to Maturity') plt.legend(loc = 4,prop={'size':10}) plt.subplot(1,2,2) plt.plot(T_par,DV01, label = "DV01") plt.ylabel('DV01') plt.xlabel('Time to Maturity')
def add_inbond(self, type, g_id, coordinate, energy): bond = Bond(type, self.get_modality_state(), coordinate, g_id, energy) bond.set_marker('in') self.__inbonds.append(bond)
def add_outbond(self, type, value): bond = Bond(type, value) bond.set_marker('out') self.__outbonds.append(bond)
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 __init__(self, Filename): self.Name = Filename.split('.')[1].split('_')[0] File = open(Filename, 'r') File_Lines = File.readlines() self.Bond_List = [] self.Angle_List = [] self.Dihedral_List = [] self.Improper_List = [] self.MW = 0.0 self.COM = np.zeros(3, float) self.Mol_ID = 0 self.basis = np.eye(3) j = -1 for Line in File_Lines: j += 1 Line = Line.strip('\n').split(' ') if len(Line) > 1: if Line[1] == 'atoms': self.N = int(Line[0]) print self.N, "Atoms" if Line[1] == 'atom': Atom_Types = int(Line[0]) self.Atom_List = np.empty(self.N, dtype=object) Mass_List = np.empty(Atom_Types, dtype=float) Pair_Coeffs = np.empty((Atom_Types, 2), dtype=float) if Line[1] == 'bonds': Num_Bonds = Line[0] if Line[1] == 'bond': Bond_Types = int(Line[0]) Bond_Coeffs = np.empty((Bond_Types, 2), dtype=float) if Line[1] == 'angles': Num_Angles = Line[0] if Line[1] == 'angle': Angle_Types = int(Line[0]) Angle_Coeffs = np.empty((Angle_Types, 2), dtype=float) if Line[1] == 'dihedrals': Num_Dihedrals = Line[0] if Line[1] == 'dihedral': Dihedral_Types = int(Line[0]) Dihedral_Coeffs = np.empty((Dihedral_Types, 4), dtype=float) if Line[1] == 'impropers': Num_Impropers = Line[0] if Line[1] == 'improper': Improper_Types = int(Line[0]) Improper_Coeffs = np.empty((Improper_Types, 3), dtype=float) try: if Line[2] == 'xlo': Box_Length = float(Line[1]) - float(Line[0]) print Box_Length, "Box_Length" except: continue if Line[0] == 'Atoms': print 'Getting Atoms' for i in range(self.N): Temp_Position = [ float(File_Lines[i + j + 2].split(' ')[4]), float(File_Lines[i + j + 2].split(' ')[5]), float(File_Lines[i + j + 2].split(' ')[6]) ] I_Flags = [ int(File_Lines[i + j + 2].split(' ')[7]), int(File_Lines[i + j + 2].split(' ')[8]), int(File_Lines[i + j + 2].split(' ')[9]) ] Temp_Position = np.asarray(Temp_Position, dtype=float) I_Flags = np.asarray(I_Flags, dtype=int) #print "IMAGE FLAGS", I_Flags Temp_Position += I_Flags * Box_Length Temp_Charge = float(File_Lines[i + j + 2].split(' ')[3]) Type = int(File_Lines[i + j + 2].split(' ')[2]) Mass = Mass_List[Type - 1] Element = Element_Dict[Mass] Atom_Id = int(File_Lines[i + j + 2].split(' ')[0]) #print Element, Mass, Atom_Id self.Atom_List[i] = Atom.Atom(Temp_Position, Element, Atom_Id) self.Atom_List[i].Charge = Temp_Charge self.Atom_List[i].Epsilon = Pair_Coeffs[Type - 1, 0] self.Atom_List[i].Sigma = Pair_Coeffs[Type - 1, 1] self.Atom_List[i].OPLS_Type = 1000 + Type self.Atom_List = sorted(self.Atom_List, key=lambda AtomO: AtomO.Atom_ID) for Atom_Obj in self.Atom_List: print Atom_Obj.Atom_ID, Atom_Obj.Position if Line[0] == 'Pair': print "Getting Pair Coefficients" for i in range(Atom_Types): Pair_Coeffs[i, 0] = float(File_Lines[i + j + 2].split(' ')[1]) Pair_Coeffs[i, 1] = float(File_Lines[i + j + 2].split(' ')[2]) if Line[0] == 'Bond': print "Getting Bond Coefficients" for i in range(Bond_Types): Bond_Coeffs[i, 0] = float(File_Lines[i + j + 2].split(' ')[1]) Bond_Coeffs[i, 1] = float(File_Lines[i + j + 2].split(' ')[2]) if Line[0] == 'Angle': print "Getting Angle Coefficients" for i in range(Angle_Types): Angle_Coeffs[i, 0] = float(File_Lines[i + j + 2].split(' ')[1]) Angle_Coeffs[i, 1] = float(File_Lines[i + j + 2].split(' ')[2]) if Line[0] == 'Dihedral': print "Getting Dihedral Coefficients" for i in range(Dihedral_Types): Dihedral_Coeffs[i, 0] = float( File_Lines[i + j + 2].split(' ')[1]) Dihedral_Coeffs[i, 1] = float( File_Lines[i + j + 2].split(' ')[2]) Dihedral_Coeffs[i, 2] = float( File_Lines[i + j + 2].split(' ')[3]) Dihedral_Coeffs[i, 3] = float( File_Lines[i + j + 2].split(' ')[4]) if Line[0] == 'Improper': print "Getting Improper Coefficients" for i in range(Improper_Types): Improper_Coeffs[i, 0] = float( File_Lines[i + j + 2].split(' ')[1]) Improper_Coeffs[i, 1] = int( File_Lines[i + j + 2].split(' ')[2]) Improper_Coeffs[i, 2] = int( File_Lines[i + j + 2].split(' ')[3]) if len(Line) == 1: if Line == ['']: continue if Line == ['Masses']: print "Extracting Masses" for i in range(Atom_Types): Mass_List[i] = float(File_Lines[i + j + 2].split(' ')[1]) if Line == ['Bonds']: print "Extracting Bonds" for i in range(int(Num_Bonds)): Bond_Info = File_Lines[i + j + 2].strip('\n').split(' ') Master = self.Atom_List[int(Bond_Info[2]) - 1] Slave = self.Atom_List[int(Bond_Info[3]) - 1] Kb = Bond_Coeffs[int(Bond_Info[1]) - 1, 0] Req = Bond_Coeffs[int(Bond_Info[1]) - 1, 1] Bond_ID = int(Bond_Info[0]) self.Bond_List.append(Bond.Bond(Master, Slave, Req)) self.Bond_List[i].kb = Kb self.Bond_List[i].Bond_ID = Bond_ID if Line == ['Angles']: print "Extracting Angles" for i in range(int(Num_Angles)): Angle_Info = File_Lines[i + j + 2].strip('\n').split(' ') Slave1 = self.Atom_List[int(Angle_Info[2]) - 1] Master = self.Atom_List[int(Angle_Info[3]) - 1] Slave2 = self.Atom_List[int(Angle_Info[4]) - 1] Ka = Angle_Coeffs[int(Angle_Info[1]) - 1, 0] Th0 = Angle_Coeffs[int(Angle_Info[1]) - 1, 1] Angle_ID = int(Angle_Info[0]) self.Angle_List.append( Angle.Angle(Master, Slave1, Slave2, Th0)) self.Angle_List[i].ka = Ka self.Angle_List[i].Angle_ID = Angle_ID if Line == ['Dihedrals']: print "Extracting Dihedrals" for i in range(int(Num_Dihedrals)): Dihedral_Info = File_Lines[i + j + 2].strip('\n').split(' ') Slave1 = self.Atom_List[int(Dihedral_Info[2]) - 1] Master1 = self.Atom_List[int(Dihedral_Info[3]) - 1] Master2 = self.Atom_List[int(Dihedral_Info[4]) - 1] Slave2 = self.Atom_List[int(Dihedral_Info[5]) - 1] Coeffs = Dihedral_Coeffs[int(Dihedral_Info[1]) - 1] Dihedral_ID = int(Dihedral_Info[0]) self.Dihedral_List.append( Dihedral.Dihedral(Master1, Master2, Slave1, Slave2, 0.0)) self.Dihedral_List[i].Coeffs = Coeffs self.Dihedral_List[i].Dihedral_ID = Dihedral_ID if Line == ['Impropers']: print "Extracting Impropers" for i in range(int(Num_Impropers)): Improper_Info = File_Lines[i + j + 2].strip('\n').split(' ') Master = self.Atom_List[int(Improper_Info[2]) - 1] Slave1 = self.Atom_List[int(Improper_Info[3]) - 1] Slave2 = self.Atom_List[int(Improper_Info[4]) - 1] Slave3 = self.Atom_List[int(Improper_Info[5]) - 1] Coeff = Improper_Coeffs[int(Improper_Info[1]) - 1, 0] Improper_ID = int(Improper_Info[0]) self.Improper_List.append( Improper.Improper(Master, Slave1, Slave2, Slave3, Coeff, 180.0, Improper_ID)) # Compute center of Mass Mass_Weighted_Sum = np.zeros(3, dtype=float) for Atom_Obj in self.Atom_List: Mass_Weighted_Sum += Atom_Obj.Position * Atom_Obj.Mass self.MW += Atom_Obj.Mass print "Molecular Weight is ", self.MW, "Grams/Mole" self.COM = Mass_Weighted_Sum / self.MW print "COM is", self.COM # Zero COM for Atom_Obj in self.Atom_List: Atom_Obj.Position -= self.COM self.COM -= self.COM print self.COM return
#FIT POLYNOMIAL MODEL from IR_Models import Polynomial poly_model = Polynomial.Polynomial() poly_model.estimate(DF, T) ## SET YILED CURVE T = np.arange(0.5, 30.5, 0.5) DF = poly_model.fit(T) fitCurve = yc.YieldCurve() fitCurve.setCurve(T, DF) # GET THE PARYIELD T_par, parYield = fitCurve.getParYield(); convex = [] for t, py in zip(T_par, parYield): parBond = Bond.Bond(100, py, t) convex.append(parBond.getConvexity(fitCurve)) plt.figure(1) plt.plot(T_par, convex, '-o') plt.ylabel('Convexity') plt.xlabel('Time to Maturity of Par Bond') ## QUESTION 2 plt.figure(2) currentRates = fitCurve.getSpotRates(2); shift = [10.0/10000, -10.0/10000, 300.0/10000, -300.0/10000]; for i,s in enumerate(shift): shiftedRates = np.asarray(currentRates) + s shiftedDF = yc.spotRates_to_DF(shiftedRates, T,2) shiftedCurve = yc.YieldCurve()
f = [f1, f2, f3, f4] return f days = ['2020/01/02', '2020/01/03', '2020/01/06', '2020/01/07', '2020/01/08', '2020/01/09', '2020/01/10', '2020/01/13', '2020/01/14', '2020/01/15'] Bond_list = [] close_price = [] df = [] for index, row in data.iterrows(): close_price.append(row['Close_price']) if index % 10 == 9: coupon = row['Coupon'] maturity_date = row['Maturity_date'] Bond_list.append(Bond(coupon, maturity_date, close_price)) close_price = [] for i in range(10): p = [10 * j + i for j in range(10)] tmp = data.iloc[p] tmp = tmp.reset_index(drop=True) print(tmp) df.append(tmp) for i in range(10): print(Bond_list[i].ytm_average[0]) plt.figure() plt.xlabel('time to maturity')
OXYGEN_COEFF_COUNT = 0 NITROGEN_COEFF_COUNT = 0 ''' # not implemented in code # unit is Angstrom(A), 1A = 10^(-10) meter C_H_SINGLE_BOND_DIST = 1.09 # 1.04 ~ 1.14 C_C_SINGLE_BOND_DIST = 1.54 # 1.49 ~ 1.59 C_C_DOUBLE_BOND_DIST = 1.34 # 1.29 ~ 1.39 C_C_TRIPPLE_BOND_DIST = 1.20 # 1.15 ~ 1.25 # how about overlapping distance? ''' # BOND_DEFINITION_LIST holds all possible bond types that belongs to the molecule. # add/change the numbers in this list if your atoms have different bond lengths, count, etc. BOND_DEFINITION_LIST = [ Bond().load('C', 'H', 1, 1.040, 1.149), Bond().load('C', 'C', 1, 1.490, 1.599), Bond().load('C', 'C', 2, 1.290, 1.399), Bond().load('C', 'C', 3, 1.150, 1.259) ] # ATOM_DEFINITION_LIST holds all possible atom types that belongs to the molecule. # add/change the list elements if your molecule have different atoms and possible inhome neighbors #TODO: dynamically load the coefficient counts based on 'qchem_input->BASIS' ATOM_DEFINITION_MAP = { 'C': Atom().load('C', 9, ['H']), 'H': Atom().load('H', 2, ['C']) } #MOLECULE_STRUCT = MoleculeStruct().load(ATOM_DEFINITION_MAP, BOND_DEFINITION_LIST) molecule_structure = MoleculeStruct()
def Set_Up_FF(self, run_orca=True, local=True): if run_orca: print "Setting up Orca input script" # Write Orca Input File File_Name = self.Name + ".inp" File = open(File_Name, 'w') File.write( '! RKS B3LYP 6-31+G** NormalSCF Opt NOSOSCF CHELPG PAL8\n\n') File.write('*xyz 0 1\n') for Atom_Obj in self.Atom_List: File.write('%s %.5f %.5f %.5f\n' % (Atom_Obj.Element, Atom_Obj.Position[0], Atom_Obj.Position[1], Atom_Obj.Position[2])) File.write('*') File.close() Finished = False File_Out = self.Name + ".out" if local: #Run subprocess on local machine os.system('mkdir Orca') os.system('mv %s ./Orca' % File_Name) os.chdir('./Orca') File_Out = self.Name + ".out" try: File = open(File_Out, 'r') except: os.system( '/usr/local/share/orca_3_0_0_macosx_openmpi165/orca %s > %s' % (File_Name, File_Out)) # Run Orca Job else: print "Running Orca Geometry Optimization on Comet" cmd = "mkdir " + Configure.Comet_Path % self.Name subprocess.call(["ssh", Configure.Comet_Login, cmd]) subtemp = Configure.Template_Path + "sub_orca_temp" submit = "submit_orca" Path = Configure.Comet_Path % self.Name # Write submit script with open(subtemp) as f: template = f.read() s = template.format(Comet_Path=Path, Orca_Path=Configure.Orca_Path, name=self.Name) with open(submit, "w") as f: f.write(s) # Copy Files over to Comet os.system(Configure.c2c % (submit, self.Name)) os.system(Configure.c2c % (File_Name, self.Name)) # Run job os.system(Configure.c2l % (self.Name, File_Out)) try: File = open(File_Out, 'r') except: subprocess.call([ "ssh", Configure.Comet_Login, Configure.SBATCH % (self.Name, submit) ]) i = 0 while not Finished: os.system(Configure.c2l % (self.Name, File_Out)) try: File = open(File_Out, 'r') File_Lines = File.readlines() print File_Lines[-1] if File_Lines[-1].split( ' ')[0] == "TOTAL" or self.UnConverged: Finished = True else: print "Not Finished" i += 10 print "Sleeping process", i, "Minutes" time.sleep(600) except: print "Sleeping process", i, "miniutes" time.sleep(600) i += 10 else: os.chdir('./Orca') File_Out = self.Name + ".out" # Extract info from Orca output file Orca_File = open(File_Out, 'r') File_Lines = Orca_File.readlines() print "Extracting Redundant Coordinates..." for i in range(len(File_Lines)): Line = File_Lines[i].strip('\n').split() #print Line Found = False try: if Line[0] == "Redundant" and self.UnConverged: Redundant = True j = i + 6 k = 0 while Redundant: R_Line = File_Lines[j] R_Line = R_Line.split() print R_Line try: if int(R_Line[0].strip('.')) >= 1: j = j + 1 Type = R_Line[1].split('(')[0] k += 1 # Extract Bonds if Type == "B": Master_ID = int(R_Line[2].split(',')[0]) Slave_ID = int(R_Line[3].split(')')[0]) req = float(R_Line[-1]) self.Atom_List[Master_ID].Bond_List.append( self.Atom_List[Slave_ID]) self.Atom_List[Slave_ID].Bond_List.append( self.Atom_List[Master_ID]) self.Bond_List.append( Bond.Bond(self.Atom_List[Master_ID], self.Atom_List[Slave_ID], req)) # Extract Angles if Type == "A": Master_ID = int(R_Line[3].split(',')[0]) Slave1_ID = int(R_Line[2].split(',')[0]) Slave2_ID = int(R_Line[4].split(')')[0]) Angle_Eq = float(R_Line[-1]) self.Angle_List.append( Angle.Angle(self.Atom_List[Master_ID], self.Atom_List[Slave1_ID], self.Atom_List[Slave2_ID], Angle_Eq)) if Type == "D": Master1_ID = int(R_Line[3].split(',')[0]) Master2_ID = int(R_Line[4].split(',')[0]) Slave1_ID = int(R_Line[2].split(',')[0]) Slave2_ID = int(R_Line[5].split(')')[0]) Dihedral_Eq = float(R_Line[-1]) self.Dihedral_List.append( Dihedral.Dihedral( self.Atom_List[Master1_ID], self.Atom_List[Master2_ID], self.Atom_List[Slave1_ID], self.Atom_List[Slave2_ID], Dihedral_Eq)) except: Redundant = False Found = True print k if Found: break elif Line[0] == "Redundant" and ( File_Lines[i + 2].strip('\n').split()[1] == "Optimized"): print "Found redundant internal coordinates" Redundant = True j = i + 7 while Redundant: R_Line = File_Lines[j] R_Line = R_Line.split() try: if int(R_Line[0].strip('.')) >= 1: j = j + 1 Type = R_Line[1].split('(')[0] # Extract Bonds if Type == "B": Master_ID = int(R_Line[2].split(',')[0]) Slave_ID = int(R_Line[3].split(')')[0]) req = float(R_Line[-1]) self.Atom_List[Master_ID].Bond_List.append( self.Atom_List[Slave_ID]) self.Atom_List[Slave_ID].Bond_List.append( self.Atom_List[Master_ID]) self.Bond_List.append( Bond.Bond(self.Atom_List[Master_ID], self.Atom_List[Slave_ID], req)) # Extract Angles if Type == "A": Master_ID = int(R_Line[3].split(',')[0]) Slave1_ID = int(R_Line[2].split(',')[0]) Slave2_ID = int(R_Line[4].split(')')[0]) Angle_Eq = float(R_Line[-1]) self.Angle_List.append( Angle.Angle(self.Atom_List[Master_ID], self.Atom_List[Slave1_ID], self.Atom_List[Slave2_ID], Angle_Eq)) if Type == "D": Master1_ID = int(R_Line[3].split(',')[0]) Master2_ID = int(R_Line[4].split(',')[0]) Slave1_ID = int(R_Line[2].split(',')[0]) Slave2_ID = int(R_Line[5].split(')')[0]) Dihedral_Eq = float(R_Line[-1]) self.Dihedral_List.append( Dihedral.Dihedral( self.Atom_List[Master1_ID], self.Atom_List[Master2_ID], self.Atom_List[Slave1_ID], self.Atom_List[Slave2_ID], Dihedral_Eq)) except: Redundant = False if Line[0] == "CHELPG" and len( Line) == 2 and not self.UnConverged: for j in range(self.N): Chelp_Line = File_Lines[i + 2 + j].split() index = int(Chelp_Line[0]) charge = float(Chelp_Line[3]) self.Atom_List[index].Charge = charge if Line[0] == "CARTESIAN" and Line[2] == "(ANGSTROEM)": for j in range(self.N): XYZ_Line = File_Lines[i + 2 + j].split() Position_Temp = np.array([ float(XYZ_Line[1]), float(XYZ_Line[2]), float(XYZ_Line[3]) ], dtype=float) self.Atom_List[j].Position = Position_Temp except: continue print "Redundant Internal Coordinates and ChelpG partial charges Extracted" print "Bond_List = ", len(self.Bond_List) if not run_orca: os.chdir('..') if local: os.chdir('..') print "Optimized XYZ Coordinates:\n" for Atom_Obj in self.Atom_List: # Finds OPLS Types and Classes print Atom_Obj.Atom_ID, Atom_Obj.Element, Atom_Obj.Position, sorted( [Atomobj.Element for Atomobj in Atom_Obj.Bond_List]) print "----------------------------------" # Find all the ring units in the molecule and add them to the ring list self.Ring_List = Ring.create_rings(self.Atom_List) return
def AddReactionGraph(self, rg, mappings = None): # self = current reaction graph # rg = reaction graph to be merged # # for the mapped regions, add to those atoms the mapped atom's molecules and reactions # the remaining unmapped regions atoms should be transferred to this graph # the mapped bonds should be added to mcs parts (reactions) # the unmapped bonds should be transferred # for svg the coordinates have to be calibrated, # basically just overlay the two reaction graphs on top of each other # causes collisions, need aritas layout algorithm? # if not mappings: mappings = self.optimal_atom_mappings(rg) aidcounter = max( [x.id for x in self.atoms] ) + 1 bidcounter = max( [x.id for x in self.bonds] ) + 1 newidstart = aidcounter # optimal mappings, basically iso/automorphic mapping = mappings[0] # we need to handle: # - reactions # - compounds # - origatoms # - origbonds # - bond.reactions # first add atoms not yet on 'self' for a in rg.atoms: if mapping[a] is None: newatom = Atom(symbol=a.symbol, id=aidcounter, graph=self) mapping[a] = newatom self.AddAtom(newatom) aidcounter += 1 # next add bonds # now we have all atoms mapped from rg to self # we have created all new atoms # we have all atom information updated # next we go through all bonds in rg and map them to self and create all new bonds # for b in rg.bonds: src = b.source tgt = b.target msrc = mapping[src] # can be none mtgt = mapping[tgt] mb = msrc.GetBond(mtgt) # bond exists if msrc and mtgt and mb: mb.reactions.update(b.reactions) mapping[b] = mb # new bond else: newbond = Bond(msrc, mtgt, b.type, bidcounter, self) newbond.reactions = b.reactions # if the new bond attaches new atom to old atom, set the bond as +1 # if (newbond.source.id < newidstart) != (newbond.target.id < newidstart): # newbond.reactions[rg.reaction] = +1 if newbond.source.id < newidstart or newbond.target.id < newidstart: newbond.reactions[rg.reaction] = +1 bidcounter += 1 self.AddBond(newbond) mapping[b] = newbond # next update information on the atoms for rhs in rg.atoms: lhs = mapping[rhs] # origatoms ( newatom -> [origatoms] ) try: self.origatoms[lhs] += rg.origatoms[rhs] except: self.origatoms[lhs] = rg.origatoms[rhs] # finally update information on all rg bonds mapped to self # origbonds ( newbond -> [origbonds] ) for rhs in rg.bonds: lhs = mapping[rhs] try: self.origbonds[lhs] += rg.origbonds[rhs] except: self.origbonds[lhs] = rg.origbonds[rhs] # TODO: a compound can exist in numerous places, the compoundatoms should be { mol: [[atoms],[atoms],..] } for c,pieces in rg.compoundatoms.items(): for atoms in pieces: if c in self.compoundatoms: indices = {} for i in range(len(self.compoundatoms[c])): Alist = self.compoundatoms[c][i] for a in atoms: if mapping[a] in Alist: indices[a] = i components = len(set(indices.values())) if c not in self.compoundatoms or components != 1: self.compoundatoms.setdefault(c,[]).append([]) for a in atoms: self.compoundatoms[c][-1].append( mapping[a] ) for c,pieces in rg.compoundbonds.items(): for bonds in pieces: if c in self.compoundbonds: # matching_areas = list(dict([ (B,b) for B in self.compoundbonds[c] for b in bonds if mapping[b] in B])) indices = {} for i in range(len(self.compoundbonds[c])): Blist = self.compoundbonds[c][i] for b in bonds: if mapping[b] in Blist: indices[b] = i components = len(set(indices.values())) if c not in self.compoundbonds or components != 1: self.compoundbonds.setdefault(c,[]).append([]) for b in bonds: self.compoundbonds[c][-1].append( mapping[b] ) for r,ats in rg.reactions.items(): if r not in self.reactions: self.reactions[r] = [] for a in ats: self.reactions[r].append( mapping[a] )