Changeset 11822:662188879b4e in orange


Ignore:
Timestamp:
12/23/13 11:30:26 (4 months ago)
Author:
astaric <anze.staric@…>
Branch:
default
committer:
astaric <anze.staric@gmail.com> 1388665309 -3600
Message:

Code Style.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • Orange/OrangeWidgets/Visualize/OWParallelCoordinates.py

    r11821 r11822  
    1111# 
    1212import os 
    13 from Orange.orange import ExampleTable 
    1413from PyQt4.QtCore import SIGNAL, Qt, QSize 
    1514from PyQt4.QtGui import QColor, QRadioButton, QFileDialog, QMessageBox, qApp 
    1615from PyQt4.Qwt5.Qwt import QwtPlot 
     16from Orange.orange import ExampleTable 
     17 
    1718from Orange.OrangeCanvas.registry.description import Default 
    1819from Orange.OrangeWidgets import OWToolbars, OWGUI, OWColorPalette 
     
    2324from Orange.OrangeWidgets.Visualize.OWParallelGraph import OWParallelGraph 
    2425from Orange.orng import orngVisFuncts 
    25 from sys import getrecursionlimit, setrecursionlimit 
     26 
    2627 
    2728########################################################################################### 
     
    3132    settingsList = ["graph.jitterSize", "graph.showDistributions", 
    3233                    "graph.showAttrValues", "graph.useAntialiasing", 
    33                     "graph.useSplines", "graph.alphaValue", "graph.alphaValue2", "graph.enabledLegend", "autoSendSelection", 
    34                     "toolbarSelection", "graph.showStatistics", "colorSettings", "selectedSchemaIndex", "showAllAttributes"] 
    35     jitterSizeNums = [0, 2,  5,  10, 15, 20, 30] 
    36     contextHandlers = {"": DomainContextHandler("", [ContextField("shownAttributes", DomainContextHandler.RequiredList, selected="selectedShown", reservoir="hiddenAttributes")])} 
    37  
    38     def __init__(self,parent=None, signalManager = None): 
     34                    "graph.useSplines", "graph.alphaValue", 
     35                    "graph.alphaValue2", "graph.enabledLegend", 
     36                    "graph.showStatistics", "autoSendSelection", 
     37                    "toolbarSelection", "colorSettings", 
     38                    "selectedSchemaIndex", "showAllAttributes"] 
     39    jitterSizeNums = [0, 2, 5, 10, 15, 20, 30] 
     40    contextHandlers = { 
     41        "": DomainContextHandler("", [ 
     42            ContextField("shownAttributes", DomainContextHandler.RequiredList, 
     43                         selected="selectedShown", reservoir="hiddenAttributes")] 
     44        ) 
     45    } 
     46 
     47    def __init__(self, parent=None, signalManager=None): 
    3948        OWWidget.__init__(self, parent, signalManager, "Parallel Coordinates", True) 
    4049 
     
    4554        self.showAllAttributes = 0 
    4655 
    47         self.inputs = [("Data", ExampleTable, self.setData, Default), ("Data Subset", ExampleTable, self.setSubsetData), ("Features", AttributeList, self.setShownAttributes)] 
    48         self.outputs = [("Selected Data", ExampleTable), ("Other Data", ExampleTable), ("Features", AttributeList)] 
     56        self.inputs = [("Data", ExampleTable, self.setData, Default), 
     57                       ("Data Subset", ExampleTable, self.setSubsetData), 
     58                       ("Features", AttributeList, self.setShownAttributes)] 
     59        self.outputs = [("Selected Data", ExampleTable), 
     60                        ("Other Data", ExampleTable), 
     61                        ("Features", AttributeList)] 
    4962 
    5063        #set default settings 
     
    7790        self.SettingsTab = OWGUI.createTabPage(self.tabs, "Settings") 
    7891 
    79         self.createShowHiddenLists(self.GeneralTab, callback = self.updateGraph) 
     92        self.createShowHiddenLists(self.GeneralTab, callback=self.updateGraph) 
    8093        self.connect(self.shownAttribsLB, SIGNAL('itemDoubleClicked(QListWidgetItem*)'), self.flipAttribute) 
    8194 
    82         self.optimizationDlg = ParallelOptimization(self, signalManager = self.signalManager) 
    83         self.optimizationDlgButton = OWGUI.button(self.GeneralTab, self, "Optimization Dialog", callback = self.optimizationDlg.reshow, debuggingEnabled = 0) 
    84  
    85         self.zoomSelectToolbar = OWToolbars.ZoomSelectToolbar(self, self.GeneralTab, self.graph, self.autoSendSelection, buttons = (1, 2, 0, 7, 8)) 
     95        self.optimizationDlg = ParallelOptimization(self, signalManager=self.signalManager) 
     96        self.optimizationDlgButton = OWGUI.button(self.GeneralTab, self, "Optimization Dialog", 
     97                                                  callback=self.optimizationDlg.reshow, debuggingEnabled=0) 
     98 
     99        self.zoomSelectToolbar = OWToolbars.ZoomSelectToolbar(self, self.GeneralTab, self.graph, self.autoSendSelection, 
     100                                                              buttons=(1, 2, 0, 7, 8)) 
    86101        self.connect(self.zoomSelectToolbar.buttonSendSelections, SIGNAL("clicked()"), self.sendSelections) 
    87102 
     
    92107        # SETTINGS functionality 
    93108        box = OWGUI.widgetBox(self.SettingsTab, "Transparency") 
    94         OWGUI.hSlider(box, self, 'graph.alphaValue', label = "Examples: ", minValue=0, maxValue=255, step=10, callback = self.updateGraph, tooltip = "Alpha value used for drawing example lines") 
    95         OWGUI.hSlider(box, self, 'graph.alphaValue2', label = "Rest:     ", minValue=0, maxValue=255, step=10, callback = self.updateGraph, tooltip = "Alpha value used to draw statistics, example subsets, ...") 
     109        OWGUI.hSlider(box, self, 'graph.alphaValue', label="Examples: ", minValue=0, maxValue=255, step=10, 
     110                      callback=self.updateGraph, tooltip="Alpha value used for drawing example lines") 
     111        OWGUI.hSlider(box, self, 'graph.alphaValue2', label="Rest:     ", minValue=0, maxValue=255, step=10, 
     112                      callback=self.updateGraph, tooltip="Alpha value used to draw statistics, example subsets, ...") 
    96113 
    97114        box = OWGUI.widgetBox(self.SettingsTab, "Jittering Options") 
    98         OWGUI.comboBox(box, self, "graph.jitterSize", label = 'Jittering size (% of size):  ', orientation='horizontal', callback = self.setJitteringSize, items = self.jitterSizeNums, sendSelectedValue = 1, valueType = float) 
     115        OWGUI.comboBox(box, self, "graph.jitterSize", label='Jittering size (% of size):  ', orientation='horizontal', 
     116                       callback=self.setJitteringSize, items=self.jitterSizeNums, sendSelectedValue=1, valueType=float) 
    99117 
    100118        # visual settings 
    101119        box = OWGUI.widgetBox(self.SettingsTab, "Visual Settings") 
    102120 
    103         OWGUI.checkBox(box, self, 'graph.showAttrValues', 'Show attribute values', callback = self.updateGraph) 
    104         OWGUI.checkBox(box, self, 'graph.useAntialiasing', 'Use antialiasing', callback = self.updateGraph) 
    105         OWGUI.checkBox(box, self, 'graph.useSplines', 'Show splines', callback = self.updateGraph, tooltip  = "Show lines using splines") 
    106         OWGUI.checkBox(box, self, 'graph.enabledLegend', 'Show legend', callback = self.updateGraph) 
     121        OWGUI.checkBox(box, self, 'graph.showAttrValues', 'Show attribute values', callback=self.updateGraph) 
     122        OWGUI.checkBox(box, self, 'graph.useAntialiasing', 'Use antialiasing', callback=self.updateGraph) 
     123        OWGUI.checkBox(box, self, 'graph.useSplines', 'Show splines', callback=self.updateGraph, 
     124                       tooltip="Show lines using splines") 
     125        OWGUI.checkBox(box, self, 'graph.enabledLegend', 'Show legend', callback=self.updateGraph) 
    107126 
    108127        box = OWGUI.widgetBox(self.SettingsTab, "Axis Distance") 
    109128        resizeColsBox = OWGUI.widgetBox(box, 0, "horizontal", 0) 
    110129        OWGUI.label(resizeColsBox, self, "Increase/decrease distance: ") 
    111         b = OWGUI.toolButton(resizeColsBox, self, "+", callback=self.increaseAxesDistance, tooltip = "Increase the distance between the axes", width=30, height = 20) 
    112         b = OWGUI.toolButton(resizeColsBox, self, "-", callback=self.decreaseAxesDistance, tooltip = "Decrease the distance between the axes", width=30, height = 20) 
     130        OWGUI.toolButton(resizeColsBox, self, "+", callback=self.increaseAxesDistance, 
     131                         tooltip="Increase the distance between the axes", width=30, height=20) 
     132        OWGUI.toolButton(resizeColsBox, self, "-", callback=self.decreaseAxesDistance, 
     133                         tooltip="Decrease the distance between the axes", width=30, height=20) 
    113134        OWGUI.rubber(resizeColsBox) 
    114         OWGUI.checkBox(box, self, "graph.autoUpdateAxes", "Auto scale X axis", tooltip = "Auto scale X axis to show all visualized attributes", callback = self.updateGraph) 
     135        OWGUI.checkBox(box, self, "graph.autoUpdateAxes", "Auto scale X axis", 
     136                       tooltip="Auto scale X axis to show all visualized attributes", callback=self.updateGraph) 
    115137 
    116138        box = OWGUI.widgetBox(self.SettingsTab, "Statistical Information") 
    117         OWGUI.comboBox(box, self, "graph.showStatistics", label = "Statistics: ", orientation = "horizontal", labelWidth=90, items = ["No statistics", "Means, deviations", "Median, quartiles"], callback = self.updateGraph, sendSelectedValue = 0, valueType = int) 
    118         OWGUI.comboBox(box, self, "middleLabels", label = "Middle labels: ", orientation="horizontal", labelWidth=90, items = ["No labels", "Correlations", "VizRank"], callback = self.updateGraph, tooltip = "The information do you wish to view on top in the middle of coordinate axes", sendSelectedValue = 1, valueType = str) 
    119         OWGUI.checkBox(box, self, 'graph.showDistributions', 'Show distributions', callback = self.updateGraph, tooltip = "Show bars with distribution of class values (only for discrete attributes)") 
    120  
    121         box = OWGUI.widgetBox(self.SettingsTab, "Colors", orientation = "horizontal") 
    122         OWGUI.button(box, self, "Set colors", self.setColors, tooltip = "Set the canvas background color and color palette for coloring continuous variables", debuggingEnabled = 0) 
     139        OWGUI.comboBox(box, self, "graph.showStatistics", label="Statistics: ", orientation="horizontal", labelWidth=90, 
     140                       items=["No statistics", "Means, deviations", "Median, quartiles"], callback=self.updateGraph, 
     141                       sendSelectedValue=0, valueType=int) 
     142        OWGUI.comboBox(box, self, "middleLabels", label="Middle labels: ", orientation="horizontal", labelWidth=90, 
     143                       items=["No labels", "Correlations", "VizRank"], callback=self.updateGraph, 
     144                       tooltip="The information do you wish to view on top in the middle of coordinate axes", 
     145                       sendSelectedValue=1, valueType=str) 
     146        OWGUI.checkBox(box, self, 'graph.showDistributions', 'Show distributions', callback=self.updateGraph, 
     147                       tooltip="Show bars with distribution of class values (only for discrete attributes)") 
     148 
     149        box = OWGUI.widgetBox(self.SettingsTab, "Colors", orientation="horizontal") 
     150        OWGUI.button(box, self, "Set colors", self.setColors, 
     151                     tooltip="Set the canvas background color and color palette for coloring continuous variables", 
     152                     debuggingEnabled=0) 
    123153 
    124154        box = OWGUI.widgetBox(self.SettingsTab, "Auto Send Selected Data When...") 
    125         OWGUI.checkBox(box, self, 'autoSendSelection', 'Adding/Removing selection areas', callback = self.selectionChanged, tooltip = "Send selected data whenever a selection area is added or removed") 
    126         OWGUI.checkBox(box, self, 'graph.sendSelectionOnUpdate', 'Moving/Resizing selection areas', tooltip = "Send selected data when a user moves or resizes an existing selection area") 
     155        OWGUI.checkBox(box, self, 'autoSendSelection', 'Adding/Removing selection areas', 
     156                       callback=self.selectionChanged, 
     157                       tooltip="Send selected data whenever a selection area is added or removed") 
     158        OWGUI.checkBox(box, self, 'graph.sendSelectionOnUpdate', 'Moving/Resizing selection areas', 
     159                       tooltip="Send selected data when a user moves or resizes an existing selection area") 
    127160        self.graph.autoSendSelectionCallback = self.selectionChanged 
    128161 
     
    134167        self.graph.discPalette = dlg.getDiscretePalette("discPalette") 
    135168        self.graph.setCanvasBackground(dlg.getColor("Canvas")) 
    136         apply([self.zoomSelectToolbar.actionZooming, self.zoomSelectToolbar.actionRectangleSelection, self.zoomSelectToolbar.actionPolygonSelection][self.toolbarSelection], []) 
     169        apply([self.zoomSelectToolbar.actionZooming, self.zoomSelectToolbar.actionRectangleSelection, 
     170               self.zoomSelectToolbar.actionPolygonSelection][self.toolbarSelection], []) 
    137171        self.cbShowAllAttributes() 
    138172 
     
    144178            self.information(0) 
    145179        else: 
    146             self.information(0, "Didn't flip the attribute. To flip a continuous attribute uncheck 'Global value scaling' checkbox.") 
     180            self.information(0, 
     181                             "Didn't flip the attribute. To flip a continuous attribute uncheck 'Global value scaling' checkbox.") 
    147182 
    148183    def updateGraph(self, *args): 
     
    150185        self.graph.updateData(attrs, self.buildMidLabels(attrs)) 
    151186 
    152  
    153187    def increaseAxesDistance(self): 
    154188        m = self.graph.axisScaleDiv(QwtPlot.xBottom).interval().minValue() 
    155189        M = self.graph.axisScaleDiv(QwtPlot.xBottom).interval().maxValue() 
    156         if (M-m) == 0: 
    157             return      # we have not yet updated the axes (self.graph.updateAxes()) 
    158         self.graph.setAxisScale(QwtPlot.xBottom, m, M - (M-m)/10., 1) 
     190        if (M - m) == 0: 
     191            return # we have not yet updated the axes (self.graph.updateAxes()) 
     192        self.graph.setAxisScale(QwtPlot.xBottom, m, M - (M - m) / 10., 1) 
    159193        self.graph.replot() 
    160194 
     
    162196        m = self.graph.axisScaleDiv(QwtPlot.xBottom).interval().minValue() 
    163197        M = self.graph.axisScaleDiv(QwtPlot.xBottom).interval().maxValue() 
    164         if (M-m) == 0: 
    165             return      # we have not yet updated the axes (self.graph.updateAxes()) 
    166  
    167         self.graph.setAxisScale(QwtPlot.xBottom, m, min(len(self.graph.visualizedAttributes)-1, M + (M-m)/10.), 1) 
     198        if (M - m) == 0: 
     199            return # we have not yet updated the axes (self.graph.updateAxes()) 
     200 
     201        self.graph.setAxisScale(QwtPlot.xBottom, m, min(len(self.graph.visualizedAttributes) - 1, M + (M - m) / 10.), 1) 
    168202        self.graph.replot() 
    169  
    170203 
    171204    # build a list of strings that will be shown in the middle of the parallel axis 
    172205    def buildMidLabels(self, attrs): 
    173206        labels = [] 
    174         if self.middleLabels == "No labels" or not self.graph.haveData: return None 
     207        if self.middleLabels == "No labels" or not self.graph.haveData: 
     208            return None 
    175209        elif self.middleLabels == "Correlations": 
    176             for i in range(len(attrs)-1): 
    177                 corr = None 
    178                 if self.correlationDict.has_key((attrs[i], attrs[i+1])):   corr = self.correlationDict[(attrs[i], attrs[i+1])] 
    179                 elif self.correlationDict.has_key((attrs[i+1], attrs[i])): corr = self.correlationDict[(attrs[i+1], attrs[i])] 
     210            for i in range(len(attrs) - 1): 
     211                if self.correlationDict.has_key((attrs[i], attrs[i + 1])): 
     212                    corr = self.correlationDict[(attrs[i], attrs[i + 1])] 
     213                elif self.correlationDict.has_key((attrs[i + 1], attrs[i])): 
     214                    corr = self.correlationDict[(attrs[i + 1], attrs[i])] 
    180215                else: 
    181216                    try: 
    182                         corr = orngVisFuncts.computeCorrelation(self.graph.rawData, attrs[i], attrs[i+1]) 
     217                        corr = orngVisFuncts.computeCorrelation(self.graph.rawData, attrs[i], attrs[i + 1]) 
    183218                    except: 
    184219                        corr = None 
    185                     self.correlationDict[(attrs[i], attrs[i+1])] = corr 
    186                 if corr and (self.graph.attributeFlipInfo.get(attrs[i], 0) != self.graph.attributeFlipInfo.get(attrs[i+1], 0)): corr = -corr 
    187                 if corr: labels.append("%2.3f" % (corr)) 
    188                 else: labels.append("") 
     220                    self.correlationDict[(attrs[i], attrs[i + 1])] = corr 
     221                if corr and ( 
     222                        self.graph.attributeFlipInfo.get(attrs[i], 0) != self.graph.attributeFlipInfo.get(attrs[i + 1], 
     223                                                                                                          0)): corr = -corr 
     224                if corr: 
     225                    labels.append("%2.3f" % (corr)) 
     226                else: 
     227                    labels.append("") 
    189228        elif self.middleLabels == "VizRank": 
    190             for i in range(len(attrs)-1): 
    191                 val = self.optimizationDlg.getVizRankVal(attrs[i], attrs[i+1]) 
    192                 if val: labels.append("%2.2f%%" % (val)) 
    193                 else: labels.append("") 
     229            for i in range(len(attrs) - 1): 
     230                val = self.optimizationDlg.getVizRankVal(attrs[i], attrs[i + 1]) 
     231                if val: 
     232                    labels.append("%2.2f%%" % (val)) 
     233                else: 
     234                    labels.append("") 
    194235        return labels 
    195  
    196236 
    197237    # ------------- SIGNALS -------------------------- 
     
    200240        if data and (len(data) == 0 or len(data.domain) == 0): 
    201241            data = None 
    202         if self.data != None and data != None and self.data.checksum() == data.checksum(): 
    203             return    # check if the new data set is the same as the old one 
     242        if self.data is not None and data is not None and self.data.checksum() == data.checksum(): 
     243            return # check if the new data set is the same as the old one 
    204244 
    205245        self.closeContext() 
     
    214254        self.resetAttrManipulation() 
    215255 
    216  
    217256    def setSubsetData(self, subData): 
    218257        self.subsetData = subData 
    219  
    220258 
    221259    # attribute selection signal - list of attributes to show 
     
    223261        self.attributeSelectionList = attributeSelectionList 
    224262 
    225  
    226263    # this is called by OWBaseWidget after setData and setSubsetData are called. this way the graph is updated only once 
    227264    def handleNewSignals(self): 
    228265        self.graph.setData(self.data, self.subsetData) 
    229         if self.attributeSelectionList and 0 not in [self.graph.attributeNameIndex.has_key(attr) for attr in self.attributeSelectionList]: 
     266        if self.attributeSelectionList and 0 not in [self.graph.attributeNameIndex.has_key(attr) for attr in 
     267                                                     self.attributeSelectionList]: 
    230268            self.setShownAttributeList(self.attributeSelectionList) 
    231269        else: 
     
    235273        self.sendSelections() 
    236274 
    237  
    238     def sendShownAttributes(self, attrList = None): 
    239         if attrList == None: 
     275    def sendShownAttributes(self, attrList=None): 
     276        if attrList is None: 
    240277            attrList = self.getShownAttributeList() 
    241278        self.send("Features", attrList) 
     
    251288        self.send("Selected Data", selected) 
    252289        self.send("Other Data", unselected) 
    253  
    254290 
    255291    # jittering options 
     
    289325 
    290326 
    291  
    292327CORRELATION = 0 
    293328VIZRANK = 1 
    294 # 
     329 
     330 
    295331# Find attribute subsets that are interesting to visualize using parallel coordinates 
    296332class ParallelOptimization(OWWidget): 
    297333    resultListList = [50, 100, 200, 500, 1000] 
    298     qualityMeasure =  ["Classification accuracy", "Average correct", "Brier score"] 
     334    qualityMeasure = ["Classification accuracy", "Average correct", "Brier score"] 
    299335    testingMethod = ["Leave one out", "10-fold cross validation", "Test on learning set"] 
    300336 
     
    302338                    "numberOfAttributes", "orderAllAttributes", "optimizationMeasure"] 
    303339 
    304     def __init__(self, parallelWidget, parent=None, signalManager = None): 
     340    def __init__(self, parallelWidget, parent=None, signalManager=None): 
    305341        OWWidget.__init__(self, parent, signalManager, "Parallel Optimization Dialog", False) 
    306342        self.setCaption("Parallel Optimization Dialog") 
     
    316352        self.allResults = [] 
    317353        self.canOptimize = 0 
    318         self.orderAllAttributes = 1 # do we wish to order all attributes or find just an interesting subset 
     354        self.orderAllAttributes = 1  # do we wish to order all attributes or find just an interesting subset 
    319355        self.worstVal = -1  # used in heuristics to stop the search in uninteresting parts of the graph 
    320356 
    321357        self.loadSettings() 
    322358 
    323         self.measureBox = OWGUI.radioButtonsInBox(self.controlArea, self, "optimizationMeasure", ["Correlation", "VizRank"], box = "Select optimization measure", callback = self.updateGUI) 
     359        self.measureBox = OWGUI.radioButtonsInBox(self.controlArea, self, "optimizationMeasure", 
     360                                                  ["Correlation", "VizRank"], box="Select optimization measure", 
     361                                                  callback=self.updateGUI) 
    324362        self.vizrankSettingsBox = OWGUI.widgetBox(self.controlArea, "VizRank settings") 
    325363        self.optimizeBox = OWGUI.widgetBox(self.controlArea, "Optimize") 
     
    328366 
    329367        self.resultList = OWGUI.listBox(self.resultsBox, self) 
    330         self.resultList.setMinimumSize(200,200) 
     368        self.resultList.setMinimumSize(200, 200) 
    331369        self.connect(self.resultList, SIGNAL("itemSelectionChanged()"), self.showSelectedAttributes) 
    332370 
    333371        # remove non-existing files 
    334372        names = [] 
    335         for i in range(len(self.fileBuffer)-1, -1, -1): 
     373        for i in range(len(self.fileBuffer) - 1, -1, -1): 
    336374            (short, longName) = self.fileBuffer[i] 
    337375            if not os.path.exists(longName): 
    338376                self.fileBuffer.remove((short, longName)) 
    339             else: names.append(short) 
     377            else: 
     378                names.append(short) 
    340379        names.append("(None)") 
    341380        self.fileName = "(None)" 
    342381 
    343         self.hbox1 = OWGUI.widgetBox(self.vizrankSettingsBox, "VizRank projections file", orientation = "horizontal") 
    344         self.vizrankFileCombo = OWGUI.comboBox(self.hbox1, self, "fileName", items = names, tooltip = "File that contains information about interestingness of scatterplots \ngenerated by VizRank method in scatterplot widget", callback = self.changeProjectionFile, sendSelectedValue = 1, valueType = str) 
    345         self.browseButton = OWGUI.button(self.hbox1, self, "...", callback = self.loadProjections) 
     382        self.hbox1 = OWGUI.widgetBox(self.vizrankSettingsBox, "VizRank projections file", orientation="horizontal") 
     383        self.vizrankFileCombo = OWGUI.comboBox(self.hbox1, self, "fileName", items=names, 
     384                                               tooltip="File that contains information about interestingness of scatterplots\n" 
     385                                                       "generated by VizRank method in scatterplot widget", 
     386                                               callback=self.changeProjectionFile, sendSelectedValue=1, valueType=str) 
     387        self.browseButton = OWGUI.button(self.hbox1, self, "...", callback=self.loadProjections) 
    346388        self.browseButton.setMaximumWidth(20) 
    347389 
     
    352394        self.qualityMeasureLabel = OWGUI.widgetLabel(self.resultsInfoBox, "Quality measure used:") 
    353395 
    354         #self.numberOfAttributesCombo = OWGUI.comboBoxWithCaption(self.optimizeBox, self, "numberOfAttributes", "Number of visualized attributes: ", tooltip = "Projections with this number of attributes will be evaluated", items = [x for x in range(3, 12)], sendSelectedValue = 1, valueType = int) 
    355396        self.allAttributesRadio = QRadioButton("Order all attributes", self.optimizeBox) 
    356397        self.optimizeBox.layout().addWidget(self.allAttributesRadio) 
    357398        self.connect(self.allAttributesRadio, SIGNAL("clicked()"), self.setAllAttributeRadio) 
    358         box = OWGUI.widgetBox(self.optimizeBox, orientation = "horizontal") 
     399        box = OWGUI.widgetBox(self.optimizeBox, orientation="horizontal") 
    359400        self.subsetAttributeRadio = QRadioButton("Find subsets of", box) 
    360 #        self.optimizeBox.layout().addWidget(self.subsetAttributeRadio) 
    361401        box.layout().addWidget(self.subsetAttributeRadio) 
    362402        self.connect(self.subsetAttributeRadio, SIGNAL("clicked()"), self.setSubsetAttributeRadio) 
    363         self.subsetAttributeEdit = OWGUI.lineEdit(box, self, "numberOfAttributes", valueType = int) 
     403        self.subsetAttributeEdit = OWGUI.lineEdit(box, self, "numberOfAttributes", valueType=int) 
    364404        self.subsetAttributeEdit.setMaximumWidth(30) 
    365         label  = OWGUI.widgetLabel(box, "attributes") 
    366  
    367         self.startOptimizationButton = OWGUI.button(self.optimizeBox, self, "Start Optimization", callback = self.startOptimization) 
     405        OWGUI.widgetLabel(box, "attributes") 
     406 
     407        self.startOptimizationButton = OWGUI.button(self.optimizeBox, self, "Start Optimization", 
     408                                                    callback=self.startOptimization) 
    368409        f = self.startOptimizationButton.font() 
    369410        f.setBold(1) 
    370411        self.startOptimizationButton.setFont(f) 
    371         self.stopOptimizationButton = OWGUI.button(self.optimizeBox, self, "Stop Evaluation", callback = self.stopOptimizationClick) 
     412        self.stopOptimizationButton = OWGUI.button(self.optimizeBox, self, "Stop Evaluation", 
     413                                                   callback=self.stopOptimizationClick) 
    372414        self.stopOptimizationButton.setFont(f) 
    373415        self.stopOptimizationButton.hide() 
    374         self.connect(self.stopOptimizationButton , SIGNAL("clicked()"), self.stopOptimizationClick) 
    375  
     416        self.connect(self.stopOptimizationButton, SIGNAL("clicked()"), self.stopOptimizationClick) 
    376417 
    377418        self.clearButton = OWGUI.button(self.manageBox, self, "Clear Results", self.clearResults) 
    378         self.loadButton  = OWGUI.button(self.manageBox, self, "Load", self.loadResults) 
    379         self.saveButton  = OWGUI.button(self.manageBox, self, "Save", self.saveResults) 
     419        self.loadButton = OWGUI.button(self.manageBox, self, "Load", self.loadResults) 
     420        self.saveButton = OWGUI.button(self.manageBox, self, "Save", self.saveResults) 
    380421        self.closeButton = OWGUI.button(self.manageBox, self, "Close Dialog", self.hide) 
    381422 
    382423        self.changeProjectionFile() 
    383424        self.updateGUI() 
    384         if self.orderAllAttributes: self.setAllAttributeRadio() 
    385         else:                       self.setSubsetAttributeRadio() 
     425        if self.orderAllAttributes: 
     426            self.setAllAttributeRadio() 
     427        else: 
     428            self.setSubsetAttributeRadio() 
    386429 
    387430    def updateGUI(self): 
     
    435478 
    436479    def changeProjectionFile(self): 
    437         for (short, long) in self.fileBuffer: 
    438             if short == self.fileName: 
    439                 self.loadProjections(long) 
     480        for (short_name, long_name) in self.fileBuffer: 
     481            if short_name == self.fileName: 
     482                self.loadProjections(long_name) 
    440483                return 
    441484 
    442485    # load projections from a file 
    443     def loadProjections(self, name = None): 
     486    def loadProjections(self, name=None): 
    444487        self.projections = [] 
    445         self.kNeighborsLabel.setText("Number of neighbors (k): " ) 
    446         self.percentDataUsedLabel.setText("Percent of data used:" ) 
    447         self.testingMethodLabel.setText("Testing method used:" ) 
    448         self.qualityMeasureLabel.setText("Quality measure used:" ) 
    449  
    450         if name == None: 
    451             name = unicode(QFileDialog.getOpenFileName(self, "Open Projections",  self.lastSaveDirName, "Interesting projections (*.proj)")) 
    452             if name == "": return 
     488        self.kNeighborsLabel.setText("Number of neighbors (k): ") 
     489        self.percentDataUsedLabel.setText("Percent of data used:") 
     490        self.testingMethodLabel.setText("Testing method used:") 
     491        self.qualityMeasureLabel.setText("Quality measure used:") 
     492 
     493        if name is None: 
     494            name = unicode(QFileDialog.getOpenFileName(self, "Open Projections", self.lastSaveDirName, 
     495                                                       "Interesting projections (*.proj)")) 
     496            if name == "": 
     497                return 
    453498 
    454499        dirName, shortFileName = os.path.split(name) 
    455500        self.lastSaveDirName = dirName 
    456501 
    457         file = open(name, "rt") 
    458         settings = eval(file.readline()[:-1]) 
     502        projection_file = open(name, "rt") 
     503        settings = eval(projection_file.readline()[:-1]) 
    459504        if settings.has_key("parentName") and settings["parentName"].lower() != "scatterplot": 
    460             QMessageBox.critical( None, "Optimization Dialog", 'Unable to load projection file. Only projection file generated by scatterplot is compatible. \nThis file was created using %s method'%(settings["parentName"]), QMessageBox.Ok) 
    461             file.close() 
     505            QMessageBox.critical(None, "Optimization Dialog", 
     506                                 'Unable to load projection file. Only projection file generated by scatterplot is compatible. \n' 
     507                                 'This file was created using %s method' % (settings["parentName"]), QMessageBox.Ok) 
     508            projection_file.close() 
    462509            return 
    463510 
    464         if type(eval(file.readline()[:-1])) != list:    # second line must contain a list of classes that we tried to separate 
    465             QMessageBox.critical(None,'Old version of projection file','This file was saved with an older version of k-NN Optimization Dialog. The new version of dialog offers \nsome additional functionality and therefore you have to compute the projection quality again.',QMessageBox.Ok) 
    466             file.close() 
     511        if type(eval(projection_file.readline()[ 
     512                     :-1])) != list:    # second line must contain a list of classes that we tried to separate 
     513            QMessageBox.critical(None, 'Old version of projection file', 
     514                                 'This file was saved with an older version of k-NN Optimization Dialog. The new version of dialog offers \n' 
     515                                 'some additional functionality and therefore you have to compute the projection quality again.', 
     516                                 QMessageBox.Ok) 
     517            projection_file.close() 
    467518            return 
    468519 
    469520        try: 
    470             line = file.readline()[:-1]; ind = 0    # first line is a settings line 
     521            line = projection_file.readline()[:-1] 
    471522            (acc, other_results, lenTable, attrList, tryIndex, strList) = eval(line) 
    472523            if len(attrList) != 2: 
    473                 QMessageBox.information(self, "Incorrect file", "File should contain projections with 2 attributes!", QMessageBox.Ok) 
    474                 file.close() 
     524                QMessageBox.information(self, "Incorrect file", "File should contain projections with 2 attributes!", 
     525                                        QMessageBox.Ok) 
     526                projection_file.close() 
    475527                return 
    476528 
    477             while (line != ""): 
     529            while line != "": 
    478530                (acc, other_results, lenTable, attrList, tryIndex, strList) = eval(line) 
    479531                self.projections += [(acc, attrList)] 
    480                 line = file.readline()[:-1] 
     532                line = projection_file.readline()[:-1] 
    481533        except: 
    482534            self.projections = [] 
    483             file.close() 
     535            projection_file.close() 
    484536            QMessageBox.information(self, "Incorrect file", "Incorrect file format!", QMessageBox.Ok) 
    485537            return 
    486538 
    487         file.close() 
     539        projection_file.close() 
    488540 
    489541        if (shortFileName, name) in self.fileBuffer: 
     
    491543 
    492544        self.fileBuffer.insert(0, (shortFileName, name)) 
    493  
    494545 
    495546        if len(self.fileBuffer) > 10: 
     
    506557        self.qualityMeasureLabel.setText("Quality measure used: " + self.qualityMeasure[settings["qualityMeasure"]]) 
    507558 
    508  
    509559    def addProjection(self, val, attrList): 
    510560        index = self.findTargetIndex(val) 
     
    512562        self.resultList.insertItem(index, "%.3f - %s" % (val, str(attrList))) 
    513563 
    514  
    515564    def findTargetIndex(self, accuracy): 
    516565        # use bisection to find correct index 
    517         top = 0; bottom = len(self.allResults) 
    518  
    519         while (bottom-top) > 1: 
    520             mid  = (bottom + top)/2 
    521             if max(accuracy, self.allResults[mid][0]) == accuracy: bottom = mid 
    522             else: top = mid 
     566        top = 0; 
     567        bottom = len(self.allResults) 
     568 
     569        while (bottom - top) > 1: 
     570            mid = (bottom + top) / 2 
     571            if max(accuracy, self.allResults[mid][0]) == accuracy: 
     572                bottom = mid 
     573            else: 
     574                top = mid 
    523575 
    524576        if len(self.allResults) == 0: return 0 
     
    528580            return bottom 
    529581 
    530  
    531582    def startOptimization(self): 
    532583        self.clearResults() 
    533         if self.parallelWidget.data == None: return 
     584        if self.parallelWidget.data is None: return 
    534585 
    535586        if self.optimizationMeasure == VIZRANK and self.fileName == "": 
    536             QMessageBox.information(self, "No projection file", "If you wish to optimize using VizRank you first have to load a projection file \ncreated by VizRank using Scatterplot widget.", QMessageBox.Ok) 
     587            QMessageBox.information(self, "No projection file", 
     588                                    "If you wish to optimize using VizRank you first have to load a projection file \n" 
     589                                    "created by VizRank using Scatterplot widget.", 
     590                                    QMessageBox.Ok) 
    537591            return 
    538         if self.parallelWidget.data == None: 
    539             QMessageBox.information(self, "Missing data set", "A data set has to be loaded in order to perform optimization.", QMessageBox.Ok) 
     592        if self.parallelWidget.data is None: 
     593            QMessageBox.information(self, "Missing data set", 
     594                                    "A data set has to be loaded in order to perform optimization.", QMessageBox.Ok) 
    540595            return 
    541596 
     
    547602            self.stopOptimizationButton.show() 
    548603            self.canOptimize = 1 
     604 
    549605            class StopOptimizationException(Exception): 
    550606                pass 
     607 
    551608            def progressSetWithStop(value): 
    552609                if not self.canContinueOptimization(): 
     
    554611                else: 
    555612                    self.progressBarSet(value * 0.9) 
    556             try:  
    557                 attrInfo = orngVisFuncts.computeCorrelationBetweenAttributes(self.parallelWidget.data, attrList, progressCallback=progressSetWithStop) 
     613 
     614            try: 
     615                attrInfo = orngVisFuncts.computeCorrelationBetweenAttributes(self.parallelWidget.data, attrList, 
     616                                                                             progressCallback=progressSetWithStop) 
    558617            except StopOptimizationException: 
    559618                attrInfo = [] 
    560619                self.startOptimizationButton.show() 
    561620                self.stopOptimizationButton.hide() 
    562                  
    563 #            self.progressBarFinished() 
    564             #attrInfo = orngVisFuncts.computeCorrelationInsideClassesBetweenAttributes(self.parallelWidget.data, attrList) 
     621 
    565622        elif self.optimizationMeasure == VIZRANK: 
    566623            for (val, [a1, a2]) in self.projections: 
     
    571628            for (v, a1, a2) in attrInfo: 
    572629                if a1 not in attrs: 
    573                     print "attribute " + a1 + " was not found in the data set. You probably loaded wrong file with VizRank projections." 
     630                    print "attribute " + a1 + " was not found in the data set. " \ 
     631                                              "You probably loaded wrong file with VizRank projections." 
    574632                    return 
    575633                if a2 not in attrs: 
    576                     print "attribute " + a2 + " was not found in the data set. You probably loaded wrong file with VizRank projections." 
     634                    print "attribute " + a2 + " was not found in the data set. " \ 
     635                                              "You probably loaded wrong file with VizRank projections." 
    577636                    return 
    578637 
    579638        if len(attrInfo) == 0: 
    580             print "len(attrInfo) == 0. No attribute pairs. Unable to optimize."; return 
     639            print "len(attrInfo) == 0. No attribute pairs. Unable to optimize." 
     640            return 
    581641 
    582642        self.worstVal = -1 
     
    593653        self.stopOptimizationButton.hide() 
    594654        self.startOptimizationButton.show() 
    595          
     655 
    596656        self.progressBarFinished() 
    597  
    598657 
    599658    # ################################ 
     
    609668        self.resultList.clear() 
    610669 
    611  
    612     def saveResults(self, filename = None): 
    613         if filename == None: 
     670    def saveResults(self, filename=None): 
     671        if filename is None: 
    614672            filename = "" 
    615673            datasetName = getattr(self.parallelWidget.graph.rawData, "name", "") 
    616674            if datasetName != "": 
    617675                filename = os.path.splitext(os.path.split(datasetName)[1])[0] 
    618             if self.optimizationMeasure == CORRELATION: filename += " - " + "correlation" 
    619             else:                                       filename += " - " + "vizrank" 
    620  
    621             name = unicode(QFileDialog.getSaveFileName(self, "Save Parallel Projections",  os.path.join(self.lastSaveDirName, filename), "Parallel projections (*.papr)")) 
    622             if name == "": return 
     676            if self.optimizationMeasure == CORRELATION: 
     677                filename += " - " + "correlation" 
     678            else: 
     679                filename += " - " + "vizrank" 
     680 
     681            name = unicode(QFileDialog.getSaveFileName(self, "Save Parallel Projections", 
     682                                                       os.path.join(self.lastSaveDirName, filename), 
     683                                                       "Parallel projections (*.papr)")) 
     684            if name == "": 
     685                return 
    623686        else: 
    624687            name = filename 
     
    631694 
    632695        # open, write and save file 
    633         file = open(name, "wt") 
     696        result_file = open(name, "wt") 
    634697        for val in self.allResults: 
    635             file.write(str(val) + "\n") 
    636         file.close() 
     698            result_file.write(str(val) + "\n") 
     699        result_file.close() 
    637700 
    638701    def loadResults(self): 
    639702        self.clearResults() 
    640703 
    641         name = unicode(QFileDialog.getOpenFileName(self, "Open Parallel Projections",  self.lastSaveDirName, "Parallel projections (*.papr)")) 
     704        name = unicode(QFileDialog.getOpenFileName(self, "Open Parallel Projections", self.lastSaveDirName, 
     705                                                   "Parallel projections (*.papr)")) 
    642706        if name == "": return 
    643707 
     
    646710 
    647711        file = open(name, "rt") 
    648         line = file.readline()[:-1]; ind = 0 
    649         while (line != ""): 
     712        line = file.readline()[:-1]; 
     713        ind = 0 
     714        while line != "": 
    650715            (val, attrList) = eval(line) 
    651716            self.allResults.insert(ind, (val, attrList)) 
    652717            self.resultList.addItem("%.2f - %s" % (val, str(attrList)), ind) 
    653718            line = file.readline()[:-1] 
    654             ind+=1 
     719            ind += 1 
    655720        file.close() 
    656721 
    657722 
    658723#test widget appearance 
    659 if __name__=="__main__": 
     724if __name__ == "__main__": 
    660725    import sys 
    661726    from PyQt4.QtGui import QApplication 
    662727    from Orange.OrangeWidgets.OWColorPalette import ColorPaletteGenerator 
    663728 
    664     a=QApplication(sys.argv) 
    665     ow=OWParallelCoordinates() 
     729    a = QApplication(sys.argv) 
     730    ow = OWParallelCoordinates() 
    666731    ow.show() 
    667     ow.graph.discPalette = ColorPaletteGenerator(rgbColors = [(127, 201, 127), (190, 174, 212), (253, 192, 134)]) 
     732    ow.graph.discPalette = ColorPaletteGenerator(rgbColors=[(127, 201, 127), (190, 174, 212), (253, 192, 134)]) 
    668733    data = ExampleTable("iris.tab") 
    669734    ow.setData(data) 
    670735    ow.handleNewSignals() 
    671      
     736 
    672737    a.exec_() 
    673738 
Note: See TracChangeset for help on using the changeset viewer.