Changeset 3489:62092e14626b in orange


Ignore:
Timestamp:
04/04/07 13:35:10 (7 years ago)
Author:
Gregor <Gregor@…>
Branch:
default
Convert:
1517064ef41f4f8f1c583b85eb9538ab23b8c86f
Message:
  • several modifications
File:
1 edited

Legend:

Unmodified
Added
Removed
  • orange/OrangeWidgets/OWkNNOptimization.py

    r3415 r3489  
    11from OWBaseWidget import * 
    22from OWWidget import OWWidget 
    3 import OWGUI, OWDlgs 
     3import OWGUI, OWDlgs, OWGraphTools, numpy 
    44from OWGraph import * 
    55from orngVizRank import * 
    66from orngScaleData import getVariableValuesSorted 
    7 import OWGraphTools 
    8 import numpy 
    9  
    107 
    118class OWVizRank(VizRank, OWBaseWidget): 
     
    2724    def __init__(self, parentWidget = None, signalManager = None, graph = None, visualizationMethod = SCATTERPLOT, parentName = "Visualization widget"): 
    2825        VizRank.__init__(self, visualizationMethod, graph) 
    29         OWBaseWidget.__init__(self, None, signalManager, "Optimization Dialog") 
     26        OWBaseWidget.__init__(self, None, signalManager, "Optimization Dialog", savePosition = True) 
    3027 
    3128        self.parentWidget = parentWidget 
     
    4845        self.boxLocalOptimization = 1 
    4946        self.boxStopOptimization = 1 
    50          
     47 
    5148        self.maxResultListLen = self.resultsListLenNums[len(self.resultsListLenNums)-1] 
    5249        #self.widgetDir = os.path.realpath(os.path.dirname(__file__)) + "/" 
    5350        self.lastSaveDirName = os.getcwd() 
    54          
     51 
    5552        self.evaluatedAttributes = None   # save last evaluated attributes 
    5653        self.evaluatedAttributesByClass = None 
    57          
     54 
    5855        self.showRank = 0 
    5956        self.showAccuracy = 1 
    6057        self.showInstances = 0 
    61  
    6258        self.shownResults = [] 
    6359        self.attrLenDict = {} 
    6460 
     61        self.interactionAnalysisDlg = None 
     62        self.identifyOutliersDlg = None 
     63        self.attributeHistogramDlg = None 
     64 
    6565        self.loadSettings() 
    6666        self.attrCont = min(self.attrCont, 3) 
     
    6868        self.tabs = QTabWidget(self, 'tabWidget') 
    6969        self.controlArea.addWidget(self.tabs) 
    70          
     70 
    7171        self.MainTab = QVGroupBox(self) 
    7272        self.SettingsTab = QVGroupBox(self) 
     73        self.ArgumentationTab = QVGroupBox(self) 
     74##        self.ClassificationTab = QVGroupBox(self) 
     75##        self.ExplorerTab = QVGroupBox(self) 
    7376        self.ManageTab = QVGroupBox(self) 
    74         self.ArgumentationTab = QVGroupBox(self) 
    75         self.ClassificationTab = QVGroupBox(self) 
    76          
     77 
    7778        self.tabs.insertTab(self.MainTab, "Main") 
    7879        self.tabs.insertTab(self.SettingsTab, "Settings") 
    7980        self.tabs.insertTab(self.ArgumentationTab, "Argumentation") 
    80         self.tabs.insertTab(self.ClassificationTab, "Classification") 
    81         self.tabs.insertTab(self.ManageTab, "Manage & Save")         
     81##        self.tabs.insertTab(self.ClassificationTab, "Classification") 
     82##        self.tabs.insertTab(self.ExplorerTab, "Explorer") 
     83        self.tabs.insertTab(self.ManageTab, "Manage & Save") 
    8284 
    8385        # ########################### 
     
    9496            self.attributeLabel = QLabel(' attributes', self.buttonBox) 
    9597 
    96         self.startOptimizationButton = OWGUI.button(self.optimizationBox, self, "    Start Evaluating Projections    ", callback = self.evaluateProjections) 
     98        self.startOptimizationButton = OWGUI.button(self.optimizationBox, self, "Start Evaluating Projections", callback = self.evaluateProjections) 
    9799        f = self.startOptimizationButton.font(); f.setBold(1);   self.startOptimizationButton.setFont(f) 
    98         self.stopOptimizationButton = OWGUI.button(self.optimizationBox, self, "    Stop Evaluation    ", callback = self.stopEvaluationClick, debuggingEnabled = 0 ) 
    99         self.stopOptimizationButton.setFont(f) 
    100         self.stopOptimizationButton.hide() 
    101         self.optimizeGivenProjectionButton = OWGUI.button(self.optimizationBox, self, "    Locally Optimize Best Projections    ", callback = self.optimizeBestProjections) 
     100        self.optimizeGivenProjectionButton = OWGUI.button(self.optimizationBox, self, "Locally Optimize Best Projections", callback = self.optimizeBestProjections) 
    102101 
    103102        self.resultList = QListBox(self.resultsBox) 
     
    118117        self.attrKNeighboursEdit = OWGUI.lineEdit(self.optimizationSettingsBox, self, "kValue", "Number of neighbors (k):                 ", orientation = "horizontal", tooltip = "Number of neighbors used in k-NN algorithm to evaluate the projection", valueType = int, validator = QIntValidator(self)) 
    119118        self.percentDataUsedCombo= OWGUI.comboBoxWithCaption(self.optimizationSettingsBox, self, "percentDataUsed", "Percent of data used: ", items = self.percentDataNums, sendSelectedValue = 1, valueType = int, tooltip = "In case that we have a large dataset the evaluation of each projection can take a lot of time.\nWe can therefore use only a subset of randomly selected examples, evaluate projection on them and thus make evaluation faster.") 
    120         self.testingCombo = OWGUI.comboBox(self.optimizationSettingsBox, self, "testingMethod", label = "Testing method:                             ", orientation = "horizontal", items = ["Leave one out (slowest)", "10 fold cross validation", "Test on learning set (fastest)"], tooltip = "Method for evaluating the classifier. Slower are more accurate while faster give only a rough approximation.")         
     119        self.testingCombo = OWGUI.comboBox(self.optimizationSettingsBox, self, "testingMethod", label = "Testing method:                             ", orientation = "horizontal", items = ["Leave one out (slowest)", "10 fold cross validation", "Test on learning set (fastest)"], tooltip = "Method for evaluating the classifier. Slower are more accurate while faster give only a rough approximation.") 
    121120        OWGUI.checkBox(self.optimizationSettingsBox, self, 'useExampleWeighting', 'Use example weighting (in case of uneven class distribution)', tooltip = "Don't try all possible permutations of an attribute subset but only those,\nthat will most likely produce interesting projections.") 
    122121        if visualizationMethod != SCATTERPLOT: 
     
    131130        self.attributeSelectionBox = OWGUI.widgetBox(self.SettingsTab, "Attribute Subset Selection") 
    132131        OWGUI.comboBox(self.attributeSelectionBox, self, "attrSubsetSelection", items = ["Deterministically using the selected attribute ranking measures", "Use gamma distribution and test all possible placements", "Use gamma distribution and test only one possible placement"]) 
    133              
     132 
    134133        self.heuristicsSettingsBox = OWGUI.widgetBox(self.SettingsTab, "Measures for Attribute Ranking") 
    135134        OWGUI.comboBoxWithCaption(self.heuristicsSettingsBox, self, "attrCont", "For continuous attributes:", items = [val for (val, m) in contMeasures], callback = self.removeEvaluatedAttributes) 
     
    162161        self.connect(self.argumentList, SIGNAL("selectionChanged()"),self.argumentSelected) 
    163162 
    164         # ########################## 
    165         # CLASSIFICATION TAB 
    166         if self.parentWidget:  
    167             self.classifierNameEdit = OWGUI.lineEdit(self.ClassificationTab, self, 'parentWidget.VizRankLearnerName', box = 'Learner / Classifier Name', tooltip='Name to be used by other widgets to identify your learner/classifier.') 
    168  
    169         #self.argumentValueFormulaIndex = OWGUI.comboBox(self.ClassificationTab, self, "argumentValueFormula", box="Argument Value is Computed As ...", items=["1.0 x Projection Value", "0.5 x Projection Value + 0.5 x Predicted Example Probability", "1.0 x Predicted Example Probability"], tooltip=None) 
    170  
    171         b = OWGUI.widgetBox(self.ClassificationTab, "Evaluating Time") 
    172         self.evaluationTimeEdit = OWGUI.comboBoxWithCaption(b, self, "evaluationTime", "Time for evaluating projections (minutes):", tooltip = "What is the maximum time that the classifier is allowed for evaluating projections (learning)", items = self.evaluationTimeNums, sendSelectedValue = 1, valueType = float, debuggingEnabled = 0) 
    173         b2 = OWGUI.widgetBox(b, orientation = "horizontal") 
    174         self.optimizeBestProjectionCheck = OWGUI.checkBox(b2, self, "optimizeBestProjection", "Afterwards use local optimization for (minutes):", tooltip = "Do you want to try to locally optimize the best projection when the time for evaluating projections runs out?", debuggingEnabled = 0) 
    175         self.optimizeBestProjectionCombo = OWGUI.comboBox(b2, self, "optimizeBestProjectionTime", items = self.evaluationTimeNums, sendSelectedValue = 1, valueType = float, debuggingEnabled = 0) 
    176         projCountBox = OWGUI.widgetBox(self.ClassificationTab, "Projection Count") 
    177         self.argumentCountEdit = OWGUI.comboBoxWithCaption(projCountBox, self, "argumentCount", "Number of projections used when classifying:", tooltip = "What is the maximum number of projections (arguments) that will be used when classifying an example.", items = self.argumentCounts, sendSelectedValue = 1, valueType = int, debuggingEnabled = 0) 
     163##        # ########################## 
     164##        # CLASSIFICATION TAB 
     165##        if self.parentWidget: 
     166##            self.classifierNameEdit = OWGUI.lineEdit(self.ClassificationTab, self, 'parentWidget.VizRankLearnerName', box = 'Learner / Classifier Name', tooltip='Name to be used by other widgets to identify your learner/classifier.') 
     167## 
     168##        #self.argumentValueFormulaIndex = OWGUI.comboBox(self.ClassificationTab, self, "argumentValueFormula", box="Argument Value is Computed As ...", items=["1.0 x Projection Value", "0.5 x Projection Value + 0.5 x Predicted Example Probability", "1.0 x Predicted Example Probability"], tooltip=None) 
     169## 
     170##        b = OWGUI.widgetBox(self.ClassificationTab, "Evaluating Time") 
     171##        self.evaluationTimeEdit = OWGUI.comboBoxWithCaption(b, self, "evaluationTime", "Time for evaluating projections (minutes):", tooltip = "What is the maximum time that the classifier is allowed for evaluating projections (learning)", items = self.evaluationTimeNums, sendSelectedValue = 1, valueType = float, debuggingEnabled = 0) 
     172##        b2 = OWGUI.widgetBox(b, orientation = "horizontal") 
     173##        self.optimizeBestProjectionCheck = OWGUI.checkBox(b2, self, "optimizeBestProjection", "Afterwards use local optimization for (minutes):", tooltip = "Do you want to try to locally optimize the best projection when the time for evaluating projections runs out?", debuggingEnabled = 0) 
     174##        self.optimizeBestProjectionCombo = OWGUI.comboBox(b2, self, "optimizeBestProjectionTime", items = self.evaluationTimeNums, sendSelectedValue = 1, valueType = float, debuggingEnabled = 0) 
     175##        projCountBox = OWGUI.widgetBox(self.ClassificationTab, "Projection Count") 
     176##        self.argumentCountEdit = OWGUI.comboBoxWithCaption(projCountBox, self, "argumentCount", "Number of projections used when classifying:", tooltip = "What is the maximum number of projections (arguments) that will be used when classifying an example.", items = self.argumentCounts, sendSelectedValue = 1, valueType = int, debuggingEnabled = 0) 
     177 
    178178 
    179179        # ########################## 
     
    184184        self.dialogsBox = OWGUI.widgetBox(self.ManageTab, "Dialogs") 
    185185        self.manageResultsBox = OWGUI.widgetBox(self.ManageTab, "Manage Projections") 
    186          
     186 
    187187        self.classesList = QListBox(self.classesBox) 
    188188        self.classesList.setSelectionMode(QListBox.Multi) 
     
    190190        self.connect(self.classesList, SIGNAL("selectionChanged()"), self.classesListChanged) 
    191191        self._guiElements = getattr(self, "_guiElements", []) + [("listBox", self.classesList, None, self.classesListChanged)]      # we want to debug this control 
    192          
     192 
    193193        self.attrLenList = QListBox(self.visualizedAttributesBox) 
    194194        self.attrLenList.setSelectionMode(QListBox.Multi) 
     
    196196        self.connect(self.attrLenList, SIGNAL("selectionChanged()"), self.attrLenListChanged) 
    197197        self._guiElements = getattr(self, "_guiElements", []) + [("listBox", self.attrLenList, None, self.attrLenListChanged)]      # we want to debug this control 
    198          
     198 
    199199        #self.removeSelectedButton = OWGUI.button(self.buttonBox5, self, "Remove selection", self.removeSelected) 
    200200        #self.filterButton = OWGUI.button(self.buttonBox5, self, "Save best graphs", self.exportMultipleGraphs) 
     
    204204        self.attributeInteractionsButton = OWGUI.button(self.buttonBox7, self, "Attribute Interactions", self.interactionAnalysis, debuggingEnabled = 0) 
    205205 
    206         self.buttonBox8 = OWGUI.widgetBox(self.dialogsBox, orientation = "horizontal")     
     206        self.buttonBox8 = OWGUI.widgetBox(self.dialogsBox, orientation = "horizontal") 
    207207        self.projectionScoresButton = OWGUI.button(self.buttonBox8, self, "Graph Projection Scores", self.graphProjectionQuality, debuggingEnabled = 0) 
    208208        self.outlierIdentificationButton = OWGUI.button(self.buttonBox8, self, "Outlier Identification", self.identifyOutliers, debuggingEnabled = 0) 
     
    225225        self.showKNNWrongButton = OWGUI.button(self.buttonBox4, self, 'Show k-NN Wrong', self.showKNNWrong) 
    226226        self.showKNNCorrectButton.setToggleButton(1); self.showKNNWrongButton.setToggleButton(1) 
    227          
     227 
    228228        self.buttonBox5 = OWGUI.widgetBox(self.manageResultsBox, orientation = "horizontal") 
    229229        self.clearButton = OWGUI.button(self.buttonBox5, self, "Clear Results", self.clearResults) 
    230              
     230 
    231231        # ########################### 
    232232        self.statusBox = OWGUI.widgetBox(self, orientation = "horizontal") 
     
    239239 
    240240        self.removeEvaluatedAttributes() 
    241          
     241 
    242242        self.setMinimumWidth(375) 
    243243        self.tabs.setMinimumWidth(375) 
    244244        self.resize(375, 700) 
    245          
     245 
    246246 
    247247    # ############################################################## 
     
    254254        self.evaluatedAttributes = None 
    255255        self.evaluatedAttributesByClass = None 
    256          
    257         
     256 
     257 
    258258    # result list can contain projections with different number of attributes 
    259259    # user clicked in the listbox that shows possible number of attributes of result list 
     
    271271        results = self.results 
    272272        self.clearResults() 
    273          
     273 
    274274        self.selectedClasses = self.getSelectedClassValues() 
    275275        if len(self.selectedClasses) in [self.classesList.count(), 0]: 
     
    284284                    sum += result[OTHER_RESULTS][OTHER_DISTRIBUTION][index] 
    285285                VizRank.insertItem(self, self.findTargetIndex(acc/max(sum,1.), funct), acc/max(sum,1.), result[OTHER_RESULTS], result[LEN_TABLE], result[ATTR_LIST], result[TRY_INDEX], result[GENERAL_DICT]) 
    286                  
     286 
    287287        self.finishedAddingResults() 
    288288 
     
    305305                self.resultList.removeItem(i) 
    306306                self.shownResults.remove(self.shownResults[i]) 
    307          
     307 
    308308    # ############################################################## 
    309309    # ############################################################## 
     
    323323            if not ok: return 
    324324            allowedPercentOfEqualAttributes = int(str(text)) 
    325              
     325 
    326326        qApp.setOverrideCursor(QWidget.waitCursor) 
    327327        self.setStatusBarText("Removing similar projections") 
     
    335335            else: 
    336336                i += 1 
    337                  
     337 
    338338        self.setStatusBarText("") 
    339339        qApp.restoreOverrideCursor() 
     
    342342    def updateShownProjections(self, *args): 
    343343        if hasattr(self, "dontUpdate"): return 
    344          
     344 
    345345        self.resultList.clear() 
    346346        self.shownResults = [] 
     
    356356                elif self.showInstances: string += " (%d) : " % (self.results[i][LEN_TABLE]) 
    357357                string += self.buildAttrString(self.results[i][ATTR_LIST], self.results[i][GENERAL_DICT].get("reverse", [])) 
    358                  
     358 
    359359                self.resultList.insertItem(string) 
    360360                self.shownResults.append(self.results[i]) 
     
    362362        qApp.processEvents() 
    363363        qApp.restoreOverrideCursor() 
    364          
     364 
    365365        if self.resultList.count() > 0: self.resultList.setCurrentItem(0) 
    366366 
     
    389389        if not hasDiscreteClass: 
    390390            return 
    391          
     391 
    392392        # add class values 
    393393        for i in range(len(data.domain.classVar.values)): 
     
    397397        self.datasetName = getattr(data, "name", "") 
    398398 
    399                  
     399 
    400400    # given a dataset return a list of attributes where attribute are sorted by their decreasing importance for class discrimination 
    401401    def getEvaluatedAttributes(self, data): 
    402402        if self.evaluatedAttributes: return self.evaluatedAttributes 
    403          
     403 
    404404        self.setStatusBarText("Evaluating attributes...") 
    405405        qApp.setOverrideCursor(QWidget.waitCursor) 
     
    426426                    data1.extend(data2) 
    427427                    data = data1 
    428              
     428 
    429429            # evaluate attributes using the selected attribute measure 
    430430            self.evaluatedAttributes = orngVisFuncts.evaluateAttributes(data, contMeasures[self.attrCont][1], discMeasures[self.attrDisc][1]) 
     
    432432            type, val, traceback = sys.exc_info() 
    433433            sys.excepthook(type, val, traceback)  # print the exception 
    434              
     434 
    435435        self.setStatusBarText("") 
    436436        qApp.restoreOverrideCursor() 
     
    439439        else:             return self.evaluatedAttributes 
    440440 
    441      
     441 
    442442    # insert new result - give parameters: accuracy of projection, number of examples in projection and list of attributes. 
    443443    def insertItem(self, index, accuracy, other_results, lenTable, attrList, tryIndex, generalDict = {}, updateStatusBar = 0): 
    444444        if index < self.maxResultListLen: 
    445445            self.results.insert(index, (accuracy, other_results, lenTable, attrList, tryIndex, generalDict)) 
    446              
     446 
    447447        if index < self.resultListLen: 
    448448            string = "" 
     
    464464            qApp.processEvents()        # allow processing of other events 
    465465 
    466      
     466 
    467467    def finishedAddingResults(self): 
    468468        self.cancelOptimization = 0 
    469469        self.cancelEvaluation = 0 
    470          
     470 
    471471        self.attrLenList.clear() 
    472472        self.attrLenDict = {} 
     
    484484        self.resultList.setCurrentItem(0) 
    485485 
    486          
     486        # make sure that if the dialogs are shown we show the updated results 
     487        if self.attributeHistogramDlg and self.attributeHistogramDlg.isVisible(): 
     488            self.attributeHistogramDlg.setResults(self.shownResults, VIZRANK_POINT) 
     489        if self.interactionAnalysisDlg and self.interactionAnalysisDlg.isVisible(): 
     490            self.interactionAnalysisDlg.setResults(self.shownResults, VIZRANK_POINT) 
     491        if self.identifyOutliersDlg and self.identifyOutliersDlg.isVisible(): 
     492            self.identifyOutliersDlg.setData(self.results, self.data, VIZRANK_POINT) 
     493 
     494 
    487495    # ############################################################## 
    488496    # kNNClassifyData - compute classification error for every example in table 
     
    494502        if not table.domain.classVar or not table.domain.classVar.varType == orange.VarTypes.Discrete: 
    495503            return [], [] 
    496          
     504 
    497505        if self.externalLearner: learner = self.externalLearner 
    498506        else:                    learner = self.createkNNLearner() 
    499507        results = apply(testingMethods[self.testingMethod], [[learner], table]) 
    500              
     508 
    501509        returnTable = [] 
    502          
     510 
    503511        if table.domain.classVar.varType == orange.VarTypes.Discrete: 
    504512            probabilities = numpy.zeros((len(table), len(table.domain.classVar.values)), numpy.float) 
     
    574582            else: 
    575583                QMessageBox.information( None, self.parentName, 'Accuracy of the model is is %.3f' % (acc), QMessageBox.Ok + QMessageBox.Default) 
    576                  
    577  
    578      
     584 
     585 
     586 
    579587    # ############################################################## 
    580588    # Loading and saving projection files 
     
    600608        # show button to stop saving 
    601609        butt = OWGUI.button(self.statusBox, self, "Stop Saving", callback = self.abortOperation); butt.show() 
    602          
     610 
    603611        VizRank.save(self, name, self.shownResults, len(self.shownResults)) 
    604612 
     
    642650    # show quality of knn model by coloring accurate predictions with lighter color and bad predictions with dark color 
    643651    def showKNNWrong(self): 
    644         self.showKNNCorrectButton.setOn(0)  
     652        self.showKNNCorrectButton.setOn(0) 
    645653        if self.parentWidget: self.parentWidget.updateGraph() 
    646654 
     
    648656    # disable all controls while evaluating projections 
    649657    def disableControls(self): 
    650         self.startOptimizationButton.hide() 
    651         self.stopOptimizationButton.show() 
    652         for control in [self.buttonBox, self.resultsDetailsBox, self.optimizeGivenProjectionButton, self.SettingsTab, self.ManageTab, self.ClassificationTab, self.ArgumentationTab]: 
     658        for control in [self.buttonBox, self.resultsDetailsBox, self.optimizeGivenProjectionButton, self.SettingsTab, self.ManageTab, self.ArgumentationTab]: 
    653659            control.setEnabled(0) 
    654                  
     660 
    655661    def enableControls(self): 
    656         self.startOptimizationButton.show() 
    657         self.stopOptimizationButton.hide() 
    658         for control in [self.buttonBox, self.resultsDetailsBox, self.optimizeGivenProjectionButton, self.SettingsTab, self.ManageTab, self.ClassificationTab, self.ArgumentationTab]: 
     662        for control in [self.buttonBox, self.resultsDetailsBox, self.optimizeGivenProjectionButton, self.SettingsTab, self.ManageTab, self.ArgumentationTab]: 
    659663            control.setEnabled(1) 
    660          
    661          
     664 
     665 
    662666    # ############################################################## 
    663667    # exporting multiple pictures 
     
    679683        (fil,ext) = os.path.splitext(fileName) 
    680684        ext = ext.replace(".","") 
    681         if ext == "":    
     685        if ext == "": 
    682686            ext = "PNG"     # if no format was specified, we choose png 
    683687            fileName = fileName + ".png" 
     
    695699    # create different dialogs 
    696700    def interactionAnalysis(self): 
    697         dialog = OWInteractionAnalysis(self, signalManager = self.signalManager) 
    698         dialog.setResults(self.shownResults, VIZRANK_POINT) 
    699         dialog.show() 
     701        if not self.interactionAnalysisDlg: 
     702            self.interactionAnalysisDlg = OWInteractionAnalysis(self, signalManager = self.signalManager) 
     703        self.interactionAnalysisDlg.setResults(self.shownResults, VIZRANK_POINT) 
     704        self.interactionAnalysisDlg.show() 
    700705 
    701706 
    702707    def attributeAnalysis(self): 
    703         dialog = OWGraphAttributeHistogram(self, signalManager = self.signalManager) 
    704         dialog.setResults(self.shownResults, VIZRANK_POINT) 
    705         dialog.show() 
     708        if not self.attributeHistogramDlg: 
     709            self.attributeHistogramDlg = OWGraphAttributeHistogram(self, signalManager = self.signalManager) 
     710        self.attributeHistogramDlg.show() 
     711        self.attributeHistogramDlg.setResults(self.shownResults, VIZRANK_POINT) 
    706712 
    707713    def graphProjectionQuality(self): 
    708714        dialog = OWGraphProjectionQuality(self, signalManager = self.signalManager) 
     715        dialog.show() 
    709716        dialog.setResults(self.results, VIZRANK_POINT) 
    710         dialog.show() 
    711717 
    712718    def identifyOutliers(self): 
    713         dialog = OWGraphIdentifyOutliers(self, signalManager = self.signalManager, widget = self.parentWidget, graph = self.graph) 
    714         dialog.setData(self.results, self.data, VIZRANK_POINT) 
    715         dialog.show() 
     719        if not self.identifyOutliersDlg: 
     720            self.identifyOutliersDlg = OWGraphIdentifyOutliers(self, signalManager = self.signalManager, widget = self.parentWidget, graph = self.graph) 
     721        self.identifyOutliersDlg.show() 
     722        self.identifyOutliersDlg.setData(self.results, self.data, VIZRANK_POINT) 
    716723 
    717724    # ###################################################### 
    718725    # Auxiliary functions 
    719      
     726 
    720727    # from a list of attributes build a nice string with attribute names 
    721728    def buildAttrString(self, attrList, attrReverseList = []): 
    722729        if len(attrList) == 0: return "" 
    723          
     730 
    724731        if attrReverseList != []: 
    725732            strList = "" 
     
    754761        return self.shownResults[self.resultList.currentItem()] 
    755762 
    756     def stopEvaluationClick(self): 
    757         self.cancelEvaluation = 1 
    758         self.cancelOptimization = 1 
    759      
     763    def evaluateProjections(self): 
     764        if str(self.startOptimizationButton.text()) == "Start Evaluating Projections": 
     765            if self.attributeCount >= 10 and not (self.useSupervisedPCA) and self.visualizationMethod != SCATTERPLOT and self.attrSubsetSelection != GAMMA_SINGLE and QMessageBox.critical(self, 'VizRank', 'You chose to evaluate projections with a high number of attributes. Since VizRank has to evaluate different placements\nof these attributes there will be a high number of projections to evaluate. Do you still want to proceed?','Continue','Cancel', '', 0,1): 
     766                return 
     767            if not self.data.domain.classVar or not self.data.domain.classVar.varType == orange.VarTypes.Discrete: 
     768                QMessageBox.information( None, self.parentName, "Projections can be evaluated only for data with a discrete class.", QMessageBox.Ok + QMessageBox.Default) 
     769                return 
     770            self.startOptimizationButton.setText("Stop Evaluation") 
     771 
     772            self.parentWidget.progressBarInit() 
     773            self.disableControls() 
     774            evaluatedProjections = VizRank.evaluateProjections(self) 
     775            self.enableControls() 
     776            self.parentWidget.progressBarFinished() 
     777 
     778            secs = time.time() - self.startTime 
     779            self.setStatusBarText("Finished evaluation (evaluated %s projections in %d min, %d sec)" % (orngVisFuncts.createStringFromNumber(evaluatedProjections), secs/60, secs%60)) 
     780            self.finishedAddingResults() 
     781            qApp.processEvents() 
     782            if self.parentWidget: 
     783                self.parentWidget.showSelectedAttributes() 
     784            self.startOptimizationButton.setText("Start Evaluating Projections") 
     785        else: 
     786            self.cancelEvaluation = 1 
     787            self.cancelOptimization = 1 
     788 
     789 
     790    def optimizeBestProjections(self, restartWhenImproved = 1): 
     791        self.startOptimizationButton.setText("Stop Optimization") 
     792 
     793        self.disableControls() 
     794        evaluatedProjections = VizRank.optimizeBestProjections(self, restartWhenImproved) 
     795        self.enableControls() 
     796 
     797        secs = time.time() - self.startTime 
     798        self.setStatusBarText("Finished evaluation (evaluated %s projections in %d min, %d sec)" % (orngVisFuncts.createStringFromNumber(evaluatedProjections), secs/60, secs%60)) 
     799        self.finishedAddingResults() 
     800        qApp.processEvents() 
     801        if self.parentWidget: 
     802            self.parentWidget.showSelectedAttributes() 
     803        self.startOptimizationButton.setText("Start Evaluating Projections") 
     804 
     805 
    760806    def isEvaluationCanceled(self): 
    761807        stop = self.cancelEvaluation 
     
    763809        if self.useProjectionLimit: stop = stop or self.evaluatedProjectionsCount >= self.projectionLimit 
    764810        return stop 
    765          
     811 
    766812    def isOptimizationCanceled(self): 
    767813        stop = self.cancelOptimization 
     
    769815        if self.useProjectionLimit: stop = stop or self.optimizedProjectionsCount >= self.projectionLimit 
    770816        return stop 
    771          
     817 
    772818    def destroy(self, dw = 1, dsw = 1): 
    773819        self.saveSettings() 
    774820        OWBaseWidget.destroy(self, dw, dsw) 
    775          
     821 
    776822 
    777823    # ###################################################### 
     
    798844            prob, d, attrList, index = self.arguments[classIndex][i] 
    799845            self.argumentList.insertItem("%.3f - %s" %(prob, attrList), i) 
    800              
     846 
    801847        if self.argumentList.count() > 0 and selectBest: 
    802848            values = getVariableValuesSorted(self.data, self.data.domain.classVar.name) 
     
    813859        #qApp.processEvents() 
    814860        return classValue, dist 
    815      
     861 
    816862 
    817863    def argumentationClassChanged(self): 
     
    828874        generalDict = self.results[self.arguments[classInd][ind][3]][GENERAL_DICT] 
    829875        self.graph.updateData(self.arguments[classInd][ind][2], setAnchors = 1, XAnchors = generalDict.get("XAnchors"), YAnchors = generalDict.get("YAnchors")) 
    830          
     876 
    831877    def setStatusBarText(self, text): 
    832878        self.statusBar.message(text) 
    833         qApp.processEvents() 
     879##        qApp.processEvents() 
    834880 
    835881 
     
    843889    settingsList = ["onlyLower", "rectColoring", "sortAttributesByQuality", "useGeneSets", "recentGeneSets"] 
    844890    def __init__(self,parent=None, signalManager = None): 
    845         OWWidget.__init__(self, parent, signalManager, "VizRank's Interaction Analysis", wantGraph = 1) 
     891        OWWidget.__init__(self, parent, signalManager, "VizRank's Interaction Analysis", wantGraph = 1, savePosition = True) 
    846892 
    847893        self.parent = parent 
     
    885931        OWGUI.button(bb5, self, '...', callback = self.browseGeneFile, disabled=0, width=25) 
    886932        self.connect(self.fileCombo, SIGNAL('activated(int)'), self.selectGeneFile) 
    887          
     933 
    888934        b1.setSizePolicy(QSizePolicy(QSizePolicy.Minimum , QSizePolicy.Fixed )) 
    889935        b2.setSizePolicy(QSizePolicy(QSizePolicy.Minimum , QSizePolicy.Fixed )) 
     
    9791025            attrCounts.reverse() 
    9801026            attributes = [attr[1] for attr in attrCounts[:self.attributeCount]] 
    981      
     1027 
    9821028        for index in range(min(len(self.results), self.projectionCount)): 
    9831029            attrs = self.results[index][self.ATTR_LIST] 
     
    9891035                    Min = min(attrs[i], attrs[j]) 
    9901036                    Max = max(attrs[i], attrs[j]) 
    991                      
     1037 
    9921038                    # frequency of occurence 
    9931039                    if self.rectColoring == 2: 
     
    10051051            best = self.results[0][self.ACCURACY] 
    10061052            worst= self.results[min(len(self.results)-1, self.projectionCount)][self.ACCURACY] 
    1007      
     1053 
    10081054        eps = 0.05 + 0.15 * self.useGeneSets 
    10091055        eps2 = 0.05 
     
    10131059            for y in range(num-x): 
    10141060                yy = num-y-1 
    1015                  
     1061 
    10161062                if attrDict.has_key((attributes[x], attributes[yy])): 
    10171063                    val = attrDict[(attributes[x], attributes[yy])] 
     
    10231069                if not self.rectColoring: 
    10241070                    color = black 
    1025                 else:  
     1071                else: 
    10261072                    v = int(255 - 255*((val-worst)/float(best - worst))) 
    10271073                    color = QColor(v,v,v) 
    1028                      
     1074 
    10291075                s = "" 
    10301076                if self.rectColoring == 1:  # projection quality 
     
    10471093                curve = PolygonCurve(self.graph, QPen(color, 1), QBrush(color), [x-0.5+eps, x+0.5-eps, x+0.5-eps, x-0.5+eps], [y+1-0.5+eps, y+1-0.5+eps, y+1+0.5-eps, y+1+0.5-eps]) 
    10481094                key = self.graph.insertCurve(curve) 
    1049                                  
     1095 
    10501096                if self.useGeneSets and self.geneToSet and sharedGeneSets != []: 
    10511097                    curve = PolygonCurve(self.graph, QPen(color, 1), QBrush(Qt.NoBrush), [x-0.5+eps2, x+0.5-eps2, x+0.5-eps2, x-0.5+eps2], [y+1-0.5+eps2, y+1-0.5+eps2, y+1+0.5-eps2, y+1+0.5-eps2]) 
     
    10531099                if s != "": 
    10541100                    self.graph.tips.addToolTip(x, y+1, s, 0.5, 0.5) 
    1055                      
     1101 
    10561102                if not self.onlyLower: 
    10571103                    curve = PolygonCurve(self.graph, QPen(color, 1), QBrush(color), [num-1-0.5-y+eps, num-1-0.5-y+eps, num-1+0.5-y-eps, num-1+0.5-y-eps], [num-0.5-x+eps, num+0.5-x-eps, num+0.5-x-eps, num-0.5-x+eps]) 
     
    10881134        self.graph.axisScaleDraw(QwtPlot.xBottom).setTickLength(0, 0, 0) 
    10891135        self.graph.axisScaleDraw(QwtPlot.yLeft).setTickLength(0, 0, 0) 
    1090         self.graph.axisScaleDraw(QwtPlot.xBottom).setOptions(0)  
    1091         self.graph.axisScaleDraw(QwtPlot.yLeft).setOptions(0)  
     1136        self.graph.axisScaleDraw(QwtPlot.xBottom).setOptions(0) 
     1137        self.graph.axisScaleDraw(QwtPlot.yLeft).setOptions(0) 
    10921138        self.graph.setAxisScale(QwtPlot.xBottom, - 1.2 - 0.1*len(attributes) , num, 1) 
    10931139        self.graph.setAxisScale(QwtPlot.yLeft, - 0.9 - 0.1*len(attributes) , num, 1) 
     
    11031149            self.graph.axisScaleDraw(QwtPlot.xBottom).setLabelRotation(-90) 
    11041150            self.graph.axisScaleDraw(QwtPlot.xBottom).setLabelAlignment(Qt.AlignLeft) 
    1105          
     1151 
    11061152        self.graph.setAxisScaleDraw(QwtPlot.yLeft, OWGraphTools.DiscreteAxisScaleDraw([""] + attributes[::-1])) 
    11071153        self.graph.axisScaleDraw(QwtPlot.yLeft).setTickLength(0, 0, 0)  # hide ticks 
     
    11101156        self.graph.setAxisMaxMinor(QwtPlot.yLeft, 0) 
    11111157        self.graph.setAxisScale(QwtPlot.yLeft, 0, len(attributes)+1, 1) 
    1112          
    1113          
     1158 
     1159 
    11141160        self.graph.update()  # don't know if this is necessary 
    11151161        self.graph.repaint() 
     
    11181164        self.saveSettings() 
    11191165        OWWidget.hideEvent(self, ev) 
    1120              
     1166 
    11211167 
    11221168class OWGraphAttributeHistogram(OWWidget): 
    11231169    settingsList = ["attributeCount", "projectionCount", "rotateXAttributes", "colorAttributes", "progressLines", "useGeneSets", "recentGeneSets"] 
    11241170    def __init__(self, parent=None, signalManager = None): 
    1125         OWWidget.__init__(self, parent, signalManager, "Attribute Histogram", wantGraph = 1) 
    1126          
     1171        OWWidget.__init__(self, parent, signalManager, "Attribute Histogram", wantGraph = 1, savePosition = True) 
     1172 
    11271173        self.results = None 
    11281174        self.dialogType = -1 
     
    11621208        OWGUI.button(bb4, self, '...', callback = self.browseGeneFile, disabled=0, width=25) 
    11631209        self.connect(self.fileCombo, SIGNAL('activated(int)'), self.selectGeneFile) 
    1164          
     1210 
    11651211        b1.setSizePolicy(QSizePolicy(QSizePolicy.Minimum , QSizePolicy.Fixed )) 
    11661212        b2.setSizePolicy(QSizePolicy(QSizePolicy.Minimum , QSizePolicy.Fixed )) 
     
    11741220        self.evaluatedAttributes = None 
    11751221        self.evaluatedAttributesByClass = None 
    1176         qApp.processEvents()         
     1222        qApp.processEvents() 
    11771223        self.updateGeneCombo() 
    11781224        self.loadGeneSet() 
     
    12101256        self.updateGraph() 
    12111257    # ----------------------------------- # 
    1212      
     1258 
    12131259    def setResults(self, results, dialogType): 
    12141260        self.results = results 
     
    12191265            import orngMosaic 
    12201266            self.ATTR_LIST = orngMosaic.ATTR_LIST 
    1221              
     1267 
    12221268        self.evaluatedAttributes = None 
    12231269        self.evaluatedAttributesByClass = None 
     
    12401286        import math 
    12411287        s = math.sqrt(-count**2 / math.log(0.001))      # normalizing factor 
    1242          
     1288 
    12431289        for index in range(count): 
    12441290            if index > (part+1) * diff+1: 
     
    12761322            classVariableValues = getVariableValuesSorted(self.parent.data, self.parent.data.domain.classVar.name) 
    12771323            classColors = ColorPaletteHSV(len(classVariableValues)) 
    1278              
     1324 
    12791325 
    12801326        attrNames = [] 
     
    12891335            else: 
    12901336                color = black 
    1291              
     1337 
    12921338            curve = PolygonCurve(self.graph, QPen(color, 1), QBrush(color)) 
    12931339            key = self.graph.insertCurve(curve) 
     
    13241370            self.graph.axisScaleDraw(QwtPlot.xBottom).setLabelRotation(0) 
    13251371            self.graph.axisScaleDraw(QwtPlot.xBottom).setLabelAlignment(Qt.AlignHCenter) 
    1326          
     1372 
    13271373        self.graph.setYLaxisTitle("Number of appearances in top projections") 
    1328          
     1374 
    13291375        """ 
    13301376        self.graph.setAxisScaleDraw(QwtPlot.xBottom, HiddenScaleDraw()) 
     
    13321378        self.graph.axisScaleDraw(QwtPlot.xBottom).setTickLength(0, 0, 0) 
    13331379        #self.graph.axisScaleDraw(QwtPlot.yLeft).setTickLength(0, 0, 0) 
    1334         self.graph.axisScaleDraw(QwtPlot.xBottom).setOptions(0)  
    1335         #self.graph.axisScaleDraw(QwtPlot.yLeft).setOptions(0)  
     1380        self.graph.axisScaleDraw(QwtPlot.xBottom).setOptions(0) 
     1381        #self.graph.axisScaleDraw(QwtPlot.yLeft).setOptions(0) 
    13361382        self.graph.setAxisScale(QwtPlot.xBottom, - 0.5 , len(attrs), 1) 
    13371383        #self.graph.setAxisScale(QwtPlot.yLeft, - 0.9 - 0.1*len(attrs) , attrs[0][0], 1) 
    13381384        """ 
    1339          
     1385 
    13401386        if self.colorAttributes: 
    13411387            classVariableValues = getVariableValuesSorted(self.parent.data, self.parent.data.domain.classVar.name) 
     
    13441390            for i,val in enumerate(classVariableValues): 
    13451391                self.graph.addCurve(val, classColors[i], classColors[i], 15, symbol = QwtSymbol.Rect, enableLegend = 1) 
    1346          
     1392 
    13471393        self.graph.update()  # don't know if this is necessary 
    13481394        self.graph.repaint() 
    1349              
     1395 
    13501396    def hideEvent(self, ev): 
    13511397        self.saveSettings() 
     
    13681414        self.smoothingBox = OWGUI.widgetBox(self.controlArea, 'Smoothing parameter') 
    13691415        b3 = OWGUI.widgetBox(self.controlArea, 'Line Width') 
    1370          
     1416 
    13711417        b1.setSizePolicy(QSizePolicy(QSizePolicy.Minimum , QSizePolicy.Fixed )) 
    13721418        self.smoothingBox.setSizePolicy(QSizePolicy(QSizePolicy.Minimum , QSizePolicy.Fixed )) 
    13731419        b3.setSizePolicy(QSizePolicy(QSizePolicy.Minimum , QSizePolicy.Fixed )) 
    13741420        box = OWGUI.widgetBox(self.controlArea) 
    1375          
    1376         OWGUI.comboBox(b1, self, "showDistributions", items = ["Drop in scores", "Distribution of scores"], callback = self.updateGraph)         
    1377         OWGUI.qwtHSlider(self.smoothingBox, self, "smoothingParameter", minValue = 0.0, maxValue = 5, step = 0.1, callback = self.updateGraph)  
     1421 
     1422        OWGUI.comboBox(b1, self, "showDistributions", items = ["Drop in scores", "Distribution of scores"], callback = self.updateGraph) 
     1423        OWGUI.qwtHSlider(self.smoothingBox, self, "smoothingParameter", minValue = 0.0, maxValue = 5, step = 0.1, callback = self.updateGraph) 
    13781424        OWGUI.comboBox(b3, self, "lineWidth", items = range(1,5), callback = self.updateGraph, sendSelectedValue = 1, valueType = int) 
    13791425 
     
    14071453        yVals = [result[self.ACCURACY] for result in self.results] 
    14081454        if not yVals: return 
    1409          
     1455 
    14101456        if self.showDistributions: 
    14111457            try: 
     
    14161462 
    14171463        self.smoothingBox.setEnabled(self.showDistributions) 
    1418                  
     1464 
    14191465        if not self.showDistributions: 
    14201466            xVals = range(len(yVals)) 
     
    14221468                fact = len(yVals)/200 
    14231469                if fact > 0:        # make the array of data smaller 
    1424                     pos = 0              
     1470                    pos = 0 
    14251471                    xTemp = []; yTemp = [] 
    14261472                    while pos < len(yVals): 
     
    14401486            ys = [0] 
    14411487            x = ymin 
    1442             for index in range(len(yVals)):         
     1488            for index in range(len(yVals)): 
    14431489                if yVals[index] > x + diff:     # if we stepped into another part, we start counting elements in here from 0 
    14441490                    ys.append(0) 
     
    14531499        self.graph.update()  # don't know if this is necessary 
    14541500        self.graph.repaint() 
    1455              
     1501 
    14561502 
    14571503# ############################################################################# 
     
    14601506    settingsList = ["projectionCountList", "showLegend", "showAllClasses", "sortProjections", "showClickedProjection"] 
    14611507    def __init__(self,parent=None, signalManager = None, widget = None, graph = None): 
    1462         OWWidget.__init__(self, parent, signalManager, "Outlier Identification", wantGraph = 1, wantStatusBar = 1) 
     1508        OWWidget.__init__(self, parent, signalManager, "Outlier Identification", wantGraph = 1, wantStatusBar = 1, savePosition = True) 
    14631509 
    14641510        self.projectionCountList = ["5", "10", "20", "50", "100", "200", "500", "1000", "2000", "5000", "10000", "Other..."] 
     
    14831529 
    14841530        self.loadSettings() 
    1485          
    1486         b1 = OWGUI.widgetBox(self.controlArea, ' Projection Count ') 
     1531 
     1532        b1 = OWGUI.widgetBox(self.controlArea, 'Projection Count') 
    14871533        self.projectionCountEdit = OWGUI.comboBoxWithCaption(b1, self, "projectionCount", "Best projections to consider:   ", tooltip = "How many projections do you want to consider when computing probabilities of correct classification?", items = self.projectionCountList, callback = self.projectionCountChanged, sendSelectedValue = 1, valueType = str) 
    14881534 
    1489         b3 = OWGUI.widgetBox(self.controlArea, ' Show Predictions for Selected Example ') 
    1490         OWGUI.checkBox(b3, self, 'showAllClasses', 'Show predictions for all classes', tooltip = "Show predicted probabilities for each class value", callback = self.updateGraph) 
    1491         OWGUI.checkBox(b3, self, 'sortProjections', 'Sort projection by decreasing probability', tooltip = "Don't show projections as they are ranked. Instead sort them by decreasing probability of correct classification", callback = self.updateGraph) 
     1535        b2 = OWGUI.widgetBox(self.controlArea, 'Example Index', orientation="horizontal") 
     1536        self.selectedExampleCombo = OWGUI.comboBox(b2, self, "selectedExampleIndex", tooltip = "Select the index of the example whose predictions you wish to analyse in the graph", callback = self.selectedExampleChanged, sendSelectedValue = 1, valueType = int) 
     1537        butt = OWGUI.button(b2, self, "Get from projection", self.updateIndexFromGraph, tooltip = "Use the index of the example that is selected in the projections") 
     1538##        butt.setMaximumWidth(60) 
     1539 
     1540        b3 = OWGUI.widgetBox(self.controlArea, 'Graph Settings') 
     1541        OWGUI.checkBox(b3, self, 'showAllClasses', 'Show probabilities for all classes', tooltip = "Show predicted probabilities for each class value", callback = self.updateGraph) 
     1542        OWGUI.checkBox(b3, self, 'sortProjections', 'Sort projections by decreasing probability', tooltip = "Don't show projections as they are ranked, but by decreasing probability of correct classification (this usually improves perception)", callback = self.updateGraph) 
    14921543        OWGUI.checkBox(b3, self, 'showLegend', 'Show class legend', callback = self.updateGraph) 
    1493         OWGUI.checkBox(b3, self, 'showClickedProjection', 'Show selected projection', tooltip = "Do you want to show the projection by clicking its horizontal bar with class predictions?", callback = self.updateGraph) 
    1494         hb1 = OWGUI.widgetBox(b3, orientation="horizontal") 
    1495         self.selectedExampleCombo = OWGUI.comboBoxWithCaption(hb1, self, "selectedExampleIndex", "Example Index: ", tooltip = "Select the index of the example whose predictions you wish to analyse in the graph?", callback = self.selectedExampleChanged, sendSelectedValue = 1, valueType = int) 
    1496         butt = OWGUI.button(hb1, self, "From proj.", self.updateIndexFromGraph, tooltip = "Update example index based on the selection in the projection") 
    1497         butt.setMaximumWidth(60) 
    1498  
    1499         b5 = OWGUI.widgetBox(self.controlArea, ' Examples by Their Uncertain Predictions ') 
    1500         self.showGraphCheck = OWGUI.checkBox(b5, self, 'showPredictionsInProjection', 'Show predicted probabilities in the projection', tooltip = "Color the points in the projection according to the probability of correct classification averaged over the selected projection count", callback = self.toggleShowPredictions) 
    1501         OWGUI.button(b5, self, "Evaluate predictions for all examples", self.evaluateAllExamples) 
    1502         self.exampleList = QListBox(b5) 
    1503         self.connect(self.exampleList, SIGNAL("selectionChanged()"),self.exampleListSelectionChanged)  
    1504         #self.exampleList.setMinimumSize(100,100) 
     1544        OWGUI.checkBox(b3, self, 'showClickedProjection', 'Show selected projection', tooltip = "Show the corresponding projection by clicking its horizontal bar in the graph", callback = self.updateGraph) 
     1545 
     1546        b6 = OWGUI.widgetBox(self.controlArea, "Show Predictions For All Examples") 
     1547        self.showGraphCheck = OWGUI.checkBox(b6, self, 'showPredictionsInProjection', 'Show probabilities in the projection', tooltip = "Color the points in the projection according to the average probability of correct classification over the selected projection count", callback = self.toggleShowPredictions) 
     1548        self.exampleList = QListBox(b6) 
     1549        QToolTip.add(self.exampleList, "Average probabilities of correct classification and indices of corresponding examples") 
     1550        self.connect(self.exampleList, SIGNAL("selectionChanged()"),self.exampleListSelectionChanged) 
    15051551 
    15061552        self.box = QVBoxLayout(self.mainArea) 
     
    15111557        self.graph.setYLaxisTitle("Projections") 
    15121558        self.graph.show() 
    1513          
     1559 
    15141560        self.box.addWidget(self.graph) 
    15151561        self.box.activate() 
     
    15201566        self.connect(self.graph, SIGNAL("plotMouseMoved(const QMouseEvent &)"), self.graphOnMouseMoved) 
    15211567        self.connect(self.graph, SIGNAL('plotMousePressed(const QMouseEvent&)'), self.graphOnMousePressed) 
    1522                  
     1568 
    15231569        self.resize(600, 400) 
    1524         self.show() 
     1570##        self.show() 
    15251571 
    15261572    # on escape 
     
    15311577        self.saveSettings() 
    15321578        OWWidget.hideEvent(self, e) 
    1533          
     1579 
    15341580    def setData(self, results, data, dialogType): 
    15351581        self.results = results 
     
    15581604        self.exampleList.clear() 
    15591605        self.evaluatedExamples = [] 
    1560          
     1606 
    15611607        if self.projectionCount == "Other...": 
    15621608            (text, ok) = QInputDialog.getText('Qt Projection Count', 'How many of the best projections do you wish to consider?') 
     
    15731619        self.evaluateProjections() 
    15741620        self.selectedExampleChanged() 
    1575          
    1576          
     1621 
     1622 
    15771623    def evaluateProjections(self): 
    15781624        if not self.results or not self.data: return 
    1579          
     1625 
    15801626        # compute predictions 
    15811627        self.widget.progressBarInit() 
     
    15971643        results = self.results[existing:min(len(self.results),projCount)] 
    15981644        index = 0 
    1599          
     1645 
     1646        self.widgetStatusArea.show() 
    16001647        for result in results: 
    16011648            if self.dialogType == VIZRANK_POINT: 
     
    16031650                attrIndices = [self.projectionGraph.attributeNameIndex[attr] for attr in attrList] 
    16041651                validDataIndices = self.projectionGraph.getValidIndices(attrIndices) 
    1605                 table = self.projectionGraph.createProjectionAsExampleTable(attrIndices, generalDict)    # TO DO: this does not work with polyviz!!! 
     1652                table = self.projectionGraph.createProjectionAsExampleTable(attrIndices, settingsDict = generalDict)    # TO DO: this does not work with polyviz!!! 
    16061653                qApp.processEvents()        # allow processing of other events 
    16071654                acc, probabilities = self.parent.kNNClassifyData(table) 
    1608              
     1655 
    16091656            elif self.dialogType == VIZRANK_MOSAIC: 
    16101657                from orngCI import FeatureByCartesianProduct 
     
    16231670                    except: 
    16241671                        validDataIndices.remove(i) 
    1625                  
     1672 
    16261673 
    16271674            #self.matrixOfPredictions[(existing + index)*classCount:(existing + index +1)*classCount] = numpy.transpose(probabilities) 
    16281675            probabilities = numpy.transpose(probabilities) 
    16291676            for i in range(classCount): 
    1630                 numpy.put(self.matrixOfPredictions[(existing + index)*classCount + i], validDataIndices, probabilities[i])             
     1677                numpy.put(self.matrixOfPredictions[(existing + index)*classCount + i], validDataIndices, probabilities[i]) 
    16311678 
    16321679            index += 1 
     
    16341681            self.widget.progressBarSet(100.0*(index)/float(projCount-existing)) 
    16351682 
     1683        # update the list box with probabilities for all examples 
     1684        self.exampleList.clear() 
     1685        projCount = min(int(self.projectionCount), len(self.results)) 
     1686        classCount = len(self.data.domain.classVar.values) 
     1687 
     1688        for i in range(len(self.data)): 
     1689            matrix = numpy.transpose(numpy.reshape(self.matrixOfPredictions[:, i], (projCount, classCount))) 
     1690            valid = numpy.where(matrix[int(self.data[i].getclass())] != -1, 1, 0) 
     1691            data = numpy.compress(valid, matrix[int(self.data[i].getclass())]) 
     1692            if len(data): ave_acc = numpy.sum(data) / float(len(data)) 
     1693            else:         ave_acc = 0 
     1694            self.insertItemToExampleList(ave_acc, i) 
     1695 
    16361696        self.widget.progressBarFinished() 
     1697        self.widgetStatusArea.hide() 
    16371698 
    16381699 
     
    16411702        if self.showPredictionsInProjection: 
    16421703            self.evaluateProjections() 
    1643              
     1704 
     1705            self.widgetStatusArea.show() 
    16441706            self.statusBar.message("Computing averages...") 
    16451707 
    16461708            projCount = min(int(self.projectionCount), len(self.results)) 
    16471709            classCount = len(self.data.domain.classVar.values) 
    1648      
     1710 
    16491711            # compute the average probability of correct classification over the selected number of top projections 
    16501712            values = [0.0 for i in range(len(self.data))] 
     
    16581720 
    16591721            self.widget.outlierValues = (values, "Probability of correct class value = %.2f%%") 
     1722            self.statusBar.message("") 
     1723            self.widgetStatusArea.hide() 
    16601724        else: 
    16611725            self.widget.outlierValues = None 
    16621726 
    16631727        self.widget.updateGraph() 
    1664              
    1665         self.statusBar.message("") 
    16661728        self.widget.showSelectedAttributes() 
    16671729 
     
    16741736        self.graphMatrix = numpy.transpose(numpy.reshape(self.matrixOfPredictions[:, self.selectedExampleIndex], (projCount, classCount))) 
    16751737        self.updateGraph() 
    1676          
     1738 
    16771739        if self.dialogType == VIZRANK_POINT: 
    16781740            valid = self.projectionGraph.getValidList([self.projectionGraph.attributeNameIndex[attr] for attr in self.widget.getShownAttributeList()]) 
     
    16801742            insideColors[self.selectedExampleIndex] = 1 
    16811743            self.widget.updateGraph(insideColors = (numpy.compress(valid, insideColors), "Focused example: %d")) 
    1682          
     1744 
    16831745 
    16841746    # find which examples is selected in the graph and draw its predictions 
     
    16861748        if self.dialogType != VIZRANK_POINT: 
    16871749            return 
    1688          
     1750 
    16891751        if self.parent.parentName == "Polyviz": 
    16901752            selected, unselected = self.projectionGraph.getSelectionsAsIndices(self.widget.getShownAttributeList(), self.widget.attributeReverse) 
    1691         else:             
     1753        else: 
    16921754            selected, unselected = self.projectionGraph.getSelectionsAsIndices(self.widget.getShownAttributeList()) 
    16931755 
     
    16981760        self.selectedExampleChanged() 
    16991761 
    1700     # evaluate predictions for all examples 
    1701     def evaluateAllExamples(self): 
    1702         if not self.data: return 
    1703  
    1704         self.evaluateProjections() 
    1705  
    1706         projCount = min(int(self.projectionCount), len(self.results)) 
    1707         classCount = len(self.data.domain.classVar.values) 
    1708  
    1709         for i in range(len(self.data)): 
    1710             matrix = numpy.transpose(numpy.reshape(self.matrixOfPredictions[:, i], (projCount, classCount))) 
    1711             valid = numpy.where(matrix[int(self.data[i].getclass())] != -1, 1, 0) 
    1712             data = numpy.compress(valid, matrix[int(self.data[i].getclass())]) 
    1713             if len(data): ave_acc = numpy.sum(data) / float(len(data)) 
    1714             else:         ave_acc = 0 
    1715             self.insertItemToExampleList(ave_acc, i) 
    1716              
    1717              
     1762 
    17181763    # insert new result - give parameters: accuracy of projection, number of examples in projection and list of attributes. 
    17191764    def insertItemToExampleList(self, val, exampleIndex): 
     
    17291774        elif min(val, self.evaluatedExamples[top][0]) == val: 
    17301775            index = top 
    1731         else:  
     1776        else: 
    17321777            index = bottom 
    1733          
     1778 
    17341779        self.evaluatedExamples.insert(index, (val, exampleIndex)) 
    17351780        self.exampleList.insertItem("%.2f - %d" % (val, exampleIndex), index) 
     
    17441789    def updateGraph(self): 
    17451790        self.graph.clear() 
     1791        self.graph.tips.removeAll() 
     1792        self.selectedRectangle = None 
    17461793        if not self.data or self.graphMatrix == None: return 
    1747          
     1794 
    17481795        classColors = ColorPaletteHSV(len(self.data.domain.classVar.values)) 
    1749          
     1796 
    17501797        if self.graphMatrix == None: return 
    17511798 
    17521799        self.graph.setAxisScale(QwtPlot.yLeft, 0, len(self.graphMatrix[0]), len(self.graphMatrix[0])/5) 
    17531800        self.graph.setAxisScale(QwtPlot.xBottom, 0, 1, 0.2) 
    1754          
     1801 
    17551802        valid = numpy.where(self.graphMatrix[0] != -1, 1, 0) 
    17561803        allValid = numpy.sum(valid) == len(valid) 
     
    17671814 
    17681815        self.projectionIndices = [val[1] for val in indices] 
    1769      
     1816        classVariableValues = getVariableValuesSorted(self.parent.data, self.parent.data.domain.classVar.name) 
     1817        classColors = ColorPaletteHSV(len(classVariableValues)) 
     1818 
    17701819        for i in range(len(self.graphMatrix[0])): 
    17711820            x = 0 
     1821            s = "Predicted class probabilities:<br>" 
    17721822            for j in classes: 
    1773                 if not self.showAllClasses and int(self.data[self.selectedExampleIndex].getclass()) != j: continue 
    17741823                (prob, index) = indices[i] 
     1824                s += "&nbsp; &nbsp; &nbsp; %s: %.2f%%<br>" % (classVariableValues[j], 100*self.graphMatrix[j][index]) 
     1825                if not self.showAllClasses and int(self.data[self.selectedExampleIndex].getclass()) != j: 
     1826                    continue 
    17751827                xDiff = self.graphMatrix[j][index] 
    17761828                self.graph.insertCurve(OWGraphTools.PolygonCurve(self.graph, QPen(classColors.getColor(j)), QBrush(classColors.getColor(j)), [x, x+xDiff, x+xDiff, x], [i, i, i+1, i+1])) 
    17771829                x += xDiff 
    1778          
     1830            self.graph.tips.addToolTip(0, i, s[:-4], 1, 1) 
     1831 
    17791832        if self.showLegend: 
    1780             classVariableValues = getVariableValuesSorted(self.parent.data, self.parent.data.domain.classVar.name) 
    1781             classColors = ColorPaletteHSV(len(classVariableValues)) 
    17821833            self.graph.addCurve("<b>" + self.parent.data.domain.classVar.name + ":</b>", QColor(0,0,0), QColor(0,0,0), 0, symbol = QwtSymbol.None, enableLegend = 1) 
    17831834            for i,val in enumerate(classVariableValues): 
     
    17851836        else: 
    17861837            self.graph.enableLegend(0) 
    1787          
     1838 
    17881839        self.graph.update()  # don't know if this is necessary 
    17891840        self.graph.repaint() 
     
    17941845            self.graph.removeCurve(self.selectedRectangle) 
    17951846            self.selectedRectangle = None 
    1796              
     1847 
    17971848        y = int(math.floor(self.graph.invTransform(QwtPlot.yLeft, e.y()))) 
    17981849        if self.showClickedProjection and y >= 0 and y < len(self.projectionIndices): 
     
    18001851            self.selectedRectangle = self.graph.insertCurve(OWGraphTools.PolygonCurve(self.graph, brush = QBrush(Qt.NoBrush), xData = [0-diff, 1+diff, 1+diff, 0-diff], yData = [y-diff, y-diff, y+1+diff, y+1+diff])) 
    18011852            self.graph.replot() 
    1802              
     1853 
    18031854 
    18041855    def graphOnMousePressed(self, e): 
     
    18161867                insideColors[self.selectedExampleIndex] = 1 
    18171868                self.widget.updateGraph(attrs, setAnchors = 1, insideColors = (numpy.compress(valid, insideColors), "Focused example: %d")) 
     1869 
    18181870 
    18191871def getGeneSet(geneset, gene): 
     
    18541906    ow.show() 
    18551907    a.exec_loop() 
    1856      
Note: See TracChangeset for help on using the changeset viewer.