Source

orange / Orange / OrangeWidgets / Visualize / OWParallelCoordinates.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
"""
<name>Parallel Coordinates</name>
<description>Parallel coordinates (multiattribute) visualization.</description>
<contact>Gregor Leban (gregor.leban@fri.uni-lj.si)</contact>
<icon>icons/ParallelCoordinates.svg</icon>
<priority>3200</priority>
"""
# ParallelCoordinates.py
#
# Show data using parallel coordinates visualization method
#
import os
from PyQt4.QtCore import SIGNAL, Qt, QSize
from PyQt4.QtGui import QColor, QRadioButton, QFileDialog, QMessageBox, qApp
from PyQt4.Qwt5.Qwt import QwtPlot
from Orange.orange import ExampleTable

from Orange.OrangeCanvas.registry.description import Default
from Orange.OrangeWidgets import OWToolbars, OWGUI, OWColorPalette
from Orange.OrangeWidgets.OWBaseWidget import AttributeList
from Orange.OrangeWidgets.OWContexts import DomainContextHandler, ContextField
from Orange.OrangeWidgets.OWVisWidget import OWVisWidget
from Orange.OrangeWidgets.OWWidget import OWWidget
from Orange.OrangeWidgets.Visualize.OWParallelGraph import OWParallelGraph
from Orange.orng import orngVisFuncts


###########################################################################################
##### WIDGET : Parallel coordinates visualization
###########################################################################################
class OWParallelCoordinates(OWVisWidget):
    settingsList = ["graph.jitterSize", "graph.showDistributions",
                    "graph.showAttrValues", "graph.useAntialiasing",
                    "graph.useSplines", "graph.alphaValue",
                    "graph.alphaValue2", "graph.enabledLegend",
                    "graph.showStatistics", "autoSendSelection",
                    "toolbarSelection", "colorSettings",
                    "selectedSchemaIndex", "showAllAttributes"]
    jitterSizeNums = [0, 2, 5, 10, 15, 20, 30]
    contextHandlers = {
        "": DomainContextHandler("", [
            ContextField("shownAttributes", DomainContextHandler.RequiredList,
                         selected="selectedShown", reservoir="hiddenAttributes")]
        )
    }

    def __init__(self, parent=None, signalManager=None):
        OWWidget.__init__(self, parent, signalManager, "Parallel Coordinates", True)

        #add a graph widget
        self.graph = OWParallelGraph(self, self.mainArea)
        self.mainArea.layout().addWidget(self.graph)

        self.showAllAttributes = 0

        self.inputs = [("Data", ExampleTable, self.setData, Default),
                       ("Data Subset", ExampleTable, self.setSubsetData),
                       ("Features", AttributeList, self.setShownAttributes)]
        self.outputs = [("Selected Data", ExampleTable),
                        ("Other Data", ExampleTable),
                        ("Features", AttributeList)]

        #set default settings
        self.data = None
        self.subsetData = None
        self.autoSendSelection = 1
        self.attrDiscOrder = "Unordered"
        self.attrContOrder = "Unordered"
        self.projections = None
        self.correlationDict = {}
        self.middleLabels = "Correlations"
        self.attributeSelectionList = None
        self.toolbarSelection = 0
        self.colorSettings = None
        self.selectedSchemaIndex = 0

        self.graph.jitterSize = 10
        self.graph.showDistributions = 1
        self.graph.showStatistics = 0
        self.graph.showAttrValues = 1
        self.graph.useSplines = 0
        self.graph.enabledLegend = 1

        #load settings
        self.loadSettings()

        #GUI
        self.tabs = OWGUI.tabWidget(self.controlArea)
        self.GeneralTab = OWGUI.createTabPage(self.tabs, "Main")
        self.SettingsTab = OWGUI.createTabPage(self.tabs, "Settings")

        self.createShowHiddenLists(self.GeneralTab, callback=self.updateGraph)
        self.connect(self.shownAttribsLB, SIGNAL('itemDoubleClicked(QListWidgetItem*)'), self.flipAttribute)

        self.optimizationDlg = ParallelOptimization(self, signalManager=self.signalManager)
        self.optimizationDlgButton = OWGUI.button(self.GeneralTab, self, "Optimization Dialog",
                                                  callback=self.optimizationDlg.reshow, debuggingEnabled=0)

        self.zoomSelectToolbar = OWToolbars.ZoomSelectToolbar(self, self.GeneralTab, self.graph, self.autoSendSelection,
                                                              buttons=(1, 2, 0, 7, 8))
        self.connect(self.zoomSelectToolbar.buttonSendSelections, SIGNAL("clicked()"), self.sendSelections)

        #connect controls to appropriate functions
        self.connect(self.graphButton, SIGNAL("clicked()"), self.graph.saveToFile)

        # ####################################
        # SETTINGS functionality
        box = OWGUI.widgetBox(self.SettingsTab, "Transparency")
        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")
        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, ...")

        box = OWGUI.widgetBox(self.SettingsTab, "Jittering Options")
        OWGUI.comboBox(box, self, "graph.jitterSize", label='Jittering size (% of size):  ', orientation='horizontal',
                       callback=self.setJitteringSize, items=self.jitterSizeNums, sendSelectedValue=1, valueType=float)

        # visual settings
        box = OWGUI.widgetBox(self.SettingsTab, "Visual Settings")

        OWGUI.checkBox(box, self, 'graph.showAttrValues', 'Show attribute values', callback=self.updateGraph)
        OWGUI.checkBox(box, self, 'graph.useAntialiasing', 'Use antialiasing', callback=self.updateGraph)
        OWGUI.checkBox(box, self, 'graph.useSplines', 'Show splines', callback=self.updateGraph,
                       tooltip="Show lines using splines")
        OWGUI.checkBox(box, self, 'graph.enabledLegend', 'Show legend', callback=self.updateGraph)

        box = OWGUI.widgetBox(self.SettingsTab, "Axis Distance")
        resizeColsBox = OWGUI.widgetBox(box, 0, "horizontal", 0)
        OWGUI.label(resizeColsBox, self, "Increase/decrease distance: ")
        OWGUI.toolButton(resizeColsBox, self, "+", callback=self.increaseAxesDistance,
                         tooltip="Increase the distance between the axes", width=30, height=20)
        OWGUI.toolButton(resizeColsBox, self, "-", callback=self.decreaseAxesDistance,
                         tooltip="Decrease the distance between the axes", width=30, height=20)
        OWGUI.rubber(resizeColsBox)
        OWGUI.checkBox(box, self, "graph.autoUpdateAxes", "Auto scale X axis",
                       tooltip="Auto scale X axis to show all visualized attributes", callback=self.updateGraph)

        box = OWGUI.widgetBox(self.SettingsTab, "Statistical Information")
        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)
        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)
        OWGUI.checkBox(box, self, 'graph.showDistributions', 'Show distributions', callback=self.updateGraph,
                       tooltip="Show bars with distribution of class values (only for discrete attributes)")

        box = OWGUI.widgetBox(self.SettingsTab, "Colors", orientation="horizontal")
        OWGUI.button(box, self, "Set colors", self.setColors,
                     tooltip="Set the canvas background color and color palette for coloring continuous variables",
                     debuggingEnabled=0)

        box = OWGUI.widgetBox(self.SettingsTab, "Auto Send Selected Data When...")
        OWGUI.checkBox(box, self, 'autoSendSelection', 'Adding/Removing selection areas',
                       callback=self.selectionChanged,
                       tooltip="Send selected data whenever a selection area is added or removed")
        OWGUI.checkBox(box, self, 'graph.sendSelectionOnUpdate', 'Moving/Resizing selection areas',
                       tooltip="Send selected data when a user moves or resizes an existing selection area")
        self.graph.autoSendSelectionCallback = self.selectionChanged

        self.SettingsTab.layout().addStretch(100)
        self.icons = self.createAttributeIconDict()

        dlg = self.createColorDialog()
        self.graph.contPalette = dlg.getContinuousPalette("contPalette")
        self.graph.discPalette = dlg.getDiscretePalette("discPalette")
        self.graph.setCanvasBackground(dlg.getColor("Canvas"))
        apply([self.zoomSelectToolbar.actionZooming, self.zoomSelectToolbar.actionRectangleSelection,
               self.zoomSelectToolbar.actionPolygonSelection][self.toolbarSelection], [])
        self.cbShowAllAttributes()

        self.resize(900, 700)

    def flipAttribute(self, item):
        if self.graph.flipAttribute(str(item.text())):
            self.updateGraph()
            self.information(0)
        else:
            self.information(0,
                             "Didn't flip the attribute. To flip a continuous attribute uncheck 'Global value scaling' checkbox.")

    def updateGraph(self, *args):
        attrs = self.getShownAttributeList()
        self.graph.updateData(attrs, self.buildMidLabels(attrs))

    def increaseAxesDistance(self):
        m = self.graph.axisScaleDiv(QwtPlot.xBottom).interval().minValue()
        M = self.graph.axisScaleDiv(QwtPlot.xBottom).interval().maxValue()
        if (M - m) == 0:
            return # we have not yet updated the axes (self.graph.updateAxes())
        self.graph.setAxisScale(QwtPlot.xBottom, m, M - (M - m) / 10., 1)
        self.graph.replot()

    def decreaseAxesDistance(self):
        m = self.graph.axisScaleDiv(QwtPlot.xBottom).interval().minValue()
        M = self.graph.axisScaleDiv(QwtPlot.xBottom).interval().maxValue()
        if (M - m) == 0:
            return # we have not yet updated the axes (self.graph.updateAxes())

        self.graph.setAxisScale(QwtPlot.xBottom, m, min(len(self.graph.visualizedAttributes) - 1, M + (M - m) / 10.), 1)
        self.graph.replot()

    # build a list of strings that will be shown in the middle of the parallel axis
    def buildMidLabels(self, attrs):
        labels = []
        if self.middleLabels == "No labels" or not self.graph.haveData:
            return None
        elif self.middleLabels == "Correlations":
            for i in range(len(attrs) - 1):
                if self.correlationDict.has_key((attrs[i], attrs[i + 1])):
                    corr = self.correlationDict[(attrs[i], attrs[i + 1])]
                elif self.correlationDict.has_key((attrs[i + 1], attrs[i])):
                    corr = self.correlationDict[(attrs[i + 1], attrs[i])]
                else:
                    try:
                        corr = orngVisFuncts.computeCorrelation(self.graph.rawData, attrs[i], attrs[i + 1])
                    except:
                        corr = None
                    self.correlationDict[(attrs[i], attrs[i + 1])] = corr
                if corr and (
                        self.graph.attributeFlipInfo.get(attrs[i], 0) != self.graph.attributeFlipInfo.get(attrs[i + 1],
                                                                                                          0)): corr = -corr
                if corr:
                    labels.append("%2.3f" % (corr))
                else:
                    labels.append("")
        elif self.middleLabels == "VizRank":
            for i in range(len(attrs) - 1):
                val = self.optimizationDlg.getVizRankVal(attrs[i], attrs[i + 1])
                if val:
                    labels.append("%2.2f%%" % (val))
                else:
                    labels.append("")
        return labels

    # ------------- SIGNALS --------------------------
    # receive new data and update all fields
    def setData(self, data):
        if data and (len(data) == 0 or len(data.domain) == 0):
            data = None
        if self.data is not None and data is not None and self.data.checksum() == data.checksum():
            return # check if the new data set is the same as the old one

        self.closeContext()
        sameDomain = self.data and data and data.domain.checksum() == self.data.domain.checksum() # preserve attribute choice if the domain is the same
        self.projections = None
        self.correlationDict = {}
        self.data = data
        self.optimizationDlg.clearResults()
        if not sameDomain:
            self.setShownAttributeList(self.attributeSelectionList)
        self.openContext("", self.data)
        self.resetAttrManipulation()

    def setSubsetData(self, subData):
        self.subsetData = subData

    # attribute selection signal - list of attributes to show
    def setShownAttributes(self, attributeSelectionList):
        self.attributeSelectionList = attributeSelectionList

    # this is called by OWBaseWidget after setData and setSubsetData are called. this way the graph is updated only once
    def handleNewSignals(self):
        self.graph.setData(self.data, self.subsetData)
        if self.attributeSelectionList and 0 not in [self.graph.attributeNameIndex.has_key(attr) for attr in
                                                     self.attributeSelectionList]:
            self.setShownAttributeList(self.attributeSelectionList)
        else:
            self.setShownAttributeList()
        self.attributeSelectionList = None
        self.updateGraph()
        self.sendSelections()

    def sendShownAttributes(self, attrList=None):
        if attrList is None:
            attrList = self.getShownAttributeList()
        self.send("Features", attrList)

    def selectionChanged(self):
        self.zoomSelectToolbar.buttonSendSelections.setEnabled(not self.autoSendSelection)
        if self.autoSendSelection:
            self.sendSelections()

    # send signals with selected and unselected examples as two datasets
    def sendSelections(self):
        (selected, unselected) = self.graph.getSelectionsAsExampleTables()
        self.send("Selected Data", selected)
        self.send("Other Data", unselected)

    # jittering options
    def setJitteringSize(self):
        self.graph.rescaleData()
        self.updateGraph()

    def setColors(self):
        dlg = self.createColorDialog()
        if dlg.exec_():
            self.colorSettings = dlg.getColorSchemas()
            self.selectedSchemaIndex = dlg.selectedSchemaIndex
            self.graph.contPalette = dlg.getContinuousPalette("contPalette")
            self.graph.discPalette = dlg.getDiscretePalette("discPalette")
            self.graph.setCanvasBackground(dlg.getColor("Canvas"))
            self.updateGraph()

    def createColorDialog(self):
        c = OWColorPalette.ColorPaletteDlg(self, "Color Palette")
        c.createDiscretePalette("discPalette", "Discrete Palette")
        c.createContinuousPalette("contPalette", "Continuous Palette")
        box = c.createBox("otherColors", "Other Colors")
        c.createColorButton(box, "Canvas", "Canvas color", QColor(Qt.white))
        c.setColorSchemas(self.colorSettings, self.selectedSchemaIndex)
        return c

    def saveSettings(self):
        OWWidget.saveSettings(self)
        self.optimizationDlg.saveSettings()

    def closeEvent(self, ce):
        self.optimizationDlg.hide()
        OWWidget.closeEvent(self, ce)

    def sendReport(self):
        self.reportImage(self.graph.saveToFileDirect, QSize(500, 500))


CORRELATION = 0
VIZRANK = 1


# Find attribute subsets that are interesting to visualize using parallel coordinates
class ParallelOptimization(OWWidget):
    resultListList = [50, 100, 200, 500, 1000]
    qualityMeasure = ["Classification accuracy", "Average correct", "Brier score"]
    testingMethod = ["Leave one out", "10-fold cross validation", "Test on learning set"]

    settingsList = ["attributeCount", "fileBuffer", "lastSaveDirName", "optimizationMeasure",
                    "numberOfAttributes", "orderAllAttributes", "optimizationMeasure"]

    def __init__(self, parallelWidget, parent=None, signalManager=None):
        OWWidget.__init__(self, parent, signalManager, "Parallel Optimization Dialog", False)
        self.setCaption("Parallel Optimization Dialog")
        self.parallelWidget = parallelWidget

        self.optimizationMeasure = 0
        self.attributeCount = 5
        self.numberOfAttributes = 6
        self.fileName = ""
        self.lastSaveDirName = os.getcwd() + "/"
        self.fileBuffer = []
        self.projections = []
        self.allResults = []
        self.canOptimize = 0
        self.orderAllAttributes = 1  # do we wish to order all attributes or find just an interesting subset
        self.worstVal = -1  # used in heuristics to stop the search in uninteresting parts of the graph

        self.loadSettings()

        self.measureBox = OWGUI.radioButtonsInBox(self.controlArea, self, "optimizationMeasure",
                                                  ["Correlation", "VizRank"], box="Select optimization measure",
                                                  callback=self.updateGUI)
        self.vizrankSettingsBox = OWGUI.widgetBox(self.controlArea, "VizRank settings")
        self.optimizeBox = OWGUI.widgetBox(self.controlArea, "Optimize")
        self.manageBox = OWGUI.widgetBox(self.controlArea, "Manage results")
        self.resultsBox = OWGUI.widgetBox(self.mainArea, "Results")

        self.resultList = OWGUI.listBox(self.resultsBox, self)
        self.resultList.setMinimumSize(200, 200)
        self.connect(self.resultList, SIGNAL("itemSelectionChanged()"), self.showSelectedAttributes)

        # remove non-existing files
        names = []
        for i in range(len(self.fileBuffer) - 1, -1, -1):
            (short, longName) = self.fileBuffer[i]
            if not os.path.exists(longName):
                self.fileBuffer.remove((short, longName))
            else:
                names.append(short)
        names.append("(None)")
        self.fileName = "(None)"

        self.hbox1 = OWGUI.widgetBox(self.vizrankSettingsBox, "VizRank projections file", orientation="horizontal")
        self.vizrankFileCombo = OWGUI.comboBox(self.hbox1, self, "fileName", items=names,
                                               tooltip="File that contains information about interestingness of scatterplots\n"
                                                       "generated by VizRank method in scatterplot widget",
                                               callback=self.changeProjectionFile, sendSelectedValue=1, valueType=str)
        self.browseButton = OWGUI.button(self.hbox1, self, "...", callback=self.loadProjections)
        self.browseButton.setMaximumWidth(20)

        self.resultsInfoBox = OWGUI.widgetBox(self.vizrankSettingsBox, "VizRank parameters")
        self.kNeighborsLabel = OWGUI.widgetLabel(self.resultsInfoBox, "Number of neighbors (k):")
        self.percentDataUsedLabel = OWGUI.widgetLabel(self.resultsInfoBox, "Percent of data used:")
        self.testingMethodLabel = OWGUI.widgetLabel(self.resultsInfoBox, "Testing method used:")
        self.qualityMeasureLabel = OWGUI.widgetLabel(self.resultsInfoBox, "Quality measure used:")

        self.allAttributesRadio = QRadioButton("Order all attributes", self.optimizeBox)
        self.optimizeBox.layout().addWidget(self.allAttributesRadio)
        self.connect(self.allAttributesRadio, SIGNAL("clicked()"), self.setAllAttributeRadio)
        box = OWGUI.widgetBox(self.optimizeBox, orientation="horizontal")
        self.subsetAttributeRadio = QRadioButton("Find subsets of", box)
        box.layout().addWidget(self.subsetAttributeRadio)
        self.connect(self.subsetAttributeRadio, SIGNAL("clicked()"), self.setSubsetAttributeRadio)
        self.subsetAttributeEdit = OWGUI.lineEdit(box, self, "numberOfAttributes", valueType=int)
        self.subsetAttributeEdit.setMaximumWidth(30)
        OWGUI.widgetLabel(box, "attributes")

        self.startOptimizationButton = OWGUI.button(self.optimizeBox, self, "Start Optimization",
                                                    callback=self.startOptimization)
        f = self.startOptimizationButton.font()
        f.setBold(1)
        self.startOptimizationButton.setFont(f)
        self.stopOptimizationButton = OWGUI.button(self.optimizeBox, self, "Stop Evaluation",
                                                   callback=self.stopOptimizationClick)
        self.stopOptimizationButton.setFont(f)
        self.stopOptimizationButton.hide()
        self.connect(self.stopOptimizationButton, SIGNAL("clicked()"), self.stopOptimizationClick)

        self.clearButton = OWGUI.button(self.manageBox, self, "Clear Results", self.clearResults)
        self.loadButton = OWGUI.button(self.manageBox, self, "Load", self.loadResults)
        self.saveButton = OWGUI.button(self.manageBox, self, "Save", self.saveResults)
        self.closeButton = OWGUI.button(self.manageBox, self, "Close Dialog", self.hide)

        self.changeProjectionFile()
        self.updateGUI()
        if self.orderAllAttributes:
            self.setAllAttributeRadio()
        else:
            self.setSubsetAttributeRadio()

    def updateGUI(self):
        self.vizrankSettingsBox.setEnabled(self.optimizationMeasure)

    # if user clicks new attribute list in optimization dialog, we update shown attributes
    def showSelectedAttributes(self):
        attrList = self.getSelectedAttributes()
        if not attrList: return

        self.parallelWidget.setShownAttributeList(attrList)
        self.parallelWidget.graph.removeAllSelections()

        self.parallelWidget.middleLabels = (self.optimizationMeasure == VIZRANK and "VizRank") or "Correlations"
        self.parallelWidget.updateGraph()

    def setAllAttributeRadio(self):
        self.orderAllAttributes = 1
        self.allAttributesRadio.setChecked(1)
        self.subsetAttributeRadio.setChecked(0)
        self.subsetAttributeEdit.setEnabled(0)

    def setSubsetAttributeRadio(self):
        self.orderAllAttributes = 0
        self.allAttributesRadio.setChecked(0)
        self.subsetAttributeRadio.setChecked(1)
        self.subsetAttributeEdit.setEnabled(1)

    # return list of selected attributes
    def getSelectedAttributes(self):
        if self.resultList.count() == 0 or self.allResults == []:
            return None
        return self.allResults[self.resultList.currentRow()][1]

    # called when optimization is in progress
    def canContinueOptimization(self):
        return self.canOptimize

    def getWorstVal(self):
        return self.worstVal

    def stopOptimizationClick(self):
        self.canOptimize = 0

    # get vizrank value for attributes attr1 and attr2
    def getVizRankVal(self, attr1, attr2):
        if not self.projections: return None
        for (val, [a1, a2]) in self.projections:
            if (attr1 == a1 and attr2 == a2) or (attr1 == a2 and attr2 == a1): return val
        return None

    def changeProjectionFile(self):
        for (short_name, long_name) in self.fileBuffer:
            if short_name == self.fileName:
                self.loadProjections(long_name)
                return

    # load projections from a file
    def loadProjections(self, name=None):
        self.projections = []
        self.kNeighborsLabel.setText("Number of neighbors (k): ")
        self.percentDataUsedLabel.setText("Percent of data used:")
        self.testingMethodLabel.setText("Testing method used:")
        self.qualityMeasureLabel.setText("Quality measure used:")

        if name is None:
            name = unicode(QFileDialog.getOpenFileName(self, "Open Projections", self.lastSaveDirName,
                                                       "Interesting projections (*.proj)"))
            if name == "":
                return

        dirName, shortFileName = os.path.split(name)
        self.lastSaveDirName = dirName

        projection_file = open(name, "rt")
        settings = eval(projection_file.readline()[:-1])
        if settings.has_key("parentName") and settings["parentName"].lower() != "scatterplot":
            QMessageBox.critical(None, "Optimization Dialog",
                                 'Unable to load projection file. Only projection file generated by scatterplot is compatible. \n'
                                 'This file was created using %s method' % (settings["parentName"]), QMessageBox.Ok)
            projection_file.close()
            return

        if type(eval(projection_file.readline()[
                     :-1])) != list:    # second line must contain a list of classes that we tried to separate
            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 \n'
                                 'some additional functionality and therefore you have to compute the projection quality again.',
                                 QMessageBox.Ok)
            projection_file.close()
            return

        try:
            line = projection_file.readline()[:-1]
            (acc, other_results, lenTable, attrList, tryIndex, strList) = eval(line)
            if len(attrList) != 2:
                QMessageBox.information(self, "Incorrect file", "File should contain projections with 2 attributes!",
                                        QMessageBox.Ok)
                projection_file.close()
                return

            while line != "":
                (acc, other_results, lenTable, attrList, tryIndex, strList) = eval(line)
                self.projections += [(acc, attrList)]
                line = projection_file.readline()[:-1]
        except:
            self.projections = []
            projection_file.close()
            QMessageBox.information(self, "Incorrect file", "Incorrect file format!", QMessageBox.Ok)
            return

        projection_file.close()

        if (shortFileName, name) in self.fileBuffer:
            self.fileBuffer.remove((shortFileName, name))

        self.fileBuffer.insert(0, (shortFileName, name))

        if len(self.fileBuffer) > 10:
            self.fileBuffer.remove(self.fileBuffer[-1])

        self.vizrankFileCombo.clear()
        for i in range(len(self.fileBuffer)):
            self.vizrankFileCombo.addItem(self.fileBuffer[i][0])
        self.fileName = shortFileName

        self.kNeighborsLabel.setText("Number of neighbors (k): " + str(settings["kValue"]))
        self.percentDataUsedLabel.setText("Percent of data used: " + "%d %%" % (settings["percentDataUsed"]))
        self.testingMethodLabel.setText("Testing method used: " + self.testingMethod[settings["testingMethod"]])
        self.qualityMeasureLabel.setText("Quality measure used: " + self.qualityMeasure[settings["qualityMeasure"]])

    def addProjection(self, val, attrList):
        index = self.findTargetIndex(val)
        self.allResults.insert(index, (val, attrList))
        self.resultList.insertItem(index, "%.3f - %s" % (val, str(attrList)))

    def findTargetIndex(self, accuracy):
        # use bisection to find correct index
        top = 0;
        bottom = len(self.allResults)

        while (bottom - top) > 1:
            mid = (bottom + top) / 2
            if max(accuracy, self.allResults[mid][0]) == accuracy:
                bottom = mid
            else:
                top = mid

        if len(self.allResults) == 0: return 0
        if max(accuracy, self.allResults[top][0]) == accuracy:
            return top
        else:
            return bottom

    def startOptimization(self):
        self.clearResults()
        if self.parallelWidget.data is None: return

        if self.optimizationMeasure == VIZRANK and self.fileName == "":
            QMessageBox.information(self, "No projection file",
                                    "If you wish to optimize using VizRank you first have to load a projection file \n"
                                    "created by VizRank using Scatterplot widget.",
                                    QMessageBox.Ok)
            return
        if self.parallelWidget.data is None:
            QMessageBox.information(self, "Missing data set",
                                    "A data set has to be loaded in order to perform optimization.", QMessageBox.Ok)
            return

        attrInfo = []
        self.progressBarInit()
        if self.optimizationMeasure == CORRELATION:
            attrList = [attr.name for attr in self.parallelWidget.data.domain.attributes]
            self.startOptimizationButton.hide()
            self.stopOptimizationButton.show()
            self.canOptimize = 1

            class StopOptimizationException(Exception):
                pass

            def progressSetWithStop(value):
                if not self.canContinueOptimization():
                    raise StopOptimizationException()
                else:
                    self.progressBarSet(value * 0.9)

            try:
                attrInfo = orngVisFuncts.computeCorrelationBetweenAttributes(self.parallelWidget.data, attrList,
                                                                             progressCallback=progressSetWithStop)
            except StopOptimizationException:
                attrInfo = []
                self.startOptimizationButton.show()
                self.stopOptimizationButton.hide()

        elif self.optimizationMeasure == VIZRANK:
            for (val, [a1, a2]) in self.projections:
                attrInfo.append((val, a1, a2))

            # check if all attributes in loaded projection file are actually present in this data set
            attrs = [attr.name for attr in self.parallelWidget.data.domain.attributes]
            for (v, a1, a2) in attrInfo:
                if a1 not in attrs:
                    print "attribute " + a1 + " was not found in the data set. " \
                                              "You probably loaded wrong file with VizRank projections."
                    return
                if a2 not in attrs:
                    print "attribute " + a2 + " was not found in the data set. " \
                                              "You probably loaded wrong file with VizRank projections."
                    return

        if len(attrInfo) == 0:
            print "len(attrInfo) == 0. No attribute pairs. Unable to optimize."
            return

        self.worstVal = -1
        self.canOptimize = 1
        self.startOptimizationButton.hide()
        self.stopOptimizationButton.show()
        #qApp.processEvents()        # allow processing of other events

        if self.orderAllAttributes:
            orngVisFuncts.optimizeAttributeOrder(attrInfo, len(self.parallelWidget.data.domain.attributes), self, qApp)
        else:
            orngVisFuncts.optimizeAttributeOrder(attrInfo, self.numberOfAttributes, self, qApp)

        self.stopOptimizationButton.hide()
        self.startOptimizationButton.show()

        self.progressBarFinished()

    # ################################
    # MANAGE RESULTS
    def updateShownProjections(self, *args):
        self.resultList.clear()
        for i in range(len(self.allResults)):
            self.resultList.addItem("%.2f - %s" % (self.allResults[i][0], str(self.allResults[i][1])), i)
        if self.resultList.count() > 0: self.resultList.setCurrentRow(0)

    def clearResults(self):
        self.allResults = []
        self.resultList.clear()

    def saveResults(self, filename=None):
        if filename is None:
            filename = ""
            datasetName = getattr(self.parallelWidget.graph.rawData, "name", "")
            if datasetName != "":
                filename = os.path.splitext(os.path.split(datasetName)[1])[0]
            if self.optimizationMeasure == CORRELATION:
                filename += " - " + "correlation"
            else:
                filename += " - " + "vizrank"

            name = unicode(QFileDialog.getSaveFileName(self, "Save Parallel Projections",
                                                       os.path.join(self.lastSaveDirName, filename),
                                                       "Parallel projections (*.papr)"))
            if name == "":
                return
        else:
            name = filename

        # take care of extension
        if os.path.splitext(name)[1] != ".papr": name += ".papr"

        dirName, shortFileName = os.path.split(name)
        self.lastSaveDirName = dirName

        # open, write and save file
        result_file = open(name, "wt")
        for val in self.allResults:
            result_file.write(str(val) + "\n")
        result_file.close()

    def loadResults(self):
        self.clearResults()

        name = unicode(QFileDialog.getOpenFileName(self, "Open Parallel Projections", self.lastSaveDirName,
                                                   "Parallel projections (*.papr)"))
        if name == "": return

        dirName, shortFileName = os.path.split(name)
        self.lastSaveDirName = dirName

        file = open(name, "rt")
        line = file.readline()[:-1];
        ind = 0
        while line != "":
            (val, attrList) = eval(line)
            self.allResults.insert(ind, (val, attrList))
            self.resultList.addItem("%.2f - %s" % (val, str(attrList)), ind)
            line = file.readline()[:-1]
            ind += 1
        file.close()


#test widget appearance
if __name__ == "__main__":
    import sys
    from PyQt4.QtGui import QApplication
    from Orange.OrangeWidgets.OWColorPalette import ColorPaletteGenerator

    a = QApplication(sys.argv)
    ow = OWParallelCoordinates()
    ow.show()
    ow.graph.discPalette = ColorPaletteGenerator(rgbColors=[(127, 201, 127), (190, 174, 212), (253, 192, 134)])
    data = ExampleTable("iris.tab")
    ow.setData(data)
    ow.handleNewSignals()

    a.exec_()

    ow.saveSettings()