1. biolab
  2. Untitled project
  3. orange-addon-chem

Commits

Aleš Erjavec  committed 3d0333d

no message

  • Participants
  • Parent commits 732a3f4
  • Branches default

Comments (0)

Files changed (3)

File OWMoleculeVisualizer.py

-"""<name>Molecule visualizer</name>"""
-
-import orange
-import orngChem
-from OWWidget import *
-from qt import *
-import OWGUI
-import sys, os
-import vis
-from openeye.oechem import *
-
-class DrawContext:
-    def __init__(self, molecule="", fragment="", size=200, imageprefix="", imagename="", title=""):
-        self.molecule=molecule
-        self.fragment=fragment
-        self.size=size
-        self.imageprefix=imageprefix
-        self.imagename=imagename
-        self.title=title
-
-class BigImage(QDialog):
-    def __init__(self, context, *args):
-        apply(QDialog.__init__, (self,)+args)
-        self.context=context
-        self.label=QLabel(self)
-        self.imagename=context.imagename or context.imageprefix+"_big.bmp"
-        self.imageSize=400
-        self.renderImage()
-
-    def renderImage(self):
-        if self.context.fragment:
-            vis.moleculeFragment2BMP(self.context.molecule, self.context.fragment, self.imagename, self.imageSize, self.context.title)
-        else:
-            vis.molecule2BMP(self.context.molecule, self.imagename, self.imageSize, self.context.title)
-        pix=QPixmap()
-        pix.load(self.imagename)
-        self.label.setPixmap(pix)
-        self.label.resize(pix.width(), pix.height())
-            
-    def resizeEvent(self, event):
-        apply(QDialog.resizeEvent, (self, event))
-        self.imageSize=min(event.size().width(), event.size().height())
-        self.renderImage()
-        
-    
-class MolImage(QLabel):
-    def __init__(self, master, parent, context):
-        apply(QLabel.__init__,(self, parent))
-        #print filename
-        self.context=context
-        self.master=master
-        imagename=context.imagename or context.imageprefix+".bmp"
-        if context.fragment:
-            vis.moleculeFragment2BMP(context.molecule, context.fragment, imagename, context.size, context.title)
-        else:
-            vis.molecule2BMP(context.molecule, imagename, context.size, context.title)
-        self.load(imagename)
-        self.selected=False
-        self.setFrameStyle(QFrame.Panel | QFrame.Raised)
-        
-    def load(self, filename):
-        self.pix=QPixmap()
-        if not self.pix.load(filename):
-            print "Failed to load "+filename
-            return
-        self.resize(self.pix.width(), self.pix.height())
-        self.setPixmap(self.pix)
-
-    def paintEvent(self, event):
-        apply(QLabel.paintEvent,(self, event))
-        if self.selected:
-            painter=QPainter(self)
-            painter.setPen(QPen(Qt.red, 2))
-            painter.drawRect(2, 2, self.width()-3, self.height()-3)
-
-    def mousePressEvent(self, event):
-        self.master.mouseAction(self, event)
-
-    def mouseDoubleClickEvent(self, event):
-        d=BigImage(self.context, self)
-        d.show()
-        
-class ScrollView(QScrollView):
-    def __init__(self, master, *args):
-        apply(QScrollView.__init__, (self,)+args)
-        self.master=master
-        self.viewport().setMouseTracking(True)
-        self.setMouseTracking(True)
-        
-    def resizeEvent(self, event):
-        apply(QScrollView.resizeEvent, (self, event))
-        size=event.size()
-        w,h=size.width(), size.height()
-        oldNumColumns=self.master.numColumns
-        numColumns=min(w/self.master.imageSize or 1, 100)
-        if numColumns!=oldNumColumns:
-            self.master.numColumns=numColumns
-            self.master.redrawImages()
-        
-
-class OWMoleculeVisualizer(OWWidget):
-    settingsList=["colorFragmets","showFragments"]
-    def __init__(self, parent=None, signalManager=None, name="Molecule visualizer"):
-        apply(OWWidget.__init__,(self, parent, signalManager, name))
-        self.inputs=[("Molecules", ExampleTable, self.setMoleculeTable), ("Fragments", ExampleTable, self.setFragmentTable)]
-        self.outputs=[("Selected Molecules", ExampleTable)]
-        self.colorFragments=1
-        self.showFragments=0
-        self.selectedFragment=""
-        self.moleculeSmiles=[]
-        self.fragmentSmiles=[]
-        self.defFragmentSmiles=[]
-        self.moleculeSmilesAttr=0
-        self.moleculeTitleAttr=0
-        self.fragmentSmilesAttr=0
-        self.imageSize=200
-        self.numColumns=4
-        self.commitOnChange=0
-        ##GUI
-        box=OWGUI.radioButtonsInBox(self.controlArea, self, "showFragments", ["Show molecules", "Show fragments"], "Show", callback=self.showImages)
-        OWGUI.checkBox(box, self, "colorFragments", "Mark fragments", callback=self.redrawImages)
-        box.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum))
-        self.moleculeSmilesCombo=OWGUI.comboBox(self.controlArea, self, "moleculeSmilesAttr", "Molecule SMILES attribute",callback=self.showImages)
-        self.moleculeSmilesCombo.box.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum))
-        self.moleculeTitleCombo=OWGUI.comboBox(self.controlArea, self, "moleculeTitleAttr", "Molecule title attribute", callback=self.redrawImages)
-        self.moleculeTitleCombo.box.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum))
-        self.fragmentSmilesCombo=OWGUI.comboBox(self.controlArea, self, "fragmentSmilesAttr", "Fragment SMILES attribute", callback=self.updateFragmentsListBox)
-        self.fragmentSmilesCombo.box.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum))
-        box=OWGUI.spin(self.controlArea, self, "imageSize", 50, 500, 50, box="Image size", callback=self.redrawImages)
-        box.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum))
-        box=OWGUI.widgetBox(self.controlArea,"Selection")
-        OWGUI.checkBox(box, self, "commitOnChange", "Commit on change")
-        OWGUI.button(box, self, "&Select marked molecules", self.selectMarked)
-        OWGUI.button(box, self, "&Commit", callback=self.commit)
-        OWGUI.rubber(self.controlArea)
-        
-        self.mainAreaLayout=QVBoxLayout(self.mainArea, QVBoxLayout.TopToBottom)
-        spliter=QSplitter(Qt.Vertical, self.mainArea)
-        self.scrollView=ScrollView(self, spliter)
-        self.scrollView.setHScrollBarMode(QScrollView.Auto)
-        self.scrollView.setVScrollBarMode(QScrollView.Auto)
-        self.molWidget=QWidget(self.scrollView.viewport())
-        self.scrollView.addChild(self.molWidget)
-        self.mainAreaLayout.addWidget(spliter)
-        self.gridLayout=QGridLayout(self.molWidget,10,100,2,2)
-        self.gridLayout.setAutoAdd(False)
-        self.listBox=QListBox(spliter)
-        self.connect(self.listBox, SIGNAL("highlighted(int)"), self.fragmentSelection)
-
-        self.imageprefix=os.path.split(__file__)[0]
-        if self.imageprefix:
-            self.imageprefix+="\molimages\image"
-        else:
-            self.imageprefix="molimages\image"
-        self.imageWidgets=[]
-        self.candidateMolSmilesAttr=[]
-        self.candidateMolTitleAttr=[None]
-        self.candidateFragSmilesAttr=[None]
-        self.molData=None
-        self.fragData=None
-        self.ctrlPressed=FALSE
-        self.resize(600,600)
-        self.listBox.setMaximumHeight(150)
-        
-    def setMoleculeTable(self, data):
-        self.molData=data
-        if data:
-            self.setMoleculeSmilesCombo()
-            self.setMoleculeTitleCombo()
-            self.setFragmentSmilesCombo()
-            self.updateFragmentsListBox()
-            self.showImages()
-        else:
-            self.moleculeSmilesCombo.clear()
-            self.moleculeTitleCombo.clear()
-            self.defFragmentSmiles=[]
-            if not self.fragmentSmilesAttr:
-                self.listBox.clear()
-            self.destroyImageWidgets()
-            self.send("Selected Molecules", None)
-            
-    def setFragmentTable(self, data):
-        self.fragData=data
-        if data:
-            self.setFragmentSmilesCombo()
-            self.updateFragmentsListBox()
-            self.selectedFragment=""
-            self.showImages()
-        else:
-            self.setFragmentSmilesCombo()
-            #self.fragmentSmilesAttr=0
-            self.updateFragmentsListBox()
-            if self.showFragments:
-                self.destroyImageWidgets()
-
-    def filterSmilesVariables(self, data):
-        candidates=data.domain.variables+data.domain.getmetas().values()
-        candidates=filter(lambda v:v.varType==orange.VarTypes.Discrete or v.varType==orange.VarTypes.String, candidates)        
-        vars=[]
-        for var in candidates:
-            count=0
-            for e in data:
-                if OEParseSmiles(OEGraphMol(), str(e[var])):
-                    count+=1
-            if float(count)/float(len(data))>0.5:
-                vars.append(var)
-        names=[v.name for v in data.domain.variables+data.domain.getmetas().values()]
-        names=filter(lambda n:OEParseSmiles(OEGraphMol(), n), names)
-        return vars, names
-        
-    def setMoleculeSmilesCombo(self):
-        candidates, self.defFragmentSmiles=self.filterSmilesVariables(self.molData)
-        self.candidateMolSmilesAttr=candidates
-        self.moleculeSmilesCombo.clear()
-        self.moleculeSmilesCombo.insertStrList([v.name for v in candidates])
-        if self.moleculeSmilesAttr>=len(candidates):
-            self.moleculeSmilesAttr=0
-
-    def setMoleculeTitleCombo(self):
-        vars=self.molData.domain.variables+self.molData.domain.getmetas().values()
-        self.moleculeTitleCombo.clear()
-        self.moleculeTitleCombo.insertStrList(["None"]+[v.name for v in vars])
-        if self.moleculeTitleAttr>len(vars):
-            self.moleculeTitleAttr=0
-        self.candidateMolTitleAttr=[None]+[v for v in vars]
-
-    def setFragmentSmilesCombo(self):
-        if self.fragData:
-            candidates, names=self.filterSmilesVariables(self.fragData)
-        else:
-            candidates=[]
-        self.candidateFragSmilesAttr=[None]+candidates
-        self.fragmentSmilesCombo.clear()
-        self.fragmentSmilesCombo.insertStrList(["Default"]+[v.name for v in candidates])
-        if self.fragmentSmilesAttr>len(candidates):
-            self.fragmentSmilesAttr=0
-
-    def updateFragmentsListBox(self):
-        fAttr=self.candidateFragSmilesAttr[self.fragmentSmilesAttr]
-        if fAttr:
-            self.fragmentSmiles=[""]+[str(e[fAttr]) for e in self.fragData if not e[fAttr].isSpecial()]
-        else:
-            self.fragmentSmiles=[""]+self.defFragmentSmiles
-        self.listBox.clear()
-        self.listBox.insertStrList(self.fragmentSmiles)
-        
-    def fragmentSelection(self, index):
-        self.selectedFragment=self.fragmentSmiles[index]
-        if not self.showFragments and self.colorFragments:
-            self.redrawImages()
-        
-    def renderImages(self):
-        self.imageWidgets=[]
-        if self.showFragments and self.fragmentSmiles:
-            for i,fragment in enumerate(self.fragmentSmiles[1:]):
-                imagename=self.imageprefix+str(i)+".bmp"
-                #vis.molecule2BMP(fragment, imagename, self.imageSize)
-                image=MolImage(self, self.molWidget, DrawContext(molecule=fragment, imagename=imagename, size=self.imageSize))
-                self.gridLayout.addWidget(image, i/self.numColumns, i%self.numColumns)
-                self.imageWidgets.append(image)
-        elif self.molData:
-            sAttr=self.candidateMolSmilesAttr[min(self.moleculeSmilesAttr, len(self.candidateMolSmilesAttr)-1)]
-            tAttr=self.candidateMolTitleAttr[min(self.moleculeTitleAttr, len(self.candidateMolTitleAttr)-1)]
-            if self.moleculeTitleAttr:
-                titleList=[str(e[tAttr]) for e in self.molData if not e[sAttr].isSpecial()]
-            else:
-                titleList=[]
-                if not sAttr:
-                    return
-            molSmiles=[str(e[sAttr]) for e in self.molData if not e[sAttr].isSpecial()]
-            for i,(molecule, title) in enumerate(zip(molSmiles, titleList or [""]*len(molSmiles))):
-                imagename=self.imageprefix+str(i)+".bmp"
-                if self.colorFragments:
-                    context=DrawContext(molecule=molecule, fragment=self.selectedFragment, imagename=imagename, size=self.imageSize, title=title)
-                    #vis.moleculeFragment2BMP(molecule, self.selectedFragment, imagename, self.imageSize)
-                else:
-                    context=DrawContext(molecule=molecule, imagename=imagename, size=self.imageSize, title=title)
-                    #vis.molecule2BMP(molecule, imagename, self.imageSize)
-                image=MolImage(self, self.molWidget, context)
-                self.gridLayout.addWidget(image, i/self.numColumns, i%self.numColumns)
-                self.imageWidgets.append(image)
-        #print "done drawing"
-        for w in self.imageWidgets:
-            w.show()
-
-    def destroyImageWidgets(self):
-        for w in self.imageWidgets:
-            self.molWidget.removeChild(w)
-        self.imageWidgets=[]
-            
-    def showImages(self):
-        self.destroyImageWidgets()
-        #print "destroyed"
-        self.renderImages()
-
-    def redrawImages(self):
-        selected=map(lambda i:self.imageWidgets.index(i), filter(lambda i:i.selected, self.imageWidgets))
-        self.showImages()
-        for i in selected:
-            self.imageWidgets[i].selected=True
-            self.imageWidgets[i].repaint()
-            
-    def mouseAction(self, image, event):
-        if self.ctrlPressed:
-            image.selected=not image.selected
-        else:
-            for i in self.imageWidgets:
-                i.selected=False
-                i.repaint()
-            image.selected=True
-        image.repaint()
-        if self.commitOnChange:
-            self.commit()
-
-    def selectMarked(self):
-        if not self.showFragments:
-            molecules=[i.context.molecule for i in self.imageWidgets]
-            fMap=orngChem.map_fragments([self.selectedFragment], molecules)
-            for i in self.imageWidgets:
-                if fMap[i.context.molecule][self.selectedFragment]:
-                    i.selected=True
-                else:
-                    i.selected=False
-                i.repaint()
-        if self.commitOnChange:
-            self.commit()
-    
-    def commit(self):
-        if self.showFragments:
-            sAttr=self.candidateMolSmilesAttr[self.moleculeSmilesAttr]
-            molecules=map(str, [e[sAttr] for e in self.molData])
-            fragments=[i.context.molecule for i in self.imageWidgets if i.selected]
-            fragmap=orngChem.map_fragments(fragments, molecules)
-            match=filter(lambda m:max(fragmap[m].values()), molecules)
-            examples=[e for e in self.molData if str(e[sAttr]) in match]
-            table=orange.ExampleTable(examples)
-            self.send("Selected Molecules", table)
-        else:
-            mols=[i.context.molecule for i in self.imageWidgets if i.selected]
-            sAttr=self.candidateMolSmilesAttr[self.moleculeSmilesAttr]
-            examples=[e for e in self.molData if str(e[sAttr]) in mols]
-            table=orange.ExampleTable(examples)
-            self.send("Selected Molecules", table)
-
-    def keyPressEvent(self, key):
-        if key.key()==Qt.Key_Control:
-            self.ctrlPressed=TRUE
-        else:
-            key.ignore()
-
-    def keyReleaseEvent(self, key):
-        if key.key()==Qt.Key_Control:
-            self.ctrlPressed=FALSE
-        else:
-            key.ignore()        
-
-if __name__=="__main__":
-    app=QApplication(sys.argv)
-    w=OWMoleculeVisualizer()
-    app.setMainWidget(w)
-    w.show()
-    data=orange.ExampleTable("E://fragG.tab")
-    w.setMoleculeTable(data)
-    data=orange.ExampleTable("E://chem//new//sf.tab")
-    w.setFragmentTable(data)
-    app.exec_loop()

File OWSensProfile.py

-"""
-<name>Sensitivity profile analisys</name>
-"""
-
-import orange
-import orngChem
-from OWWidget import *
-from qt import *
-import OWGUI
-import go
-
-go.loadGO()
-go.loadAnnotation()
-
-class OWSensProfile(OWWidget):
-    settingsList=["aspectNum", "fragFreq", "smilesFileName"]
-    def __init__(self, parent=None, signalManager=None, name="Sens profile"):
-        OWWidget.__init__(self, parent, signalManager, name)
-        self.inputs=[("Sensitivity", ExampleTable, self.sensData)]
-        self.outputs=[("Molecule fragmetns", ExampleTable),("Slim-based molecular profiles", ExampleTable),("Molecule-based slim profiles", ExampleTable),("Slim-based fragment profiles", ExampleTable), ("Fragment-based slim profiles", ExampleTable)]
-
-        self.aspectNum=0
-        self.fragFreq=0.1
-        self.smilesFileName=""
-        self.slimsOnly=1
-        self.maxTerms=100
-        
-        OWGUI.radioButtonsInBox(self.controlArea, self, "aspectNum",["Process", "Function", "Component"], "Aspect")
-        #self.findTermsButton=OWGUI.button(self.controlArea, self, "Find slim terms", callback=self.findTerms)
-        OWGUI.checkBox(self.controlArea, self, "slimsOnly","Slims only")
-        OWGUI.spin(self.controlArea, self, "maxTerms", 10, 1000, box="Number of terms")
-        self.findTermsButton=OWGUI.button(self.controlArea, self, "Find terms", callback=self.findTerms)
-        OWGUI.button(self.controlArea, self, "Load selected terms", callback=self.loadSelectedTerms)
-        OWGUI.doubleSpin(self.controlArea, self, "fragFreq", 0.1, 1.0, 0.1, "Fragment frequency")
-        self.findFragmentsButton=OWGUI.button(self.controlArea, self, "Find fragments", callback=self.findFragments)
-        OWGUI.button(self.controlArea, self, "Load smiles", callback=self.loadSmiles)
-        self.commitButton=OWGUI.button(self.controlArea, self, "Commit", callback=self.commitData)
-        self.findTermsButton.setEnabled(0)
-        self.findFragmentsButton.setEnabled(0)
-        self.commitButton.setEnabled(0)
-        self.resize(100,100)
-        self.fragments=[]
-        self.sensDict={}
-        self.smilesDict={}
-        self.reverseSmilesDict={}
-        self.data=None
-        self.fragmentMap=None
-        self.terms=None
-        self.loadSmiles(self.smilesFileName)
-        self.selectedTerms=[]
-        self.loadSettings()
-        
-    def findFragments(self):
-        if self.smilesDict:
-            smiles=[self.smilesDict[chem] for chem in self.chemicals if chem in self.smilesDict]
-            self.fragments=orngChem.find_fragments(smiles, self.fragFreq)
-            self.fragmentMap=orngChem.map_fragments(self.fragments, smiles)
-            if self.terms:
-                self.commitButton.setEnabled(1)
-
-    def findTerms(self):
-        if not self.data:
-            return 
-        genes=[str(e[0]) for e in self.data]
-        aspect=["P","F","C"][self.aspectNum]
-        if not go.loadedGO:
-            go.loadGO()
-        if not go.loadedSlimGO:
-            go.setSlims("goslim_yeast")
-        if not go.loadedAnnotation:
-            go.loadAnnotation()
-        self.progressBarInit()
-        #self.terms=go.GOTermFinder(genes, slimsOnly=self.slimsOnly, aspect=aspect, progressCallback=self.progressBarSet)
-        self.terms=go.findTerms(genes, slimsOnly=self.slimsOnly, aspect=[aspect],reportEvidence=False, progressCallback=self.progressBarSet)
-        self.progressBarFinished()
-        self.filterTerms()
-        if self.fragments:
-            self.commitButton.setEnabled(1)
-
-    def filterTerms(self):
-        ll=[]
-        for key, val in self.terms.items():
-            if self.selectedTerms and key in self.selectedTerms:
-                ll.append((key, val))
-            elif not self.selectedTerms:
-                ll.append((key, val))
-        #ll.sort(lambda a,b:-cmp(a[1][1], b[1][1]))
-        #ll=ll[:max(len(ll),self.maxTerms)]
-        self.terms=dict(ll)
-
-    def sendFragments(self):
-        vars=[orange.FloatVariable(frag) for frag in self.fragments]
-        mid=orange.newmetaid()
-        chemVar=orange.StringVariable("chemical name")
-        domain=orange.Domain(vars,0)
-        domain.addmeta(mid, chemVar)
-        table=orange.ExampleTable(domain)
-        for chem, map in self.fragmentMap.items():
-            val=[map[frag] for frag in self.fragments]
-            e=orange.Example(domain, val)
-            e[mid]=chem
-            table.append(e)
-        self.send("Molecule fragmetns", table)
-
-    def sendFragmentTerms(self):
-        matrix=[]
-        for frag in self.fragments:
-            vec=[]
-            for term in self.terms.keys():
-                genes=self.terms[term]#[0]
-                #print genes
-                chem=filter(lambda a:self.fragmentMap[a][frag], self.fragmentMap.keys())
-                avgSens=0.0
-                for g in genes:
-                    for c in chem:
-                        avgSens+=self.sensDict[g][self.reverseSmilesDict[c]]
-                avgSens/=len(genes)*len(chem)
-                vec.append(avgSens)
-            matrix.append(vec)
-            
-        vars=[orange.FloatVariable(term) for term in self.terms.keys()]
-        mid=orange.newmetaid()
-        domain=orange.Domain(vars,0)
-        domain.addmeta(mid, orange.StringVariable("fragment"))
-        table=orange.ExampleTable(domain)
-        for frag, vec in zip(self.fragments, matrix):
-            e=orange.Example(domain, vec)
-            e[mid]=frag
-            table.append(e)
-        self.send("Slim-based fragment profiles", table)
-        
-        import Numeric
-        matrix=Numeric.transpose(matrix)
-        vars=[orange.FloatVariable(frag) for frag in self.fragments]
-        mid=orange.newmetaid()
-        mid1=orange.newmetaid()
-        domain=orange.Domain(vars,0)
-        domain.addmeta(mid, orange.StringVariable("term id"))
-        domain.addmeta(mid1, orange.StringVariable("term name"))
-        table=orange.ExampleTable(domain)
-        for term, vec in zip(self.terms.keys(),matrix):
-            e=orange.Example(domain, list(vec))
-            e[mid]=term
-            e[mid1]=go.loadedGO.termDict[term].name
-            table.append(e)
-        self.send("Fragment-based slim profiles", table)
-
-    def sendMoleculeTerms(self):
-        matrix=[]
-        for chem in self.data.domain.variables[1:]:
-            vec=[]
-            for term in self.terms.keys():
-                genes=self.terms[term]#[0]
-                avgSens=0.0
-                for g in genes:
-                    avgSens+=self.sensDict[g][chem]
-                avgSens/=len(genes)
-                vec.append(avgSens)
-            matrix.append(vec)
-            
-        vars=[orange.FloatVariable(term) for term in self.terms.keys()]
-        mid=orange.newmetaid()
-        domain=orange.Domain(vars,0)
-        domain.addmeta(mid, orange.StringVariable("chemical name"))
-        table=orange.ExampleTable(domain)
-        for chem, vec in zip(self.chemicals,matrix):
-            e=orange.Example(domain, vec)
-            e[mid]=chem
-            table.append(e)
-        self.send("Slim-based molecular profiles", table)
-        
-        import Numeric
-        matrix=Numeric.transpose(matrix)
-        vars=[orange.FloatVariable(chem) for chem in self.chemicals]
-        mid=orange.newmetaid()
-        mid1=orange.newmetaid()
-        domain=orange.Domain(vars,0)
-        domain.addmeta(mid, orange.StringVariable("term id"))
-        domain.addmeta(mid1, orange.StringVariable("term name"))
-        table=orange.ExampleTable(domain)
-        for term, vec in zip(self.terms.keys(),matrix):
-            e=orange.Example(domain, list(vec))
-            e[mid]=term
-            e[mid1]=go.loadedGO.termDict[term].name
-            table.append(e)
-        self.send("Molecule-based slim profiles", table)
-
-    def sensData(self, data=None):
-        self.data=data
-        self.send("Molecule fragmetns", None)
-        self.send("Slim-based molecular profiles", None)
-        self.send("Molecule-based slim profiles", None)
-        self.send("Slim-based fragment profiles", None)
-        self.send("Fragment-based slim profiles", None)
-        if self.data:
-            self.findTermsButton.setEnabled(1)
-            self.sensDict={}
-            for e in data:
-                self.sensDict[str(e[0])]=e
-                self.sensDict[go.mapGeneName(str(e[0]))]=e
-            self.chemicals=[var.name for var in data.domain.variables[1:]]
-        else:
-            self.findTermsButton.setEnabled(0)
-            self.commitButton.setEnabled(0)
-            self.sensDict={}
-            self.chemicals=[]
-            
-    def commitData(self):
-        if self.fragments:
-            self.sendFragments()
-            self.sendFragmentTerms()
-        self.sendMoleculeTerms()
-        
-    def loadSmiles(self, filename=""):
-        if not filename:
-            filename=str(QFileDialog.getOpenFileName("./","Text files (*.txt *.tab)",self,"open", "Choose a smiles file"))
-        try:
-            #if filename.endswith(".txt"):
-            #    raise ""
-            data=orange.ExampleTable(filename)
-            self.smilesDict=[(str(e[0]), str(e[1])) for e in data if not e[1].isSpecial()]
-        except:
-            file=open(filename)
-            data=file.read()
-            lines=data.split("\n")
-            self.smilesDict=[l.split("\t") for l in lines]
-        self.smilesDict=dict([(a[0].strip(), a[1].strip()) for a in self.smilesDict if a[1].strip() or a[1].strip()!="?"])
-        self.reverseSmilesDict=dict([(val, key) for key, val in self.smilesDict.items()])
-        self.smilesFileName=filename
-        self.findFragmentsButton.setEnabled(1)
-
-    def loadSelectedTerms(self):
-        filename=str(QFileDialog.getOpenFileName("./","Text file (*.txt)",self,"open", "Choose file containing terms"))
-        data=open(filename)
-        data=data.read().split("\n")
-        self.selectedTerms=data
-        
-if __name__=="__main__":
-    import sys
-    go.setDataDir("E://GO//data")
-    app=QApplication(sys.argv)
-    w=OWSensProfile()
-    app.setMainWidget(w)
-    d=orange.ExampleTable("E://chem//boone//sens.tab")
-    w.sensData(d)
-    w.show()
-    app.exec_loop()
-    w.saveSettings()
-    
-            
-        

File widgets/OWSensProfile.py

View file
+"""
+<name>Sensitivity profile analisys</name>
+"""
+
+import orange
+import orngChem
+from OWWidget import *
+from qt import *
+import OWGUI
+import go
+
+go.loadGO()
+go.loadAnnotation()
+
+class OWSensProfile(OWWidget):
+    settingsList=["aspectNum", "fragFreq", "smilesFileName"]
+    def __init__(self, parent=None, signalManager=None, name="Sens profile"):
+        OWWidget.__init__(self, parent, signalManager, name)
+        self.inputs=[("Sensitivity", ExampleTable, self.sensData)]
+        self.outputs=[("Molecule fragmetns", ExampleTable),("Slim-based molecular profiles", ExampleTable),("Molecule-based slim profiles", ExampleTable),("Slim-based fragment profiles", ExampleTable), ("Fragment-based slim profiles", ExampleTable)]
+
+        self.aspectNum=0
+        self.fragFreq=0.1
+        self.smilesFileName=""
+        self.slimsOnly=1
+        self.maxTerms=100
+        
+        OWGUI.radioButtonsInBox(self.controlArea, self, "aspectNum",["Process", "Function", "Component"], "Aspect")
+        #self.findTermsButton=OWGUI.button(self.controlArea, self, "Find slim terms", callback=self.findTerms)
+        OWGUI.checkBox(self.controlArea, self, "slimsOnly","Slims only")
+        OWGUI.spin(self.controlArea, self, "maxTerms", 10, 1000, box="Number of terms")
+        self.findTermsButton=OWGUI.button(self.controlArea, self, "Find terms", callback=self.findTerms)
+        OWGUI.button(self.controlArea, self, "Load selected terms", callback=self.loadSelectedTerms)
+        OWGUI.doubleSpin(self.controlArea, self, "fragFreq", 0.1, 1.0, 0.1, "Fragment frequency")
+        self.findFragmentsButton=OWGUI.button(self.controlArea, self, "Find fragments", callback=self.findFragments)
+        OWGUI.button(self.controlArea, self, "Load smiles", callback=self.loadSmiles)
+        self.commitButton=OWGUI.button(self.controlArea, self, "Commit", callback=self.commitData)
+        self.findTermsButton.setEnabled(0)
+        self.findFragmentsButton.setEnabled(0)
+        self.commitButton.setEnabled(0)
+        self.resize(100,100)
+        self.fragments=[]
+        self.sensDict={}
+        self.smilesDict={}
+        self.reverseSmilesDict={}
+        self.data=None
+        self.fragmentMap=None
+        self.terms=None
+        self.loadSmiles(self.smilesFileName)
+        self.selectedTerms=[]
+        self.loadSettings()
+        
+    def findFragments(self):
+        if self.smilesDict:
+            smiles=[self.smilesDict[chem] for chem in self.chemicals if chem in self.smilesDict]
+            self.fragments=orngChem.find_fragments(smiles, self.fragFreq)
+            self.fragmentMap=orngChem.map_fragments(self.fragments, smiles)
+            if self.terms:
+                self.commitButton.setEnabled(1)
+
+    def findTerms(self):
+        if not self.data:
+            return 
+        genes=[str(e[0]) for e in self.data]
+        aspect=["P","F","C"][self.aspectNum]
+        if not go.loadedGO:
+            go.loadGO()
+        if not go.loadedSlimGO:
+            go.setSlims("goslim_yeast")
+        if not go.loadedAnnotation:
+            go.loadAnnotation()
+        self.progressBarInit()
+        #self.terms=go.GOTermFinder(genes, slimsOnly=self.slimsOnly, aspect=aspect, progressCallback=self.progressBarSet)
+        self.terms=go.findTerms(genes, slimsOnly=self.slimsOnly, aspect=[aspect],reportEvidence=False, progressCallback=self.progressBarSet)
+        self.progressBarFinished()
+        self.filterTerms()
+        if self.fragments:
+            self.commitButton.setEnabled(1)
+
+    def filterTerms(self):
+        ll=[]
+        for key, val in self.terms.items():
+            if self.selectedTerms and key in self.selectedTerms:
+                ll.append((key, val))
+            elif not self.selectedTerms:
+                ll.append((key, val))
+        #ll.sort(lambda a,b:-cmp(a[1][1], b[1][1]))
+        #ll=ll[:max(len(ll),self.maxTerms)]
+        self.terms=dict(ll)
+
+    def sendFragments(self):
+        vars=[orange.FloatVariable(frag) for frag in self.fragments]
+        mid=orange.newmetaid()
+        chemVar=orange.StringVariable("chemical name")
+        domain=orange.Domain(vars,0)
+        domain.addmeta(mid, chemVar)
+        table=orange.ExampleTable(domain)
+        for chem, map in self.fragmentMap.items():
+            val=[map[frag] for frag in self.fragments]
+            e=orange.Example(domain, val)
+            e[mid]=chem
+            table.append(e)
+        self.send("Molecule fragmetns", table)
+
+    def sendFragmentTerms(self):
+        matrix=[]
+        for frag in self.fragments:
+            vec=[]
+            for term in self.terms.keys():
+                genes=self.terms[term]#[0]
+                #print genes
+                chem=filter(lambda a:self.fragmentMap[a][frag], self.fragmentMap.keys())
+                avgSens=0.0
+                for g in genes:
+                    for c in chem:
+                        avgSens+=self.sensDict[g][self.reverseSmilesDict[c]]
+                avgSens/=len(genes)*len(chem)
+                vec.append(avgSens)
+            matrix.append(vec)
+            
+        vars=[orange.FloatVariable(term) for term in self.terms.keys()]
+        mid=orange.newmetaid()
+        domain=orange.Domain(vars,0)
+        domain.addmeta(mid, orange.StringVariable("fragment"))
+        table=orange.ExampleTable(domain)
+        for frag, vec in zip(self.fragments, matrix):
+            e=orange.Example(domain, vec)
+            e[mid]=frag
+            table.append(e)
+        self.send("Slim-based fragment profiles", table)
+        
+        import Numeric
+        matrix=Numeric.transpose(matrix)
+        vars=[orange.FloatVariable(frag) for frag in self.fragments]
+        mid=orange.newmetaid()
+        mid1=orange.newmetaid()
+        domain=orange.Domain(vars,0)
+        domain.addmeta(mid, orange.StringVariable("term id"))
+        domain.addmeta(mid1, orange.StringVariable("term name"))
+        table=orange.ExampleTable(domain)
+        for term, vec in zip(self.terms.keys(),matrix):
+            e=orange.Example(domain, list(vec))
+            e[mid]=term
+            e[mid1]=go.loadedGO.termDict[term].name
+            table.append(e)
+        self.send("Fragment-based slim profiles", table)
+
+    def sendMoleculeTerms(self):
+        matrix=[]
+        for chem in self.data.domain.variables[1:]:
+            vec=[]
+            for term in self.terms.keys():
+                genes=self.terms[term]#[0]
+                avgSens=0.0
+                for g in genes:
+                    avgSens+=self.sensDict[g][chem]
+                avgSens/=len(genes)
+                vec.append(avgSens)
+            matrix.append(vec)
+            
+        vars=[orange.FloatVariable(term) for term in self.terms.keys()]
+        mid=orange.newmetaid()
+        domain=orange.Domain(vars,0)
+        domain.addmeta(mid, orange.StringVariable("chemical name"))
+        table=orange.ExampleTable(domain)
+        for chem, vec in zip(self.chemicals,matrix):
+            e=orange.Example(domain, vec)
+            e[mid]=chem
+            table.append(e)
+        self.send("Slim-based molecular profiles", table)
+        
+        import Numeric
+        matrix=Numeric.transpose(matrix)
+        vars=[orange.FloatVariable(chem) for chem in self.chemicals]
+        mid=orange.newmetaid()
+        mid1=orange.newmetaid()
+        domain=orange.Domain(vars,0)
+        domain.addmeta(mid, orange.StringVariable("term id"))
+        domain.addmeta(mid1, orange.StringVariable("term name"))
+        table=orange.ExampleTable(domain)
+        for term, vec in zip(self.terms.keys(),matrix):
+            e=orange.Example(domain, list(vec))
+            e[mid]=term
+            e[mid1]=go.loadedGO.termDict[term].name
+            table.append(e)
+        self.send("Molecule-based slim profiles", table)
+
+    def sensData(self, data=None):
+        self.data=data
+        self.send("Molecule fragmetns", None)
+        self.send("Slim-based molecular profiles", None)
+        self.send("Molecule-based slim profiles", None)
+        self.send("Slim-based fragment profiles", None)
+        self.send("Fragment-based slim profiles", None)
+        if self.data:
+            self.findTermsButton.setEnabled(1)
+            self.sensDict={}
+            for e in data:
+                self.sensDict[str(e[0])]=e
+                self.sensDict[go.mapGeneName(str(e[0]))]=e
+            self.chemicals=[var.name for var in data.domain.variables[1:]]
+        else:
+            self.findTermsButton.setEnabled(0)
+            self.commitButton.setEnabled(0)
+            self.sensDict={}
+            self.chemicals=[]
+            
+    def commitData(self):
+        if self.fragments:
+            self.sendFragments()
+            self.sendFragmentTerms()
+        self.sendMoleculeTerms()
+        
+    def loadSmiles(self, filename=""):
+        if not filename:
+            filename=str(QFileDialog.getOpenFileName("./","Text files (*.txt *.tab)",self,"open", "Choose a smiles file"))
+        try:
+            #if filename.endswith(".txt"):
+            #    raise ""
+            data=orange.ExampleTable(filename)
+            self.smilesDict=[(str(e[0]), str(e[1])) for e in data if not e[1].isSpecial()]
+        except:
+            file=open(filename)
+            data=file.read()
+            lines=data.split("\n")
+            self.smilesDict=[l.split("\t") for l in lines]
+        self.smilesDict=dict([(a[0].strip(), a[1].strip()) for a in self.smilesDict if a[1].strip() or a[1].strip()!="?"])
+        self.reverseSmilesDict=dict([(val, key) for key, val in self.smilesDict.items()])
+        self.smilesFileName=filename
+        self.findFragmentsButton.setEnabled(1)
+
+    def loadSelectedTerms(self):
+        filename=str(QFileDialog.getOpenFileName("./","Text file (*.txt)",self,"open", "Choose file containing terms"))
+        data=open(filename)
+        data=data.read().split("\n")
+        self.selectedTerms=data
+        
+if __name__=="__main__":
+    import sys
+    go.setDataDir("E://GO//data")
+    app=QApplication(sys.argv)
+    w=OWSensProfile()
+    app.setMainWidget(w)
+    d=orange.ExampleTable("E://chem//boone//sens.tab")
+    w.sensData(d)
+    w.show()
+    app.exec_loop()
+    w.saveSettings()
+    
+            
+