def makeMoleculePattern(mol): '''Make molecule pattern from Molecule ''' m = st.Molecule(mol.name, mol.idx) sp = st.Species() sp.addMolecule(m) return sp
def makeUnboundPattern(mol,comp): '''Make unbound pattern from Molecule Component ''' c = st.Component(comp.name,comp.idx,[],[]) m = st.Molecule(mol.name,mol.idx) m.addComponent(c) sp = st.Species() sp.addMolecule(m) return sp
def makeStatePattern(mol,comp,state): '''Make state pattern from Molecule Component State ''' c = st.Component(comp.name,comp.idx,[],[]) c.addState(state) c.setActiveState(state) m = st.Molecule(mol.name,mol.idx) m.addComponent(c) sp = st.Species() sp.addMolecule(m) return sp
def merge(reactant1, reactant2, r1, r2, translator, outputFlag=False): ''' Receives two species reactant1 and reactant1, and their intersection points r1 and r2 and creates a new complex that is the union ''' species = st.Species() if reactant1 in translator: species.append(translator[reactant1]) if reactant2 in translator: species.append(translator[reactant2]) if outputFlag: print '-----------', species, reactant1, reactant2, reactant2 in translator rnd = max(species.getBondNumbers()) + 1 molecule1 = st.Molecule(binding1) molecule2 = st.Molecule(binding2) component1 = st.Component(r1) component2 = st.Component(r2) component1.addBond(str(rnd)) component2.addBond(str(rnd)) molecule1.addComponent(component1) molecule2.addComponent(component2) species.addMolecule(molecule1, True, 1) counter = 2 if binding1 == binding2 else 1 species.addMolecule(molecule2, True, counter) ####TODO: update the rawDAtabase with the m1m2 information if molecule1.name in translator: sp = st.Species() sp.addMolecule(deepcopy(molecule1)) translator[molecule1.name].extend(sp) translator[molecule1.name].reset() if molecule2.name in translator: sp = st.Species() sp.addMolecule(deepcopy(molecule2)) translator[molecule2.name].extend(sp) translator[molecule2.name].reset()
def createSpecies(pattern): tmpDict = {} species = st.Species() species.idx = pattern.get('id') mol = pattern.find('.//{http://www.sbml.org/sbml/level3}ListOfMolecules') bonds = pattern.find('.//{http://www.sbml.org/sbml/level3}ListOfBonds') for molecule in mol.getchildren(): molecule, nameDict = createMolecule(molecule, bonds) tmpDict.update(nameDict) species.addMolecule(molecule) if bonds != None: species.bonds = [(bond.get('site1'), bond.get('site2')) for bond in bonds] tmpDict.update(nameDict) return species, tmpDict
def makeBondPattern(mc1,mc2): '''Make bond pattern from [Molecule Component], [Molecule Component] ''' [m1,c1] = mc1 [m2,c2] = mc2 c_1 = st.Component(c1.name,c1.idx,[],[]) c_1.addBond('1') m_1 = st.Molecule(m1.name, m1.idx) m_1.addComponent(c_1) c_2 = st.Component(c2.name,c2.idx,[],[]) c_2.addBond('1') m_2 = st.Molecule(m2.name, m2.idx) m_2.addComponent(c_2) sp = st.Species() sp.addMolecule(m_1) sp.addMolecule(m_2) return sp
def catalysis(original, dictionary, rawDatabase, catalysisDatabase, translator, namingConvention, classification, reactionProperties): """ This method is for reactions of the form A+ B -> A' + B """ #if 'EGF_EGFRim2_GAP_Grb2_Sos_Ras_GDP' in original[0] or 'EGF_EGFRim2_GAP_Grb2_Sos_Ras_GDP' in original[1]: # print original,'EGF_EGFRim2_GAP_Grb2_Sos_Ras_GDP' in translator result = catalyze(namingConvention[0], namingConvention[1], classification, rawDatabase, translator, reactionProperties) k = [min(namingConvention, key=len) in x for x in original[0]] k2 = [max(namingConvention, key=len) in x for x in original[1]] k = k and k2 sortedResult = [result[0], result[1]] if any(k) else [result[1], result[0]] sortedConvention = [ namingConvention[0], namingConvention[1] ] if any(k) else [namingConvention[1], namingConvention[0]] flag = False if 'EGF_EGFRm2' in original[1]: print 'hello' for reactantGroup, res, conv in zip(original, sortedResult, sortedConvention): for reactant in reactantGroup: flag = False species = st.Species() #if original[0][0] in translator: # species = deepcopy(translator[original[0][0]]) #make a copy of the original element we are going to modify if reactant in translator: species = deepcopy(translator[reactant]) elif sortedConvention[0] in translator: species = deepcopy(translator[sortedConvention[0]]) tmp = dictionary[reactant] for element in tmp: molecule = st.Molecule(element) #here it would be much more precise to have the molecule #that is going to be modified instead of just modifying the #first thing you find if element in conv: #chunk = result[1] if reactant == max(namingConvention,key=len) else result[0] component = st.Component(res[0]) component.addState(res[1]) molecule.addComponent(component, 1) flag = True finalMolecule = molecule ''' else: if conv in reactant: component = st.Component(res[0]) component.addState(res[1]) molecule.addComponent(component,1) print conv,molecule,element flag = True #continue ''' #FIXME: the comparison should be done a lil more carefully #to avoid overlap species.addMolecule(molecule, True) if str(species) == '': species.addMolecule(molecule) break if flag: if reactant not in translator: translator[reactant] = species else: translator[reactant].extend(species, False) if finalMolecule.name in translator: if len(translator[finalMolecule.name].molecules) == 1: sp = st.Species() sp.addMolecule(deepcopy(finalMolecule)) translator[finalMolecule.name].extend(sp, False) translator[finalMolecule.name].reset() else: sp = st.Species() sp.addMolecule(molecule) translator[molecule.name] = deepcopy(sp) if len(original[0]) < len(original[1]): rebalance(original, sortedConvention, translator)
def findCorrespondence(reactants, products, dictionary, sbml_name, rawDatabase, synthesisDatabase, translator, outputFlag=False): """ this method reconstructs the component structure for a set of sbml molecules that undergo synthesis using context and history information """ #print reactants,products,dictionary,sbml_name species = dictionary[sbml_name] if isinstance(species, str): species = dictionary[species] product = dictionary[products[0]] #if the element is already in the synthesisDatabase if species in synthesisDatabase: return species, synthesisDatabase[species] if products[0] in translator: return None, None #elif species in rawDatabase: #for product in productArray: #if product in synthesisDatabase: # temp = [(x[0],) for x in synthesisDatabase[product][product.index(dictionary[species[0]][0])]] # return species,(temp,) #print '::::::::::',species,rawDatabase[species] #return species,rawDatabase[species] #this means we are dealing with the basic components rather than the #synthetized product extended1, extended2, intersection, extendedComponent = getIntersection( reactants, product, dictionary, rawDatabase, translator, synthesisDatabase, products, outputFlag) #print 'aaaaa',dictionary if outputFlag: print '---', extended1, extended2, intersection, extendedComponent if len(species) < 2 and species in rawDatabase: return species, rawDatabase[species] if (extended1, extended2, intersection) == (None, None, None): return None, None if isinstance(extended1, st.Species): return products[0], extended1 constructed = [[] for element in species] #add elements preexistent in the first molecule print '2........' species2 = st.Species() species2.append(translator[reactants[0]]) species2.append(translator[reactants[1]]) species2.addChunk(intersection[0], synthesisDatabase[intersection[0]], []) print intersection[0], synthesisDatabase[intersection[0]] #add elements preexistent in the second molecule #add the intersection ''' for element in [intersection[0],extended1,extended2]: if len(element) > 1: for tag,molecule in zip(element,synthesisDatabase[element]): #in case we know that one element name is actually another in a special form realTag = dictionary[tag][0] for member in [x for x in molecule if x not in constructed[species.index(realTag)]]: flag = True for temp in deepcopy(constructed[species.index(realTag)]): if member[0] in temp: if len(member) == 1: flag = False else: constructed[species.index(realTag)].remove(temp) if flag: constructed[species.index(realTag)].append(tuple(member)) ''' return species, species2
def getIntersection(reactants, product, dictionary, rawDatabase, translator, synthesisDatabase, originalProductName, outputFlag=False): ''' this method goes through two complexes and tries to check how they get together to create a product (e.g. how their components link) either by using previous knowledge or by creating a new complex ''' #global log extended1 = (copy(dictionary[reactants[0]])) extended2 = (copy(dictionary[reactants[1]])) if isinstance(extended1, str): extended1 = [extended1] if isinstance(extended2, str): extended2 = [extended2] #if we can find an element in the database that is a subset of #union(extended1,extended2) we take it intersection = findIntersection(extended1, extended2, synthesisDatabase) #otherwise we create it from scratch if not intersection: r1 = getFreeRadical(extended1, extended2[0], rawDatabase, translator, product, dictionary) r2 = getFreeRadical(extended2, extended1[0], rawDatabase, translator, product, dictionary) binding1, binding2 = getBindingPoints(extended1, extended2, reactants, originalProductName[0]) if not r1 or not r2: #prin t 'Cannot infer how',extended1,'binds to',extended2 #log['reactions'].append((reactants,product)) #return None,None,None #TODO this section should be activated by a flag instead #of being accessed by default #print extended1,extended2 createIntersection((binding1, binding2), rawDatabase, translator, dictionary) r1 = getFreeRadical((binding1, ), binding2, rawDatabase, translator, product, dictionary) r2 = getFreeRadical((binding2, ), binding1, rawDatabase, translator, product, dictionary) #print 'rrrrrrrrrrr',r1,r2 if not r1 or not r2: return (None, None, None, None) ##todo: modify code to allow for carry over free radicals #FIXME: we can remove synthesisDatabase easily species = st.Species() if reactants[0] in translator: species.append(translator[reactants[0]]) if reactants[1] in translator: species.append(translator[reactants[1]]) if outputFlag: print '-----------', species, reactants[0], reactants[ 1], reactants[1] in translator print '+++', binding1, binding2, r1, r2 bondName = max(species.getBondNumbers()) + 1 molecule1 = st.Molecule(binding1) molecule2 = st.Molecule(binding2) component1 = st.Component(r1) component2 = st.Component(r2) component1.addBond(str(bondName)) component2.addBond(str(bondName)) molecule1.addComponent(component1) molecule2.addComponent(component2) if outputFlag: print '////////', molecule1, molecule2 species.addMolecule(molecule1, True, 1) counter = 2 if binding1 == binding2 else 1 species.addMolecule(molecule2, True, counter) if outputFlag: print '\\\\\\', species ####TODO: update the rawDAtabase with the m1m2 information sp = st.Species() sp.addMolecule(deepcopy(molecule1)) if molecule1.name in translator: translator[molecule1.name].extend(sp) else: translator[molecule1.name] = sp translator[molecule1.name].reset() sp = st.Species() sp.addMolecule(deepcopy(molecule2)) if molecule2.name in translator: translator[molecule2.name].extend(sp) else: translator[molecule2.name] = sp translator[molecule2.name].reset() if outputFlag: print '||||||||||||||||||||||', translator[molecule2.name] #print reactants,product,str(species) #print name1,name2,extended1,extended2 #print {x:str(translator[x]) for x in translator}, translator if len(species.molecules) == 0: return (None, None, None, None) return species, [], [], [] return extended1, extended2, intersection, []
def synthesis(original, dictionary, rawDatabase, synthesisDatabase, translator, outputFlag=False): #reaction = [] for elements in original: #temp = [] for sbml_name in elements: ## If we have translated it before and its in mem ory # if molecule in translator: # species.append(translator[molecule]) # else: if outputFlag: print '-', sbml_name #if 'EGF_EGFRim2_GAP_Grb2_Sos_Ras_GTP' in original[1]: # print original #if 'P_KKK_KK' in translator: # print 'hola' if 'EGF_EGFR2_PLCg' in original[1]: print original tags, molecules = findCorrespondence(original[0], original[1], dictionary, sbml_name, rawDatabase, synthesisDatabase, translator, outputFlag) if (tags, molecules) == (None, None): tmp = st.Species() tmp.addMolecule(st.Molecule(sbml_name)) if sbml_name not in translator: translator[sbml_name] = tmp #raise InsufficientInformationError libsbml2bngl.log['reactions'].append(original) #TODO: probably we will need to add a check if there are several ways of defining a reaction elif isinstance(molecules, st.Species): #FIXME: there shouls be a better way to check whether i actually want to check or not if tags not in translator: translator[tags] = molecules else: #tags = list(tags) #tags.sort() #tags = tuple(tags) precursors = [] if sbml_name not in translator: species = st.Species() #here we check if the new species is made of already existing molecules else: species = translator[sbml_name] species.addChunk(tags, molecules, precursors) if sbml_name not in translator: other = original[ 0] if original[0] != elements else original[1] for tag in [x for x in other if x in translator]: species.extend(translator[tag]) translator[sbml_name] = species if tags not in synthesisDatabase and tags not in rawDatabase: synthesisDatabase[tags] = tuple(molecules) return 0
def createBindingRBM(element, translator, dependencyGraph, bioGridFlag): species = st.Species() #go over the sct and reuse existing stuff for molecule in dependencyGraph[element[0]][0]: if molecule in translator: tmpSpecies = translator[molecule] if molecule != getTrueTag(dependencyGraph, molecule): original = translator[getTrueTag(dependencyGraph, molecule)] updateSpecies(tmpSpecies, original.molecules[0]) species.addMolecule(deepcopy(tmpSpecies.molecules[0])) else: mol = st.Molecule(molecule) dependencyGraph[molecule] = deepcopy(mol) species.addMolecule(mol) #how do things bind together? moleculePairsList = getComplexationComponents2(species, bioGridFlag) #TODO: update basic molecules with new components #translator[molecule[0].name].molecules[0].components.append(deepcopy(newComponent1)) #translator[molecule[1].name].molecules[0].components.append(deepcopy(newComponent2)) for idx, molecule in enumerate(moleculePairsList): flag = False #add bonds where binding components already exist for component in molecule[0].components: if component.name == molecule[1].name.lower() and \ len(component.bonds) == 0: component.bonds.append(idx) flag = True break if not flag: #create components if they dont exist already. #Add a bond afterwards newComponent1 = st.Component(molecule[1].name.lower()) molecule[0].components.append(newComponent1) if newComponent1.name not in [x.name for x in translator[molecule[0].name].molecules[0]. \ components]: translator[molecule[0].name].molecules[0]. \ components.append(deepcopy(newComponent1)) molecule[0].components[-1].bonds.append(idx) flag = False #same thing for the other member of the bond for component in molecule[1].components: if component.name == molecule[0].name.lower() and len( component.bonds) == 0: component.bonds.append(idx) flag = True break if not flag: newComponent2 = st.Component(molecule[0].name.lower()) molecule[1].components.append(newComponent2) if molecule[0].name != molecule[1].name: if newComponent2.name not in [x.name for x in translator[molecule[0].name].molecules[0]. \ components]: translator[ molecule[1].name].molecules[0].components.append( deepcopy(newComponent2)) molecule[1].components[-1].bonds.append(idx) #update the translator translator[element[0]] = species
def createEmptySpecies(name): species = st.Species() molecule = st.Molecule(name) species.addMolecule(molecule) return species
def extractTransformations(rules): ''' goes through the list of rules and extracts its reactioncenter,context and product atomic patterns per transformation action also resolves wildcard patterns to create additional context links and deleting the wildcard pattern - js ''' atomicArray = {} transformationCenter = [] transformationContext = [] productElements = [] actionName = [] index = 0 label = [] #for idx,(react,product,act,mapp,nameDict) in enumerate(rules): # print idx #print "react\t"," ".join([str(x) for x in react]) #print "product\t"," ".join([str(x) for x in product]) #print "act\t"," ".join([str(x) for x in act]) #print "mapp\t"," ".join([str(x) for x in mapp]) #print "nameDict\t"," ".join([x+":"+y for x,y in nameDict.items()]) for react, product, act, mapp, nameDict in rules: index += 1 for action in act: atomic, reactionCenter, context = extractMolecules( action.action, action.site1, action.site2, react) atomicArray.update(atomic) # this method does not extract reaction centers for creation and deletion transformations # however it extracts context correctly # so generate the reactioncenter here if action.action == 'Delete': temp = st.Species() temp.addMolecule(st.Molecule(nameDict[action.site1], 1)) atomic = dict() atomic[str(temp)] = temp atomicArray.update(atomic) transformationCenter.append(set([str(temp)])) productElements.append(set()) transformationContext.append(context) elif action.action == 'Add': temp = st.Species() temp.addMolecule(st.Molecule(nameDict[action.site1], 1)) atomic = dict() atomic[str(temp)] = temp atomicArray.update(atomic) transformationCenter.append(set()) productElements.append(set([str(temp)])) transformationContext.append(context) else: transformationCenter.append(reactionCenter) transformationContext.append(context) atomicArray.update(atomic) productSites = [ getMapping(mapp, action.site1), getMapping(mapp, action.site2) ] atomic, rc, _ = extractMolecules(action.action, productSites[0], productSites[1], product) productElements.append(rc) atomicArray.update(atomic) actionName.append('%i-%s' % (index, action.action)) r = '+'.join([str(x) for x in react]) p = '+'.join([str(x) for x in product]) label.append('->'.join([r, p, '%i-%s' % (index, action.action)])) # resolving bond wildcards wildcards = [x for x in atomicArray if '!+' in x] bondedpatterns = [ x for x in atomicArray if '!' in x and x not in wildcards ] for item in wildcards: loc = string.find(item, '+') selected_bondedpatterns = [ x for x in bondedpatterns if item[0:loc] in x ] for idx, set1 in enumerate(transformationContext): if item in set1: set1.update(selected_bondedpatterns) set1.remove(item) transformationContext[idx] = set1 del atomicArray[item] return atomicArray, transformationCenter, transformationContext, productElements, actionName, label