Miha Stajdohar avatar Miha Stajdohar committed 3ea3e3d Merge

Merged.

Comments (0)

Files changed (9)

Orange/OrangeCanvas/orngCanvasItems.py

     else:
         return None
     
-def setDropShadow(self):
+def setDropShadow(self, offset=QPointF(0.3, 0.5), blur_radius=5):
     if qVersion() >= "4.6" and self.canvasDlg.settings["enableCanvasDropShadows"]:
         effect = QGraphicsDropShadowEffect(self.scene())
-        effect.setOffset(QPointF(0.3, 0.5))
-        effect.setBlurRadius(5)
+        effect.setOffset(offset)
+        effect.setBlurRadius(blur_radius)
         self.setGraphicsEffect(effect)
     
 class TempCanvasLine(QGraphicsPathItem):
 
         self.setPen(QPen(QColor(180, 180, 180), 3, Qt.SolidLine))
         
-        self.setDropShadow()
+        self.setDropShadow(offset=QPointF(0.0, 0.0))
     
     setDropShadow = setDropShadow
     getDropShadow = getDropShadow
             
         QObject.connect(self.outWidget.instance, SIGNAL("dynamicLinkEnabledChanged(PyQt_PyObject, bool)"), self.updateDynamicEnableState)
         
-        self.setDropShadow()
+        self.setDropShadow(offset=QPointF(0.0, 0.0))
         
     setDropShadow = setDropShadow
     getDropShadow = getDropShadow

Orange/OrangeCanvas/orngView.py

 
     def unselectAllWidgets(self):
         for item in self.doc.widgets:
-            item.setSelected(0)
+            item.setSelected(False)
+            
+    def selectAllWidgets(self):
+        for item in self.doc.widgets:
+            item.setSelected(True)
 
     def getItemsAtPos(self, pos, itemType = None):
         if isinstance(pos, QGraphicsItem):
             self.tempWidget = None
             rect = self.maxSelectionRect(QRectF(self.mouseDownPosition, self.mouseDownPosition))
             self.widgetSelectionRect = QGraphicsRectItem(rect, None, self.scene())
-            self.widgetSelectionRect.setPen(QPen(QBrush(QColor(51, 153, 255, 192)), 1, Qt.SolidLine, Qt.RoundCap))
+            self.widgetSelectionRect.setPen(QPen(QBrush(QColor(51, 153, 255, 192)), 0.4, Qt.SolidLine, Qt.RoundCap))
             self.widgetSelectionRect.setBrush(QBrush(QColor(168, 202, 236, 192)))
             self.widgetSelectionRect.setZValue(-100)
             self.widgetSelectionRect.show()
 
         # we clicked on a widget or on a line
         else:
-            if type(activeItem) == orngCanvasItems.CanvasWidget:        # if we clicked on a widget
+            if type(activeItem) == orngCanvasItems.CanvasWidget:
+                # if we clicked on a widget
                 self.tempWidget = activeItem
 
                 if ev.button() == Qt.LeftButton:
                     self.bWidgetDragging = True
-                    if ev.modifiers() & Qt.ControlModifier: #self.doc.ctrlPressed:
+                    if ev.modifiers() & Qt.ControlModifier:
                         activeItem.setSelected(not activeItem.isSelected())
                     elif activeItem.isSelected() == 0:
                         self.unselectAllWidgets()
                         self.unselectAllWidgets() 
                     activeItem.setSelected(True)
                     self.doc.canvasDlg.widgetPopup.popup(ev.globalPos())
-                    return # Don't call QGraphicsView.mousePressEvent. It unselects the active item
                 else:
                     self.unselectAllWidgets()
+                return # Don't call QGraphicsView.mousePressEvent. It unselects the active item
 
             # if we right clicked on a line we show a popup menu
             elif type(activeItem) == orngCanvasItems.CanvasLine and ev.button() == Qt.RightButton:
         minGeom = self.mapToScene(QRect(QPoint(0, 0), minSize)).boundingRect()
         sceneRect = minGeom.united(b_rect)
         return rect.intersected(sceneRect).adjusted(penWidth, penWidth, -penWidth, -penWidth)
-#        
-#    def resizeEvent(self, event):
-#        self.updateSceneRect()
 
+    def keyPressEvent(self, event):
+        if event == QKeySequence.SelectAll:
+            self.selectAllWidgets()
+        else:
+            return QGraphicsView.keyPressEvent(self, event)

Orange/OrangeWidgets/Classify/OWSVM.py

                              0, 0, Qt.AlignLeft)
         
         b.layout().addWidget(QLabel("Cost (C)", b), 0, 1, Qt.AlignRight)
-        b.layout().addWidget(OWGUI.doubleSpin(b, self, "C", 0.5, 512.0, 0.5, 
-                                addToLayout=False, 
-                                callback=lambda *x: self.setType(0), 
+        b.layout().addWidget(OWGUI.doubleSpin(b, self, "C", 0.1, 512.0, 0.1,
+                                decimals=2,
+                                addToLayout=False,
+                                callback=lambda *x: self.setType(0),
                                 alignment=Qt.AlignRight,
                                 tooltip= "Cost for a mis-classified training instance."),
                              0, 2)
         
-        b.layout().addWidget(OWGUI.appendRadioButton(b, self, "useNu", u"ν-SVM", 
+        b.layout().addWidget(OWGUI.appendRadioButton(b, self, "useNu", u"ν-SVM",
                                                      addToLayout=False),
                              1, 0, Qt.AlignLeft)
-        
+
         b.layout().addWidget(QLabel(u"Complexity bound (\u03bd)", b), 1, 1, Qt.AlignRight)
-        b.layout().addWidget(OWGUI.doubleSpin(b, self, "nu", 0.1, 1.0, 0.1, 
+        b.layout().addWidget(OWGUI.doubleSpin(b, self, "nu", 0.05, 1.0, 0.05,
                                 tooltip="Lower bound on the ratio of support vectors",
-                                addToLayout=False, 
+                                addToLayout=False,
                                 callback=lambda *x: self.setType(1),
                                 alignment=Qt.AlignRight),
                              1, 2)
         OWGUI.separator(b)
         self.gcd = OWGUI.widgetBox(b, orientation="horizontal")
         self.leg = OWGUI.doubleSpin(self.gcd, self, "gamma",0.0,10.0,0.0001,
+                                decimals=5,
                                 label="  g: ",
                                 orientation="horizontal",
                                 callback=self.changeKernel,
         if self.kernel_type==1:
             params.append("degree")
         try:
-            learner.tuneParameters(self.data, params, 4, verbose=0, progressCallback=self.progres)
+            learner.tuneParameters(self.data, params, 4, verbose=0,
+                                   progressCallback=self.progres)
         except UnhandledException:
             pass
         for param in params:

Orange/OrangeWidgets/Data/OWEditDomain.py

         vlayout.setSpacing(1)
         
         self.labels_edit = QTreeView()
-        self.labels_edit.setEditTriggers(QTreeView.DoubleClicked | \
-                                         QTreeView.EditKeyPressed)
+        self.labels_edit.setEditTriggers(QTreeView.CurrentChanged)
         self.labels_edit.setRootIsDecorated(False)
         
         self.labels_model = DictItemsModel()
         
     def _setup_gui_values(self):
         self.values_edit = QListView()
-        self.values_edit.setEditTriggers(QListView.DoubleClicked | \
-                                         QListView.EditKeyPressed)
+        self.values_edit.setEditTriggers(QTreeView.CurrentChanged)
         self.values_model = PyListModel(flags=Qt.ItemIsSelectable | \
                                         Qt.ItemIsEnabled | Qt.ItemIsEditable)
         self.values_edit.setModel(self.values_model)

Orange/OrangeWidgets/Data/OWPaintData.py

         
         self.classValuesView = listView = QListView()
         listView.setSelectionMode(QListView.SingleSelection)
-        listView.setEditTriggers(QListView.SelectedClicked)
         
         self.classValuesModel = EnumVariableModel(self.classVariable, self, flags=Qt.ItemIsSelectable | Qt.ItemIsEnabled| Qt.ItemIsEditable)
         self.classValuesModel.wrap(self.classVariable.values)

Orange/OrangeWidgets/Data/OWPythonScript.py

         self.controlBox = OWGUI.widgetBox(self.controlArea, 'Library')
         self.controlBox.layout().setSpacing(1)
         self.libraryView = QListView()
-        self.libraryView.pyqtConfigure(editTriggers=QListView.DoubleClicked | QListView.SelectedClicked)
+        self.libraryView.setEditTriggers(QListView.DoubleClicked | QListView.EditKeyPressed)
         self.libraryView.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred)
         self.libraryView.setItemDelegate(ScriptItemDelegate(self))
         self.libraryView.setModel(self.libraryList)

Orange/OrangeWidgets/OWGUI.py

          box=None, label=None, labelWidth=None, orientation=None, tooltip=None,
          callback=None, debuggingEnabled = 1, controlWidth = None, callbackOnReturn = False,
          checked = "", checkCallback = None, posttext = None, addToLayout=True, alignment = Qt.AlignLeft,
-         keyboardTracking=True): #widget, master, value, min, max, step=1, box=None, label=None, labelWidth=None, orientation=None, tooltip=None, callback=None, controlWidth=None):
+         keyboardTracking=True, decimals=None):
     if box or label and not checked:
         b = widgetBox(widget, box, orientation)
         hasHBox = orientation == 'horizontal' or not orientation
 
 
     wa = bi.control = DoubleSpinBoxWFocusOut(min, max, step, bi)
+
+    if decimals is not None:
+        wa.setDecimals(decimals)
+
     wa.setAlignment(alignment)
     wa.setKeyboardTracking(keyboardTracking) # If false it wont emit valueChanged signals while editing the text
     if addToLayout and bi.layout() is not None:

Orange/OrangeWidgets/OWItemModels.py

     yield
     object.blockSignals(blocked)
 
-    
+
 class PyListModel(QAbstractListModel):
     """ A model for displaying python list like objects in Qt item view classes
     """
     MIME_TYPES = ["application/x-Orange-PyListModelData"]
-    
+
     def __init__(self, iterable=[], parent=None,
                  flags=Qt.ItemIsSelectable | Qt.ItemIsEnabled,
                  list_item_role=Qt.DisplayRole,
         self._other_data = []
         self._flags = flags
         self.list_item_role = list_item_role
-        
+
         self._supportedDropActions = supportedDropActions
         self.extend(iterable)
-        
+
+    def _is_index_valid_for(self, index, list_like):
+        if isinstance(index, QModelIndex) and index.isValid() :
+            row, column = index.row(), index.column()
+            return row < len(list_like) and row >= 0 and column == 0
+        elif isinstance(index, int):
+            return index < len(list_like) and index > -len(self)
+        else:
+            return False
+
     def wrap(self, list):
         """ Wrap the list with this model. All changes to the model
         are done in place on the passed list
         self._list = list
         self._other_data = [_store() for _ in list]
         self.reset()
-    
+
     def index(self, row, column=0, parent=QModelIndex()):
-        return QAbstractListModel.createIndex(self, row, column, parent)
-    
+        if self._is_index_valid_for(row, self) and column == 0:
+            return QAbstractListModel.createIndex(self, row, column, parent)
+        else:
+            return QModelIndex()
+
     def headerData(self, section, orientation, role=Qt.DisplayRole):
         if role == Qt.DisplayRole:
             return QVariant(str(section))
-    
+
     def rowCount(self, parent=QModelIndex()):
         return 0 if parent.isValid() else len(self)
-    
+
     def columnCount(self, parent=QModelIndex()):
         return 0 if parent.isValid() else 1
-    
+
     def data(self, index, role=Qt.DisplayRole):
         row = index.row()
-        if role in [self.list_item_role, Qt.EditRole]:
-            return QVariant(self[index.row()])
+        if role in [self.list_item_role, Qt.EditRole] \
+                and self._is_index_valid_for(index, self):
+            return QVariant(self[row])
+        elif self._is_index_valid_for(row, self._other_data):
+            return QVariant(self._other_data[row].get(role, QVariant()))
         else:
-            return QVariant(self._other_data[index.row()].get(role, QVariant()))
-    
+            return QVariant()
+
     def itemData(self, index):
         map = QAbstractListModel.itemData(self, index)
-        for key, value in self._other_data[index.row()].items():
+        if self._is_index_valid_for(index, self._other_data):
+            items = self._other_data[index.row()].items()
+        else:
+            items = []
+
+        for key, value in items:
             map[key] = QVariant(value)
+
         return map
-    
+
     def parent(self, index=QModelIndex()):
         return QModelIndex()
-    
+
     def setData(self, index, value, role=Qt.EditRole):
-        if role == Qt.EditRole:
+        if role == Qt.EditRole and self._is_index_valid_for(index, self):
             obj = value.toPyObject()
-            self[index.row()] = obj
-        else:
+            self[index.row()] = obj # Will emit proper dataChanged signal
+            return True
+        elif self._is_index_valid_for(index, self._other_data):
             self._other_data[index.row()][role] = value
             self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), index, index)
-        return True
-        
+            return True
+        else:
+            return False
+
     def setItemData(self, index, data):
         data = dict(data)
         with signal_blocking(self):
             for role, value in data.items():
-                if role == Qt.EditRole:
+                if role == Qt.EditRole and \
+                        self._is_index_valid_for(index, self):
                     self[index.row()] = value.toPyObject()
-                else:
+                elif self._is_index_valid_for(index, self._other_data):
                     self._other_data[index.row()][role] = value
-                    
+
         self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), index, index)
         return True
-#        return QAbstractListModel.setItemData(self, index, data)
-    
+
     def flags(self, index):
-        if index.isValid() and index.row() < len(self._other_data):
+        if self._is_index_valid_for(index, self._other_data):
             return self._other_data[index.row()].get("flags", self._flags)
         else:
             return self._flags | Qt.ItemIsDropEnabled
-        
+
     def insertRows(self, row, count, parent=QModelIndex()):
         """ Insert ``count`` rows at ``row``, the list fill be filled 
         with ``None`` 
         """
-#        print "Insert", row, count
         if not parent.isValid():
             self.__setslice__(row, row, [None] * count)
             return True
         else:
             return False
-        
+
     def removeRows(self, row, count, parent=QModelIndex()):
+        """Remove ``count`` rows starting at ``row``
         """
-        """
-#        print "Remove", row, count
         if not parent.isValid():
             self.__delslice__(row, row + count)
             return True
         else:
             return False
-    
+
     def extend(self, iterable):
         list_ = list(iterable)
         self.beginInsertRows(QModelIndex(), len(self), len(self) + len(list_) - 1)
         self._list.extend(list_)
         self._other_data.extend([_store() for _ in list_])
         self.endInsertRows()
-    
+
     def append(self, item):
         self.extend([item])
-        
+
     def insert(self, i, val):
         self.beginInsertRows(QModelIndex(), i, i)
         self._list.insert(i, val)
         self._other_data.insert(i, _store())
         self.endInsertRows()
-        
+
     def remove(self, val):
         i = self._list.index(val)
         self.__delitem__(i)
-        
+
     def pop(self, i):
         item = self._list[i]
         self.__delitem__(i)
         return item
-    
+
     def __len__(self):
         return len(self._list)
-    
+
     def __iter__(self):
         return iter(self._list)
-    
+
     def __getitem__(self, i):
         return self._list[i]
-    
+
     def __getslice__(self, i, j):
         return self._list[i:j]
-        
+
     def __add__(self, iterable):
-        # Does not preserve flags or other data.
-        return PyListModel(self._list + iterable, self.parent())
-    
+        new_list = PyListModel(list(self._list), 
+                           self.parent(),
+                           flags=self._flags,
+                           list_item_role=self.list_item_role,
+                           supportedDropActions=self.supportedDropActions()
+                           )
+        new_list._other_data = list(self._other_data)
+        new_list.extend(iterable)
+        return new_list
+
     def __iadd__(self, iterable):
         self.extend(iterable)
-        
+
     def __delitem__(self, i):
         self.beginRemoveRows(QModelIndex(), i, i)
         del self._list[i]
         del self._other_data[i]
         self.endRemoveRows()
-        
+
     def __delslice__(self, i, j):
         if j > i:
             self.beginRemoveRows(QModelIndex(), i, j - 1)
             del self._list[i:j]
             del self._other_data[i:j]
             self.endRemoveRows()
-        
+
     def __setitem__(self, i, value):
         self._list[i] = value
         self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), self.index(i), self.index(i))
-        
+
     def __setslice__(self, i, j, iterable):
         self.__delslice__(i, j)
         all = list(iterable)
             self._list[i:i] = all
             self._other_data[i:i] = [_store() for _ in all]
             self.endInsertRows()
-        
+
     def reverse(self):
         self._list.reverse()
         self._other_data.reverse()
         self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), self.index(0), self.index(len(self) -1))
-        
+
     def sort(self, *args, **kwargs):
         indices = _argsort(self._list, *args, **kwargs)
         list = [self._list[i] for i in indices]
         for i, new_l, new_o in enumerate(zip(list, other)):
             self._list[i] = new_l
             self._other_data[i] = new_o
-#        self._list.sort(*args, **kwargs)
         self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), self.index(0), self.index(len(self) -1))
-        
+
     def __repr__(self):
         return "PyListModel(%s)" % repr(self._list)
-    
+
     def __nonzero__(self):
         return len(self) != 0
-    
+
     #for Python 3000
     def __bool__(self):
         return len(self) != 0
-    
+
     def emitDataChanged(self, indexList):
         if isinstance(indexList, int):
             indexList = [indexList]
+
+        #TODO: group indexes into ranges
         for ind in indexList:
             self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), self.index(ind), self.index(ind))
-            
+
     ###########
     # Drag/drop
     ###########
-    
+
     def supportedDropActions(self):
         return self._supportedDropActions
-    
+
     def decode_qt_data(self, data):
         """ Decode internal Qt 'application/x-qabstractitemmodeldatalist'
         mime data 
                 item[role] = value
             items.append((row, column, item))
         return items
-    
+
     def mimeTypes(self):
         return self.MIME_TYPES + list(QAbstractListModel.mimeTypes(self))
-    
+
     def mimeData(self, indexlist):
         if len(indexlist) <= 0:
             return None
-        
+
         items = [self[i.row()] for i in indexlist]
         mime = QAbstractListModel.mimeData(self, indexlist)
         data = cPickle.dumps(vars)
         mime.setData(self.MIME_TYPE, QByteArray(data))
         mime._items = items
         return mime
-    
+
     def dropMimeData(self, mime, action, row, column, parent):
         if action == Qt.IgnoreAction:
             return True
-        
+
         if not mime.hasFormat(self.MIME_TYPE):
             return False
-        
+
         if hasattr(mime, "_vars"):
             vars = mime._vars
         else:
             desc = str(mime.data(self.MIME_TYPE))
             vars = cPickle.loads(desc)
-        
+
         return QAbstractListModel.dropMimeData(self, mime, action, row, column, parent)
-    
-    
+
+
 import OWGUI
 import orange
 import Orange
 import cPickle
 
 class VariableListModel(PyListModel):
-    
+
     MIME_TYPE = "application/x-Orange-VariableList"
-    
+
     def data(self, index, role=Qt.DisplayRole):
-        i = index.row()
-        var = self[i]
-        if role == Qt.DisplayRole:
-            return QVariant(var.name)
-        elif role == Qt.DecorationRole:
-            return QVariant(OWGUI.getAttributeIcons().get(var.varType, -1))
-        elif role == Qt.ToolTipRole:
-            return QVariant(self.variable_tooltip(var))
+        if self._is_index_valid_for(index, self):
+            i = index.row()
+            var = self[i]
+            if role == Qt.DisplayRole:
+                return QVariant(var.name)
+            elif role == Qt.DecorationRole:
+                return QVariant(OWGUI.getAttributeIcons().get(var.varType, -1))
+            elif role == Qt.ToolTipRole:
+                return QVariant(self.variable_tooltip(var))
+            else:
+                return PyListModel.data(self, index, role)
         else:
-            return PyListModel.data(self, index, role)
-        
+            return QVariant()
+
     def variable_tooltip(self, var):
         if isinstance(var, Orange.feature.Discrete):
             return self.discrete_variable_tooltip(var)
             return self.continuous_variable_toltip(var)
         elif isinstance(var, Orange.feature.String):
             return self.string_variable_tooltip(var)
-        
+
     def variable_labels_tooltip(self, var):
         text = ""
         if var.attributes:
             text += "<br/>Variable Labels:<br/>"
             text += "<br/>".join(labels)
         return text
-            
+
     def discrete_variable_tooltip(self, var):
         text = "<b>%s</b><br/>Discrete with %i values: " % (safe_text(var.name), len(var.values))
         text += ", ".join("%r" % safe_text(v) for v in var.values)
         text += self.variable_labels_tooltip(var)
         return text
-            
+
     def continuous_variable_toltip(self, var):
         text = "<b>%s</b><br/>Continuous" % safe_text(var.name)
         text += self.variable_labels_tooltip(var)
         return text
-    
+
     def string_variable_tooltip(self, var):
         text = "<b>%s</b><br/>String" % safe_text(var.name)
         text += self.variable_labels_tooltip(var)
         return text
-    
+
     def python_variable_tooltip(self, var):
         text = "<b>%s</b><br/>Python" % safe_text(var.name)
         text += self.variable_labels_tooltip(var)
         return text
-    
+
 _html_replace = [("<", "&lt;"), (">", "&gt;")]
 
 def safe_text(text):

Orange/OrangeWidgets/Regression/OWSVMRegression.py

 from Orange.classification import svm
 
 class OWSVMRegression(OWSVM):
+    settingsList = OWSVM.settingsList + ["C_epsilon", "C_nu"]
+
     def __init__(self, parent=None, signalManager=None, title="SVM Regression"):
         OWWidget.__init__(self, parent, signalManager, title, wantMainArea=False)
-        
+
         self.inputs=[("Data", Orange.data.Table, self.setData), 
                      ("Preprocess", PreprocessedLearner, self.setPreprocessor)]
-        
+
         self.outputs=[("Learner", orange.Learner, Default),
                       ("Predictor", orange.Classifier, Default),
                       ("Support Vectors", Orange.data.Table)]
         self.gamma = 0.0
         self.coef0 = 0.0
         self.degree = 3
-        self.C = 1.0
+        self.C_epsilon = 1.0
+        self.C_nu = 1.0
         self.p = 0.1
         self.eps = 1e-3
         self.nu = 0.5
         self.shrinking = 1
-        self.probability=1
-        self.useNu=0
-        self.nomogram=0
-        self.normalization=1
+        self.probability = 1
+        self.useNu = 0
+        self.nomogram = 0
+        self.normalization = 1
         self.data = None
-        self.selFlag=False
+        self.selFlag = False
         self.preprocessor = None
         self.name = "SVM Regression"
-        
+
         self.loadSettings()
 
-        
-        OWGUI.lineEdit(self.controlArea, self, 'name', box='Learner/predictor Name',
+        OWGUI.lineEdit(self.controlArea, self, 'name',
+                       box='Learner/predictor Name',
                        tooltip='Name to be used by other widgets to identify your learner/predictor.')
         OWGUI.separator(self.controlArea)
 
         b = OWGUI.radioButtonsInBox(self.controlArea, self, "useNu", [], 
-                                    box="SVM Type", 
-                                    orientation = QGridLayout(), 
+                                    box="SVM Type",
+                                    orientation = QGridLayout(),
                                     addSpace=True)
-        
+
         # Epsilon SVR
         b.layout().addWidget(OWGUI.appendRadioButton(b, self, 
                                                 "useNu", u"ε-SVR",
                              0, 0, Qt.AlignLeft)
         
         b.layout().addWidget(QLabel("Cost (C)", b), 0, 1, Qt.AlignRight)
-        b.layout().addWidget(OWGUI.doubleSpin(b, self, "C", 0.5, 512.0, 0.5, 
-                          addToLayout=False, 
-                          callback=lambda *x: self.setType(0), 
+        b.layout().addWidget(OWGUI.doubleSpin(b, self, "C_epsilon", 0.1, 512.0, 0.1,
+                          decimals=2,
+                          addToLayout=False,
+                          callback=lambda *x: self.setType(0),
                           alignment=Qt.AlignRight,
                           tooltip="Cost for out of epsilon training points."),
                           0, 2)
-        
+    
         b.layout().addWidget(QLabel(u"Loss Epsilon (ε)", b), 1, 1, Qt.AlignRight)
         b.layout().addWidget(OWGUI.doubleSpin(b, self, "p", 0.05, 1.0, 0.05,
                                       addToLayout=False,
                                       tooltip="Epsilon bound (all points inside this interval are not penalized)."
                                       ),
                              1, 2)
-        
+
         # Nu SVR
-        b.layout().addWidget(OWGUI.appendRadioButton(b, self, 
+        b.layout().addWidget(OWGUI.appendRadioButton(b, self,
                                                 "useNu", u"ν-SVR",
                                                 tooltip="Nu SVR",
                                                 addToLayout=False),
                              2, 0, Qt.AlignLeft)
         
-        b.layout().addWidget(QLabel("Cost (C)", b), 
+        b.layout().addWidget(QLabel("Cost (C)", b),
                              2, 1, Qt.AlignRight)
-        b.layout().addWidget(OWGUI.doubleSpin(b, self, "C", 0.5, 512.0, 0.5, 
-                        addToLayout=False, 
-                        callback=lambda *x: self.setType(0), 
+        b.layout().addWidget(OWGUI.doubleSpin(b, self, "C_nu", 0.1, 512.0, 0.1,
+                        decimals=2, 
+                        addToLayout=False,
+                        callback=lambda *x: self.setType(1),
                         alignment=Qt.AlignRight,
                         tooltip="Cost for out of epsilon training points."),
                         2, 2)
         
         b.layout().addWidget(QLabel(u"Complexity bound (\u03bd)", b),
                              3, 1, Qt.AlignRight)
-        b.layout().addWidget(OWGUI.doubleSpin(b, self, "nu", 0.1, 1.0, 0.1,
+        b.layout().addWidget(OWGUI.doubleSpin(b, self, "nu", 0.05, 1.0, 0.05,
                         tooltip="Lower bound on the ratio of support vectors",
                         addToLayout=False, 
                         callback=lambda *x: self.setType(1), 
         OWGUI.separator(b)
         self.gcd = OWGUI.widgetBox(b, orientation="horizontal")
         self.leg = OWGUI.doubleSpin(self.gcd, self, "gamma", 0.0, 10.0, 0.0001,
+                                    decimals=5,
                                     label="  g: ", orientation="horizontal",
                                     callback=self.changeKernel, 
                                     alignment=Qt.AlignRight)
         self.paramButton.setDisabled(not self.data)
         
     def applySettings(self):
-        learner = svm.SVMLearner(svm_type=svm.SVMLearner.Nu_SVR 
-                                          if self.useNu else
-                                          svm.SVMLearner.Epsilon_SVR,
-                                 C=self.C,
+        if self.useNu:
+            svm_type = svm.SVMLearner.Nu_SVR
+            C = self.C_nu
+        else:
+            svm_type = svm.SVMLearner.Epsilon_SVR
+            C = self.C_epsilon
+
+        learner = svm.SVMLearner(svm_type=svm_type,
+                                 C=C,
                                  p=self.p,
                                  nu=self.nu,
                                  kernel_type=self.kernel_type,
         support_vectors = None
         if self.preprocessor:
             learner = self.preprocessor.wrapLearner(learner)
-        
+
         if self.data is not None:
             predictor = learner(self.data)
             support_vectors = predictor.support_vectors
             predictor.name = self.name
-            
+
         self.send("Learner", learner)
         self.send("Predictor", predictor)
         self.send("Support Vectors", support_vectors)
-        
+
     def sendReport(self):
         if self.useNu:
             settings = [("Type", "Nu SVM regression"),
-                        ("Cost (C)", "%.3f" % self.C),
-                        ("Complexity bound (nu)", "%.2f" % self.nu)]
+                        ("Cost (C)", "%.3f" % self.C_nu),
+                        ("Complexity bound (nu)", "%.3f" % self.nu)]
         else:
             settings = [("Type", "Epsilon SVM regression"),
-                        ("Cost (C)", "%.3f" % self.C),
+                        ("Cost (C)", "%.3f" % self.C_epsilon),
                         ("Loss epsilon", "%.3f" % self.p)]
-            
+
         if self.kernel_type == 0:
             kernel = "Linear, x.y"
         elif self.kernel_type == 1:
             kernel = "RBF, e<sup>-%.4f*(x-y).(x-y)</sup>" % self.gamma
         else:
             kernel = "Sigmoid, tanh(%.4f*x.y+%.4f)" % (self.gamma, self.coef0)
-            
+
         settings.extend([("Kernel", kernel),
                          ("Tolerance", self.eps),
                          ("Normalize data", OWGUI.YesNo[self.normalization])])
-        
-            
+
         self.reportSettings("Settings", settings)
         self.reportData(self.data)
-            
-        
+
+    def search_(self):
+        learner = orngSVM.SVMLearner()
+        for attr in ("name", "kernel_type", "degree", "shrinking", "probability", "normalization"):
+            setattr(learner, attr, getattr(self, attr))
+
+        for attr in ("gamma", "coef0", "p", "eps", "nu"):
+            setattr(learner, attr, float(getattr(self, attr)))
+
+        if self.useNu:
+            learner.svm_type = learner.Nu_SVR
+            learner.C = self.C_nu
+        else:
+            learner.svm_type = learner.Epsilon_SVR
+            learner.C = self.C_epsilon
+
+        params = []        
+        params.append("C")
+        if self.kernel_type in [1, 2]:
+            params.append("gamma")
+        if self.kernel_type == 1:
+            params.append("degree")
+        try:
+            learner.tuneParameters(self.data, params, 4, verbose=0,
+                                   progressCallback=self.progres)
+        except UnhandledException:
+            pass
+        for param in params:
+            setattr(self, param, getattr(learner, param))
+
+        if self.useNu:
+            self.C_nu = learner.C
+        else:
+            self.C_epsilon = learner.C
+
+        self.finishSearch()
+
 if __name__ == "__main__":
     app = QApplication([])
     w = OWSVMRegression()
     w.show()
     data = Orange.data.Table("housing")
     w.setData(data)
-    app.exec_()
+    app.exec_()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.