Esempio n. 1
0
    def __init__(self,
                 parentWidget=None,
                 signalManager=None,
                 graph=None,
                 parentName="Visualization widget"):
        OWWidget.__init__(self,
                          None,
                          signalManager,
                          "FreeViz Dialog",
                          savePosition=True,
                          wantMainArea=0,
                          wantStatusBar=1)
        FreeViz.__init__(self, graph)

        self.parentWidget = parentWidget
        self.parentName = parentName
        self.setCaption("FreeViz Optimization Dialog")
        self.cancelOptimization = 0
        self.forceRelation = 5
        self.disableAttractive = 0
        self.disableRepulsive = 0
        self.touringSpeed = 4
        self.graph = graph

        if self.graph:
            self.graph.hideRadius = 0
            self.graph.showAnchors = 1

        # differential evolution
        self.differentialEvolutionPopSize = 100
        self.DERadvizSolver = None

        self.loadSettings()

        self.layout().setMargin(0)
        self.tabs = OWGUI.tabWidget(self.controlArea)
        self.MainTab = OWGUI.createTabPage(self.tabs, "Main")
        self.ProjectionsTab = OWGUI.createTabPage(self.tabs, "Projections")

        # ###########################
        # MAIN TAB
        OWGUI.comboBox(self.MainTab,
                       self,
                       "implementation",
                       box="FreeViz implementation",
                       items=[
                           "Fast (C) implementation",
                           "Slow (Python) implementation", "LDA"
                       ])

        box = OWGUI.widgetBox(self.MainTab, "Optimization")

        self.optimizeButton = OWGUI.button(box,
                                           self,
                                           "Optimize Separation",
                                           callback=self.optimizeSeparation)
        self.stopButton = OWGUI.button(box,
                                       self,
                                       "Stop Optimization",
                                       callback=self.stopOptimization)
        self.singleStepButton = OWGUI.button(
            box, self, "Single Step", callback=self.singleStepOptimization)
        f = self.optimizeButton.font()
        f.setBold(1)
        self.optimizeButton.setFont(f)
        self.stopButton.setFont(f)
        self.stopButton.hide()
        self.attrKNeighboursCombo = OWGUI.comboBoxWithCaption(
            box,
            self,
            "stepsBeforeUpdate",
            "Number of steps before updating graph: ",
            tooltip=
            "Set the number of optimization steps that will be executed before the updated anchor positions will be visualized",
            items=[1, 3, 5, 10, 15, 20, 30, 50, 75, 100, 150, 200, 300],
            sendSelectedValue=1,
            valueType=int)
        OWGUI.checkBox(box,
                       self,
                       "mirrorSymmetry",
                       "Keep mirror symmetry",
                       tooltip="'Rotational' keeps the second anchor upside")

        vbox = OWGUI.widgetBox(self.MainTab, "Set anchor positions")
        hbox1 = OWGUI.widgetBox(vbox, orientation="horizontal")
        OWGUI.button(hbox1, self, "Circle", callback=self.radialAnchors)
        OWGUI.button(hbox1, self, "Random", callback=self.randomAnchors)
        self.manualPositioningButton = OWGUI.button(
            hbox1, self, "Manual", callback=self.setManualPosition)
        self.manualPositioningButton.setCheckable(1)
        OWGUI.comboBox(vbox,
                       self,
                       "restrain",
                       label="Restrain anchors:",
                       orientation="horizontal",
                       items=["Unrestrained", "Fixed Length", "Fixed Angle"],
                       callback=self.setRestraints)

        box2 = OWGUI.widgetBox(self.MainTab, "Forces", orientation="vertical")

        self.cbLaw = OWGUI.comboBox(
            box2,
            self,
            "law",
            label="Law",
            labelWidth=40,
            orientation="horizontal",
            items=["Linear", "Square", "Gaussian", "KNN", "Variance"],
            callback=self.forceLawChanged)

        hbox2 = OWGUI.widgetBox(box2, orientation="horizontal")
        hbox2.layout().addSpacing(10)

        validSigma = QDoubleValidator(self)
        validSigma.setBottom(0.01)
        self.spinSigma = OWGUI.lineEdit(hbox2,
                                        self,
                                        "forceSigma",
                                        label="Kernel width (sigma) ",
                                        labelWidth=110,
                                        orientation="horizontal",
                                        valueType=float)
        self.spinSigma.setFixedSize(60, self.spinSigma.sizeHint().height())
        self.spinSigma.setSizePolicy(
            QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed))

        box2.layout().addSpacing(20)

        self.cbforcerel = OWGUI.comboBox(box2,
                                         self,
                                         "forceRelation",
                                         label="Attractive : Repulsive  ",
                                         orientation="horizontal",
                                         items=self.forceRelValues,
                                         callback=self.updateForces)
        self.cbforcebal = OWGUI.checkBox(
            box2,
            self,
            "forceBalancing",
            "Dynamic force balancing",
            tooltip=
            "Normalize the forces so that the total sums of the\nrepulsive and attractive are in the above proportion."
        )

        box2.layout().addSpacing(20)

        self.cbDisableAttractive = OWGUI.checkBox(
            box2,
            self,
            "disableAttractive",
            "Disable attractive forces",
            callback=self.setDisableAttractive)
        self.cbDisableRepulsive = OWGUI.checkBox(
            box2,
            self,
            "disableRepulsive",
            "Disable repulsive forces",
            callback=self.setDisableRepulsive)

        box = OWGUI.widgetBox(self.MainTab, "Show anchors")
        OWGUI.checkBox(box,
                       self,
                       'graph.showAnchors',
                       'Show attribute anchors',
                       callback=self.parentWidget.updateGraph)
        OWGUI.qwtHSlider(box,
                         self,
                         "graph.hideRadius",
                         label="Hide radius",
                         minValue=0,
                         maxValue=9,
                         step=1,
                         ticks=0,
                         callback=self.parentWidget.updateGraph)
        self.freeAttributesButton = OWGUI.button(box,
                                                 self,
                                                 "Remove hidden attributes",
                                                 callback=self.removeHidden)

        if parentName.lower() != "radviz":
            pcaBox = OWGUI.widgetBox(self.ProjectionsTab,
                                     "Principal Component Analysis")
            OWGUI.button(pcaBox,
                         self,
                         "Principal component analysis",
                         callback=self.findPCAProjection)
            OWGUI.button(pcaBox,
                         self,
                         "Supervised principal component analysis",
                         callback=self.findSPCAProjection)
            OWGUI.checkBox(pcaBox, self, "useGeneralizedEigenvectors",
                           "Merge examples with same class value")
            plsBox = OWGUI.widgetBox(self.ProjectionsTab,
                                     "Partial Least Squares")
            OWGUI.button(plsBox,
                         self,
                         "Partial least squares",
                         callback=self.findPLSProjection)

        box = OWGUI.widgetBox(self.ProjectionsTab, "Projection Tours")
        self.startTourButton = OWGUI.button(box,
                                            self,
                                            "Start Random Touring",
                                            callback=self.startRandomTouring)
        self.stopTourButton = OWGUI.button(box,
                                           self,
                                           "Stop Touring",
                                           callback=self.stopRandomTouring)
        self.stopTourButton.hide()
        OWGUI.hSlider(box,
                      self,
                      'touringSpeed',
                      label="Speed:  ",
                      minValue=1,
                      maxValue=10,
                      step=1)
        OWGUI.rubber(self.ProjectionsTab)

        box = OWGUI.widgetBox(self.ProjectionsTab, "Signal to Noise Heuristic")
        #OWGUI.comboBoxWithCaption(box, self, "s2nSpread", "Anchor spread: ", tooltip = "Are the anchors for each class value placed together or are they distributed along the circle", items = range(11), callback = self.s2nMixAnchors)
        box2 = OWGUI.widgetBox(box, 0, orientation="horizontal")
        OWGUI.widgetLabel(box2, "Anchor spread:           ")
        OWGUI.hSlider(box2,
                      self,
                      's2nSpread',
                      minValue=0,
                      maxValue=10,
                      step=1,
                      callback=self.s2nMixAnchors,
                      labelFormat="  %d",
                      ticks=0)
        OWGUI.comboBoxWithCaption(
            box,
            self,
            "s2nPlaceAttributes",
            "Attributes to place: ",
            tooltip=
            "Set the number of top ranked attributes to place. You can select a higher value than the actual number of attributes",
            items=self.attrsNum,
            callback=self.s2nMixAnchors,
            sendSelectedValue=1,
            valueType=int)
        OWGUI.checkBox(box, self, 'autoSetParameters',
                       'Automatically find optimal parameters')
        self.s2nMixButton = OWGUI.button(box,
                                         self,
                                         "Place anchors",
                                         callback=self.s2nMixAnchorsAutoSet)

        self.forceLawChanged()
        self.updateForces()
        self.cbforcebal.setDisabled(self.cbDisableAttractive.isChecked()
                                    or self.cbDisableRepulsive.isChecked())
        self.resize(320, 650)
Esempio n. 2
0
 def hideEvent(self, ev):
     self.stopRandomTouring()  # if we were touring then stop
     self.saveSettings()
     OWWidget.hideEvent(self, ev)
Esempio n. 3
0
    def __init__(self,
                 parent=None,
                 signalManager=None,
                 title="CSV File Import"):
        OWWidget.__init__(self,
                          parent,
                          signalManager,
                          title,
                          wantMainArea=False,
                          noReport=True)

        self.symbol_DC = ""
        self.symbol_DK = ""

        #: List of recent opened files.
        self.recent_files = []
        #: Current selected file name
        self.selected_file = None
        #: Variable reuse flag
        self.create_new_on = 2
        #: Display advanced var reuse options
        self.show_advanced = False

        self.loadSettings()

        self.recent_files = filter(os.path.exists, self.recent_files)

        self._loader = None
        self._invalidated = False
        self._datareport = None

        layout = QHBoxLayout()
        OWGUI.widgetBox(self.controlArea, "File", orientation=layout)

        icons = standard_icons(self)

        self.recent_combo = QComboBox(self,
                                      objectName="recent_combo",
                                      toolTip="Recent files.",
                                      activated=self.activate_recent)
        cb_append_file_list(self.recent_combo, self.recent_files)

        self.recent_combo.insertSeparator(self.recent_combo.count())
        self.recent_combo.addItem(u"Browse documentation data sets…")

        self.browse_button = QPushButton(u"…",
                                         icon=icons.dir_open_icon,
                                         toolTip="Browse filesystem",
                                         clicked=self.browse)

        self.reload_button = QPushButton("Reload",
                                         icon=icons.reload_icon,
                                         toolTip="Reload the selected file",
                                         clicked=self.reload,
                                         default=True)

        layout.addWidget(self.recent_combo, 2)
        layout.addWidget(self.browse_button)
        layout.addWidget(self.reload_button)

        ###########
        # Info text
        ###########
        box = OWGUI.widgetBox(self.controlArea, "Info", addSpace=True)
        self.infoa = OWGUI.widgetLabel(box, "No data loaded.")
        self.infob = OWGUI.widgetLabel(box, " ")
        self.warnings = OWGUI.widgetLabel(box, " ")

        # Set word wrap so long warnings won't expand the widget
        self.warnings.setWordWrap(True)
        self.warnings.setSizePolicy(QSizePolicy.Ignored,
                                    QSizePolicy.MinimumExpanding)

        advanced = QGroupBox("Advanced Settings",
                             checkable=True,
                             checked=self.show_advanced)
        advanced.setLayout(QVBoxLayout())

        def set_group_visible(groupbox, state):
            layout = groupbox.layout()
            for i in range(layout.count()):
                item = layout.itemAt(i)
                widget = item.widget()
                if widget is not None:
                    widget.setVisible(state)
            groupbox.setFlat(not state)

        def toogle_advanced(state):
            self.show_advanced = state
            set_group_visible(advanced, state)
            self.layout().activate()
            QApplication.instance().processEvents()
            QTimer.singleShot(0, self.adjustSize)

        advanced.toggled.connect(toogle_advanced)

        self.taboptions = QWidget()
        self.taboptions.setLayout(QVBoxLayout())
        box = QGroupBox("Missing Value Symbols", flat=True)
        form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow)
        form.addRow(
            "Don't care:",
            OWGUI.lineEdit(None,
                           self,
                           "symbol_DC",
                           tooltip="Default values: '~' or '*'"))
        form.addRow(
            "Don't know:",
            OWGUI.lineEdit(None,
                           self,
                           "symbol_DK",
                           tooltip="Default values: empty fields (space), "
                           "'?' or 'NA'"))
        box.setLayout(form)
        advanced.layout().addWidget(box)

        rb = OWGUI.radioButtonsInBox(
            advanced,
            self,
            "create_new_on",
            box="New Attributes",
            callback=self._invalidate,
            label=u"Create a new attribute when existing attribute(s) …",
            btnLabels=[
                u"Have mismatching order of values",
                u"Have no common values with the new (recommended)",
                u"Miss some values of the new attribute",
                u"… Always create a new attribute"
            ])
        rb.setFlat(True)
        self.controlArea.layout().addWidget(advanced)

        button_box = QDialogButtonBox(orientation=Qt.Horizontal)
        self.import_options_button = QPushButton(u"Import Options…",
                                                 enabled=False)
        self.import_options_button.pressed.connect(
            self._activate_import_dialog)
        button_box.addButton(self.import_options_button,
                             QDialogButtonBox.ActionRole)
        button_box.addButton(
            QPushButton("&Report", pressed=self.reportAndFinish),
            QDialogButtonBox.ActionRole)
        self.controlArea.layout().addWidget(button_box)

        OWGUI.rubber(self.controlArea)

        set_group_visible(advanced, self.show_advanced)

        if self.recent_files and self.recent_files[0] == self.selected_file:
            QTimer.singleShot(0, lambda: self.activate_recent(0))
        else:
            self.selected_file = None
            self.recent_combo.setCurrentIndex(-1)
Esempio n. 4
0
    def __init__(self, parent=None, signalManager=None,
                 title="CSV File Import"):
        OWWidget.__init__(self, parent, signalManager, title,
                          wantMainArea=False, noReport=True)

        self.symbol_DC = ""
        self.symbol_DK = ""

        #: List of recent opened files.
        self.recent_files = []
        #: Current selected file name
        self.selected_file = None
        #: Variable reuse flag
        self.create_new_on = 2
        #: Display advanced var reuse options
        self.show_advanced = False

        self.loadSettings()

        self.recent_files = filter(os.path.exists, self.recent_files)

        self._loader = None
        self._invalidated = False
        self._datareport = None

        layout = QHBoxLayout()
        OWGUI.widgetBox(self.controlArea, "File", orientation=layout)

        icons = standard_icons(self)

        self.recent_combo = QComboBox(
            self, objectName="recent_combo",
            toolTip="Recent files.",
            activated=self.activate_recent
        )
        cb_append_file_list(self.recent_combo, self.recent_files)

        self.recent_combo.insertSeparator(self.recent_combo.count())
        self.recent_combo.addItem(u"Browse documentation data sets…")

        self.browse_button = QPushButton(
            u"…",
            icon=icons.dir_open_icon, toolTip="Browse filesystem",
            clicked=self.browse
        )

        self.reload_button = QPushButton(
            "Reload", icon=icons.reload_icon,
            toolTip="Reload the selected file", clicked=self.reload,
            default=True
        )

        layout.addWidget(self.recent_combo, 2)
        layout.addWidget(self.browse_button)
        layout.addWidget(self.reload_button)

        ###########
        # Info text
        ###########
        box = OWGUI.widgetBox(self.controlArea, "Info", addSpace=True)
        self.infoa = OWGUI.widgetLabel(box, "No data loaded.")
        self.infob = OWGUI.widgetLabel(box, " ")
        self.warnings = OWGUI.widgetLabel(box, " ")

        # Set word wrap so long warnings won't expand the widget
        self.warnings.setWordWrap(True)
        self.warnings.setSizePolicy(QSizePolicy.Ignored,
                                    QSizePolicy.MinimumExpanding)

        advanced = QGroupBox(
            "Advanced Settings", checkable=True, checked=self.show_advanced
        )
        advanced.setLayout(QVBoxLayout())

        def set_group_visible(groupbox, state):
            layout = groupbox.layout()
            for i in range(layout.count()):
                item = layout.itemAt(i)
                widget = item.widget()
                if widget is not None:
                    widget.setVisible(state)
            groupbox.setFlat(not state)

        def toogle_advanced(state):
            self.show_advanced = state
            set_group_visible(advanced, state)
            self.layout().activate()
            QApplication.instance().processEvents()
            QTimer.singleShot(0, self.adjustSize)

        advanced.toggled.connect(toogle_advanced)

        self.taboptions = QWidget()
        self.taboptions.setLayout(QVBoxLayout())
        box = QGroupBox("Missing Value Symbols", flat=True)
        form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow)
        form.addRow(
            "Don't care:",
            OWGUI.lineEdit(None, self, "symbol_DC",
                           tooltip="Default values: '~' or '*'"))
        form.addRow(
            "Don't know:",
            OWGUI.lineEdit(None, self, "symbol_DK",
                           tooltip="Default values: empty fields (space), "
                                   "'?' or 'NA'"))
        box.setLayout(form)
        advanced.layout().addWidget(box)

        rb = OWGUI.radioButtonsInBox(
            advanced, self, "create_new_on",
            box="New Attributes",
            callback=self._invalidate,
            label=u"Create a new attribute when existing attribute(s) …",
            btnLabels=[u"Have mismatching order of values",
                       u"Have no common values with the new (recommended)",
                       u"Miss some values of the new attribute",
                       u"… Always create a new attribute"]
        )
        rb.setFlat(True)
        self.controlArea.layout().addWidget(advanced)

        button_box = QDialogButtonBox(orientation=Qt.Horizontal)
        self.import_options_button = QPushButton(
            u"Import Options…", enabled=False
        )
        self.import_options_button.pressed.connect(self._activate_import_dialog)
        button_box.addButton(
            self.import_options_button, QDialogButtonBox.ActionRole
        )
        button_box.addButton(
            QPushButton("&Report", pressed=self.reportAndFinish),
            QDialogButtonBox.ActionRole
        )
        self.controlArea.layout().addWidget(button_box)

        OWGUI.rubber(self.controlArea)

        set_group_visible(advanced, self.show_advanced)

        if self.recent_files and self.recent_files[0] == self.selected_file:
            QTimer.singleShot(
                0, lambda: self.activate_recent(0)
            )
        else:
            self.selected_file = None
            self.recent_combo.setCurrentIndex(-1)
    def __init__(self, parent=None, signalManager=None):
        OWWidget.__init__(self,
                          parent,
                          signalManager,
                          'Hierarchical Clustering',
                          wantGraph=True)

        self.inputs = [("Distances", Orange.misc.SymMatrix, self.set_matrix)]

        self.outputs = [("Selected Data", Orange.data.Table),
                        ("Other Data", Orange.data.Table),
                        ("Centroids", Orange.data.Table)]

        self.linkage = [
            ("Single linkage", hierarchical.HierarchicalClustering.Single),
            ("Average linkage", hierarchical.HierarchicalClustering.Average),
            ("Ward's linkage", hierarchical.HierarchicalClustering.Ward),
            ("Complete linkage", hierarchical.HierarchicalClustering.Complete),
        ]

        self.Linkage = 3
        self.Annotation = 0
        self.PrintDepthCheck = 0
        self.PrintDepth = 10
        # initial horizontal and vertical dendrogram size
        self.HDSize = 500
        self.VDSize = 800
        self.ManualHorSize = 0
        self.AutoResize = 0
        self.TextSize = 8
        self.LineSpacing = 4
        self.SelectionMode = 0
        self.AppendClusters = 0
        self.CommitOnChange = 0
        self.ClassifyName = "HC_class"
        self.addIdAs = 0

        self.loadSettings()

        self.inputMatrix = None
        self.root_cluster = None
        self.selectedExamples = None

        self.selectionChanged = False

        self.linkageMethods = [a[0] for a in self.linkage]

        #################################
        ##GUI
        #################################

        #HC Settings
        OWGUI.comboBox(self.controlArea,
                       self,
                       "Linkage",
                       box="Linkage",
                       items=self.linkageMethods,
                       tooltip="Choose linkage method",
                       callback=self.run_clustering,
                       addSpace=True)
        #Label
        box = OWGUI.widgetBox(self.controlArea, "Annotation", addSpace=True)
        self.labelCombo = OWGUI.comboBox(box,
                                         self,
                                         "Annotation",
                                         items=["None"],
                                         tooltip="Choose label attribute",
                                         callback=self.update_labels)

        OWGUI.spin(box,
                   self,
                   "TextSize",
                   label="Text size",
                   min=5,
                   max=15,
                   step=1,
                   callback=self.update_font,
                   controlWidth=40,
                   keyboardTracking=False)

        # Dendrogram graphics settings
        dendrogramBox = OWGUI.widgetBox(self.controlArea,
                                        "Limits",
                                        addSpace=True)

        form = QFormLayout()
        form.setLabelAlignment(Qt.AlignLeft)

        # Depth settings
        sw = OWGUI.widgetBox(dendrogramBox,
                             orientation="horizontal",
                             addToLayout=False)
        cw = OWGUI.widgetBox(dendrogramBox,
                             orientation="horizontal",
                             addToLayout=False)

        OWGUI.hSlider(sw,
                      self,
                      "PrintDepth",
                      minValue=1,
                      maxValue=50,
                      callback=self.on_depth_change)

        cblp = OWGUI.checkBox(cw,
                              self,
                              "PrintDepthCheck",
                              "Show to depth",
                              callback=self.on_depth_change,
                              disables=[sw])
        form.addRow(cw, sw)

        checkWidth = OWGUI.checkButtonOffsetHint(cblp)

        # Width settings
        sw = OWGUI.widgetBox(dendrogramBox,
                             orientation="horizontal",
                             addToLayout=False)
        cw = OWGUI.widgetBox(dendrogramBox,
                             orientation="horizontal",
                             addToLayout=False)

        hsb = OWGUI.spin(sw,
                         self,
                         "HDSize",
                         min=200,
                         max=10000,
                         step=10,
                         callback=self.on_width_changed,
                         callbackOnReturn=False,
                         keyboardTracking=False)

        OWGUI.checkBox(cw,
                       self,
                       "ManualHorSize",
                       "Horizontal size",
                       callback=self.on_width_changed,
                       disables=[sw])

        sw.setEnabled(self.ManualHorSize)

        self.hSizeBox = hsb
        form.addRow(cw, sw)
        dendrogramBox.layout().addLayout(form)

        # Selection settings
        box = OWGUI.widgetBox(self.controlArea, "Selection")
        OWGUI.checkBox(box,
                       self,
                       "SelectionMode",
                       "Show cutoff line",
                       callback=self.update_cutoff_line)

        cb = OWGUI.checkBox(box,
                            self,
                            "AppendClusters",
                            "Append cluster IDs",
                            callback=self.commit_data_if)

        self.classificationBox = ib = OWGUI.widgetBox(box, margin=0)

        form = QWidget()
        le = OWGUI.lineEdit(form,
                            self,
                            "ClassifyName",
                            None,
                            callback=None,
                            orientation="horizontal")
        self.connect(le, SIGNAL("editingFinished()"), self.commit_data_if)

        aa = OWGUI.comboBox(
            form,
            self,
            "addIdAs",
            label=None,
            orientation="horizontal",
            items=["Class attribute", "Attribute", "Meta attribute"],
            callback=self.commit_data_if)

        layout = QFormLayout()
        layout.setSpacing(8)
        layout.setContentsMargins(0, 5, 0, 5)
        layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
        layout.setLabelAlignment(Qt.AlignLeft)
        layout.addRow("Name  ", le)
        layout.addRow("Place  ", aa)

        form.setLayout(layout)

        ib.layout().addWidget(form)
        ib.layout().setContentsMargins(checkWidth, 5, 5, 5)

        cb.disables.append(ib)
        cb.makeConsistent()

        OWGUI.separator(box)
        cbAuto = OWGUI.checkBox(box, self, "CommitOnChange",
                                "Commit on change")
        btCommit = OWGUI.button(box,
                                self,
                                "&Commit",
                                self.commit_data,
                                default=True)
        OWGUI.setStopper(self, btCommit, cbAuto, "selectionChanged",
                         self.commit_data)

        OWGUI.rubber(self.controlArea)
        self.connect(self.graphButton, SIGNAL("clicked()"), self.saveGraph)

        self.scale_scene = scale = ScaleScene(self, self)
        self.headerView = ScaleView(scale, self)
        self.footerView = ScaleView(scale, self)

        self.dendrogram = DendrogramScene(self)
        self.dendrogramView = DendrogramView(self.dendrogram, self.mainArea)

        self.connect(self.dendrogram, SIGNAL("clusterSelectionChanged()"),
                     self.on_selection_change)

        self.connect(self.dendrogram, SIGNAL("sceneRectChanged(QRectF)"),
                     scale.scene_rect_update)

        self.connect(self.dendrogram,
                     SIGNAL("dendrogramGeometryChanged(QRectF)"),
                     self.on_dendrogram_geometry_change)

        self.connect(self.dendrogram, SIGNAL("cutoffValueChanged(float)"),
                     self.on_cuttof_value_changed)

        self.connect(self.dendrogramView, SIGNAL("viewportResized(QSize)"),
                     self.on_width_changed)

        self.connect(self.dendrogramView,
                     SIGNAL("transformChanged(QTransform)"),
                     self.headerView.setTransform)
        self.connect(self.dendrogramView,
                     SIGNAL("transformChanged(QTransform)"),
                     self.footerView.setTransform)

        self.mainArea.layout().addWidget(self.headerView)
        self.mainArea.layout().addWidget(self.dendrogramView)
        self.mainArea.layout().addWidget(self.footerView)

        self.dendrogram.header = self.headerView
        self.dendrogram.footer = self.footerView

        self.connect(self.dendrogramView.horizontalScrollBar(),
                     SIGNAL("valueChanged(int)"),
                     self.footerView.horizontalScrollBar().setValue)

        self.connect(self.dendrogramView.horizontalScrollBar(),
                     SIGNAL("valueChanged(int)"),
                     self.headerView.horizontalScrollBar().setValue)

        self.dendrogram.setSceneRect(0, 0, self.HDSize, self.VDSize)
        self.dendrogram.update()
        self.resize(800, 500)

        self.natural_dendrogram_width = 800
        self.dendrogramView.set_fit_to_width(not self.ManualHorSize)

        self.matrix = None
        self.selectionList = []
        self.selected_clusters = []
    def __init__(self, parent=None, signalManager=None):
        OWWidget.__init__(self, parent, signalManager,
                          'Hierarchical Clustering', wantGraph=True)

        self.inputs = [("Distances", Orange.misc.SymMatrix, self.set_matrix)]

        self.outputs = [("Selected Data", Orange.data.Table),
                        ("Other Data", Orange.data.Table),
                        ("Centroids", Orange.data.Table)]

        self.linkage = [
            ("Single linkage", hierarchical.HierarchicalClustering.Single),
            ("Average linkage", hierarchical.HierarchicalClustering.Average),
            ("Ward's linkage", hierarchical.HierarchicalClustering.Ward),
            ("Complete linkage", hierarchical.HierarchicalClustering.Complete),
        ]

        self.Linkage = 3
        self.Annotation = 0
        self.PrintDepthCheck = 0
        self.PrintDepth = 10
        # initial horizontal and vertical dendrogram size
        self.HDSize = 500
        self.VDSize = 800
        self.ManualHorSize = 0
        self.AutoResize = 0
        self.TextSize = 8
        self.LineSpacing = 4
        self.SelectionMode = 0
        self.AppendClusters = 0
        self.CommitOnChange = 0
        self.ClassifyName = "HC_class"
        self.addIdAs = 0

        self.loadSettings()

        self.inputMatrix = None
        self.root_cluster = None
        self.selectedExamples = None

        self.selectionChanged = False

        self.linkageMethods = [a[0] for a in self.linkage]

        #################################
        ##GUI
        #################################

        #HC Settings
        OWGUI.comboBox(self.controlArea, self, "Linkage", box="Linkage",
                       items=self.linkageMethods,
                       tooltip="Choose linkage method",
                       callback=self.run_clustering,
                       addSpace=True)
        #Label
        box = OWGUI.widgetBox(self.controlArea, "Annotation", addSpace=True)
        self.labelCombo = OWGUI.comboBox(
            box, self, "Annotation",
            items=["None"],
            tooltip="Choose label attribute",
            callback=self.update_labels
        )

        OWGUI.spin(box, self, "TextSize", label="Text size",
                   min=5, max=15, step=1,
                   callback=self.update_font,
                   controlWidth=40,
                   keyboardTracking=False)

        # Dendrogram graphics settings
        dendrogramBox = OWGUI.widgetBox(self.controlArea, "Limits",
                                        addSpace=True)

        form = QFormLayout()
        form.setLabelAlignment(Qt.AlignLeft)

        # Depth settings
        sw = OWGUI.widgetBox(dendrogramBox, orientation="horizontal",
                             addToLayout=False)
        cw = OWGUI.widgetBox(dendrogramBox, orientation="horizontal",
                             addToLayout=False)

        OWGUI.hSlider(sw, self, "PrintDepth", minValue=1, maxValue=50,
                      callback=self.on_depth_change)

        cblp = OWGUI.checkBox(cw, self, "PrintDepthCheck", "Show to depth",
                              callback=self.on_depth_change,
                              disables=[sw])
        form.addRow(cw, sw)

        checkWidth = OWGUI.checkButtonOffsetHint(cblp)

        # Width settings
        sw = OWGUI.widgetBox(dendrogramBox, orientation="horizontal",
                             addToLayout=False)
        cw = OWGUI.widgetBox(dendrogramBox, orientation="horizontal",
                             addToLayout=False)

        hsb = OWGUI.spin(sw, self, "HDSize", min=200, max=10000, step=10,
                         callback=self.on_width_changed,
                         callbackOnReturn=False,
                         keyboardTracking=False)

        OWGUI.checkBox(cw, self, "ManualHorSize", "Horizontal size",
                       callback=self.on_width_changed,
                       disables=[sw])

        sw.setEnabled(self.ManualHorSize)

        self.hSizeBox = hsb
        form.addRow(cw, sw)
        dendrogramBox.layout().addLayout(form)

        # Selection settings
        box = OWGUI.widgetBox(self.controlArea, "Selection")
        OWGUI.checkBox(box, self, "SelectionMode", "Show cutoff line",
                       callback=self.update_cutoff_line)

        cb = OWGUI.checkBox(box, self, "AppendClusters", "Append cluster IDs",
                            callback=self.commit_data_if)

        self.classificationBox = ib = OWGUI.widgetBox(box, margin=0)

        form = QWidget()
        le = OWGUI.lineEdit(form, self, "ClassifyName", None, callback=None,
                            orientation="horizontal")
        self.connect(le, SIGNAL("editingFinished()"), self.commit_data_if)

        aa = OWGUI.comboBox(form, self, "addIdAs", label=None,
                            orientation="horizontal",
                            items=["Class attribute",
                                   "Attribute",
                                   "Meta attribute"],
                            callback=self.commit_data_if)

        layout = QFormLayout()
        layout.setSpacing(8)
        layout.setContentsMargins(0, 5, 0, 5)
        layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
        layout.setLabelAlignment(Qt.AlignLeft)
        layout.addRow("Name  ", le)
        layout.addRow("Place  ", aa)

        form.setLayout(layout)

        ib.layout().addWidget(form)
        ib.layout().setContentsMargins(checkWidth, 5, 5, 5)

        cb.disables.append(ib)
        cb.makeConsistent()

        OWGUI.separator(box)
        cbAuto = OWGUI.checkBox(box, self, "CommitOnChange",
                                "Commit on change")
        btCommit = OWGUI.button(box, self, "&Commit", self.commit_data,
                                default=True)
        OWGUI.setStopper(self, btCommit, cbAuto, "selectionChanged",
                         self.commit_data)

        OWGUI.rubber(self.controlArea)
        self.connect(self.graphButton, SIGNAL("clicked()"), self.saveGraph)

        self.scale_scene = scale = ScaleScene(self, self)
        self.headerView = ScaleView(scale, self)
        self.footerView = ScaleView(scale, self)

        self.dendrogram = DendrogramScene(self)
        self.dendrogramView = DendrogramView(self.dendrogram, self.mainArea)

        self.connect(self.dendrogram,
                     SIGNAL("clusterSelectionChanged()"),
                     self.on_selection_change)

        self.connect(self.dendrogram,
                     SIGNAL("sceneRectChanged(QRectF)"),
                     scale.scene_rect_update)

        self.connect(self.dendrogram,
                     SIGNAL("dendrogramGeometryChanged(QRectF)"),
                     self.on_dendrogram_geometry_change)

        self.connect(self.dendrogram,
                     SIGNAL("cutoffValueChanged(float)"),
                     self.on_cuttof_value_changed)

        self.connect(self.dendrogramView,
                     SIGNAL("viewportResized(QSize)"),
                     self.on_width_changed)

        self.connect(self.dendrogramView,
                     SIGNAL("transformChanged(QTransform)"),
                     self.headerView.setTransform)
        self.connect(self.dendrogramView,
                     SIGNAL("transformChanged(QTransform)"),
                     self.footerView.setTransform)

        self.mainArea.layout().addWidget(self.headerView)
        self.mainArea.layout().addWidget(self.dendrogramView)
        self.mainArea.layout().addWidget(self.footerView)

        self.dendrogram.header = self.headerView
        self.dendrogram.footer = self.footerView

        self.connect(self.dendrogramView.horizontalScrollBar(),
                     SIGNAL("valueChanged(int)"),
                     self.footerView.horizontalScrollBar().setValue)

        self.connect(self.dendrogramView.horizontalScrollBar(),
                     SIGNAL("valueChanged(int)"),
                     self.headerView.horizontalScrollBar().setValue)

        self.dendrogram.setSceneRect(0, 0, self.HDSize, self.VDSize)
        self.dendrogram.update()
        self.resize(800, 500)

        self.natural_dendrogram_width = 800
        self.dendrogramView.set_fit_to_width(not self.ManualHorSize)

        self.matrix = None
        self.selectionList = []
        self.selected_clusters = []
Esempio n. 7
0
 def getSettings(self, *args, **kwargs):
     self._storeRoles()
     return OWWidget.getSettings(self, *args, **kwargs)
 def hideEvent(self, ev):
     self.stopRandomTouring()        # if we were touring then stop
     self.saveSettings()
     OWWidget.hideEvent(self, ev)
    def __init__(self, parentWidget = None, signalManager = None, graph = None, parentName = "Visualization widget"):
        OWWidget.__init__(self, None, signalManager, "FreeViz Dialog", savePosition = True, wantMainArea = 0, wantStatusBar = 1)
        FreeViz.__init__(self, graph)

        self.parentWidget = parentWidget
        self.parentName = parentName
        self.setCaption("FreeViz Optimization Dialog")
        self.cancelOptimization = 0
        self.forceRelation = 5
        self.disableAttractive = 0
        self.disableRepulsive = 0
        self.touringSpeed = 4
        self.graph = graph

        if self.graph:
            self.graph.hideRadius = 0
            self.graph.showAnchors = 1

        # differential evolution
        self.differentialEvolutionPopSize = 100
        self.DERadvizSolver = None

        self.loadSettings()

        self.layout().setMargin(0)
        self.tabs = OWGUI.tabWidget(self.controlArea)
        self.MainTab = OWGUI.createTabPage(self.tabs, "Main")
        self.ProjectionsTab = OWGUI.createTabPage(self.tabs, "Projections")

        # ###########################
        # MAIN TAB
        OWGUI.comboBox(self.MainTab, self, "implementation", box = "FreeViz implementation", items = ["Fast (C) implementation", "Slow (Python) implementation", "LDA"])

        box = OWGUI.widgetBox(self.MainTab, "Optimization")

        self.optimizeButton = OWGUI.button(box, self, "Optimize Separation", callback = self.optimizeSeparation)
        self.stopButton = OWGUI.button(box, self, "Stop Optimization", callback = self.stopOptimization)
        self.singleStepButton = OWGUI.button(box, self, "Single Step", callback = self.singleStepOptimization)
        f = self.optimizeButton.font(); f.setBold(1)
        self.optimizeButton.setFont(f)
        self.stopButton.setFont(f); self.stopButton.hide()
        self.attrKNeighboursCombo = OWGUI.comboBoxWithCaption(box, self, "stepsBeforeUpdate", "Number of steps before updating graph: ", tooltip = "Set the number of optimization steps that will be executed before the updated anchor positions will be visualized", items = [1, 3, 5, 10, 15, 20, 30, 50, 75, 100, 150, 200, 300], sendSelectedValue = 1, valueType = int)
        OWGUI.checkBox(box, self, "mirrorSymmetry", "Keep mirror symmetry", tooltip = "'Rotational' keeps the second anchor upside")

        vbox = OWGUI.widgetBox(self.MainTab, "Set anchor positions")
        hbox1 = OWGUI.widgetBox(vbox, orientation = "horizontal")
        OWGUI.button(hbox1, self, "Sphere" if "3d" in self.parentName.lower() else "Circle", callback = self.radialAnchors)
        OWGUI.button(hbox1, self, "Random", callback = self.randomAnchors)
        self.manualPositioningButton = OWGUI.button(hbox1, self, "Manual", callback = self.setManualPosition)
        self.manualPositioningButton.setCheckable(1)
        OWGUI.comboBox(vbox, self, "restrain", label="Restrain anchors:", orientation = "horizontal", items = ["Unrestrained", "Fixed Length", "Fixed Angle"], callback = self.setRestraints)

        box2 = OWGUI.widgetBox(self.MainTab, "Forces", orientation = "vertical")

        self.cbLaw = OWGUI.comboBox(box2, self, "law", label="Law", labelWidth = 40, orientation="horizontal", items=["Linear", "Square", "Gaussian", "KNN", "Variance"], callback = self.forceLawChanged)

        hbox2 = OWGUI.widgetBox(box2, orientation = "horizontal")
        hbox2.layout().addSpacing(10)

        validSigma = QDoubleValidator(self); validSigma.setBottom(0.01)
        self.spinSigma = OWGUI.lineEdit(hbox2, self, "forceSigma", label = "Kernel width (sigma) ", labelWidth = 110, orientation = "horizontal", valueType = float)
        self.spinSigma.setFixedSize(60, self.spinSigma.sizeHint().height())
        self.spinSigma.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed))

        box2.layout().addSpacing(20)

        self.cbforcerel = OWGUI.comboBox(box2, self, "forceRelation", label= "Attractive : Repulsive  ",orientation = "horizontal", items=self.forceRelValues, callback = self.updateForces)
        self.cbforcebal = OWGUI.checkBox(box2, self, "forceBalancing", "Dynamic force balancing", tooltip="Normalize the forces so that the total sums of the\nrepulsive and attractive are in the above proportion.")

        box2.layout().addSpacing(20)

        self.cbDisableAttractive = OWGUI.checkBox(box2, self, "disableAttractive", "Disable attractive forces", callback = self.setDisableAttractive)
        self.cbDisableRepulsive = OWGUI.checkBox(box2, self, "disableRepulsive", "Disable repulsive forces", callback = self.setDisableRepulsive)

        box = OWGUI.widgetBox(self.MainTab, "Show anchors")
        OWGUI.checkBox(box, self, 'graph.showAnchors', 'Show attribute anchors', callback = self.parentWidget.updateGraph)
        OWGUI.qwtHSlider(box, self, "graph.hideRadius", label="Hide radius", minValue=0, maxValue=9, step=1, ticks=0, callback = self.parentWidget.updateGraph)
        self.freeAttributesButton = OWGUI.button(box, self, "Remove hidden attributes", callback = self.removeHidden)

        if parentName.lower() != "radviz" and parentName.lower() != "sphereviz":
            pcaBox = OWGUI.widgetBox(self.ProjectionsTab, "Principal Component Analysis")
            OWGUI.button(pcaBox, self, "Principal component analysis", callback = self.findPCAProjection)
            OWGUI.button(pcaBox, self, "Supervised principal component analysis", callback = self.findSPCAProjection)
            OWGUI.checkBox(pcaBox, self, "useGeneralizedEigenvectors", "Merge examples with same class value")
            plsBox = OWGUI.widgetBox(self.ProjectionsTab, "Partial Least Squares")
            OWGUI.button(plsBox, self, "Partial least squares", callback = self.findPLSProjection)
        
        box = OWGUI.widgetBox(self.ProjectionsTab, "Projection Tours")
        self.startTourButton = OWGUI.button(box, self, "Start Random Touring", callback = self.startRandomTouring)
        self.stopTourButton = OWGUI.button(box, self, "Stop Touring", callback = self.stopRandomTouring)
        self.stopTourButton.hide()
        OWGUI.hSlider(box, self, 'touringSpeed', label = "Speed:  ", minValue=1, maxValue=10, step=1)
        OWGUI.rubber(self.ProjectionsTab)
        
        box = OWGUI.widgetBox(self.ProjectionsTab, "Signal to Noise Heuristic")
        #OWGUI.comboBoxWithCaption(box, self, "s2nSpread", "Anchor spread: ", tooltip = "Are the anchors for each class value placed together or are they distributed along the circle", items = range(11), callback = self.s2nMixAnchors)
        box2 = OWGUI.widgetBox(box, 0, orientation = "horizontal")
        OWGUI.widgetLabel(box2, "Anchor spread:           ")
        OWGUI.hSlider(box2, self, 's2nSpread', minValue=0, maxValue=10, step=1, callback = self.s2nMixAnchors, labelFormat="  %d", ticks=0)
        OWGUI.comboBoxWithCaption(box, self, "s2nPlaceAttributes", "Attributes to place: ", tooltip = "Set the number of top ranked attributes to place. You can select a higher value than the actual number of attributes", items = self.attrsNum, callback = self.s2nMixAnchors, sendSelectedValue = 1, valueType = int)
        OWGUI.checkBox(box, self, 'autoSetParameters', 'Automatically find optimal parameters')
        self.s2nMixButton = OWGUI.button(box, self, "Place anchors", callback = self.s2nMixAnchorsAutoSet)


        self.forceLawChanged()
        self.updateForces()
        self.cbforcebal.setDisabled(self.cbDisableAttractive.isChecked() or self.cbDisableRepulsive.isChecked())
        self.resize(320,650)