Exemplo n.º 1
0
    def populateList(self):
        model = QStandardItemModel()
        for option in self.selectedoptions:
            item = QStandardItem(option)
            model.appendRow(item)

        self.lstLayers.setModel(model)
    def __addFirstRowToModel(self, oldModel, newRow):
        """

        :type oldModel: QAbstractItemModel
        :type newRow: list
        :return: QStandardItemModel
        """
        model = QStandardItemModel(self)
        items = []

        for str in newRow:
            items.append(QStandardItem(str))

        model.appendRow(items)

        for i in xrange(oldModel.rowCount()):
            items = []

            for j in xrange(oldModel.columnCount()):
                index = QModelIndex(oldModel.index(i, j))
                data = oldModel.data(index)
                item = QStandardItem(data)
                items.append(item)

            model.appendRow(items)

        return model
Exemplo n.º 3
0
class PrvTreeviewNest(QTreeView):
    def __init__(self):
        super(PrvTreeviewNest, self).__init__()

        loadUi('treeview_nest.ui')

        # row can be 0 even when it's more than 0.
        self._datamodel = QStandardItemModel(0, 2)
        self.setModel(self._datamodel)

        for i in range(4):
            self.add_widget(i + 1)

        self.show()

    def add_widget(self, n):
        std_item = QStandardItem('{}th item'.format(n))
        self._datamodel.setItem(n, 0, std_item)

        node_widget = QPushButton('{}th button'.format(n))
        qindex_widget = self._datamodel.index(n, 1, QModelIndex())
        self.setIndexWidget(qindex_widget, node_widget)

        if n == 2:
            std_item_child = QStandardItem('child')
            std_item.appendRow(std_item_child)

            node_widget_child = QPushButton('petit button')
            qindex_widget_child = self._datamodel.index(n, 1, QModelIndex())
            self.setIndexWidget(qindex_widget_child, node_widget_child)
Exemplo n.º 4
0
 def __init__(self, widget, parent=None):
     QStandardItemModel.__init__(self, parent)
     self.setHorizontalHeaderLabels(self.labels)
     items = [(name, getattr(widget, name)) for name in dir(widget)
              if not name.startswith('_')]
     for name, value in sorted(items):
         self.appendRow(self.makeRowItems(name, value))
Exemplo n.º 5
0
 def __init__(self):
     QStandardItemModel.__init__(self)
     self.layout_changed_sig.connect(self.layout_changed)
     self.layout_change_to_conn_sig.connect(self.layout_change_to_conn)
     self.layout_change_to_rule_sig.connect(self.layout_change_to_rule)
     self.setHorizontalHeaderLabels((u"协议簇",u"类型",u"本地地址", u"本地端口",u"远程地址", u"远程端口",
                                           u"状态",u"进程ID",u"进程名"))
Exemplo n.º 6
0
 def __init__(self, velat, sections, parent=None, change_balance=True):
     QStandardItemModel.__init__(self, parent)
     self._velat = velat
     self._sections = sections
     self._new_item_name = "this new item"
     self._new_item_title = "New item"
     self._change_balance = change_balance
Exemplo n.º 7
0
 def __init__(self):
     QStandardItemModel.__init__(self)
     self.layout_changed_sig.connect(self.layout_changed)
     self.layout_change_to_conn_sig.connect(self.layout_change_to_conn)
     self.layout_change_to_rule_sig.connect(self.layout_change_to_rule)
     self.setHorizontalHeaderLabels(("Family","Type","Local address&port","Remote address&port",
                                           "Status","Pid","Name"))
Exemplo n.º 8
0
def setupChecklist(widget, names, checks = None):
    tp = type(widget)
    # Prepare checks
    if checks is None:
        checks = []
        for name in names:
            checks.append(Qt.Unchecked)
    else:
        newChecks = []
        for check in checks:
            if check: newChecks.append(Qt.Checked)
            else: newChecks.append(Qt.Unchecked)
        checks = newChecks

    ## QListView
    if tp is QListView:
        model = QStandardItemModel()
        for i in xrange(len(names)):
            item = QStandardItem(names[i])
            item.setCheckable(True)
            item.setCheckState(checks[i])
            model.appendRow(item)
        widget.setModel(model)

    ## QListWidget
    elif tp is QListWidget:
        for i in xrange(len(names)):
            item = QListWidgetItem(names[i])
            item.setFlags(Qt.ItemFlags(48)) # 48 = checkable(16), enabled(32)
            item.setCheckState(checks[i])
            widget.addItem(item)

    ## NOT SUPPORTED
    else: raise TypeError('Class ' + str(tp) + ' is not supported.')
Exemplo n.º 9
0
 def __init__( self, terms, parent ):
     items = {}
     model = QStandardItemModel(parent)
     
     for term in terms:
         parts = str(term).split('.')
         for i in range(len(parts)):
             parent_key  = '.'.join(parts[:i])
             item_key    = '.'.join(parts[:i+1])
             
             if ( item_key in items ):
                 continue
             
             parent_item = items.get(parent_key)
             
             item = QStandardItem(parts[i])
             if ( parent_item ):
                 parent_item.appendRow(item)
             else:
                 model.appendRow(item)
             
             items[item_key] = item
     
     self._model = model
     super(XQueryCompleter, self).__init__(model, parent)
Exemplo n.º 10
0
    def _select_tags(self):
        tag_dialog = SelectTagsDialog()
        # if the user has their own taglist, use it
        user_tag_list = os.path.join(os.path.expanduser("~"), '.plugin_tags.txt')
        if os.path.exists(user_tag_list):
            tag_file = user_tag_list
        else:
            tag_file = os.path.join(str(self.plugin_builder_path),
                                          'taglist.txt')

        with open(tag_file) as tf:
            tags = tf.readlines()

        model = QStandardItemModel()

        for tag in tags:
            item = QStandardItem(tag[:-1])
            model.appendRow(item)

        tag_dialog.listView.setModel(model)
        tag_dialog.show()
        ok = tag_dialog.exec_()
        if ok:
            selected = tag_dialog.listView.selectedIndexes()
            seltags = []
            for tag in selected:
                seltags.append(tag.data())
            taglist = ", ".join(seltags)
            self.dialog.tags.setText(taglist)
Exemplo n.º 11
0
    def test_tooltree(self):
        tree = ToolTree()
        role = tree.actionRole()
        model = QStandardItemModel()
        tree.setModel(model)
        item = QStandardItem("One")
        item.setData(QAction("One", tree), role)
        model.appendRow([item])

        cat = QStandardItem("A Category")
        item = QStandardItem("Two")
        item.setData(QAction("Two", tree), role)
        cat.appendRow([item])
        item = QStandardItem("Three")
        item.setData(QAction("Three", tree), role)
        cat.appendRow([item])

        model.appendRow([cat])

        def p(action):
            print "triggered", action.text()

        tree.triggered.connect(p)

        tree.show()

        self.app.exec_()
Exemplo n.º 12
0
    def __init__(self, parent=None, items=None):
        QStandardItemModel.__init__(self, parent)

        if items is not None:
            self.insertColumn(0, items)

        self.__timer = QTimer(self)
Exemplo n.º 13
0
	def __loadRules(self, the_rules, tree_view):
		model = QStandardItemModel(self)
		for r in the_rules:
			item = QStandardItem(r)
			model.appendRow(item)
		model.setHeaderData(0, Qt.Horizontal, "Regular Expression")
		tree_view.setModel(model)
Exemplo n.º 14
0
class CurvePanel(QListView):
    def __init__(self, curve_source):
        QListView.__init__(self)
        self.curve_source = curve_source
        self.setViewMode(QListView.IconMode)
        self.setIconSize(QSize(64,64))
        self.model = QStandardItemModel()
        for curve in curve_source._curves:
            self.add_curve(curve)
        self.setModel(self.model)
        self.setWrapping(True)
        self.show()

    def edit(self, index, trigger, event):
        if trigger == QAbstractItemView.DoubleClicked:
            item = self.model.item(index.row())
            curve = item.curve
            print curve.name()
            return True
        else:
            return False

    def add_new_curve(self):
        pass
    
    def add_curve(self, curve):
        name = curve.name()
        plot = self._create_plot(name)
        item = PlotItem(plot)
        item.curve = curve
        self.model.appendRow(item)

    def _create_plot(self, xcurve_name):
        index = self.curve_source.index()
        return Plot.of(xcurve_name, index.name()).from_(self.curve_source)
Exemplo n.º 15
0
    def __display_table_rslt(self, table_rows):
        '''
        controls table_comp_rslt widget
        fill the widget with table_rows list
        @param table_rows: []
        '''

        rows_count = len(table_rows)
        model = QStandardItemModel(rows_count, 3)

        model.setHorizontalHeaderLabels(TAB_LABELS)

        # fill model with data
        for row in range(rows_count):
            for col in range(3):
                item = QStandardItem()
                item.setData(str(table_rows[row][col]), Qt.DisplayRole)
                model.setItem(row, col, item)

        # self.table_comp_rslt.clearContents()
        if self.table_comp_rslt.isSortingEnabled():
            self.table_comp_rslt.setSortingEnabled(False)

        proxy = numsort.NumberSortModel()
        proxy.setSourceModel(model)
        self.table_comp_rslt.setModel(proxy)
        self.table_comp_rslt.resizeColumnsToContents()
        self.table_comp_rslt.setSortingEnabled(True)
    def __init__(self,parrent=None):
        super(MainWindow,self).__init__(parrent)
        self.setupUi(self)
        QtCore.QObject.connect(self.loadFile, QtCore.SIGNAL(mainWindow._fromUtf8("clicked()")), self.loadFile_btn_Kliked)
        QtCore.QObject.connect(self.testPlagia_btn, QtCore.SIGNAL(mainWindow._fromUtf8("clicked()")), self.plagiaStrat_btn)
        QtCore.QObject.connect(self.repport_btn, QtCore.SIGNAL(mainWindow._fromUtf8("clicked()")), self.repport)
        QtCore.QObject.connect(self.sava_btn, QtCore.SIGNAL(mainWindow._fromUtf8("clicked()")), self.saveFile)

        QtCore.QObject.connect(self.actionNew_File, QtCore.SIGNAL(mainWindow._fromUtf8("triggered()")), self.loadFile_btn_Kliked)
        QtCore.QObject.connect(self.actionADD_user, QtCore.SIGNAL(mainWindow._fromUtf8("triggered()")), self.addUser)
        QtCore.QObject.connect(self.actionSetting, QtCore.SIGNAL(mainWindow._fromUtf8("triggered()")), self.setting)
        #QtCore.QObject.connect(self.docs_Rsult_ListView, QtCore.SIGNAL(mainWindow._fromUtf8("clicked()")), self.listViewChange)
        QtCore.QObject.connect(self.docs_Rsult_ListView, QtCore.SIGNAL(mainWindow._fromUtf8("clicked(QModelIndex)")), self.listViewChange)
        QtCore.QObject.connect(self.docs_Rsult_ListView_2, QtCore.SIGNAL(mainWindow._fromUtf8("clicked(QModelIndex)")), self.listViewWebChange)

        self.userName_label.setText(self.userName)
        self.dialogDoc=addDocImpl.AddDocD()

        self.addUserDia=AddUserDia()
        self.settingD=SettingDiaIm()
        self.dialogMe=errorDiaImpl.ErrorDia()
        self.modelList=QStandardItemModel(self.docs_Rsult_ListView)
        self.modelListWeb=QStandardItemModel(self.docs_Rsult_ListView_2)
        self.setting=self.dataM.getSetting()
        self.sava_btn.setEnabled(False)
        self.repport_btn.setEnabled(False)
Exemplo n.º 17
0
  def __init__(self, __parent = None, event=False, fm = False):
    """
    Model constructor. Create the default QStandardItem's for the default nodes.
    """
    QStandardItemModel.__init__(self, __parent)
    EventHandler.__init__(self)
    self.__parent = __parent
    self.VFS = VFS.Get()
    self.ch = False

    # init translation
    self.translation()

    # creating qstandarditem for the default nodes (the four displayed nodes when dff is launched)
    self.root_item = self.invisibleRootItem()
    tmp = self.VFS.GetNode("/").children()
    item_list = []
    for i in tmp:
      node_item = QStandardItem(i.name())
      node_item.setData(QVariant(long(i.this)), Qt.UserRole + 1)
      node_item.setData(QVariant(False), Qt.UserRole + 2)
      item_list.append(node_item)
    if len(item_list):
      self.root_item.appendRows(item_list)

    if event:
      self.VFS.connection(self)
Exemplo n.º 18
0
 def __init__(self, __parent = None):
   QStandardItemModel.__init__(self, __parent)
   self.__parent = __parent
   self.regmap = {}
   self.indexmap = {}
   if self.createRegMap():
     self.createRootItems()
 def createComboBoxWithStrings(self, array):
     dbList = QComboBox()
     dbsListModel = QStandardItemModel(dbList)
     for f in array:
         item = QStandardItem(f)
         dbsListModel.appendRow(item)
     dbList.setModel(dbsListModel)
     return dbList
Exemplo n.º 20
0
class BreakpointsViewer(QTreeView):
    """ showing bps  """
    def __init__(self, parent):
        super(QTreeView, self).__init__(parent)
        self.setAutoScroll(True)
        self.source_files = {}
        self.focus_signal = None
        self.header().setResizeMode(QHeaderView.ResizeToContents)
        self._show_args = None
        self.bp_data = QStandardItemModel()
        self.setModel(self.bp_data)
        self.setAlternatingRowColors(True)

    def set_focus_signal(self, signal):
        """ set callback to focus source file line"""
        self.focus_signal = signal

    def clear(self):
        """ clear the widget"""
        self.bp_data.clear()
        self.bp_data.setHorizontalHeaderLabels(['ID', 'Hits', 'Ignore Count', 'Condition'])

    def update_bp_info(self, target):
        """ update breakpoint info """
        self.clear()
        root = self.bp_data.invisibleRootItem()
        for breakpoint in target.breakpoint_iter():
            if not breakpoint.IsValid() or breakpoint.IsInternal():
                continue
            bp_item = QStandardItem(str(breakpoint.id))
            bp_row =[bp_item, QStandardItem(str(breakpoint.GetHitCount())), 
                       QStandardItem(str(breakpoint.GetIgnoreCount())), QStandardItem(str(breakpoint.GetCondition()))]
            for loc in breakpoint:
                loc_row = [QStandardItem(str(loc.GetID())), QStandardItem(str(loc.GetAddress().GetLineEntry()))]
                bp_item.appendRow(loc_row)
            root.appendRow(bp_row)
        self.expandToDepth(1)

    def mousePressEvent(self, event):
        """ overrided """
        idx = self.indexAt(event.pos())
        if idx.isValid() and self.focus_signal:
            model = idx.model()
            idx = idx.sibling(idx.row(), 0)
            if idx.isValid():
                item = model.itemFromIndex(idx)
                if item and item.isSelectable():
                    if item in self.source_files:
                        file_info = self.source_files[item]
                        if self.focus_signal:
                            self.focus_signal.emit(file_info.GetFileSpec().fullpath,
                                                   file_info.GetLine())
                        self.frame_changed.emit(self.frames[item])

                    else:
                        logging.error('frame cannot find associated source file')

        QTreeView.mousePressEvent(self, event)
Exemplo n.º 21
0
    def populateList(self):
        model = QStandardItemModel()
        for i, option in enumerate(self.options):
            item = QStandardItem(option)
            item.setCheckState(Qt.Checked if i in self.selectedoptions else Qt.Unchecked)
            item.setCheckable(True)
            model.appendRow(item)

        self.lstLayers.setModel(model)
Exemplo n.º 22
0
 def __init__(self, name, layer_type, neurons_count, inputs, minWeight, maxWeight, *__args):
     QStandardItemModel.__init__(self, *__args)
     self.setHorizontalHeaderLabels(LayerModel.DEFAULT_HEADER)
     self.name = name
     self.type = layer_type
     self.minWeight = minWeight
     self.maxWeight = maxWeight
     self.set_neurons(neurons_count)
     self.set_input_neurons(inputs)
Exemplo n.º 23
0
 def on_show_history_wifi_name(self):
     self.history_wifi_list = get_history_connected_wifi()
     model = QStandardItemModel(self.showWIFIListView)
     # Get each history wifi name
     for wifi_name in  self.history_wifi_list:
         item = QStandardItem(wifi_name)
         # Add the item to the model
         model.appendRow(item)
     self.showWIFIListView.setModel(model)
     self.showWIFIListView.show()
Exemplo n.º 24
0
    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletGPSV2, *args)

        self.setupUi(self)

        self.gps = self.device

        self.cbe_universal = CallbackEmulator(self.get_universal, self.cb_universal, self.increase_error_count)

        self.cbe_universal_gps = CallbackEmulator(
            self.get_universal_gps, self.cb_universal_gps, self.increase_error_count
        )

        self.cbe_universal_glo = CallbackEmulator(
            self.get_universal_glo, self.cb_universal_glo, self.increase_error_count
        )

        self.qtcb_pps.connect(self.cb_pps)
        self.gps.register_callback(self.gps.CALLBACK_PULSE_PER_SECOND, self.qtcb_pps.emit)

        self.format_combobox.currentIndexChanged.connect(self.format_changed)
        self.show_pos.clicked.connect(self.show_pos_clicked)
        self.hot_start.clicked.connect(lambda: self.restart_clicked(0))
        self.warm_start.clicked.connect(lambda: self.restart_clicked(1))
        self.cold_start.clicked.connect(lambda: self.restart_clicked(2))
        self.factory_reset.clicked.connect(lambda: self.restart_clicked(3))

        self.had_fix = False

        self.last_lat = 0
        self.last_ns = "U"
        self.last_long = 0
        self.last_ew = "U"

        self.gps_counter = 0
        self.glo_counter = 0

        self.gps_model = QStandardItemModel(32, 3, self)
        self.gps_table.setModel(self.gps_model)
        self.gps_model.setHorizontalHeaderItem(0, QStandardItem(u"Elevation (°)"))
        self.gps_model.setHorizontalHeaderItem(1, QStandardItem(u"Azimuth (°)"))
        self.gps_model.setHorizontalHeaderItem(2, QStandardItem(u"SNR (dB)"))
        for i in range(32):
            self.gps_model.setVerticalHeaderItem(i, QStandardItem(u"Sat " + str(i + 1)))
        self.gps_table.horizontalHeader().setResizeMode(QHeaderView.Stretch)

        self.glo_model = QStandardItemModel(32, 3, self)
        self.glo_table.setModel(self.glo_model)
        self.glo_model.setHorizontalHeaderItem(0, QStandardItem(u"Elevation (°)"))
        self.glo_model.setHorizontalHeaderItem(1, QStandardItem(u"Azimuth (°)"))
        self.glo_model.setHorizontalHeaderItem(2, QStandardItem(u"SNR (dB)"))
        for i in range(32):
            self.glo_model.setVerticalHeaderItem(i, QStandardItem(u"Sat " + str(i + 1 + 64)))
        self.glo_table.horizontalHeader().setResizeMode(QHeaderView.Stretch)
Exemplo n.º 25
0
	def __init__(self):
		QStandardItemModel.__init__(self)
		role_names = {
			self.foo: "",
			self.nama: "nama",
			self.userPicture: "userpicture",
			self.address: "address",
			self.realname: "realname",
			self.locked: "locked"
		}
		self.setRoleNames(role_names)
Exemplo n.º 26
0
 def __init__(self):
     """ Constructor. """
     
     QStandardItemModel.__init__(self)
     
     self._rowItemMap = dict()
     self._itemRowMap = dict()
     self.setColumnCount(4) # principal, content, properties, administration
     self._headers = [self.tr(constants.PRINCIPAL_COLUMN_NAME),
                      self.tr(constants.CONTENT_PRIVILEGE_COLUMN_NAME),
                      self.tr(constants.PROPERTY_PRIVILEGE_COLUMN_NAME),
                      self.tr(constants.ADMINISTRATION_PRIVILEGE_COLUMN_NAME)]
Exemplo n.º 27
0
    def _configure_model(self):
        model = QStandardItemModel(0, 3, self)

        # Set headers
        headers = [
            self.tr('Name'),
            self.tr('Data Type'),
            self.tr('Description')
        ]
        model.setHorizontalHeaderLabels(headers)

        self.setModel(model)
Exemplo n.º 28
0
 def __init__(self, model):
     """ Constructor. 
     
     @param model: The repository model.
     @type model: L{<RepositoryModel>datafinder.gui.user.models.repository.repository.RepositoryModel} 
     """
     
     QStandardItemModel.__init__(self)
     
     self._model = model
     self._currentResult = SPECIAL_PRINCIPALS
     self.enableCurrentResult()
Exemplo n.º 29
0
 def __init__(self):
     QStandardItemModel.__init__(self)
     self.rootItem = self.invisibleRootItem()
     self.setHorizontalHeaderLabels(['Element'])
     self.files = {}
     import Icons
     self.icons = {
         'file' : QIcon(QPixmap(Icons.ncFile)),
         'variable' : QIcon(QPixmap(Icons.ncVar)),
         'dimension' : QIcon(QPixmap(Icons.ncDim)),
         'attribute' : QIcon(QPixmap(Icons.ncAtt))
     }
 def update_commands(self,meas_prog_list_byname):
     global Regexprogramfile
     Regexprogramfile="("+"|".join(meas_prog_list_byname)+")"
     self.valid_list_of_commands = self.get_list_of_commands()
     #initiate syntax highlighting for the macro editor
     self.highlighter = MacroHighlighter(self.ui.macro_textbox.document(),self.valid_list_of_commands)
     #update the list of available macro commands in the user interface
     model=QStandardItemModel()
     parentItem = model.invisibleRootItem()
     for command in self.valid_list_of_commands:
         parentItem.appendRow(QStandardItem(command.label))
     self.ui.macrocommandtree.setModel(model)
Exemplo n.º 31
0
    def __init__(self):
        super().__init__()

        self.data = None
        self.km = None
        self.optimization_runs = []

        box = gui.vBox(self.controlArea, "Number of Clusters")
        layout = QGridLayout()
        self.n_clusters = bg = gui.radioButtonsInBox(box,
                                                     self,
                                                     "optimize_k", [],
                                                     orientation=layout,
                                                     callback=self.update)
        layout.addWidget(
            gui.appendRadioButton(bg, "Fixed:", addToLayout=False), 1, 1)
        sb = gui.hBox(None, margin=0)
        self.fixedSpinBox = gui.spin(sb,
                                     self,
                                     "k",
                                     minv=2,
                                     maxv=30,
                                     controlWidth=60,
                                     alignment=Qt.AlignRight,
                                     callback=self.update_k)
        gui.rubber(sb)
        layout.addWidget(sb, 1, 2)

        layout.addWidget(
            gui.appendRadioButton(bg, "Optimized from", addToLayout=False), 2,
            1)
        ftobox = gui.hBox(None)
        ftobox.layout().setContentsMargins(0, 0, 0, 0)
        layout.addWidget(ftobox)
        gui.spin(ftobox,
                 self,
                 "k_from",
                 minv=2,
                 maxv=29,
                 controlWidth=60,
                 alignment=Qt.AlignRight,
                 callback=self.update_from)
        gui.widgetLabel(ftobox, "to")
        self.fixedSpinBox = gui.spin(ftobox,
                                     self,
                                     "k_to",
                                     minv=3,
                                     maxv=30,
                                     controlWidth=60,
                                     alignment=Qt.AlignRight,
                                     callback=self.update_to)
        gui.rubber(ftobox)

        layout.addWidget(gui.widgetLabel(None, "Scoring: "), 5, 1,
                         Qt.AlignRight)
        layout.addWidget(
            gui.comboBox(None,
                         self,
                         "scoring",
                         label="Scoring",
                         items=list(zip(*self.SCORING_METHODS))[0],
                         callback=self.update), 5, 2)

        box = gui.vBox(self.controlArea, "Initialization")
        gui.comboBox(box,
                     self,
                     "smart_init",
                     items=self.INIT_METHODS,
                     callback=self.update)

        layout = QGridLayout()
        box2 = gui.widgetBox(box, orientation=layout)
        box2.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        layout.addWidget(gui.widgetLabel(None, "Re-runs: "), 0, 0,
                         Qt.AlignLeft)
        sb = gui.hBox(None, margin=0)
        layout.addWidget(sb, 0, 1)
        gui.lineEdit(sb,
                     self,
                     "n_init",
                     controlWidth=60,
                     valueType=int,
                     validator=QIntValidator(),
                     callback=self.update)
        layout.addWidget(gui.widgetLabel(None, "Maximal iterations: "), 1, 0,
                         Qt.AlignLeft)
        sb = gui.hBox(None, margin=0)
        layout.addWidget(sb, 1, 1)
        gui.lineEdit(sb,
                     self,
                     "max_iterations",
                     controlWidth=60,
                     valueType=int,
                     validator=QIntValidator(),
                     callback=self.update)

        box = gui.vBox(self.controlArea, "Output")
        gui.comboBox(box,
                     self,
                     "place_cluster_ids",
                     label="Append cluster ID as:",
                     orientation=Qt.Horizontal,
                     callback=self.send_data,
                     items=self.OUTPUT_METHODS)
        gui.lineEdit(box,
                     self,
                     "output_name",
                     label="Name:",
                     orientation=Qt.Horizontal,
                     callback=self.send_data)

        gui.separator(self.buttonsArea, 30)
        self.apply_button = gui.auto_commit(self.buttonsArea,
                                            self,
                                            "auto_run",
                                            "Apply",
                                            box=None)
        gui.rubber(self.controlArea)

        self.table_model = QStandardItemModel(self)
        self.table_model.setHorizontalHeaderLabels(["k", "Score"])
        self.table_model.setColumnCount(2)

        self.table_box = gui.vBox(self.mainArea,
                                  "Optimization Report",
                                  addSpace=0)
        table = self.table_view = QTableView(self.table_box)
        table.setHorizontalScrollMode(QTableView.ScrollPerPixel)
        table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        table.setSelectionMode(QTableView.SingleSelection)
        table.setSelectionBehavior(QTableView.SelectRows)
        table.verticalHeader().hide()
        table.setItemDelegateForColumn(1, gui.TableBarItem(self))
        table.setModel(self.table_model)
        table.selectionModel().selectionChanged.connect(
            self.table_item_selected)
        table.setColumnWidth(0, 40)
        table.setColumnWidth(1, 120)
        table.horizontalHeader().setStretchLastSection(True)

        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.mainArea.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
        self.table_box.setSizePolicy(QSizePolicy.Fixed,
                                     QSizePolicy.MinimumExpanding)
        self.table_view.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.MinimumExpanding)
        self.table_box.layout().addWidget(self.table_view)
        self.hide_show_opt_results()
Exemplo n.º 32
0
 def __init__(self, parent=None):
     super(CheckableComboBox, self).__init__(parent)
     self.view().pressed.connect(self.handleItemPressed)
     self.setModel(QStandardItemModel(self))
Exemplo n.º 33
0
class ConfigManagerDialog(ui_configmanager.Ui_ProjectInstallerDialog, QDialog):
    def __init__(self, roamapp, parent=None):
        super(ConfigManagerDialog, self).__init__(parent)
        self.setupUi(self)
        self.bar = roam.messagebaritems.MessageBar(self)

        self.roamapp = roamapp

        # Nope!
        self.projectwidget.roamapp = roamapp
        self.projectwidget.bar = self.bar

        self.treemodel = QStandardItemModel()
        self.projectList.setModel(self.treemodel)
        self.projectList.setHeaderHidden(True)

        self.projectList.selectionModel().currentChanged.connect(
            self.nodeselected)

        self.projectwidget.adjustSize()
        self.setWindowFlags(Qt.Window)

        self.projectwidget.projectupdated.connect(self.projectupdated)

        self.projectwidget.setaboutinfo()
        self.projectwidget.projects_page.projectlocationchanged.connect(
            self.loadprojects)
        self.setuprootitems()

        ConfigEvents.deleteForm.connect(self.delete_form)

    def raiseerror(self, *exinfo):
        self.bar.pushError(*exinfo)
        import roam.errors
        roam.errors.send_exception(exinfo)

    def setuprootitems(self):
        rootitem = self.treemodel.invisibleRootItem()
        self.roamnode = RoamNode()
        rootitem.appendRow(self.roamnode)

        self.projectsnode = ProjectsNode(folder=None)
        rootitem.appendRow(self.projectsnode)

        self.pluginsnode = PluginsNode()
        pluginpath = os.path.join(self.roamapp.apppath, "plugins")
        rootitem.appendRow(self.pluginsnode)
        self.pluginsnode.add_plugin_paths([pluginpath])

    def delete_form(self):
        index = self.projectList.currentIndex()
        node = index.data(Qt.UserRole)
        if not node.type() == Treenode.FormNode:
            return

        title, removemessage = node.removemessage
        delete = node.canremove
        if node.canremove and removemessage:
            button = QMessageBox.warning(self, title, removemessage,
                                         QMessageBox.Yes | QMessageBox.No)
            delete = button == QMessageBox.Yes

        print "Delete"
        if delete:
            parentindex = index.parent()
            newindex = self.treemodel.index(index.row(), 0, parentindex)
            if parentindex.isValid():
                parent = parentindex.data(Qt.UserRole)
                parent.delete(index.row())

            print parentindex
            self.projectList.setCurrentIndex(parentindex)

    def delete_project(self):
        index = self.projectList.currentIndex()
        node = index.data(Qt.UserRole)
        if node.type() == Treenode.ProjectNode:
            self.projectwidget._closeqgisproject()

        title, removemessage = node.removemessage
        delete = node.canremove
        if node.canremove and removemessage:
            button = QMessageBox.warning(self, title, removemessage,
                                         QMessageBox.Yes | QMessageBox.No)
            delete = button == QMessageBox.Yes

        if delete:
            parentindex = index.parent()
            newindex = self.treemodel.index(index.row(), 0, parentindex)
            if parentindex.isValid():
                parent = parentindex.data(Qt.UserRole)
                parent.delete(index.row())

            self.projectList.setCurrentIndex(newindex)

    def addprojectfolders(self, folders):
        self.projectwidget.projects_page.setprojectfolders(folders)

    def loadprojects(self, projectpath):
        projects = roam.project.getProjects([projectpath])
        self.projectsnode.loadprojects(projects, projectsbase=projectpath)

        index = self.treemodel.indexFromItem(self.projectsnode)
        self.projectList.setCurrentIndex(index)
        self.projectList.expand(index)

    def nodeselected(self, index, _):
        node = index.data(Qt.UserRole)
        if node is None:
            return

        project = node.project
        if project and not self.projectwidget.project == project:
            # Only load the project if it's different the current one.
            self.projectwidget.setproject(project)
            node.create_children()

            validateresults = list(project.validate())
            if validateresults:
                text = "Here are some reasons we found: \n\n"
                for message in validateresults:
                    text += "- {} \n".format(message)

                self.projectwidget.reasons_label.setText(text)

        if node.nodetype == Treenode.RoamNode:
            self.projectwidget.projectlabel.setText(
                "IntraMaps Roam Config Manager")

        if node.nodetype == Treenode.AddNew:
            try:
                item = node.additem()
            except ValueError:
                return
            newindex = self.treemodel.indexFromItem(item)
            self.projectList.setCurrentIndex(newindex)
            return

        self.projectwidget.projectbuttonframe.setVisible(not project is None)
        self.projectwidget.setpage(node.page, node)

    def projectupdated(self):
        index = self.projectList.currentIndex()
        node = find_node(index)
        node.refresh()
Exemplo n.º 34
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.train_data = None
        self.test_data = None

        #: An Ordered dictionary with current inputs and their testing
        #: results.
        self.learners = OrderedDict()

        sbox = gui.widgetBox(self.controlArea, "Sampling")
        rbox = gui.radioButtons(sbox,
                                self,
                                "resampling",
                                callback=self._param_changed)
        gui.appendRadioButton(rbox, "Cross validation")
        ibox = gui.indentedBox(rbox)
        gui.spin(ibox,
                 self,
                 "k_folds",
                 2,
                 50,
                 label="Number of folds:",
                 callback=self._param_changed)
        gui.appendRadioButton(rbox, "Leave one out")
        gui.appendRadioButton(rbox, "Random sampling")
        ibox = gui.indentedBox(rbox)
        gui.spin(ibox,
                 self,
                 "n_repeat",
                 2,
                 50,
                 label="Repeat train/test",
                 callback=self._param_changed)
        gui.widgetLabel(ibox, "Relative training set size:")
        gui.hSlider(ibox,
                    self,
                    "sample_p",
                    minValue=1,
                    maxValue=100,
                    ticks=20,
                    vertical=False,
                    callback=self._param_changed)

        gui.appendRadioButton(rbox, "Test on train data")
        gui.appendRadioButton(rbox, "Test on test data")

        rbox.layout().addSpacing(5)
        gui.button(rbox, self, "Apply", callback=self.apply)

        gui.rubber(self.controlArea)

        self.view = QTreeView(rootIsDecorated=False,
                              uniformRowHeights=True,
                              wordWrap=True,
                              editTriggers=QTreeView.NoEditTriggers)

        self.result_model = QStandardItemModel()
        self.view.setModel(self.result_model)
        self._update_header()
        box = gui.widgetBox(self.mainArea, "Evaluation Results")
        box.layout().addWidget(self.view)
    def initParametersPan(self):
        ui = Ui_GeoDetermine()
        self.parametersPanel = ui
        FlightPlanBaseDlg.initParametersPan(self)

        self.parametersPanel.pnlStartPosP = PositionPanel(
            self.parametersPanel.gbStartPosP, None, None, "Degree")
        # self.parametersPanel.pnlStartPosP.degreeFormat = "ddmmss.ssssH"
        self.parametersPanel.pnlStartPosP.alwwaysShowString = "Degree"
        #         self.parametersPanel.pnlWaypoint.groupBox.setTitle("FAWP")
        self.parametersPanel.pnlStartPosP.btnCalculater.hide()
        self.parametersPanel.pnlStartPosP.hideframe_Altitude()
        # self.parametersPanel.pnlStartPosP.showframe_ID()
        self.parametersPanel.pnlStartPosP.setObjectName("pnlStartPosP")
        self.connect(self.parametersPanel.pnlStartPosP,
                     SIGNAL("positionChanged"), self.autoCalcFinishMagVar)

        ui.verticalLayout_gbStartPosP.addWidget(
            self.parametersPanel.pnlStartPosP)

        self.parametersPanel.pnlVarStartP = DegreesBoxPanel(self)
        self.parametersPanel.pnlVarStartP.CaptionLabel = "Magnetic Variation"
        self.connect(self.parametersPanel.pnlVarStartP,
                     SIGNAL("btnDegreeBoxPanel_clicked"), self.method_32_P)
        self.connect(self.parametersPanel.pnlVarStartP,
                     SIGNAL("txtDegreeBox_textChanged"),
                     self.txtDegreeBox_textChangedP)
        ui.verticalLayout_gbStartPosP.addWidget(
            self.parametersPanel.pnlVarStartP)

        self.parametersPanel.pnlVarFinishP = DegreesBoxPanel(self)
        self.parametersPanel.pnlVarFinishP.ButtonVisible = False
        self.parametersPanel.pnlVarFinishP.Enabled = False
        self.parametersPanel.pnlVarFinishP.CaptionLabel = "Magnetic Variation at Finish"
        ui.vLayout_grbParametersP.insertWidget(
            1, self.parametersPanel.pnlVarFinishP)
        # self.connect(self.parametersPanel.pnlVarStartP, SIGNAL("btnDegreeBoxPanel_clicked"), self.method_32_P)

        self.parametersPanel.pnlStartPosBD = PositionPanel(
            self.parametersPanel.gbFinishPosBD, None, None, "Degree")
        #         self.parametersPanel.pnlStartPosBD.groupBox.setTitle("FAWP")
        #         self.parametersPanel.pnlStartPosBD.degreeFormat = "ddmmss.ssssH"
        self.parametersPanel.pnlStartPosBD.alwwaysShowString = "Degree"
        self.parametersPanel.pnlStartPosBD.btnCalculater.hide()
        self.parametersPanel.pnlStartPosBD.hideframe_Altitude()
        self.parametersPanel.pnlStartPosBD.showframe_ID()
        self.parametersPanel.pnlStartPosBD.setObjectName("pnlStartPosBD")
        ui.verticalLayout_gbStartPosBD.insertWidget(
            0, self.parametersPanel.pnlStartPosBD)
        self.connect(self.parametersPanel.pnlStartPosBD,
                     SIGNAL("positionChanged"), self.positionChangedStartBD)

        self.parametersPanel.pnlVarStartBD = DegreesBoxPanel(self)
        self.parametersPanel.pnlVarStartBD.CaptionLabel = "Magnetic Variation"
        # self.parametersPanel.pnlVarStartBD.Enabled = False
        self.connect(self.parametersPanel.pnlVarStartBD,
                     SIGNAL("btnDegreeBoxPanel_clicked"), self.method_34_BD)
        # self.connect(self.parametersPanel.pnlVarStartBD, SIGNAL("txtDegreeBox_textChanged"), self.txtDegreeBox_textChangedP)
        ui.verticalLayout_gbStartPosBD.addWidget(
            self.parametersPanel.pnlVarStartBD)

        self.parametersPanel.pnlFinishPosBD = PositionPanel(
            self.parametersPanel.gbFinishPosBD, None, None, "Degree")
        #         self.parametersPanel.pnlStartPosBD.groupBox.setTitle("FAWP")
        #         self.parametersPanel.pnlFinishPosBD.degreeFormat = "ddmmss.ssssH"
        self.parametersPanel.pnlFinishPosBD.alwwaysShowString = "Degree"
        self.parametersPanel.pnlFinishPosBD.btnCalculater.hide()
        self.parametersPanel.pnlFinishPosBD.hideframe_Altitude()
        self.parametersPanel.pnlFinishPosBD.showframe_ID()
        self.parametersPanel.pnlFinishPosBD.setObjectName("pnlFinishPosBD")
        ui.verticalLayout_gbFinishPosBD.insertWidget(
            0, self.parametersPanel.pnlFinishPosBD)
        self.connect(self.parametersPanel.pnlFinishPosBD,
                     SIGNAL("positionChanged"), self.positionChangedFinishBD)

        self.parametersPanel.pnlVarFinishBD = DegreesBoxPanel(self)
        self.parametersPanel.pnlVarFinishBD.CaptionLabel = "Magnetic Variation"
        # self.parametersPanel.pnlVarFinishBD.Enabled = False
        self.connect(self.parametersPanel.pnlVarFinishBD,
                     SIGNAL("btnDegreeBoxPanel_clicked"), self.method_36_BD)
        # self.connect(self.parametersPanel.pnlVarFinishBD, SIGNAL("txtDegreeBox_textChanged"), self.txtDegreeBox_textChangedP)
        ui.verticalLayout_gbFinishPosBD.addWidget(
            self.parametersPanel.pnlVarFinishBD)

        self.parametersPanel.pnlPositionMVD = PositionPanel(
            self.parametersPanel.tabGeoDetermineMV, None, None, "Degree")
        self.parametersPanel.pnlPositionMVD.groupBox.setTitle("Position")
        self.parametersPanel.pnlPositionMVD.alwwaysShowString = "Degree"
        self.parametersPanel.pnlPositionMVD.btnCalculater.hide()
        self.parametersPanel.pnlPositionMVD.setObjectName("pnlPositionMVD")
        ui.verticalLayout_3.insertWidget(0,
                                         self.parametersPanel.pnlPositionMVD)
        self.connect(self.parametersPanel.pnlPositionMVD,
                     SIGNAL("positionChanged"), self.method_28_MVD)

        self.connect(self.parametersPanel.txtForwardTP, SIGNAL("Event_0"),
                     self.txtForwardTP_textChanged)
        self.connect(self.parametersPanel.chbAutoFinishMagVar,
                     SIGNAL("Event_0"), self.chbAutoFinishMagVar_clicked)
        self.connect(self.parametersPanel.txtDistanceP, SIGNAL("Event_0"),
                     self.autoCalcFinishMagVar)

        self.connect(self.parametersPanel.txtForwardMP, SIGNAL("Event_0"),
                     self.txtForwardMP_textChanged)
        self.parametersPanel.btnResultP.clicked.connect(
            self.btnResultP_clicked)
        self.parametersPanel.tabGeneral.currentChanged.connect(
            self.tabGeneral_CurrentChanged)
        self.parametersPanel.chbAutoVarBD.clicked.connect(
            self.chbAutoVarBD_clicked)
        self.parametersPanel.dtpDate.dateChanged.connect(self.method_28_MVD)
        self.connect(self.parametersPanel.cmbModel, SIGNAL("Event_0"),
                     self.method_28_MVD)
        self.parametersPanel.btnDtpDate.clicked.connect(
            self.btnDtpDate_clicked)

        self.resultModelP = QStandardItemModel()
        self.parametersPanel.tblResultP.setModel(self.resultModelP)

        self.resultModelBD = QStandardItemModel()
        self.parametersPanel.tblResultBD.setModel(self.resultModelBD)

        self.ttt = 0
        self.txtForwardTP_textChanged()

        self.setHistoryData()

        self.autoVarSet = False
        self.dateBD = QDate.currentDate()
        self.modelBD = MagneticModel.WMM2010
        self.parametersPanel.btnResultBD.setVisible(False)

        self.parametersPanel.dtpDate.setDate(QDate.currentDate())

        self.calendar = QCalendarWidget()
        self.calendar.clicked.connect(self.calendar_clicked)

        self.menu = QMenu()
        layout = QVBoxLayout(self.menu)
        layout.addWidget(self.calendar)
Exemplo n.º 36
0
    def __init__(self, iface, db, parent=None):
        QWidget.__init__(self, parent)
        self.iface = iface
        self.db = db
        self.allowMultiColumnPk = isinstance(
            db, PGDatabase
        )  # at the moment only PostGIS allows a primary key to span multiple columns, spatialite doesn't
        self.setupUi(self)
        self.setWindowTitle(
            u"%s - %s [%s]" %
            (self.windowTitle(), db.connection().connectionName(),
             db.connection().typeNameString()))

        self.defaultLayerName = 'QueryLayer'

        if self.allowMultiColumnPk:
            self.uniqueColumnCheck.setText(
                self.trUtf8("Column(s) with unique values"))
        else:
            self.uniqueColumnCheck.setText(
                self.trUtf8("Column with unique values"))

        self.editSql.setFocus()
        self.editSql.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.initCompleter()

        # allow to copy results
        copyAction = QAction("copy", self)
        self.viewResult.addAction(copyAction)
        copyAction.setShortcuts(QKeySequence.Copy)

        copyAction.triggered.connect(self.copySelectedResults)

        self.btnExecute.clicked.connect(self.executeSql)
        self.btnClear.clicked.connect(self.clearSql)

        self.presetStore.clicked.connect(self.storePreset)
        self.presetDelete.clicked.connect(self.deletePreset)
        self.presetCombo.activated[str].connect(self.loadPreset)
        self.presetCombo.activated[str].connect(self.presetName.setText)

        self.updatePresetsCombobox()

        self.geomCombo.setEditable(True)
        self.geomCombo.lineEdit().setReadOnly(True)

        self.uniqueCombo.setEditable(True)
        self.uniqueCombo.lineEdit().setReadOnly(True)
        self.uniqueModel = QStandardItemModel(self.uniqueCombo)
        self.uniqueCombo.setModel(self.uniqueModel)
        if self.allowMultiColumnPk:
            self.uniqueCombo.setItemDelegate(QStyledItemDelegate())
            self.uniqueModel.itemChanged.connect(
                self.uniqueChanged)  # react to the (un)checking of an item
            self.uniqueCombo.lineEdit().textChanged.connect(
                self.uniqueTextChanged
            )  # there are other events that change the displayed text and some of them can not be caught directly

        # hide the load query as layer if feature is not supported
        self._loadAsLayerAvailable = self.db.connector.hasCustomQuerySupport()
        self.loadAsLayerGroup.setVisible(self._loadAsLayerAvailable)
        if self._loadAsLayerAvailable:
            self.layerTypeWidget.hide()  # show if load as raster is supported
            self.loadLayerBtn.clicked.connect(self.loadSqlLayer)
            self.getColumnsBtn.clicked.connect(self.fillColumnCombos)
            self.loadAsLayerGroup.toggled.connect(self.loadAsLayerToggled)
            self.loadAsLayerToggled(False)

        self._createViewAvailable = self.db.connector.hasCreateSpatialViewSupport(
        )
        self.btnCreateView.setVisible(self._createViewAvailable)
        if self._createViewAvailable:
            self.btnCreateView.clicked.connect(self.createView)

        self.queryBuilderFirst = True
        self.queryBuilderBtn.setIcon(QIcon(":/db_manager/icons/sql.gif"))
        self.queryBuilderBtn.clicked.connect(self.displayQueryBuilder)

        self.presetName.textChanged.connect(self.nameChanged)
Exemplo n.º 37
0
class OWTestLearners(widget.OWWidget):
    name = "Test & Score"
    description = "Cross-validation accuracy estimation."
    icon = "icons/TestLearners1.svg"
    priority = 100

    inputs = [("Learner", Learner, "set_learner", widget.Multiple),
              ("Data", Table, "set_train_data", widget.Default),
              ("Test Data", Table, "set_test_data"),
              ("Preprocessor", Preprocess, "set_preprocessor")]

    outputs = [("Predictions", Orange.data.Table),
               ("Evaluation Results", Orange.evaluation.Results)]

    settingsHandler = settings.ClassValuesContextHandler()

    #: Resampling/testing types
    KFold, LeaveOneOut, ShuffleSplit, TestOnTrain, TestOnTest = 0, 1, 2, 3, 4

    #: Selected resampling type
    resampling = settings.Setting(0)
    #: Number of folds for K-fold cross validation
    k_folds = settings.Setting(10)
    #: Number of repeats for ShuffleSplit sampling
    n_repeat = settings.Setting(10)
    #: ShuffleSplit sampling p
    sample_p = settings.Setting(75)

    TARGET_AVERAGE = "(Average over classes)"
    class_selection = settings.ContextSetting(TARGET_AVERAGE)

    def __init__(self):
        super().__init__()

        self.data = None
        self.test_data = None
        self.preprocessor = None
        self.train_data_missing_vals = False
        self.test_data_missing_vals = False

        #: An Ordered dictionary with current inputs and their testing
        #: results.
        self.learners = OrderedDict()

        sbox = gui.widgetBox(self.controlArea, "Sampling")
        rbox = gui.radioButtons(sbox,
                                self,
                                "resampling",
                                callback=self._param_changed)
        gui.appendRadioButton(rbox, "Cross validation")
        ibox = gui.indentedBox(rbox)
        gui.spin(ibox,
                 self,
                 "k_folds",
                 2,
                 50,
                 label="Number of folds:",
                 callback=self.kfold_changed)
        gui.appendRadioButton(rbox, "Leave one out")
        gui.appendRadioButton(rbox, "Random sampling")
        ibox = gui.indentedBox(rbox)
        gui.spin(ibox,
                 self,
                 "n_repeat",
                 2,
                 50,
                 label="Repeat train/test",
                 callback=self.shuffle_split_changed)
        gui.widgetLabel(ibox, "Relative training set size:")
        gui.hSlider(ibox,
                    self,
                    "sample_p",
                    minValue=1,
                    maxValue=99,
                    ticks=20,
                    vertical=False,
                    labelFormat="%d %%",
                    callback=self.shuffle_split_changed)

        gui.appendRadioButton(rbox, "Test on train data")
        gui.appendRadioButton(rbox, "Test on test data")

        rbox.layout().addSpacing(5)
        self.apply_button = gui.button(rbox,
                                       self,
                                       "Apply",
                                       callback=self.apply,
                                       default=True)

        self.cbox = gui.widgetBox(self.controlArea, "Target class")
        self.class_selection_combo = gui.comboBox(
            self.cbox,
            self,
            "class_selection",
            items=[],
            sendSelectedValue=True,
            valueType=str,
            callback=self._on_target_class_changed,
            contentsLength=8)

        gui.rubber(self.controlArea)

        self.view = QTreeView(rootIsDecorated=False,
                              uniformRowHeights=True,
                              wordWrap=True,
                              editTriggers=QTreeView.NoEditTriggers)
        header = self.view.header()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setDefaultAlignment(Qt.AlignCenter)
        header.setStretchLastSection(False)

        self.result_model = QStandardItemModel(self)
        self.result_model.setHorizontalHeaderLabels(["Method"])
        self.view.setModel(self.result_model)
        self.view.setItemDelegate(ItemDelegate())

        box = gui.widgetBox(self.mainArea, "Evaluation Results")
        box.layout().addWidget(self.view)

    def sizeHint(self):
        return QSize(780, 1)

    def set_learner(self, learner, key):
        """
        Set the input `learner` for `key`.
        """
        if key in self.learners and learner is None:
            # Removed
            del self.learners[key]
        else:
            self.learners[key] = Input(learner, None, None)
            self._invalidate([key])

    def set_train_data(self, data):
        """
        Set the input training dataset.
        """
        self.error(0)
        self.information(0)
        if data and not data.domain.class_var:
            self.error(0, "Train data input requires a class variable")
            data = None

        if isinstance(data, SqlTable):
            if data.approx_len() < AUTO_DL_LIMIT:
                data = Table(data)
            else:
                self.information(0, "Train data has been sampled")
                data_sample = data.sample_time(1, no_cache=True)
                data_sample.download_data(AUTO_DL_LIMIT, partial=True)
                data = Table(data_sample)

        self.warning(4)
        self.train_data_missing_vals = data is not None and \
                                       np.isnan(data.Y).any()
        if self.train_data_missing_vals or self.test_data_missing_vals:
            self.warning(
                4,
                self._get_missing_data_warning(self.train_data_missing_vals,
                                               self.test_data_missing_vals))
            if data:
                data = RemoveNaNClasses(data)

        self.data = data
        self.closeContext()
        if data is not None:
            self._update_class_selection()
            self.openContext(data.domain.class_var)
        self._invalidate()

    def set_test_data(self, data):
        """
        Set the input separate testing dataset.
        """
        self.error(1)
        self.information(1)
        if data and not data.domain.class_var:
            self.error(1, "Test data input requires a class variable")
            data = None

        if isinstance(data, SqlTable):
            if data.approx_len() < AUTO_DL_LIMIT:
                data = Table(data)
            else:
                self.information(1, "Test data has been sampled")
                data_sample = data.sample_time(1, no_cache=True)
                data_sample.download_data(AUTO_DL_LIMIT, partial=True)
                data = Table(data_sample)

        self.warning(4)
        self.test_data_missing_vals = data is not None and \
                                      np.isnan(data.Y).any()
        if self.train_data_missing_vals or self.test_data_missing_vals:
            self.warning(
                4,
                self._get_missing_data_warning(self.train_data_missing_vals,
                                               self.test_data_missing_vals))
            if data:
                data = RemoveNaNClasses(data)

        self.test_data = data
        if self.resampling == OWTestLearners.TestOnTest:
            self._invalidate()

    def _get_missing_data_warning(self, train_missing, test_missing):
        return "Instances with unknown target values were removed from{}data"\
            .format(train_missing * test_missing * " "
                    or train_missing * " train " or test_missing * " test ")

    def set_preprocessor(self, preproc):
        """
        Set the input preprocessor to apply on the training data.
        """
        self.preprocessor = preproc
        self._invalidate()

    def handleNewSignals(self):
        """Reimplemented from OWWidget.handleNewSignals."""
        self._update_class_selection()
        self.apply()

    def kfold_changed(self):
        self.resampling = OWTestLearners.KFold
        self._param_changed()

    def shuffle_split_changed(self):
        self.resampling = OWTestLearners.ShuffleSplit
        self._param_changed()

    def _param_changed(self):
        self._invalidate()

    def _update_results(self):
        """
        Run/evaluate the learners.
        """
        self.warning([1, 2])
        self.error(2)

        if self.data is None:
            return

        class_var = self.data.domain.class_var

        if self.resampling == OWTestLearners.TestOnTest:
            if self.test_data is None:
                self.warning(2, "Missing separate test data input")
                return
            elif self.test_data.domain.class_var != class_var:
                self.error(2, ("Inconsistent class variable between test " +
                               "and train data sets"))
                return

        # items in need of an update
        items = [(key, slot) for key, slot in self.learners.items()
                 if slot.results is None]
        learners = [slot.learner for _, slot in items]
        if len(items) == 0:
            return

        if self.test_data is not None and \
                self.resampling != OWTestLearners.TestOnTest:
            self.warning(
                1, "Test data is present but unused. "
                "Select 'Test on test data' to use it.")

        rstate = 42

        def update_progress(finished):
            self.progressBarSet(100 * finished)

        common_args = dict(store_data=True,
                           preprocessor=self.preprocessor,
                           callback=update_progress)
        self.setStatusMessage("Running")
        self.progressBarInit()

        try:
            if self.resampling == OWTestLearners.KFold:
                warnings = []
                results = Orange.evaluation.CrossValidation(
                    self.data,
                    learners,
                    k=self.k_folds,
                    random_state=rstate,
                    warnings=warnings,
                    **common_args)
                if warnings:
                    self.warning(2, warnings[0])
            elif self.resampling == OWTestLearners.LeaveOneOut:
                results = Orange.evaluation.LeaveOneOut(
                    self.data, learners, **common_args)
            elif self.resampling == OWTestLearners.ShuffleSplit:
                train_size = self.sample_p / 100
                results = Orange.evaluation.ShuffleSplit(
                    self.data,
                    learners,
                    n_resamples=self.n_repeat,
                    train_size=train_size,
                    test_size=None,
                    random_state=rstate,
                    **common_args)
            elif self.resampling == OWTestLearners.TestOnTrain:
                results = Orange.evaluation.TestOnTrainingData(
                    self.data, learners, **common_args)
            elif self.resampling == OWTestLearners.TestOnTest:
                results = Orange.evaluation.TestOnTestData(
                    self.data, self.test_data, learners, **common_args)
            else:
                assert False
        except RuntimeError as e:
            self.error(2, str(e))
            self.setStatusMessage("")
            self.progressBarFinished()
            return

        learner_key = {
            slot.learner: key
            for key, slot in self.learners.items()
        }
        for learner, result in zip(learners, split_by_model(results)):
            stats = None
            if class_var.is_discrete:
                scorers = classification_stats.scores
            elif class_var.is_continuous:
                scorers = regression_stats.scores
            else:
                scorers = None
            if scorers:
                ex = result.failed[0]
                if ex:
                    stats = [Try.Fail(ex)] * len(scorers)
                    result = Try.Fail(ex)
                else:
                    stats = [Try(lambda: score(result)) for score in scorers]
                    result = Try.Success(result)
            key = learner_key[learner]
            self.learners[key] = \
                self.learners[key]._replace(results=result, stats=stats)

        self.setStatusMessage("")
        self.progressBarFinished()

    def _update_header(self):
        # Set the correct horizontal header labels on the results_model.
        headers = ["Method"]
        if self.data is not None:
            if self.data.domain.has_discrete_class:
                headers.extend(classification_stats.headers)
            else:
                headers.extend(regression_stats.headers)

        # remove possible extra columns from the model.
        for i in reversed(range(len(headers),
                                self.result_model.columnCount())):
            self.result_model.takeColumn(i)

        self.result_model.setHorizontalHeaderLabels(headers)

    def _update_stats_model(self):
        # Update the results_model with up to date scores.
        # Note: The target class specific scores (if requested) are
        # computed as needed in this method.
        model = self.view.model()
        # clear the table model, but preserving the header labels
        for r in reversed(range(model.rowCount())):
            model.takeRow(r)

        target_index = None
        if self.data is not None:
            class_var = self.data.domain.class_var
            if class_var.is_discrete and \
                    self.class_selection != self.TARGET_AVERAGE:
                target_index = class_var.values.index(self.class_selection)
        else:
            class_var = None

        errors = []
        has_missing_scores = False

        for key, slot in self.learners.items():
            name = learner_name(slot.learner)
            head = QStandardItem(name)
            head.setData(key, Qt.UserRole)
            if isinstance(slot.results, Try.Fail):
                head.setToolTip(str(slot.results.exception))
                head.setText("{} (error)".format(name))
                head.setForeground(QtGui.QBrush(Qt.red))
                errors.append("{name} failed with error:\n"
                              "{exc.__class__.__name__}: {exc!s}".format(
                                  name=name, exc=slot.results.exception))

            row = [head]

            if class_var is not None and class_var.is_discrete and \
                    target_index is not None:
                if slot.results is not None and slot.results.success:
                    ovr_results = results_one_vs_rest(slot.results.value,
                                                      target_index)

                    stats = [
                        Try(lambda: score(ovr_results))
                        for score in classification_stats.scores
                    ]
                else:
                    stats = None
            else:
                stats = slot.stats

            if stats is not None:
                for stat in stats:
                    item = QStandardItem()
                    if stat.success:
                        item.setText("{:.3f}".format(stat.value[0]))
                    else:
                        item.setToolTip(str(stat.exception))
                        has_missing_scores = True
                    row.append(item)

            model.appendRow(row)

        if errors:
            self.error(3, "\n".join(errors))
        else:
            self.error(3)

        if has_missing_scores:
            self.warning(3, "Some scores could not be computed")
        else:
            self.warning(3)

    def _update_class_selection(self):
        self.class_selection_combo.setCurrentIndex(-1)
        self.class_selection_combo.clear()
        if not self.data:
            return

        if self.data.domain.has_discrete_class:
            self.cbox.setVisible(True)
            class_var = self.data.domain.class_var
            items = [self.TARGET_AVERAGE] + class_var.values
            self.class_selection_combo.addItems(items)

            class_index = 0
            if self.class_selection in class_var.values:
                class_index = class_var.values.index(self.class_selection) + 1

            self.class_selection_combo.setCurrentIndex(class_index)
            self.class_selection = items[class_index]
        else:
            self.cbox.setVisible(False)

    def _on_target_class_changed(self):
        self._update_stats_model()

    def _invalidate(self, which=None):
        # Invalidate learner results for `which` input keys
        # (if None then all learner results are invalidated)
        if which is None:
            which = self.learners.keys()

        model = self.view.model()
        statmodelkeys = [
            model.item(row, 0).data(Qt.UserRole)
            for row in range(model.rowCount())
        ]

        for key in which:
            self.learners[key] = \
                self.learners[key]._replace(results=None, stats=None)

            if key in statmodelkeys:
                row = statmodelkeys.index(key)
                for c in range(1, model.columnCount()):
                    item = model.item(row, c)
                    if item is not None:
                        item.setData(None, Qt.DisplayRole)
                        item.setData(None, Qt.ToolTipRole)

        self.apply_button.setEnabled(True)

    def apply(self):
        self.apply_button.setEnabled(False)
        self._update_header()
        # Update the view to display the model names
        self._update_stats_model()
        self._update_results()
        self._update_stats_model()
        self.commit()

    def commit(self):
        valid = [
            slot for slot in self.learners.values()
            if slot.results is not None and slot.results.success
        ]
        if valid:
            # Evaluation results
            combined = results_merge([slot.results.value for slot in valid])
            combined.learner_names = [
                learner_name(slot.learner) for slot in valid
            ]

            # Predictions & Probabilities
            predictions = combined.get_augmented_data(combined.learner_names)
        else:
            combined = None
            predictions = None
        self.send("Evaluation Results", combined)
        self.send("Predictions", predictions)
Exemplo n.º 38
0
class AbstractSTREnityListView(QListView):
    """
    A widget for listing and selecting one or more STR entities.
    .. versionadded:: 1.7
    """
    def __init__(self, parent=None, **kwargs):
        super(AbstractSTREnityListView, self).__init__(parent)

        self._model = QStandardItemModel(self)
        self._model.setColumnCount(1)
        self.setModel(self._model)
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self._model.itemChanged.connect(self._on_item_changed)

        self._profile = kwargs.get('profile', None)
        self._social_tenure = kwargs.get('social_tenure', None)

        # Load appropriate entities to the view
        if not self._profile is None:
            self._load_profile_entities()

        # Load entities in the STR definition
        if not self._social_tenure is None:
            self._select_str_entities()

    def _on_item_changed(self, item):
        # Emit signals when an item has been (de)selected. To be
        # implemented by subclasses.
        pass

    @property
    def profile(self):
        """
        :return: Returns the current profile object in the configuration.
        :rtype: Profile
        """
        return self._profile

    @profile.setter
    def profile(self, profile):
        """
        Sets the current profile object in the configuration.
        :param profile: Profile object.
        :type profile: Profile
        """
        self._profile = profile
        self._load_profile_entities()

    @property
    def social_tenure(self):
        """
        :return: Returns the profile's social tenure entity.
        :rtype: SocialTenure
        """
        return self._social_tenure

    @social_tenure.setter
    def social_tenure(self, social_tenure):
        """
        Set the social_tenure entity.
        :param social_tenure: A profile's social tenure entity.
        :type social_tenure: SocialTenure
        """
        self._social_tenure = social_tenure
        self._select_str_entities()

    def _select_str_entities(self):
        """
        Select the entities defined in the STR. E.g. parties for party 
        entity and spatial units for spatial unit entity. Default 
        implementation does nothing, to be implemented by subclasses.
        """
        pass

    def _load_profile_entities(self):
        # Reset view
        self.clear()

        # Populate entity items in the view
        for e in self._profile.user_entities():
            self._add_entity(e)

    def _add_entity(self, entity):
        # Add entity item to view
        item = QStandardItem(
            QIcon(':/plugins/stdm/images/icons/table.png'),
            entity.short_name
        )
        item.setCheckable(True)
        item.setCheckState(Qt.Unchecked)

        self._model.appendRow(item)

    def select_entities(self, entities):
        """
        Checks STR entities in the view and emit the entity_selected
        signal for each item selected.
        :param entities: Collection of STR entities.
        :type entities: list
        """
        # Clear selection
        self.clear_selection()

        for e in entities:
            name = e.short_name
            self.select_entity(name)

    def selected_entities(self):
        """
        :return: Returns a list of selected entity short names.
        :rtype: list
        """
        selected_items = []

        for i in range(self._model.rowCount()):
            item = self._model.item(i)
            if item.checkState() == Qt.Checked:
                selected_items.append(item.text())

        return selected_items

    def clear(self):
        """
        Remove all party items in the view.
        """
        self._model.clear()
        self._model.setColumnCount(1)

    def clear_selection(self):
        """
        Uncheck all items in the view.
        """
        for i in range(self._model.rowCount()):
            item = self._model.item(i)
            if item.checkState() == Qt.Checked:
                item.setCheckState(Qt.Unchecked)

    def select_entity(self, name):
        """
        Selects a party entity with the given short name.
        :param name: Entity short name
        :type name: str
        """
        items = self._model.findItems(name)
        if len(items) > 0:
            item = items[0]
            if item.checkState() == Qt.Unchecked:
                item.setCheckState(Qt.Checked)

    def deselect_entity(self, name):
        """
        Deselects an entity with the given short name.
        :param name: Entity short name
        :type name: str
        """
        items = self._model.findItems(name)
        if len(items) > 0:
            item = items[0]
            if item.checkState() == Qt.Checked:
                item.setCheckState(Qt.Unchecked)
Exemplo n.º 39
0
class DlgSqlWindow(QWidget, Ui_Dialog):
    nameChanged = pyqtSignal(str)

    def __init__(self, iface, db, parent=None):
        QWidget.__init__(self, parent)
        self.iface = iface
        self.db = db
        self.allowMultiColumnPk = isinstance(
            db, PGDatabase
        )  # at the moment only PostGIS allows a primary key to span multiple columns, spatialite doesn't
        self.setupUi(self)
        self.setWindowTitle(
            u"%s - %s [%s]" %
            (self.windowTitle(), db.connection().connectionName(),
             db.connection().typeNameString()))

        self.defaultLayerName = 'QueryLayer'

        if self.allowMultiColumnPk:
            self.uniqueColumnCheck.setText(
                self.trUtf8("Column(s) with unique values"))
        else:
            self.uniqueColumnCheck.setText(
                self.trUtf8("Column with unique values"))

        self.editSql.setFocus()
        self.editSql.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.initCompleter()

        # allow to copy results
        copyAction = QAction("copy", self)
        self.viewResult.addAction(copyAction)
        copyAction.setShortcuts(QKeySequence.Copy)

        copyAction.triggered.connect(self.copySelectedResults)

        self.btnExecute.clicked.connect(self.executeSql)
        self.btnClear.clicked.connect(self.clearSql)

        self.presetStore.clicked.connect(self.storePreset)
        self.presetDelete.clicked.connect(self.deletePreset)
        self.presetCombo.activated[str].connect(self.loadPreset)
        self.presetCombo.activated[str].connect(self.presetName.setText)

        self.updatePresetsCombobox()

        self.geomCombo.setEditable(True)
        self.geomCombo.lineEdit().setReadOnly(True)

        self.uniqueCombo.setEditable(True)
        self.uniqueCombo.lineEdit().setReadOnly(True)
        self.uniqueModel = QStandardItemModel(self.uniqueCombo)
        self.uniqueCombo.setModel(self.uniqueModel)
        if self.allowMultiColumnPk:
            self.uniqueCombo.setItemDelegate(QStyledItemDelegate())
            self.uniqueModel.itemChanged.connect(
                self.uniqueChanged)  # react to the (un)checking of an item
            self.uniqueCombo.lineEdit().textChanged.connect(
                self.uniqueTextChanged
            )  # there are other events that change the displayed text and some of them can not be caught directly

        # hide the load query as layer if feature is not supported
        self._loadAsLayerAvailable = self.db.connector.hasCustomQuerySupport()
        self.loadAsLayerGroup.setVisible(self._loadAsLayerAvailable)
        if self._loadAsLayerAvailable:
            self.layerTypeWidget.hide()  # show if load as raster is supported
            self.loadLayerBtn.clicked.connect(self.loadSqlLayer)
            self.getColumnsBtn.clicked.connect(self.fillColumnCombos)
            self.loadAsLayerGroup.toggled.connect(self.loadAsLayerToggled)
            self.loadAsLayerToggled(False)

        self._createViewAvailable = self.db.connector.hasCreateSpatialViewSupport(
        )
        self.btnCreateView.setVisible(self._createViewAvailable)
        if self._createViewAvailable:
            self.btnCreateView.clicked.connect(self.createView)

        self.queryBuilderFirst = True
        self.queryBuilderBtn.setIcon(QIcon(":/db_manager/icons/sql.gif"))
        self.queryBuilderBtn.clicked.connect(self.displayQueryBuilder)

        self.presetName.textChanged.connect(self.nameChanged)

    def updatePresetsCombobox(self):
        self.presetCombo.clear()

        names = []
        entries = QgsProject.instance().subkeyList('DBManager', 'savedQueries')
        for entry in entries:
            name = QgsProject.instance().readEntry(
                'DBManager', 'savedQueries/' + entry + '/name')[0]
            names.append(name)

        for name in sorted(names):
            self.presetCombo.addItem(name)
        self.presetCombo.setCurrentIndex(-1)

    def storePreset(self):
        query = self._getSqlQuery()
        if query == "":
            return
        name = self.presetName.text()
        QgsProject.instance().writeEntry(
            'DBManager', 'savedQueries/q' + unicode(name.__hash__()) + '/name',
            name)
        QgsProject.instance().writeEntry(
            'DBManager',
            'savedQueries/q' + unicode(name.__hash__()) + '/query', query)
        index = self.presetCombo.findText(name)
        if index == -1:
            self.presetCombo.addItem(name)
            self.presetCombo.setCurrentIndex(self.presetCombo.count() - 1)
        else:
            self.presetCombo.setCurrentIndex(index)

    def deletePreset(self):
        name = self.presetCombo.currentText()
        QgsProject.instance().removeEntry(
            'DBManager', 'savedQueries/q' + unicode(name.__hash__()))
        self.presetCombo.removeItem(self.presetCombo.findText(name))
        self.presetCombo.setCurrentIndex(-1)

    def loadPreset(self, name):
        query = QgsProject.instance().readEntry(
            'DBManager',
            'savedQueries/q' + unicode(name.__hash__()) + '/query')[0]
        name = QgsProject.instance().readEntry(
            'DBManager',
            'savedQueries/q' + unicode(name.__hash__()) + '/name')[0]
        self.editSql.setText(query)

    def loadAsLayerToggled(self, checked):
        self.loadAsLayerGroup.setChecked(checked)
        self.loadAsLayerWidget.setVisible(checked)
        if checked:
            self.fillColumnCombos()

    def clearSql(self):
        self.editSql.clear()
        self.editSql.setFocus()

    def executeSql(self):

        sql = self._getSqlQuery()
        if sql == "":
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        # delete the old model
        old_model = self.viewResult.model()
        self.viewResult.setModel(None)
        if old_model:
            old_model.deleteLater()

        cols = []
        quotedCols = []

        try:
            # set the new model
            model = self.db.sqlResultModel(sql, self)
            self.viewResult.setModel(model)
            self.lblResult.setText(
                self.tr("%d rows, %.1f seconds") %
                (model.affectedRows(), model.secs()))
            cols = self.viewResult.model().columnNames()
            for col in cols:
                quotedCols.append(self.db.connector.quoteId(col))

        except BaseError as e:
            QApplication.restoreOverrideCursor()
            DlgDbError.showError(e, self)
            self.uniqueModel.clear()
            self.geomCombo.clear()
            return

        self.setColumnCombos(cols, quotedCols)

        self.update()
        QApplication.restoreOverrideCursor()

    def loadSqlLayer(self):
        hasUniqueField = self.uniqueColumnCheck.checkState() == Qt.Checked
        if hasUniqueField:
            if self.allowMultiColumnPk:
                checkedCols = []
                for item in self.uniqueModel.findItems("*", Qt.MatchWildcard):
                    if item.checkState() == Qt.Checked:
                        checkedCols.append(item.data())
                uniqueFieldName = ",".join(checkedCols)
            elif self.uniqueCombo.currentIndex() >= 0:
                uniqueFieldName = self.uniqueModel.item(
                    self.uniqueCombo.currentIndex()).data()
            else:
                uniqueFieldName = None
        else:
            uniqueFieldName = None
        hasGeomCol = self.hasGeometryCol.checkState() == Qt.Checked
        if hasGeomCol:
            geomFieldName = self.geomCombo.currentText()
        else:
            geomFieldName = None

        query = self._getSqlQuery()
        if query == "":
            return

        # remove a trailing ';' from query if present
        if query.strip().endswith(';'):
            query = query.strip()[:-1]

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        from qgis.core import QgsMapLayer, QgsMapLayerRegistry

        layerType = QgsMapLayer.VectorLayer if self.vectorRadio.isChecked(
        ) else QgsMapLayer.RasterLayer

        # get a new layer name
        names = []
        for layer in QgsMapLayerRegistry.instance().mapLayers().values():
            names.append(layer.name())

        layerName = self.layerNameEdit.text()
        if layerName == "":
            layerName = self.defaultLayerName
        newLayerName = layerName
        index = 1
        while newLayerName in names:
            index += 1
            newLayerName = u"%s_%d" % (layerName, index)

        # create the layer
        layer = self.db.toSqlLayer(query, geomFieldName, uniqueFieldName,
                                   newLayerName, layerType,
                                   self.avoidSelectById.isChecked())
        if layer.isValid():
            QgsMapLayerRegistry.instance().addMapLayers([layer], True)

        QApplication.restoreOverrideCursor()

    def fillColumnCombos(self):
        query = self._getSqlQuery()
        if query == "":
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        # get a new alias
        aliasIndex = 0
        while True:
            alias = "_%s__%d" % ("subQuery", aliasIndex)
            escaped = re.compile('\\b("?)' + re.escape(alias) + '\\1\\b')
            if not escaped.search(query):
                break
            aliasIndex += 1

        # remove a trailing ';' from query if present
        if query.strip().endswith(';'):
            query = query.strip()[:-1]

        # get all the columns
        cols = []
        quotedCols = []
        connector = self.db.connector
        sql = u"SELECT * FROM (%s\n) AS %s LIMIT 0" % (
            unicode(query), connector.quoteId(alias))

        c = None
        try:
            c = connector._execute(None, sql)
            cols = connector._get_cursor_columns(c)
            for col in cols:
                quotedCols.append(connector.quoteId(col))

        except BaseError as e:
            QApplication.restoreOverrideCursor()
            DlgDbError.showError(e, self)
            self.uniqueModel.clear()
            self.geomCombo.clear()
            return

        finally:
            if c:
                c.close()
                del c

        self.setColumnCombos(cols, quotedCols)

        QApplication.restoreOverrideCursor()

    def setColumnCombos(self, cols, quotedCols):
        # get sensible default columns. do this before sorting in case there's hints in the column order (eg, id is more likely to be first)
        try:
            defaultGeomCol = next(
                col for col in cols
                if col in ['geom', 'geometry', 'the_geom', 'way'])
        except:
            defaultGeomCol = None
        try:
            defaultUniqueCol = [col for col in cols if 'id' in col][0]
        except:
            defaultUniqueCol = None

        colNames = sorted(zip(cols, quotedCols))
        newItems = []
        uniqueIsFilled = False
        for (col, quotedCol) in colNames:
            item = QStandardItem(col)
            item.setData(quotedCol)
            item.setEnabled(True)
            item.setCheckable(self.allowMultiColumnPk)
            item.setSelectable(not self.allowMultiColumnPk)
            if self.allowMultiColumnPk:
                matchingItems = self.uniqueModel.findItems(col)
                if matchingItems:
                    item.setCheckState(matchingItems[0].checkState())
                    uniqueIsFilled = uniqueIsFilled or matchingItems[
                        0].checkState() == Qt.Checked
                else:
                    item.setCheckState(Qt.Unchecked)
            newItems.append(item)
        if self.allowMultiColumnPk:
            self.uniqueModel.clear()
            self.uniqueModel.appendColumn(newItems)
            self.uniqueChanged()
        else:
            previousUniqueColumn = self.uniqueCombo.currentText()
            self.uniqueModel.clear()
            self.uniqueModel.appendColumn(newItems)
            if self.uniqueModel.findItems(previousUniqueColumn):
                self.uniqueCombo.setEditText(previousUniqueColumn)
                uniqueIsFilled = True

        oldGeometryColumn = self.geomCombo.currentText()
        self.geomCombo.clear()
        self.geomCombo.addItems(cols)
        self.geomCombo.setCurrentIndex(
            self.geomCombo.findText(oldGeometryColumn, Qt.MatchExactly))

        # set sensible default columns if the columns are not already set
        try:
            if self.geomCombo.currentIndex() == -1:
                self.geomCombo.setCurrentIndex(cols.index(defaultGeomCol))
        except:
            pass
        items = self.uniqueModel.findItems(defaultUniqueCol)
        if items and not uniqueIsFilled:
            if self.allowMultiColumnPk:
                items[0].setCheckState(Qt.Checked)
            else:
                self.uniqueCombo.setEditText(defaultUniqueCol)
        try:
            pass
        except:
            pass

    def copySelectedResults(self):
        if len(self.viewResult.selectedIndexes()) <= 0:
            return
        model = self.viewResult.model()

        # convert to string using tab as separator
        text = model.headerToString("\t")
        for idx in self.viewResult.selectionModel().selectedRows():
            text += "\n" + model.rowToString(idx.row(), "\t")

        QApplication.clipboard().setText(text, QClipboard.Selection)
        QApplication.clipboard().setText(text, QClipboard.Clipboard)

    def initCompleter(self):
        dictionary = None
        if self.db:
            dictionary = self.db.connector.getSqlDictionary()
        if not dictionary:
            # use the generic sql dictionary
            from .sql_dictionary import getSqlDictionary

            dictionary = getSqlDictionary()

        wordlist = []
        for name, value in dictionary.iteritems():
            wordlist += value  # concat lists
        wordlist = list(set(wordlist))  # remove duplicates

        api = QsciAPIs(self.editSql.lexer())
        for word in wordlist:
            api.add(word)

        api.prepare()
        self.editSql.lexer().setAPIs(api)

    def displayQueryBuilder(self):
        dlg = QueryBuilderDlg(self.iface,
                              self.db,
                              self,
                              reset=self.queryBuilderFirst)
        self.queryBuilderFirst = False
        r = dlg.exec_()
        if r == QDialog.Accepted:
            self.editSql.setText(dlg.query)

    def createView(self):
        name, ok = QInputDialog.getText(None, "View name", "View name")
        if ok:
            try:
                self.db.connector.createSpatialView(name, self._getSqlQuery())
            except BaseError as e:
                DlgDbError.showError(e, self)

    def _getSqlQuery(self):
        sql = self.editSql.selectedText()
        if len(sql) == 0:
            sql = self.editSql.text()
        return sql

    def uniqueChanged(self):
        # when an item is (un)checked, simply trigger an update of the combobox text
        self.uniqueTextChanged(None)

    def uniqueTextChanged(self, text):
        # Whenever there is new text displayed in the combobox, check if it is the correct one and if not, display the correct one.
        checkedItems = []
        for item in self.uniqueModel.findItems("*", Qt.MatchWildcard):
            if item.checkState() == Qt.Checked:
                checkedItems.append(item.text())
        label = ", ".join(checkedItems)
        if text != label:
            self.uniqueCombo.setEditText(label)
Exemplo n.º 40
0
    def randomize_groups(self):
        #participant_list_form = Participant_list()
        #participant_list_form.show()
        #participant_list_form.ui3.label.setText("sdsdfdsf")
        #ex2.ui.label_6.setText("test")
        participant_list_form = ex3
        # participant_list_form = Participant_list()
        # participant_list_form.show()
        tv = participant_list_form.ui3.tableView

        # set the table model
        tablemdata = 0
        #tabledata.append([2, 2, 2, 2, 2])
        # tabledata.remove([0])
        # tabledata.append([1, 1, 1, 1, 1])
        # table.model().layoutChanged.emit()
        tablemodel = MyTableModel(tabledata, header, self)
        rowcount = int(tablemodel.rowCount(None))
        tvmodel = tv.model()
        nums = [x+1 for x in range(rowcount)]
        random.shuffle(nums)

        print nums

        #iterating list





        #print i+1 % groups_to_create

        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # init widgets
        view = ex8.ui8.treeView
        view.setSelectionBehavior(QAbstractItemView.SelectRows)
        model = QStandardItemModel()
        model.setHorizontalHeaderLabels(header)
        view.setModel(model)
        view.setUniformRowHeights(True)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # populate data

        groups_to_create = int(self.ui.lineEdit.text())
        participants_in_group = int(self.ui.lineEdit_2.text())
        divider = 0
        group = 1
        parent1 = QStandardItem('Grupa {}'.format(group))
        for i, val in enumerate(nums):

            if divider == participants_in_group:
                divider = 0
                group = group + 1
                parent1 = QStandardItem('Grupa {}'.format(group))
            divider = divider + 1
            if val != 0:
                print "Grupa " + str(group) + " Osoby: " + str(val)
                self.tableindex_id = tablemodel.index (val-1,1)
                self.tableindex_surname = tablemodel.index (val-1,2)
                child1 = QStandardItem(str(val)+' '+" ")
                child2 = QStandardItem(str(tablemodel.data(self.tableindex_id,  Qt.DisplayRole)))
                child3 = QStandardItem(str(tablemodel.data(self.tableindex_surname,  Qt.DisplayRole)))
                parent1.appendRow([child1, child2, child3])


                model.appendRow(parent1)
                # span container columns
                view.setFirstColumnSpanned(i, view.rootIndex(), True)


        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # expand third container
        index = model.indexFromItem(parent1)
        view.expand(index)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # select last row
        selmod = view.selectionModel()
        index2 = model.indexFromItem(child3)
        selmod.select(index2, QItemSelectionModel.Select | QItemSelectionModel.Rows)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        print i+1
        if i+1 > 3:
            print i / groups_to_create
        else:
            print i / groups_to_create

        #index = tablemodel.index(row, 1)

        print nums
Exemplo n.º 41
0
    def __init__(self, *args):
        QWidget.__init__(self, *args)
        self.setContentsMargins(0, 0, 0, 0)
        gridLayout = QGridLayout()
        gridLayout.setContentsMargins(0, 0, 0, 0)
        gridLayout.setSpacing(1)

        model = QStandardItemModel(self)
        model.rowsInserted.connect(self.__changed)
        model.rowsRemoved.connect(self.__changed)
        model.dataChanged.connect(self.__changed)

        self._listView = QListView(self)
        self._listView.setModel(model)
        #        self._listView.setDragEnabled(True)
        self._listView.setDropIndicatorShown(True)
        self._listView.setDragDropMode(QListView.InternalMove)
        self._listView.viewport().setAcceptDrops(True)
        self._listView.setMinimumHeight(100)

        gridLayout.addWidget(self._listView, 0, 0, 2, 2)

        vButtonLayout = QVBoxLayout()

        self._upAction = QAction("\u2191", self, toolTip="Move up")

        self._upButton = QToolButton(self)
        self._upButton.setDefaultAction(self._upAction)
        self._upButton.setSizePolicy(QSizePolicy.Fixed,
                                     QSizePolicy.MinimumExpanding)

        self._downAction = QAction("\u2193", self, toolTip="Move down")

        self._downButton = QToolButton(self)
        self._downButton.setDefaultAction(self._downAction)
        self._downButton.setSizePolicy(QSizePolicy.Fixed,
                                       QSizePolicy.MinimumExpanding)

        vButtonLayout.addWidget(self._upButton)
        vButtonLayout.addWidget(self._downButton)

        gridLayout.addLayout(vButtonLayout, 0, 2, 2, 1)

        hButtonLayout = QHBoxLayout()

        self._addAction = QAction("+", self)
        self._addButton = QToolButton(self)
        self._addButton.setDefaultAction(self._addAction)

        self._removeAction = QAction("-", self)
        self._removeButton = QToolButton(self)
        self._removeButton.setDefaultAction(self._removeAction)
        hButtonLayout.addWidget(self._addButton)
        hButtonLayout.addWidget(self._removeButton)
        hButtonLayout.addStretch(10)
        gridLayout.addLayout(hButtonLayout, 2, 0, 1, 2)

        self.setLayout(gridLayout)
        self._addAction.triggered.connect(self._onAddAction)
        self._removeAction.triggered.connect(self._onRemoveAction)
        self._upAction.triggered.connect(self._onUpAction)
        self._downAction.triggered.connect(self._onDownAction)
class GeoDetermineDlg(FlightPlanBaseDlg):
    HistoryDataP = []
    HistoryDataBD = []
    HistoryDataMV = []

    def __init__(self, parent):
        FlightPlanBaseDlg.__init__(self, parent)
        self.setObjectName("HoldingRnavDlg")
        self.surfaceType = SurfaceTypes.GeoDetermine
        self.initParametersPan()
        self.setWindowTitle(SurfaceTypes.GeoDetermine)
        self.resize(540, 550)
        self.surfaceList = None

        self.date = QDate.currentDate()
        self.model = MagneticModel.WMM2010
        geo = Geo()

        self.resultLayerList = []
        self.resultPoint3d = None

        self.resultLat = None
        self.resultLon = None

    def uiStateInit(self):
        self.ui.grbMostCritical.setVisible(False)
        self.ui.grbResult_2.setVisible(False)
        self.ui.btnUpdateQA.setVisible(False)
        self.ui.btnUpdateQA_2.setVisible(False)
        self.ui.btnExportResult.setVisible(False)
        self.ui.btnEvaluate.setVisible(False)
        self.ui.btnPDTCheck.setVisible(False)
        self.ui.frm_cmbObstSurface.setVisible(False)
        self.ui.tabCtrlGeneral.removeTab(1)

        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/Calculator.bmp")), QIcon.Normal,
                       QIcon.Off)
        self.ui.btnConstruct.setIcon(icon)
        self.ui.btnConstruct.setToolTip("Calculate")

        return FlightPlanBaseDlg.uiStateInit(self)

    def tblHistory_Click(self, modelIndex):
        if modelIndex != None:
            if self.parametersPanel.tabGeneral.currentIndex() == 0:
                dataList = GeoDetermineDlg.HistoryDataP[modelIndex.row()]

                self.parametersPanel.pnlStartPosP.Point3d = Point3D(
                    float(dataList[1][1]), float(dataList[1][0]))
                self.parametersPanel.pnlVarStartP.Value = float(dataList[1][2])
                self.parametersPanel.txtForwardTP.Value = float(dataList[1][3])
                self.parametersPanel.txtForwardMP.Value = float(dataList[1][4])
                self.parametersPanel.txtDistanceP.Value = Distance(
                    float(dataList[1][5]), DistanceUnits.NM)
                self.parametersPanel.pnlVarFinishP.Value = float(
                    dataList[1][9])

                self.method_29_P()
                self.resultModelP.setItem(0, 0,
                                          QStandardItem(Captions.LATITUDE))
                self.resultModelP.setItem(0, 1, QStandardItem(dataList[1][7]))

                self.resultModelP.setItem(1, 0,
                                          QStandardItem(Captions.LONGITUDE))
                self.resultModelP.setItem(1, 1, QStandardItem(dataList[1][8]))

                self.resultModelP.setItem(
                    2, 0, QStandardItem(Captions.REVERSE_TRUE_BEARING))
                self.resultModelP.setItem(2, 1, QStandardItem(dataList[1][10]))

                self.resultModelP.setItem(
                    3, 0, QStandardItem(Captions.REVERSE_MAGNETIC_BEARING))
                self.resultModelP.setItem(3, 1, QStandardItem(dataList[1][11]))
            elif self.parametersPanel.tabGeneral.currentIndex() == 1:
                dataList = GeoDetermineDlg.HistoryDataBD[modelIndex.row()]

                self.parametersPanel.pnlStartPosBD.ID = dataList[1][0]
                self.parametersPanel.pnlStartPosBD.Point3d = Point3D(
                    float(dataList[1][2]), float(dataList[1][1]))
                self.parametersPanel.pnlVarStartBD.Value = float(
                    dataList[1][3])
                self.parametersPanel.pnlFinishPosBD.ID = dataList[1][4]
                self.parametersPanel.pnlFinishPosBD.Point3d = Point3D(
                    float(dataList[1][6]), float(dataList[1][5]))
                self.parametersPanel.pnlVarFinishBD.Value = float(
                    dataList[1][7])

                self.method_31_BD()
                self.resultModelBD.setItem(
                    0, 0, QStandardItem(Captions.FORWARD_TRUE_BEARING))
                self.resultModelBD.setItem(0, 1, QStandardItem(dataList[1][8]))

                self.resultModelBD.setItem(
                    1, 0, QStandardItem(Captions.FORWARD_MAGNETIC_BEARING))
                self.resultModelBD.setItem(1, 1, QStandardItem(dataList[1][9]))

                self.resultModelBD.setItem(
                    2, 0, QStandardItem(Captions.REVERSE_TRUE_BEARING))
                self.resultModelBD.setItem(2, 1,
                                           QStandardItem(dataList[1][10]))

                self.resultModelBD.setItem(
                    3, 0, QStandardItem(Captions.REVERSE_MAGNETIC_BEARING))
                self.resultModelBD.setItem(3, 1,
                                           QStandardItem(dataList[1][11]))

                self.resultModelBD.setItem(
                    2, 0, QStandardItem(Captions.DISTANCE_BETWEEN_POSITIONS))
                self.resultModelBD.setItem(2, 1,
                                           QStandardItem(dataList[1][12]))

                self.resultModelBD.setItem(
                    3, 0, QStandardItem(Captions.DISTANCE_BETWEEN_POSITIONS))
                self.resultModelBD.setItem(3, 1,
                                           QStandardItem(dataList[1][13]))
            else:
                dataList = GeoDetermineDlg.HistoryDataMV[modelIndex.row()]

                self.parametersPanel.pnlPositionMVD.Point3d = Point3D(
                    float(dataList[1][1]), float(dataList[1][0]))
                self.parametersPanel.pnlPositionMVD.txtAltitudeM.setText(
                    dataList[1][2])
                self.parametersPanel.txtResult.Value = dataList[1][6]

    def calculateP(self):
        degree = None
        degree1 = None
        degree2 = None
        degree3 = None
        num = None
        result, degree, degree1 = self.parametersPanel.pnlStartPosP.method_3()
        if (result):
            # self.pnlVarStart.Value.smethod_17();
            num1 = float(self.parametersPanel.pnlVarFinishP.Value)
            value = float(self.parametersPanel.txtForwardTP.Value)
            value1 = float(self.parametersPanel.txtForwardTP.Value)
            distance = self.parametersPanel.txtDistanceP.Value
            result, degree2, degree3, num = Geo.smethod_6(
                self.parametersPanel.cmbCalculationTypeP.SelectedItem, degree,
                degree1, value, distance)
            if (result):
                num2 = MathHelper.smethod_3(num - num1)
                self.method_29_P()
                self.resultPoint3d = Point3D(degree3, degree2)

                self.resultLat = degree2
                self.resultLon = degree3

                latStr = Degrees(degree2, None, None,
                                 DegreesType.Latitude).ToString()

                self.resultModelP.setItem(0, 0,
                                          QStandardItem(Captions.LATITUDE))
                self.resultModelP.setItem(0, 1, QStandardItem(latStr))

                lonStr = Degrees(degree3, None, None,
                                 DegreesType.Longitude).ToString()
                if String.Str2QString(lonStr).mid(0, 1) == "0":
                    lonStr = String.Str2QString(lonStr).mid(
                        1,
                        String.Str2QString(lonStr).length() - 1)

                self.resultModelP.setItem(1, 0,
                                          QStandardItem(Captions.LONGITUDE))
                self.resultModelP.setItem(1, 1, QStandardItem(lonStr))

                self.resultModelP.setItem(
                    2, 0, QStandardItem(Captions.REVERSE_TRUE_BEARING))
                self.resultModelP.setItem(2, 1,
                                          QStandardItem(str(round(num, 4))))

                self.resultModelP.setItem(
                    3, 0, QStandardItem(Captions.REVERSE_MAGNETIC_BEARING))
                self.resultModelP.setItem(3, 1,
                                          QStandardItem(str(round(num2, 4))))

                dataList = []
                dataList.append([
                    "Latitude (Start)", "Longitude (Start)",
                    "Variation (Start)", "Forward (° T)", "Forward (° M)",
                    "Distance (nm)", "Distance (km)", "Latitude (Finish)",
                    "Longitude (Finish)", "Variation (Finish)",
                    "Reverse (° T)", "Reverse (° M)"
                ])
                dataList.append([
                    str(degree),
                    str(degree1),
                    str(self.parametersPanel.pnlVarStartP.Value),
                    str(self.parametersPanel.txtForwardTP.Value),
                    str(self.parametersPanel.txtForwardMP.Value),
                    str(distance.NauticalMiles),
                    str(distance.Kilometres),
                    str(degree2),
                    str(degree3),
                    str(self.parametersPanel.pnlVarFinishP.Value),
                    str(round(num, 4)),
                    str(round(num2, 4))
                ])
                GeoDetermineDlg.HistoryDataP.append(dataList)
                self.setDataInHistoryModel(dataList)
                self.method_28_P(degree2, degree3)

    def calculateBD(self):
        degree = None
        degree1 = None
        degree2 = None
        degree3 = None
        num = None
        result, degree, degree1 = self.parametersPanel.pnlStartPosBD.method_3()
        if (result):
            num2 = self.parametersPanel.pnlVarStartBD.Value
            result1, degree2, degree3 = self.parametersPanel.pnlFinishPosBD.method_3(
            )
            if (result1):
                num3 = self.parametersPanel.pnlVarFinishBD.Value
                result2, distance, num, num1 = Geo.smethod_4(
                    self.parametersPanel.cmbCalculationTypeBD.SelectedItem,
                    degree, degree1, degree2, degree3)
                if define._units == QGis.Meters:
                    QgisHelper.convertMeasureUnits(QGis.Degrees)
                    distance = Distance(
                        MathHelper.calcDistance(
                            self.parametersPanel.pnlStartPosBD.Point3d,
                            self.parametersPanel.pnlFinishPosBD.Point3d))
                    QgisHelper.convertMeasureUnits(QGis.Meters)
                else:
                    distance = Distance(
                        MathHelper.calcDistance(
                            self.parametersPanel.pnlStartPosBD.Point3d,
                            self.parametersPanel.pnlFinishPosBD.Point3d))
                if result2:
                    num4 = MathHelper.smethod_3(num - num2)
                    num5 = MathHelper.smethod_3(num1 - num3)
                    self.method_31_BD()

                    self.resultModelBD.setItem(
                        0, 0, QStandardItem(Captions.FORWARD_TRUE_BEARING))
                    self.resultModelBD.setItem(
                        0, 1, QStandardItem(str(round(num, 4))))

                    self.resultModelBD.setItem(
                        1, 0, QStandardItem(Captions.FORWARD_MAGNETIC_BEARING))
                    self.resultModelBD.setItem(
                        1, 1, QStandardItem(str(round(num4, 4))))

                    self.resultModelBD.setItem(
                        2, 0, QStandardItem(Captions.REVERSE_TRUE_BEARING))
                    self.resultModelBD.setItem(
                        2, 1, QStandardItem(str(round(num1, 4))))

                    self.resultModelBD.setItem(
                        3, 0, QStandardItem(Captions.REVERSE_MAGNETIC_BEARING))
                    self.resultModelBD.setItem(
                        3, 1, QStandardItem(str(round(num5, 4))))

                    self.resultModelBD.setItem(
                        4, 0,
                        QStandardItem(Captions.DISTANCE_BETWEEN_POSITIONS))
                    self.resultModelBD.setItem(
                        4, 1,
                        QStandardItem(
                            str(round(distance.NauticalMiles, 4)) + " nm"))

                    self.resultModelBD.setItem(
                        5, 0,
                        QStandardItem(Captions.DISTANCE_BETWEEN_POSITIONS))
                    self.resultModelBD.setItem(
                        5, 1,
                        QStandardItem(
                            str(round(distance.Kilometres, 4)) + " km"))

                    dataList = []
                    dataList.append([
                        "ID (Start)", "Latitude (Start)", "Longitude (Start)",
                        "Variation (Start)", "ID (Finish)",
                        "Latitude (Finish)", "Longitude (Finish)",
                        "Variation (Finish)", "Forward (° T)", "Forward (° M)",
                        "Reverse (° T)", "Reverse (° M)", "Distance (nm)",
                        "Distance (km)"
                    ])
                    dataList.append([
                        self.parametersPanel.pnlStartPosBD.ID,
                        str(degree),
                        str(degree1),
                        str(self.parametersPanel.pnlVarStartBD.Value),
                        self.parametersPanel.pnlFinishPosBD.ID,
                        str(degree2),
                        str(degree3),
                        str(self.parametersPanel.pnlVarFinishBD.Value),
                        str(num),
                        str(num4),
                        str(round(num, 4)),
                        str(round(num2, 4)),
                        str(distance.NauticalMiles),
                        str(distance.Kilometres)
                    ])
                    GeoDetermineDlg.HistoryDataBD.append(dataList)
                    self.setDataInHistoryModel(dataList)
                    self.method_28_BD()

    def calculateMVD(self):
        degree = None
        degree1 = None
        degree2 = None

        result, degree, degree1 = self.parametersPanel.pnlPositionMVD.method_3(
        )
        # position.method_1(out degree, out degree1);
        altitude = self.parametersPanel.pnlPositionMVD.Altitude()
        result, degree2 = Geo.smethod_7(
            degree, degree1, altitude,
            self.parametersPanel.cmbModel.SelectedIndex,
            self.parametersPanel.dtpDate.date())
        if (result):
            self.parametersPanel.txtResult.Value = str(round(
                degree2, 4))  #.method_1(Formats.VariationFormat);
            date = self.parametersPanel.dtpDate.date()
            dataList = []
            dataList.append([
                "Latitude", "Longitude", "Altitude  (m)", "Altitude (ft)",
                "Date", "Magnetic Model", "Magnetic Variation"
            ])
            dataList.append([
                str(degree),
                str(degree1),
                str(altitude.Metres),
                str(altitude.Feet),
                date.toString(), self.parametersPanel.cmbModel.SelectedItem,
                self.parametersPanel.txtResult.Value
            ])
            GeoDetermineDlg.HistoryDataMV.append(dataList)
            self.setDataInHistoryModel(dataList)

    def autoCalcFinishMagVar(self):
        try:
            if self.parametersPanel.chbAutoFinishMagVar.Checked:
                finishPt = None
                finishLat = None
                finishLon = None
                degree3 = None
                num = None
                result, degree, degree1 = self.parametersPanel.pnlStartPosP.method_3(
                )
                if (result):
                    value = float(self.parametersPanel.txtForwardTP.Value)
                    value1 = float(self.parametersPanel.txtForwardTP.Value)
                    distance = self.parametersPanel.txtDistanceP.Value
                    result1, degree2, degree3, num = Geo.smethod_6(
                        self.parametersPanel.cmbCalculationTypeP.SelectedItem,
                        degree, degree1, value, distance)
                    if (result1):
                        finishPt = Point3D(degree3, degree2)

                        finishLat = degree2
                        finishLon = degree3
                if finishPt != None and self.model != None and self.date != None:
                    # result, degree, degree1 = self.parametersPanel.pnlStartPosP.method_3();
                    result2, degree2 = Geo.smethod_7(finishLat, finishLon,
                                                     Altitude(0), self.model,
                                                     self.date)
                    if (result2):
                        degree2 = round(degree2, 2)
                        self.parametersPanel.pnlVarFinishP.Value = degree2
        except:
            pass

    def btnConstruct_Click(self):
        # flag = FlightPlanBaseDlg.btnConstruct_Click(self)
        # if not flag:
        #     return
        if self.parametersPanel.tabGeneral.currentIndex() == 0:
            self.autoCalcFinishMagVar()
            self.calculateP()

        elif self.parametersPanel.tabGeneral.currentIndex() == 1:
            self.calculateBD()
        else:
            self.calculateMVD()

    def initParametersPan(self):
        ui = Ui_GeoDetermine()
        self.parametersPanel = ui
        FlightPlanBaseDlg.initParametersPan(self)

        self.parametersPanel.pnlStartPosP = PositionPanel(
            self.parametersPanel.gbStartPosP, None, None, "Degree")
        # self.parametersPanel.pnlStartPosP.degreeFormat = "ddmmss.ssssH"
        self.parametersPanel.pnlStartPosP.alwwaysShowString = "Degree"
        #         self.parametersPanel.pnlWaypoint.groupBox.setTitle("FAWP")
        self.parametersPanel.pnlStartPosP.btnCalculater.hide()
        self.parametersPanel.pnlStartPosP.hideframe_Altitude()
        # self.parametersPanel.pnlStartPosP.showframe_ID()
        self.parametersPanel.pnlStartPosP.setObjectName("pnlStartPosP")
        self.connect(self.parametersPanel.pnlStartPosP,
                     SIGNAL("positionChanged"), self.autoCalcFinishMagVar)

        ui.verticalLayout_gbStartPosP.addWidget(
            self.parametersPanel.pnlStartPosP)

        self.parametersPanel.pnlVarStartP = DegreesBoxPanel(self)
        self.parametersPanel.pnlVarStartP.CaptionLabel = "Magnetic Variation"
        self.connect(self.parametersPanel.pnlVarStartP,
                     SIGNAL("btnDegreeBoxPanel_clicked"), self.method_32_P)
        self.connect(self.parametersPanel.pnlVarStartP,
                     SIGNAL("txtDegreeBox_textChanged"),
                     self.txtDegreeBox_textChangedP)
        ui.verticalLayout_gbStartPosP.addWidget(
            self.parametersPanel.pnlVarStartP)

        self.parametersPanel.pnlVarFinishP = DegreesBoxPanel(self)
        self.parametersPanel.pnlVarFinishP.ButtonVisible = False
        self.parametersPanel.pnlVarFinishP.Enabled = False
        self.parametersPanel.pnlVarFinishP.CaptionLabel = "Magnetic Variation at Finish"
        ui.vLayout_grbParametersP.insertWidget(
            1, self.parametersPanel.pnlVarFinishP)
        # self.connect(self.parametersPanel.pnlVarStartP, SIGNAL("btnDegreeBoxPanel_clicked"), self.method_32_P)

        self.parametersPanel.pnlStartPosBD = PositionPanel(
            self.parametersPanel.gbFinishPosBD, None, None, "Degree")
        #         self.parametersPanel.pnlStartPosBD.groupBox.setTitle("FAWP")
        #         self.parametersPanel.pnlStartPosBD.degreeFormat = "ddmmss.ssssH"
        self.parametersPanel.pnlStartPosBD.alwwaysShowString = "Degree"
        self.parametersPanel.pnlStartPosBD.btnCalculater.hide()
        self.parametersPanel.pnlStartPosBD.hideframe_Altitude()
        self.parametersPanel.pnlStartPosBD.showframe_ID()
        self.parametersPanel.pnlStartPosBD.setObjectName("pnlStartPosBD")
        ui.verticalLayout_gbStartPosBD.insertWidget(
            0, self.parametersPanel.pnlStartPosBD)
        self.connect(self.parametersPanel.pnlStartPosBD,
                     SIGNAL("positionChanged"), self.positionChangedStartBD)

        self.parametersPanel.pnlVarStartBD = DegreesBoxPanel(self)
        self.parametersPanel.pnlVarStartBD.CaptionLabel = "Magnetic Variation"
        # self.parametersPanel.pnlVarStartBD.Enabled = False
        self.connect(self.parametersPanel.pnlVarStartBD,
                     SIGNAL("btnDegreeBoxPanel_clicked"), self.method_34_BD)
        # self.connect(self.parametersPanel.pnlVarStartBD, SIGNAL("txtDegreeBox_textChanged"), self.txtDegreeBox_textChangedP)
        ui.verticalLayout_gbStartPosBD.addWidget(
            self.parametersPanel.pnlVarStartBD)

        self.parametersPanel.pnlFinishPosBD = PositionPanel(
            self.parametersPanel.gbFinishPosBD, None, None, "Degree")
        #         self.parametersPanel.pnlStartPosBD.groupBox.setTitle("FAWP")
        #         self.parametersPanel.pnlFinishPosBD.degreeFormat = "ddmmss.ssssH"
        self.parametersPanel.pnlFinishPosBD.alwwaysShowString = "Degree"
        self.parametersPanel.pnlFinishPosBD.btnCalculater.hide()
        self.parametersPanel.pnlFinishPosBD.hideframe_Altitude()
        self.parametersPanel.pnlFinishPosBD.showframe_ID()
        self.parametersPanel.pnlFinishPosBD.setObjectName("pnlFinishPosBD")
        ui.verticalLayout_gbFinishPosBD.insertWidget(
            0, self.parametersPanel.pnlFinishPosBD)
        self.connect(self.parametersPanel.pnlFinishPosBD,
                     SIGNAL("positionChanged"), self.positionChangedFinishBD)

        self.parametersPanel.pnlVarFinishBD = DegreesBoxPanel(self)
        self.parametersPanel.pnlVarFinishBD.CaptionLabel = "Magnetic Variation"
        # self.parametersPanel.pnlVarFinishBD.Enabled = False
        self.connect(self.parametersPanel.pnlVarFinishBD,
                     SIGNAL("btnDegreeBoxPanel_clicked"), self.method_36_BD)
        # self.connect(self.parametersPanel.pnlVarFinishBD, SIGNAL("txtDegreeBox_textChanged"), self.txtDegreeBox_textChangedP)
        ui.verticalLayout_gbFinishPosBD.addWidget(
            self.parametersPanel.pnlVarFinishBD)

        self.parametersPanel.pnlPositionMVD = PositionPanel(
            self.parametersPanel.tabGeoDetermineMV, None, None, "Degree")
        self.parametersPanel.pnlPositionMVD.groupBox.setTitle("Position")
        self.parametersPanel.pnlPositionMVD.alwwaysShowString = "Degree"
        self.parametersPanel.pnlPositionMVD.btnCalculater.hide()
        self.parametersPanel.pnlPositionMVD.setObjectName("pnlPositionMVD")
        ui.verticalLayout_3.insertWidget(0,
                                         self.parametersPanel.pnlPositionMVD)
        self.connect(self.parametersPanel.pnlPositionMVD,
                     SIGNAL("positionChanged"), self.method_28_MVD)

        self.connect(self.parametersPanel.txtForwardTP, SIGNAL("Event_0"),
                     self.txtForwardTP_textChanged)
        self.connect(self.parametersPanel.chbAutoFinishMagVar,
                     SIGNAL("Event_0"), self.chbAutoFinishMagVar_clicked)
        self.connect(self.parametersPanel.txtDistanceP, SIGNAL("Event_0"),
                     self.autoCalcFinishMagVar)

        self.connect(self.parametersPanel.txtForwardMP, SIGNAL("Event_0"),
                     self.txtForwardMP_textChanged)
        self.parametersPanel.btnResultP.clicked.connect(
            self.btnResultP_clicked)
        self.parametersPanel.tabGeneral.currentChanged.connect(
            self.tabGeneral_CurrentChanged)
        self.parametersPanel.chbAutoVarBD.clicked.connect(
            self.chbAutoVarBD_clicked)
        self.parametersPanel.dtpDate.dateChanged.connect(self.method_28_MVD)
        self.connect(self.parametersPanel.cmbModel, SIGNAL("Event_0"),
                     self.method_28_MVD)
        self.parametersPanel.btnDtpDate.clicked.connect(
            self.btnDtpDate_clicked)

        self.resultModelP = QStandardItemModel()
        self.parametersPanel.tblResultP.setModel(self.resultModelP)

        self.resultModelBD = QStandardItemModel()
        self.parametersPanel.tblResultBD.setModel(self.resultModelBD)

        self.ttt = 0
        self.txtForwardTP_textChanged()

        self.setHistoryData()

        self.autoVarSet = False
        self.dateBD = QDate.currentDate()
        self.modelBD = MagneticModel.WMM2010
        self.parametersPanel.btnResultBD.setVisible(False)

        self.parametersPanel.dtpDate.setDate(QDate.currentDate())

        self.calendar = QCalendarWidget()
        self.calendar.clicked.connect(self.calendar_clicked)

        self.menu = QMenu()
        layout = QVBoxLayout(self.menu)
        layout.addWidget(self.calendar)

    def chbAutoFinishMagVar_clicked(self):
        if self.parametersPanel.chbAutoFinishMagVar.Checked:
            self.parametersPanel.pnlVarFinishP.Enabled = False
        else:
            self.parametersPanel.pnlVarFinishP.Enabled = True

    def calendar_clicked(self, date):
        self.parametersPanel.dtpDate.setDate(date)

    def btnDtpDate_clicked(self):
        rcRect = self.parametersPanel.btnDtpDate.geometry()
        ptPoint = rcRect.bottomLeft()
        self.menu.exec_(self.mapToGlobal(ptPoint))

    def positionChangedStartBD(self):
        if (self.parametersPanel.chbAutoVarBD.isChecked() and self.autoVarSet):
            self.method_29_BD()
        self.method_31_BD()

    def positionChangedFinishBD(self):
        if (self.parametersPanel.chbAutoVarBD.isChecked() and self.autoVarSet):
            self.method_30_BD()
        self.method_31_BD()

    def chbAutoVarBD_clicked(self):
        if (self.parametersPanel.chbAutoVarBD.isChecked()
                and not self.autoVarSet):
            result, self.dateBD, self.modelBD = DlgMagneticVariationParameters.smethod_0(
                self.dateBD, self.modelBD)
            self.parametersPanel.chbAutoVarBD.setChecked(result)
            self.autoVarSet = self.parametersPanel.chbAutoVarBD.isChecked()
        if (self.parametersPanel.chbAutoVarBD.isChecked()):
            self.method_29_BD()
            self.method_30_BD()
        self.method_31_BD()

    def tabGeneral_CurrentChanged(self):
        if self.parametersPanel.tabGeneral.currentIndex() == 0:
            self.stdItemModelHistory.clear()
            if len(GeoDetermineDlg.HistoryDataP) > 0:
                self.setDataInHistoryModel(GeoDetermineDlg.HistoryDataP, True)
                pass
        elif self.parametersPanel.tabGeneral.currentIndex() == 1:
            self.stdItemModelHistory.clear()
            if len(GeoDetermineDlg.HistoryDataBD) > 0:
                self.setDataInHistoryModel(GeoDetermineDlg.HistoryDataBD, True)
                pass
        else:
            self.stdItemModelHistory.clear()
            if len(GeoDetermineDlg.HistoryDataMV) > 0:
                self.setDataInHistoryModel(GeoDetermineDlg.HistoryDataMV, True)
                pass

    def setHistoryData(self):
        if len(self.HistoryDataP) > 0:
            self.setDataInHistoryModel(GeoDetermineDlg.HistoryDataP, True)
            pass

    def btnResultP_clicked(self):
        self.resultModelP.clear()
        self.parametersPanel.pnlVarStartP.Value = self.parametersPanel.pnlVarFinishP.Value
        self.parametersPanel.pnlVarFinishP.Value = 0.0
        self.parametersPanel.pnlStartPosP.Point3d = self.resultPoint3d

    def txtForwardTP_textChanged(self):
        if self.ttt == 0:
            self.ttt = 1
        if self.ttt == 2:
            self.ttt = 0
        if self.ttt == 1:
            try:
                value = float(self.parametersPanel.txtForwardTP.Value)
                self.parametersPanel.txtForwardMP.Value = MathHelper.smethod_3(
                    value - float(self.parametersPanel.pnlVarStartP.Value))
                self.autoCalcFinishMagVar()
            except:
                self.parametersPanel.txtForwardMP.Value = 0.0

    def txtForwardMP_textChanged(self):
        if self.ttt == 0:
            self.ttt = 2
        if self.ttt == 1:
            self.ttt = 0
        if self.ttt == 2:
            try:
                value = float(self.parametersPanel.txtForwardMP.Value)
                self.parametersPanel.txtForwardTP.Value = MathHelper.smethod_3(
                    value + float(self.parametersPanel.pnlVarStartP.Value))
            except:
                self.parametersPanel.txtForwardTP.Value = 0.0

    def txtDegreeBox_textChangedP(self):

        try:
            value = float(self.parametersPanel.txtForwardTP.Value)
            self.parametersPanel.txtForwardMP.Value = MathHelper.smethod_3(
                value - float(self.parametersPanel.pnlVarStartP.Value))
        except:
            self.parametersPanel.txtForwardMP.Value = 0.0

    def method_28_P(self, degrees_Lat, degrees_Lon):
        point3d = None
        point3d1 = None
        self.surfaceType = SurfaceTypes.GeoDeterminePosition
        flag = FlightPlanBaseDlg.btnConstruct_Click(self)
        if not flag:
            return
        if define._units == QGis.Meters:
            point3d0 = self.parametersPanel.pnlStartPosP.Point3d

            point3d = QgisHelper.CrsTransformPoint(point3d0.get_X(),
                                                   point3d0.get_Y(),
                                                   define._latLonCrs,
                                                   define._xyCrs)
            point3d1 = QgisHelper.CrsTransformPoint(degrees_Lon, degrees_Lat,
                                                    define._latLonCrs,
                                                    define._xyCrs)
        else:
            point3d = self.parametersPanel.pnlStartPosP.Point3d
            point3d1 = Point3D(degrees_Lon, degrees_Lat)

        constructionLayer = None
        mapUnits = define._canvas.mapUnits()
        if self.parametersPanel.chbMarkPointsP.isChecked():
            constructionLayer = AcadHelper.createVectorLayer(
                SurfaceTypes.GeoDeterminePosition + "_MarkPoint", QGis.Point)
            AcadHelper.setGeometryAndAttributesInLayer(constructionLayer,
                                                       point3d)
            AcadHelper.setGeometryAndAttributesInLayer(constructionLayer,
                                                       point3d1)

            # if mapUnits == QGis.Meters:
            #     constructionLayer = QgsVectorLayer("point?crs=%s"%define._xyCrs.authid (), SurfaceTypes.GeoDeterminePosition + "_MarkPoint", "memory")
            # else:
            #     constructionLayer = QgsVectorLayer("point?crs=%s"%define._latLonCrs.authid (), SurfaceTypes.GeoDeterminePosition + " MarkPoint", "memory")
            #
            # shpPath = ""
            # if define.obstaclePath != None:
            #     shpPath = define.obstaclePath
            # elif define.xmlPath != None:
            #     shpPath = define.xmlPath
            # else:
            #     shpPath = define.appPath
            # er = QgsVectorFileWriter.writeAsVectorFormat(constructionLayer, shpPath + "/" + SurfaceTypes.GeoDeterminePosition + "_MarkPoint" + ".shp", "utf-8", constructionLayer.crs())
            # constructionLayer = QgsVectorLayer(shpPath + "/" + SurfaceTypes.GeoDeterminePosition + "_MarkPoint" + ".shp", SurfaceTypes.GeoDeterminePosition + " MarkPoint", "ogr")
            #
            # constructionLayer.startEditing()
            #
            # feature = QgsFeature()
            # feature.setGeometry(QgsGeometry.fromPoint(point3d))
            # constructionLayer.addFeature(feature)
            # feature.setGeometry(QgsGeometry.fromPoint(point3d1))
            # constructionLayer.addFeature(feature)
            # constructionLayer.commitChanges()
            QgisHelper.appendToCanvas(define._canvas, [constructionLayer],
                                      SurfaceTypes.GeoDeterminePosition)

            self.resultLayerList.append(constructionLayer)
        if self.parametersPanel.chbDrawLineP.isChecked():
            constructionLayer1 = AcadHelper.createVectorLayer(
                SurfaceTypes.GeoDeterminePosition + "_Line", QGis.Line)
            AcadHelper.setGeometryAndAttributesInLayer(constructionLayer1,
                                                       [point3d, point3d1])
            QgisHelper.appendToCanvas(define._canvas, [constructionLayer1],
                                      SurfaceTypes.GeoDeterminePosition)
            self.resultLayerList.append(constructionLayer1)

    def method_28_BD(self):
        point3d = None
        point3d1 = None
        self.surfaceType = SurfaceTypes.GeoDetermineBD
        flag = FlightPlanBaseDlg.btnConstruct_Click(self)
        if not flag:
            return
        if define._units == QGis.Meters:
            point3d0 = self.parametersPanel.pnlStartPosBD.Point3d
            point3dF0 = self.parametersPanel.pnlFinishPosBD.Point3d

            point3d = QgisHelper.CrsTransformPoint(point3d0.get_X(),
                                                   point3d0.get_Y(),
                                                   define._latLonCrs,
                                                   define._xyCrs)
            point3d1 = QgisHelper.CrsTransformPoint(point3dF0.get_X(),
                                                    point3dF0.get_Y(),
                                                    define._latLonCrs,
                                                    define._xyCrs)
        else:
            point3d = self.parametersPanel.pnlStartPosBD.Point3d
            point3d1 = self.parametersPanel.pnlFinishPosBD.Point3d

        constructionLayer = None
        mapUnits = define._canvas.mapUnits()
        if self.parametersPanel.chbMarkPointsBD.isChecked():
            constructionLayer = AcadHelper.createVectorLayer(
                SurfaceTypes.GeoDetermineBD + "_MarkPoint", QGis.Point)
            AcadHelper.setGeometryAndAttributesInLayer(constructionLayer,
                                                       point3d)
            AcadHelper.setGeometryAndAttributesInLayer(constructionLayer,
                                                       point3d1)

            # if mapUnits == QGis.Meters:
            #     constructionLayer = QgsVectorLayer("point?crs=%s"%define._xyCrs.authid (), SurfaceTypes.GeoDetermineBD + "_MarkPoint", "memory")
            # else:
            #     constructionLayer = QgsVectorLayer("point?crs=%s"%define._latLonCrs.authid (), SurfaceTypes.GeoDetermineBD + " MarkPoint", "memory")
            #
            # shpPath = ""
            # if define.obstaclePath != None:
            #     shpPath = define.obstaclePath
            # elif define.xmlPath != None:
            #     shpPath = define.xmlPath
            # else:
            #     shpPath = define.appPath
            # er = QgsVectorFileWriter.writeAsVectorFormat(constructionLayer, shpPath + "/" + QString(SurfaceTypes.GeoDetermineBD).replace(" ", "") + "_MarkPoint" + ".shp", "utf-8", constructionLayer.crs())
            # constructionLayer = QgsVectorLayer(shpPath + "/" + QString(SurfaceTypes.GeoDetermineBD).replace(" ", "") + "_MarkPoint" + ".shp", SurfaceTypes.GeoDetermineBD + " MarkPoint", "ogr")
            #
            # constructionLayer.startEditing()
            #
            #
            # feature = QgsFeature()
            # feature.setGeometry(QgsGeometry.fromPoint(point3d))
            # constructionLayer.addFeature(feature)
            # feature.setGeometry(QgsGeometry.fromPoint(point3d1))
            # constructionLayer.addFeature(feature)
            # constructionLayer.commitChanges()
            QgisHelper.appendToCanvas(define._canvas, [constructionLayer],
                                      SurfaceTypes.GeoDetermineBD)
            self.resultLayerList.append(constructionLayer)
        if self.parametersPanel.chbDrawLineBD.isChecked():
            constructionLayer = AcadHelper.createVectorLayer(
                SurfaceTypes.GeoDetermineBD + "_Line", QGis.Line)
            AcadHelper.setGeometryAndAttributesInLayer(constructionLayer,
                                                       [point3d, point3d1])
            QgisHelper.appendToCanvas(define._canvas, [constructionLayer],
                                      SurfaceTypes.GeoDetermineBD)
            self.resultLayerList.append(constructionLayer)

    def method_28_MVD(self):
        self.parametersPanel.txtResult.Value = ""

    def method_29_P(self):
        self.resultModelP.clear()
        self.resultModelP.setHorizontalHeaderLabels(["Type", "Value"])

    def method_29_BD(self):
        degree = None
        degree1 = None
        degree2 = None
        if (self.parametersPanel.pnlStartPosBD.IsValid()):

            result, degree, degree1 = self.parametersPanel.pnlStartPosBD.method_3(
            )
            result, degree2 = Geo.smethod_7(degree, degree1, Altitude(0),
                                            self.modelBD, self.dateBD)
            if (result):
                degree2 = round(degree2, 2)
                self.parametersPanel.pnlVarStartBD.Value = degree2

    def method_30_BD(self):
        degree = None
        degree1 = None
        degree2 = None
        if (self.parametersPanel.pnlFinishPosBD.IsValid()):

            result, degree, degree1 = self.parametersPanel.pnlFinishPosBD.method_3(
            )
            result, degree2 = Geo.smethod_7(degree, degree1, Altitude(0),
                                            self.modelBD, self.dateBD)
            if (result):
                degree2 = round(degree2, 2)
                self.parametersPanel.pnlVarFinishBD.Value = degree2

    def method_31_BD(self):
        self.resultModelBD.clear()
        self.resultModelBD.setHorizontalHeaderLabels(["Type", "Value"])

    def method_32_P(self):
        startPos = self.parametersPanel.pnlStartPosP.Point3d
        result, self.date, self.model = DlgMagneticVariationParameters.smethod_0(
            self.date, self.model)
        if self.parametersPanel.pnlStartPosP.IsValid() and result:
            result, degree, degree1 = self.parametersPanel.pnlStartPosP.method_3(
            )
            result, degree2 = Geo.smethod_7(degree, degree1, Altitude(0),
                                            self.model, self.date)
            if (result):
                degree2 = round(degree2, 2)
                self.parametersPanel.pnlVarStartP.Value = degree2
                try:
                    self.parametersPanel.txtForwardMP.Value = MathHelper.smethod_3(
                        float(self.parametersPanel.txtForwardTP.Value) -
                        degree2)
                except:
                    self.parametersPanel.txtForwardMP.Value = 0.0
                self.method_29_P()

    def method_34_BD(self):
        startPos = self.parametersPanel.pnlStartPosBD.Point3d
        result, self.dateBD, self.modelBD = DlgMagneticVariationParameters.smethod_0(
            self.dateBD, self.modelBD)
        if self.parametersPanel.pnlStartPosBD.IsValid() and result:
            self.method_29_BD()
            self.method_31_BD()

    def method_36_BD(self):
        startPos = self.parametersPanel.pnlFinishPosBD.Point3d
        result, self.dateBD, self.modelBD = DlgMagneticVariationParameters.smethod_0(
            self.dateBD, self.modelBD)
        if self.parametersPanel.pnlFinishPosBD.IsValid() and result:
            self.method_30_BD()
            self.method_31_BD()
Exemplo n.º 43
0
class SelectionSetsWidget(QFrame):
    """
    Widget for managing multiple stored item selections
    """
    selectionModified = Signal(bool)

    def __init__(self, parent):
        QFrame.__init__(self, parent)
        self.setContentsMargins(0, 0, 0, 0)
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(1)
        self._setNameLineEdit = QLineEdit(self)
        layout.addWidget(self._setNameLineEdit)

        self._setListView = QListView(self)
        self._listModel = QStandardItemModel(self)
        self._proxyModel = QSortFilterProxyModel(self)
        self._proxyModel.setSourceModel(self._listModel)

        self._setListView.setModel(self._proxyModel)
        self._setListView.setItemDelegate(ListItemDelegate(self))

        self._setNameLineEdit.textChanged.connect(
            self._proxyModel.setFilterFixedString)

        self._completer = QCompleter(self._listModel, self)

        self._setNameLineEdit.setCompleter(self._completer)

        self._listModel.itemChanged.connect(self._onSetNameChange)
        layout.addWidget(self._setListView)
        buttonLayout = QHBoxLayout()

        self._addAction = QAction("+", self, toolTip="Add a new sort key")
        self._updateAction = QAction("Update",
                                     self,
                                     toolTip="Update/save current selection")
        self._removeAction = QAction("\u2212",
                                     self,
                                     toolTip="Remove selected sort key.")

        self._addToolButton = QToolButton(self)
        self._updateToolButton = QToolButton(self)
        self._removeToolButton = QToolButton(self)
        self._updateToolButton.setSizePolicy(QSizePolicy.MinimumExpanding,
                                             QSizePolicy.Minimum)

        self._addToolButton.setDefaultAction(self._addAction)
        self._updateToolButton.setDefaultAction(self._updateAction)
        self._removeToolButton.setDefaultAction(self._removeAction)

        buttonLayout.addWidget(self._addToolButton)
        buttonLayout.addWidget(self._updateToolButton)
        buttonLayout.addWidget(self._removeToolButton)

        layout.addLayout(buttonLayout)
        self.setLayout(layout)

        self._addAction.triggered.connect(self.addCurrentSelection)
        self._updateAction.triggered.connect(self.updateSelectedSelection)
        self._removeAction.triggered.connect(self.removeSelectedSelection)

        self._setListView.selectionModel().selectionChanged.connect(
            self._onListViewSelectionChanged)
        self.selectionModel = None
        self._selections = []

    def sizeHint(self):
        size = QFrame.sizeHint(self)
        return QSize(size.width(), 150)

    def _onSelectionChanged(self, selected, deselected):
        self.setSelectionModified(True)

    def _onListViewSelectionChanged(self, selected, deselected):
        try:
            index = self._setListView.selectedIndexes()[0]
        except IndexError:
            return
        self.commitSelection(self._proxyModel.mapToSource(index).row())

    def _onSetNameChange(self, item):
        self.selections[item.row()].name = str(item.text())

    def _setButtonStates(self, val):
        self._updateToolButton.setEnabled(val)

    def setSelectionModel(self, selectionModel):
        if self.selectionModel:
            self.selectionModel.selectionChanged.disconnect(
                self._onSelectionChanged)
        self.selectionModel = selectionModel
        self.selectionModel.selectionChanged.connect(self._onSelectionChanged)

    def addCurrentSelection(self):
        item = self.addSelection(
            SelectionByKey(self.selectionModel.selection(),
                           name="New selection",
                           key=(1, 2, 3, 10)))
        index = self._proxyModel.mapFromSource(item.index())
        self._setListView.setCurrentIndex(index)
        self._setListView.edit(index)
        self.setSelectionModified(False)

    def removeSelectedSelection(self):
        i = self._proxyModel.mapToSource(
            self._setListView.currentIndex()).row()
        self._listModel.takeRow(i)
        del self.selections[i]

    def updateCurentSelection(self):
        i = self._proxyModel.mapToSource(
            self._setListView.selectedIndex()).row()
        self.selections[i].setSelection(self.selectionModel.selection())
        self.setSelectionModified(False)

    def addSelection(self, selection, name=""):
        self._selections.append(selection)
        item = QStandardItem(selection.name)
        item.setFlags(item.flags() ^ Qt.ItemIsDropEnabled)
        self._listModel.appendRow(item)
        self.setSelectionModified(False)
        return item

    def updateSelectedSelection(self):
        i = self._proxyModel.mapToSource(
            self._setListView.currentIndex()).row()
        self.selections[i].setSelection(self.selectionModel.selection())
        self.setSelectionModified(False)

    def setSelectionModified(self, val):
        self._selectionModified = val
        self._setButtonStates(val)
        self.selectionModified.emit(bool(val))

    def commitSelection(self, index):
        selection = self.selections[index]
        selection.select(self.selectionModel)

    def setSelections(self, selections):
        self._listModel.clear()
        for selection in selections:
            self.addSelection(selection)

    def selections(self):
        return self._selections

    selections = property(selections, setSelections)
Exemplo n.º 44
0
    def __init__(self, parent):
        QFrame.__init__(self, parent)
        self.setContentsMargins(0, 0, 0, 0)
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(1)
        self._setNameLineEdit = QLineEdit(self)
        layout.addWidget(self._setNameLineEdit)

        self._setListView = QListView(self)
        self._listModel = QStandardItemModel(self)
        self._proxyModel = QSortFilterProxyModel(self)
        self._proxyModel.setSourceModel(self._listModel)

        self._setListView.setModel(self._proxyModel)
        self._setListView.setItemDelegate(ListItemDelegate(self))

        self._setNameLineEdit.textChanged.connect(
            self._proxyModel.setFilterFixedString)

        self._completer = QCompleter(self._listModel, self)

        self._setNameLineEdit.setCompleter(self._completer)

        self._listModel.itemChanged.connect(self._onSetNameChange)
        layout.addWidget(self._setListView)
        buttonLayout = QHBoxLayout()

        self._addAction = QAction("+", self, toolTip="Add a new sort key")
        self._updateAction = QAction("Update",
                                     self,
                                     toolTip="Update/save current selection")
        self._removeAction = QAction("\u2212",
                                     self,
                                     toolTip="Remove selected sort key.")

        self._addToolButton = QToolButton(self)
        self._updateToolButton = QToolButton(self)
        self._removeToolButton = QToolButton(self)
        self._updateToolButton.setSizePolicy(QSizePolicy.MinimumExpanding,
                                             QSizePolicy.Minimum)

        self._addToolButton.setDefaultAction(self._addAction)
        self._updateToolButton.setDefaultAction(self._updateAction)
        self._removeToolButton.setDefaultAction(self._removeAction)

        buttonLayout.addWidget(self._addToolButton)
        buttonLayout.addWidget(self._updateToolButton)
        buttonLayout.addWidget(self._removeToolButton)

        layout.addLayout(buttonLayout)
        self.setLayout(layout)

        self._addAction.triggered.connect(self.addCurrentSelection)
        self._updateAction.triggered.connect(self.updateSelectedSelection)
        self._removeAction.triggered.connect(self.removeSelectedSelection)

        self._setListView.selectionModel().selectionChanged.connect(
            self._onListViewSelectionChanged)
        self.selectionModel = None
        self._selections = []
Exemplo n.º 45
0
 def __init__(self, parent=None, dict={}):
     QStandardItemModel.__init__(self, parent)
     self.setHorizontalHeaderLabels(["Key", "Value"])
     self.set_dict(dict)
Exemplo n.º 46
0
class OWTestLearners(widget.OWWidget):
    name = "Test Learners"
    description = ""
    icon = "icons/TestLearners1.svg"
    priority = 100

    inputs = [("Learner", Orange.classification.Fitter, "set_learner",
               widget.Multiple),
              ("Data", Orange.data.Table, "set_train_data", widget.Default),
              ("Test Data", Orange.data.Table, "set_test_data")]

    outputs = [("Evaluation Results", testing.Results)]

    #: Resampling/testing types
    KFold, LeaveOneOut, Bootstrap, TestOnTrain, TestOnTest = 0, 1, 2, 3, 4

    #: Selected resampling type
    resampling = settings.Setting(0)
    #: Number of folds for K-fold cross validation
    k_folds = settings.Setting(10)
    #: Number of repeats for bootstrap sampling
    n_repeat = settings.Setting(10)
    #: Bootstrap sampling p
    sample_p = settings.Setting(75)

    def __init__(self, parent=None):
        super().__init__(parent)

        self.train_data = None
        self.test_data = None

        #: An Ordered dictionary with current inputs and their testing
        #: results.
        self.learners = OrderedDict()

        sbox = gui.widgetBox(self.controlArea, "Sampling")
        rbox = gui.radioButtons(sbox,
                                self,
                                "resampling",
                                callback=self._param_changed)
        gui.appendRadioButton(rbox, "Cross validation")
        ibox = gui.indentedBox(rbox)
        gui.spin(ibox,
                 self,
                 "k_folds",
                 2,
                 50,
                 label="Number of folds:",
                 callback=self._param_changed)
        gui.appendRadioButton(rbox, "Leave one out")
        gui.appendRadioButton(rbox, "Random sampling")
        ibox = gui.indentedBox(rbox)
        gui.spin(ibox,
                 self,
                 "n_repeat",
                 2,
                 50,
                 label="Repeat train/test",
                 callback=self._param_changed)
        gui.widgetLabel(ibox, "Relative training set size:")
        gui.hSlider(ibox,
                    self,
                    "sample_p",
                    minValue=1,
                    maxValue=100,
                    ticks=20,
                    vertical=False,
                    callback=self._param_changed)

        gui.appendRadioButton(rbox, "Test on train data")
        gui.appendRadioButton(rbox, "Test on test data")

        rbox.layout().addSpacing(5)
        gui.button(rbox, self, "Apply", callback=self.apply)

        gui.rubber(self.controlArea)

        self.view = QTreeView(rootIsDecorated=False,
                              uniformRowHeights=True,
                              wordWrap=True,
                              editTriggers=QTreeView.NoEditTriggers)

        self.result_model = QStandardItemModel()
        self.view.setModel(self.result_model)
        self._update_header()
        box = gui.widgetBox(self.mainArea, "Evaluation Results")
        box.layout().addWidget(self.view)

    def set_learner(self, learner, key):
        if key in self.learners and learner is None:
            del self.learners[key]
        else:
            self.learners[key] = Input(learner, None, ())
        self._update_stats_model()

    def set_train_data(self, data):
        self.train_data = data
        self._update_header()
        self._invalidate()

    def set_test_data(self, data):
        self.test_data = data
        if self.resampling == OWTestLearners.TestOnTest:
            self._invalidate()

    def handleNewSignals(self):
        self.update_results()
        self.commit()

    def _param_changed(self):
        self._invalidate()

    def update_results(self):
        self.warning(1, "")
        if self.train_data is None:
            return

        # items in need of an update
        items = [(key, input) for key, input in self.learners.items()
                 if input.results is None]
        learners = [input.learner for _, input in items]

        self.setStatusMessage("Running")
        if self.test_data is not None and \
                self.resampling != OWTestLearners.TestOnTest:
            self.warning(1, "Select 'Test on test data' to use the test data")

        # TODO: Test each learner individually

        if self.resampling == OWTestLearners.KFold:
            results = testing.CrossValidation(self.train_data,
                                              learners,
                                              k=self.k_folds,
                                              store_data=True)
        elif self.resampling == OWTestLearners.LeaveOneOut:
            results = testing.LeaveOneOut(self.train_data,
                                          learners,
                                          store_data=True)
        elif self.resampling == OWTestLearners.Bootstrap:
            p = self.sample_p / 100.0
            results = testing.Bootstrap(self.train_data,
                                        learners,
                                        n_resamples=self.n_repeat,
                                        p=p,
                                        store_data=True)
        elif self.resampling == OWTestLearners.TestOnTrain:
            results = testing.TestOnTrainingData(self.train_data,
                                                 learners,
                                                 store_data=True)
        elif self.resampling == OWTestLearners.TestOnTest:
            if self.test_data is None:
                return
            results = testing.TestOnTestData(self.train_data,
                                             self.test_data,
                                             learners,
                                             store_data=True)
        else:
            assert False

        results = list(split_by_model(results))
        class_var = self.train_data.domain.class_var

        if is_discrete(class_var):
            test_stats = classification_stats
        else:
            test_stats = regression_stats

        self._update_header()

        stats = [test_stats(res) for res in results]
        for (key, input), res, stat in zip(items, results, stats):
            self.learners[key] = input._replace(results=res, stats=stat)

        self.setStatusMessage("")

        self._update_stats_model()

    def _update_header(self):
        headers = ["Method"]
        if self.train_data is not None:
            if is_discrete(self.train_data.domain.class_var):
                if len(self.train_data.domain.class_var.values) == 2:
                    headers.extend(classification_stats.headers_binary)
                headers.extend(classification_stats.headers)
            else:
                headers.extend(regression_stats.headers)
        for i in reversed(range(len(headers),
                                self.result_model.columnCount())):
            self.result_model.takeColumn(i)

        self.result_model.setHorizontalHeaderLabels(headers)

    def _update_stats_model(self):
        model = self.view.model()

        for r in reversed(range(model.rowCount())):
            model.takeRow(r)

        for input in self.learners.values():
            name = learner_name(input.learner)
            row = []
            head = QStandardItem()
            head.setData(name, Qt.DisplayRole)
            row.append(head)
            for stat in input.stats:
                item = QStandardItem()
                item.setData(float(stat[0]), Qt.DisplayRole)
                row.append(item)
            model.appendRow(row)

        self.view.resizeColumnToContents(0)

    def _invalidate(self, which=None):
        if which is None:
            which = self.learners.keys()

        all_keys = list(self.learners.keys())
        model = self.view.model()

        for key in which:
            self.learners[key] = \
                self.learners[key]._replace(results=None, stats=None)

            if key in self.learners:
                row = all_keys.index(key)
                for c in range(1, model.columnCount()):
                    item = model.item(row, c)
                    if item is not None:
                        item.setData(None, Qt.DisplayRole)

    def apply(self):
        self.update_results()
        self.commit()

    def commit(self):
        results = [
            val.results for val in self.learners.values()
            if val.results is not None
        ]
        if results:
            combined = results_merge(results)
            combined.fitter_names = [
                learner_name(val.learner) for val in self.learners.values()
            ]
        else:
            combined = None
        self.send("Evaluation Results", combined)
Exemplo n.º 47
0
    def __init__(self):
        super().__init__()

        self.data = None
        self.test_data = None
        self.preprocessor = None
        self.train_data_missing_vals = False
        self.test_data_missing_vals = False

        #: An Ordered dictionary with current inputs and their testing
        #: results.
        self.learners = OrderedDict()

        sbox = gui.widgetBox(self.controlArea, "Sampling")
        rbox = gui.radioButtons(sbox,
                                self,
                                "resampling",
                                callback=self._param_changed)
        gui.appendRadioButton(rbox, "Cross validation")
        ibox = gui.indentedBox(rbox)
        gui.spin(ibox,
                 self,
                 "k_folds",
                 2,
                 50,
                 label="Number of folds:",
                 callback=self.kfold_changed)
        gui.appendRadioButton(rbox, "Leave one out")
        gui.appendRadioButton(rbox, "Random sampling")
        ibox = gui.indentedBox(rbox)
        gui.spin(ibox,
                 self,
                 "n_repeat",
                 2,
                 50,
                 label="Repeat train/test",
                 callback=self.shuffle_split_changed)
        gui.widgetLabel(ibox, "Relative training set size:")
        gui.hSlider(ibox,
                    self,
                    "sample_p",
                    minValue=1,
                    maxValue=99,
                    ticks=20,
                    vertical=False,
                    labelFormat="%d %%",
                    callback=self.shuffle_split_changed)

        gui.appendRadioButton(rbox, "Test on train data")
        gui.appendRadioButton(rbox, "Test on test data")

        rbox.layout().addSpacing(5)
        self.apply_button = gui.button(rbox,
                                       self,
                                       "Apply",
                                       callback=self.apply,
                                       default=True)

        self.cbox = gui.widgetBox(self.controlArea, "Target class")
        self.class_selection_combo = gui.comboBox(
            self.cbox,
            self,
            "class_selection",
            items=[],
            sendSelectedValue=True,
            valueType=str,
            callback=self._on_target_class_changed,
            contentsLength=8)

        gui.rubber(self.controlArea)

        self.view = QTreeView(rootIsDecorated=False,
                              uniformRowHeights=True,
                              wordWrap=True,
                              editTriggers=QTreeView.NoEditTriggers)
        header = self.view.header()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setDefaultAlignment(Qt.AlignCenter)
        header.setStretchLastSection(False)

        self.result_model = QStandardItemModel(self)
        self.result_model.setHorizontalHeaderLabels(["Method"])
        self.view.setModel(self.result_model)
        self.view.setItemDelegate(ItemDelegate())

        box = gui.widgetBox(self.mainArea, "Evaluation Results")
        box.layout().addWidget(self.view)
Exemplo n.º 48
0
    def __init__(self):
        super().__init__()

        self.data = None
        self.results = None
        self.learners = []
        self.headers = []

        box = gui.vBox(self.controlArea, "Learners")

        self.learners_box = gui.listBox(box,
                                        self,
                                        "selected_learner",
                                        "learners",
                                        callback=self._learner_changed)
        box = gui.vBox(self.controlArea, "Show")

        gui.comboBox(box,
                     self,
                     "selected_quantity",
                     items=self.quantities,
                     callback=self._update)

        box = gui.vBox(self.controlArea, "Select")

        gui.button(box,
                   self,
                   "Correct",
                   callback=self.select_correct,
                   autoDefault=False)
        gui.button(box,
                   self,
                   "Misclassified",
                   callback=self.select_wrong,
                   autoDefault=False)
        gui.button(box,
                   self,
                   "None",
                   callback=self.select_none,
                   autoDefault=False)

        self.outputbox = box = gui.vBox(self.controlArea, "Output")
        gui.checkBox(box,
                     self,
                     "append_predictions",
                     "Predictions",
                     callback=self._invalidate)
        gui.checkBox(box,
                     self,
                     "append_probabilities",
                     "Probabilities",
                     callback=self._invalidate)

        gui.auto_commit(self.controlArea, self, "autocommit", "Send Data",
                        "Auto send is on")

        grid = QGridLayout()

        self.tablemodel = QStandardItemModel(self)
        view = self.tableview = QTableView(
            editTriggers=QTableView.NoEditTriggers)
        view.setModel(self.tablemodel)
        view.horizontalHeader().hide()
        view.verticalHeader().hide()
        view.horizontalHeader().setMinimumSectionSize(60)
        view.selectionModel().selectionChanged.connect(self._invalidate)
        view.setShowGrid(False)
        view.setItemDelegate(BorderedItemDelegate(Qt.white))
        view.clicked.connect(self.cell_clicked)
        grid.addWidget(view, 0, 0)
        self.mainArea.layout().addLayout(grid)
Exemplo n.º 49
0
class QMapManager(QDialog):
    def __init__(self, config, parent=None):
        QDialog.__init__(self, parent)
        curdir = os.path.abspath(os.path.dirname(__file__))
        PyQt4.uic.loadUi(os.path.join(curdir, 'manager.ui'), self)
        self.model = QStandardItemModel()
        self.projectsmodel = QStandardItemModel()
        self.projectlist.setModel(self.projectsmodel)
        self.clientlist.setModel(self.model)
        self.clientlist.selectionModel().selectionChanged.connect(self.update)
        self.installbutton.pressed.connect(self.installToClient)
        self.mapper = QDataWidgetMapper()
        self.mapper.setModel(self.model)
        self.mapper.addMapping(self.installpath, 1)
        self.config = config
        self.populateProjects()
        self.populateClients()

    def installToClient(self):
        index = self.clientlist.selectionModel().currentIndex()
        item = self.model.itemFromIndex(index)
        print "Deploying to " + item.text()
        build.deployTargetByName(item.text())

    def update(self, selected, deselected):
        index = selected.indexes()[0]
        self.mapper.setCurrentModelIndex(index)
        item = self.model.itemFromIndex(index)
        settings = item.data()

        for row in xrange(0, self.projectsmodel.rowCount()):
            index = self.projectsmodel.index(row, 0)
            item = self.projectsmodel.itemFromIndex(index)
            item.setCheckState(Qt.Unchecked)

        projects = settings['projects']

        for project in projects:
            if project == "All":
                i = 0
                while self.projectsmodel.item(i):
                    item = self.projectsmodel.item(i)
                    item.setCheckState(Qt.Checked)
                    i += 1
                break

            projectitem = self.projectsmodel.findItems(project)[0]
            projectitem.setCheckState(Qt.Checked)

    def populateClients(self):
        row = 0
        for client, settings in self.config['clients'].iteritems():
            name = QStandardItem(client)
            name.setData(settings)
            path = QStandardItem(settings['path'])
            self.model.insertRow(row, [name, path])
            row += 1

    def populateProjects(self):
        row = 0
        for project in getProjects():
            projectitem = QStandardItem(project.name)
            projectitem.setCheckable(True)
            self.projectsmodel.insertRow(row, projectitem)
            row += 1
Exemplo n.º 50
0
    class VizRank(OWWidget):
        name = "Rank projections (Scatter Plot)"

        want_control_area = False

        def __init__(self, parent_widget):
            super().__init__()
            self.parent_widget = parent_widget
            self.running = False
            self.progress = None
            self.k = 10

            self.projectionTable = QTableView()
            self.mainArea.layout().addWidget(self.projectionTable)
            self.projectionTable.setSelectionBehavior(QTableView.SelectRows)
            self.projectionTable.setSelectionMode(QTableView.SingleSelection)
            self.projectionTable.setSortingEnabled(True)
            self.projectionTableModel = QStandardItemModel(self)
            self.projectionTable.setModel(self.projectionTableModel)
            self.projectionTable.selectionModel().selectionChanged.connect(
                self.on_selection_changed)

            self.button = gui.button(self.mainArea, self, "Start evaluation",
                                     callback=self.toggle, default=True)
            self.resize(380, 512)
            self._initialize()

        def _initialize(self):
            self.running = False
            self.projectionTableModel.clear()
            self.projectionTableModel.setHorizontalHeaderLabels(
                ["Score", "Feature 1", "Feature 2"])
            self.projectionTable.setColumnWidth(0, 60)
            self.projectionTable.setColumnWidth(1, 120)
            self.projectionTable.setColumnWidth(2, 120)
            self.button.setText("Start evaluation")
            self.button.setEnabled(False)
            self.pause = False
            self.data = None
            self.attrs = []
            self.scores = []
            self.i, self.j = 0, 0
            if self.progress:
                self.progress.finish()
            self.progress = None


            self.information(0)
            if self.parent_widget.data:
                if not self.parent_widget.data.domain.class_var:
                    self.information(
                        0, "Data with a class variable is required.")
                    return
                if len(self.parent_widget.data.domain.attributes) < 2:
                    self.information(
                        0, 'At least 2 unique features are needed.')
                    return
                if len(self.parent_widget.data) < 2:
                    self.information(
                        0, 'At least 2 instances are needed.')
                    return
                self.button.setEnabled(True)

        def on_selection_changed(self, selected, deselected):
            """Called when the ranks view selection changes."""
            a1 = selected.indexes()[1].data()
            a2 = selected.indexes()[2].data()
            self.parent_widget.update_attr(attributes=(a1, a2))

        def toggle(self):
            self.running ^= 1
            if self.running:
                self.button.setText("Pause")
                self.run()
            else:
                self.button.setText("Continue")
                self.button.setEnabled(False)

        def run(self):
            graph = self.parent_widget.graph
            y_full = self.parent_widget.data.Y
            if not self.attrs:
                self.attrs = self.score_heuristic()
            if not self.progress:
                self.progress = gui.ProgressBar(
                    self, len(self.attrs) * (len(self.attrs) - 1) / 2)
            for i in range(self.i, len(self.attrs)):
                ind1 = graph.attribute_name_index[self.attrs[i]]
                for j in range(self.j, i):
                    if not self.running:
                        self.i, self.j = i, j
                        if not self.projectionTable.selectedIndexes():
                            self.projectionTable.selectRow(0)
                        self.button.setEnabled(True)
                        return
                    ind2 = graph.attribute_name_index[self.attrs[j]]
                    X = graph.scaled_data[[ind1, ind2], :]
                    valid = graph.get_valid_list([ind1, ind2])
                    X = X[:, valid].T
                    y = y_full[valid]
                    n_neighbors = min(self.k, len(X) - 1)
                    knn = NearestNeighbors(n_neighbors=n_neighbors).fit(X)
                    ind = knn.kneighbors(return_distance=False)
                    if self.parent_widget.data.domain.has_discrete_class:
                        score = np.sum(y[ind] == y.reshape(-1, 1)) / (
                            len(y_full) * n_neighbors)
                    else:
                        score = r2_score(y, np.mean(y[ind], axis=1)) * (
                            len(y) / len(y_full))
                    pos = bisect_left(self.scores, score)
                    self.projectionTableModel.insertRow(
                        len(self.scores) - pos,
                        [QStandardItem("{:.4f}".format(score)),
                         QStandardItem(self.attrs[j]),
                         QStandardItem(self.attrs[i])])
                    self.scores.insert(pos, score)
                    self.progress.advance()
                self.j = 0
            self.progress.finish()
            if not self.projectionTable.selectedIndexes():
                self.projectionTable.selectRow(0)
            self.button.setText("Finished")
            self.button.setEnabled(False)

        def score_heuristic(self):
            X = self.parent_widget.graph.scaled_data.T
            Y = self.parent_widget.data.Y
            dom = Domain([ContinuousVariable(str(i))
                          for i in range(X.shape[1])],
                         self.parent_widget.data.domain.class_vars)
            data = Table(dom, X, Y)
            relief = ReliefF if isinstance(dom.class_var,
                                           DiscreteVariable) else RReliefF
            weights = relief(n_iterations=100, k_nearest=self.k)(data)
            attrs = sorted(zip(weights,
                               (x.name for x in
                                self.parent_widget.data.domain.attributes)),
                           reverse=True)
            return [a for _, a in attrs]
Exemplo n.º 51
0
class DevicesDialog(QDialog, Ui_DevicesDialog):
  def __init__(self, parent = None):
    QDialog.__init__(self)
    self.setupUi(self)
    self.selectedDevice = None
    self.listdevices = {}
    self.devices = Devices()
    self.logical = Logical()
    self.combodevice = TreeComboBox()
    self.gridLayout.addWidget(self.combodevice, 0, 1, 1, 1)
    self.__model = QStandardItemModel()
    
    lidx = 0
    if len(self.logical):
        logicalitems = QStandardItem(self.tr("Logical drives"))
        self.__model.appendRow(logicalitems)
        for lidx in range(0, len(self.logical)):
            logicalitem = QStandardItem(self.logical[lidx].model())
            logicalitems.appendRow(logicalitem)
            self.listdevices[lidx] = self.logical[lidx]
        lidx += 1

    if len(self.devices):
        physicalitems = QStandardItem(self.tr("Physical drives"))
        self.__model.appendRow(physicalitems)
        for pidx in range(0, len(self.devices)):
            model = self.devices[pidx].model()
            if model != "Unknown":
              physicalitem = QStandardItem(self.devices[pidx].blockDevice() + " (" + model + ")")
            else:
              physicalitem = QStandardItem(self.devices[pidx].blockDevice())
            physicalitems.appendRow(physicalitem)
            self.listdevices[lidx+pidx] = self.devices[pidx]
    self.combodevice.setModel(self.__model)
    self.combodevice.view().expandAll()

    if len(self.devices):
      self.setDeviceInformations(self.devices[0], True)
      self.selectedDevice = self.devices[0]
    self.connect(self.combodevice, SIGNAL("currentIndexChanged(int)"), self.deviceChanged) 

    
  def __del__(self):
      del self.devices
      del self.logical


  def setDeviceInformations(self, device, init=False):
      self.blockdevice.setText(QString.fromUtf8(device.blockDevice()))
      self.model.setText(QString.fromUtf8(device.model()))
      self.serial.setText(QString.fromUtf8(device.serialNumber()))
      self.size.setText(str(device.size()))


  def deviceChanged(self, index):
      parent = self.combodevice.view().currentIndex().parent()
      if parent != QModelIndex():
          if parent.row() == 1:
              index += len(self.logical)    
      self.setDeviceInformations(self.listdevices[index])
      self.selectedDevice = self.listdevices[index]
Exemplo n.º 52
0
class OWMPR(OWWidget):
    name = 'ModelMap Projection Rank'
    description = "Rank projections according to the " \
                  "class-related projection quality"
    icon = "icons/ModelMap.svg"

    inputs = [('Data', Table, 'set_data', Default)]
    outputs = [('Features', AttributeList)]
    want_main_area = False
    settingsHandler = DomainContextHandler()

    variable_changed = Signal()

    def __init__(self):
        super().__init__()
        self.data = None
        self.progress = None

        self.infoa = gui.widgetLabel(self.controlArea, "No data loaded.")

        self.projectionTable = QTableView()
        self.controlArea.layout().addWidget(self.projectionTable)
        self.projectionTable.setSelectionBehavior(QTableView.SelectRows)
        self.projectionTable.setSelectionMode(QTableView.SingleSelection)
        self.projectionTable.setSortingEnabled(True)

        self.projectionTableModel = QStandardItemModel(self)
        self.projectionTableModel.setHorizontalHeaderLabels(
            ["P-Index", "", ""])
        self.projectionTable.setModel(self.projectionTableModel)

        self.projectionTable.setColumnWidth(0, 90)
        self.projectionTable.sortByColumn(0, Qt.DescendingOrder)
        self.projectionTable.selectionModel().selectionChanged.connect(
            self.on_selection_changed)

        gui.button(self.controlArea,
                   self,
                   "Rank Projections",
                   callback=self.rank,
                   default=True)
        self.resize(370, 600)

    def set_data(self, data):
        self.data = data
        self.infoa.setText("Data set: {}".format(data.name) if self.
                           data else "No data loaded.")

    def rank(self):
        if self.progress:
            return

        disc = Orange.preprocess.discretize.EqualWidth(n=10)

        ndomain = Orange.data.Domain([
            disc(self.data, attr) if attr.is_continuous else attr
            for attr in self.data.domain.attributes
        ], self.data.domain.class_vars)

        t = self.data.from_table(ndomain, self.data)

        attrs = t.domain.attributes

        tables = {}
        l = 0
        self.progress = gui.ProgressBar(self,
                                        len(attrs) * (len(attrs) - 1) / 2)
        for i in range(len(attrs)):
            for j in range(i):
                ct = np.array(
                    contingency.get_contingency(t, attrs[j], attrs[i]))
                pindex, _, _ = p_index(ct)
                tables[i, j] = ct

                item = QStandardItem()
                item.setData(float(pindex), Qt.DisplayRole)
                self.projectionTableModel.setItem(l, 0, item)

                item = QStandardItem()
                item.setData(attrs[i].name, Qt.DisplayRole)
                self.projectionTableModel.setItem(l, 1, item)

                item = QStandardItem()
                item.setData(attrs[j].name, Qt.DisplayRole)
                self.projectionTableModel.setItem(l, 2, item)

                self.progress.advance()
                l += 1

        self.progress.finish()
        self.progress = None

    def on_selection_changed(self, selected, deselected):
        """Called when the ranks view selection changes."""
        a1 = selected.indexes()[1].data()
        a2 = selected.indexes()[2].data()
        d = self.data.domain
        self.send("Features", AttributeList([d[a1], d[a2]]))
Exemplo n.º 53
0
class OWConfusionMatrix(widget.OWWidget):
    name = "Confusion Matrix"
    description = "Display confusion matrix constructed from results " \
                  "of evaluation of classifiers."
    icon = "icons/ConfusionMatrix.svg"
    priority = 1001

    inputs = [("Evaluation Results", Orange.evaluation.Results, "set_results")]
    outputs = [("Selected Data", Orange.data.Table)]

    quantities = [
        "Number of instances", "Proportion of predicted",
        "Proportion of actual"
    ]

    selected_learner = settings.Setting([])
    selected_quantity = settings.Setting(0)
    append_predictions = settings.Setting(True)
    append_probabilities = settings.Setting(False)
    autocommit = settings.Setting(True)

    UserAdviceMessages = [
        widget.Message(
            "Clicking on cells or in headers outputs the corresponding "
            "data instances", "click_cell")
    ]

    def __init__(self):
        super().__init__()

        self.data = None
        self.results = None
        self.learners = []
        self.headers = []

        box = gui.vBox(self.controlArea, "Learners")

        self.learners_box = gui.listBox(box,
                                        self,
                                        "selected_learner",
                                        "learners",
                                        callback=self._learner_changed)
        box = gui.vBox(self.controlArea, "Show")

        gui.comboBox(box,
                     self,
                     "selected_quantity",
                     items=self.quantities,
                     callback=self._update)

        box = gui.vBox(self.controlArea, "Select")

        gui.button(box,
                   self,
                   "Correct",
                   callback=self.select_correct,
                   autoDefault=False)
        gui.button(box,
                   self,
                   "Misclassified",
                   callback=self.select_wrong,
                   autoDefault=False)
        gui.button(box,
                   self,
                   "None",
                   callback=self.select_none,
                   autoDefault=False)

        self.outputbox = box = gui.vBox(self.controlArea, "Output")
        gui.checkBox(box,
                     self,
                     "append_predictions",
                     "Predictions",
                     callback=self._invalidate)
        gui.checkBox(box,
                     self,
                     "append_probabilities",
                     "Probabilities",
                     callback=self._invalidate)

        gui.auto_commit(self.controlArea, self, "autocommit", "Send Data",
                        "Auto send is on")

        grid = QGridLayout()

        self.tablemodel = QStandardItemModel(self)
        view = self.tableview = QTableView(
            editTriggers=QTableView.NoEditTriggers)
        view.setModel(self.tablemodel)
        view.horizontalHeader().hide()
        view.verticalHeader().hide()
        view.horizontalHeader().setMinimumSectionSize(60)
        view.selectionModel().selectionChanged.connect(self._invalidate)
        view.setShowGrid(False)
        view.setItemDelegate(BorderedItemDelegate(Qt.white))
        view.clicked.connect(self.cell_clicked)
        grid.addWidget(view, 0, 0)
        self.mainArea.layout().addLayout(grid)

    def sizeHint(self):
        return QSize(750, 490)

    def _item(self, i, j):
        return self.tablemodel.item(i, j) or QStandardItem()

    def _set_item(self, i, j, item):
        self.tablemodel.setItem(i, j, item)

    def set_results(self, results):
        """Set the input results."""

        self.clear()
        self.warning([0, 1])

        data = None
        if results is not None:
            if results.data is not None:
                data = results.data

        if data is not None and not data.domain.has_discrete_class:
            data = None
            results = None
            self.warning(
                0, "Confusion Matrix cannot be used for regression results.")

        self.results = results
        self.data = data

        if data is not None:
            class_values = data.domain.class_var.values
        elif results is not None:
            raise NotImplementedError

        if results is None:
            self.report_button.setDisabled(True)
        else:
            self.report_button.setDisabled(False)

            nmodels, ntests = results.predicted.shape
            self.headers = class_values + \
                           [unicodedata.lookup("N-ARY SUMMATION")]

            # NOTE: The 'learner_names' is set in 'Test Learners' widget.
            if hasattr(results, "learner_names"):
                self.learners = results.learner_names
            else:
                self.learners = [
                    "Learner #%i" % (i + 1) for i in range(nmodels)
                ]

            item = self._item(0, 2)
            item.setData("Predicted", Qt.DisplayRole)
            item.setTextAlignment(Qt.AlignCenter)
            item.setFlags(Qt.NoItemFlags)

            self._set_item(0, 2, item)
            item = self._item(2, 0)
            item.setData("Actual", Qt.DisplayRole)
            item.setTextAlignment(Qt.AlignHCenter | Qt.AlignBottom)
            item.setFlags(Qt.NoItemFlags)
            self.tableview.setItemDelegateForColumn(0,
                                                    gui.VerticalItemDelegate())
            self._set_item(2, 0, item)
            self.tableview.setSpan(0, 2, 1, len(class_values))
            self.tableview.setSpan(2, 0, len(class_values), 1)

            font = self.tablemodel.invisibleRootItem().font()
            bold_font = QFont(font)
            bold_font.setBold(True)

            for i in (0, 1):
                for j in (0, 1):
                    item = self._item(i, j)
                    item.setFlags(Qt.NoItemFlags)
                    self._set_item(i, j, item)

            for p, label in enumerate(self.headers):
                for i, j in ((1, p + 2), (p + 2, 1)):
                    item = self._item(i, j)
                    item.setData(label, Qt.DisplayRole)
                    item.setFont(bold_font)
                    item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
                    item.setFlags(Qt.ItemIsEnabled)
                    if p < len(self.headers) - 1:
                        item.setData("br"[j == 1], BorderRole)
                        item.setData(QColor(192, 192, 192), BorderColorRole)
                    self._set_item(i, j, item)

            hor_header = self.tableview.horizontalHeader()
            if len(' '.join(self.headers)) < 120:
                hor_header.setResizeMode(QHeaderView.ResizeToContents)
            else:
                hor_header.setDefaultSectionSize(60)
            self.tablemodel.setRowCount(len(class_values) + 3)
            self.tablemodel.setColumnCount(len(class_values) + 3)
            self.selected_learner = [0]
            self._update()

    def clear(self):
        self.results = None
        self.data = None
        self.tablemodel.clear()
        self.headers = []
        # Clear learners last. This action will invoke `_learner_changed`
        # method
        self.learners = []

    def select_correct(self):
        selection = QItemSelection()
        n = self.tablemodel.rowCount()
        for i in range(2, n):
            index = self.tablemodel.index(i, i)
            selection.select(index, index)

        self.tableview.selectionModel().select(
            selection, QItemSelectionModel.ClearAndSelect)

    def select_wrong(self):
        selection = QItemSelection()
        n = self.tablemodel.rowCount()

        for i in range(2, n):
            for j in range(i + 1, n):
                index = self.tablemodel.index(i, j)
                selection.select(index, index)
                index = self.tablemodel.index(j, i)
                selection.select(index, index)

        self.tableview.selectionModel().select(
            selection, QItemSelectionModel.ClearAndSelect)

    def select_none(self):
        self.tableview.selectionModel().clear()

    def cell_clicked(self, model_index):
        i, j = model_index.row(), model_index.column()
        if not i or not j:
            return
        n = self.tablemodel.rowCount()
        index = self.tablemodel.index
        selection = None
        if i == j == 1 or i == j == n - 1:
            selection = QItemSelection(index(2, 2), index(n - 1, n - 1))
        elif i in (1, n - 1):
            selection = QItemSelection(index(2, j), index(n - 1, j))
        elif j in (1, n - 1):
            selection = QItemSelection(index(i, 2), index(i, n - 1))

        if selection is not None:
            self.tableview.selectionModel().select(
                selection, QItemSelectionModel.ClearAndSelect)

    def commit(self):
        if self.results is not None and self.data is not None \
                and self.selected_learner:
            indices = self.tableview.selectedIndexes()
            indices = {(ind.row() - 2, ind.column() - 2) for ind in indices}
            actual = self.results.actual
            selected_learner = self.selected_learner[0]
            learner_name = self.learners[selected_learner]
            predicted = self.results.predicted[selected_learner]
            selected = [
                i for i, t in enumerate(zip(actual, predicted)) if t in indices
            ]
            row_indices = self.results.row_indices[selected]

            extra = []
            class_var = self.data.domain.class_var
            metas = self.data.domain.metas

            if self.append_predictions:
                predicted = numpy.array(predicted[selected], dtype=object)
                extra.append(predicted.reshape(-1, 1))
                var = Orange.data.DiscreteVariable(
                    "{}({})".format(class_var.name, learner_name),
                    class_var.values)
                metas = metas + (var, )

            if self.append_probabilities and \
                    self.results.probabilities is not None:
                probs = self.results.probabilities[selected_learner, selected]
                extra.append(numpy.array(probs, dtype=object))
                pvars = [
                    Orange.data.ContinuousVariable("p({})".format(value))
                    for value in class_var.values
                ]
                metas = metas + tuple(pvars)

            X = self.data.X[row_indices]
            Y = self.data.Y[row_indices]
            M = self.data.metas[row_indices]
            row_ids = self.data.ids[row_indices]

            M = numpy.hstack((M, ) + tuple(extra))
            domain = Orange.data.Domain(self.data.domain.attributes,
                                        self.data.domain.class_vars, metas)
            data = Orange.data.Table.from_numpy(domain, X, Y, M)
            data.ids = row_ids
            data.name = learner_name

        else:
            data = None

        self.send("Selected Data", data)

    def _invalidate(self):
        self.commit()

    def _learner_changed(self):
        # The selected learner has changed
        indices = self.tableview.selectedIndexes()
        self._update()
        selection = QItemSelection()
        for sel in indices:
            selection.select(sel, sel)
        self.tableview.selectionModel().select(
            selection, QItemSelectionModel.ClearAndSelect)
        self.commit()

    def _update(self):
        def isinvalid(x):
            return isnan(x) or isinf(x)

        # Update the displayed confusion matrix
        if self.results is not None and self.selected_learner:
            index = self.selected_learner[0]
            cmatrix = confusion_matrix(self.results, index)
            colsum = cmatrix.sum(axis=0)
            rowsum = cmatrix.sum(axis=1)
            total = rowsum.sum()
            n = len(cmatrix)
            diag = numpy.diag_indices(n)

            colors = cmatrix.astype(numpy.double)
            colors[diag] = 0
            if self.selected_quantity == 0:
                normalized = cmatrix.astype(numpy.int)
                formatstr = "{}"
                div = numpy.array([colors.max()])
            else:
                if self.selected_quantity == 1:
                    normalized = 100 * cmatrix / colsum
                    div = colors.max(axis=0)
                else:
                    normalized = 100 * cmatrix / rowsum[:, numpy.newaxis]
                    div = colors.max(axis=1)[:, numpy.newaxis]
                formatstr = "{:2.1f} %"
            div[div == 0] = 1
            colors /= div
            colors[diag] = normalized[diag] / normalized[diag].max()

            hue = [0, 240]
            for i in range(n):
                for j in range(n):
                    val = normalized[i, j]
                    col_val = colors[i, j]
                    item = self._item(i + 2, j + 2)
                    item.setData(
                        "NA" if isinvalid(val) else formatstr.format(val),
                        Qt.DisplayRole)
                    bkcolor = QColor.fromHsl(
                        hue[i == j], 160,
                        255 if isinvalid(col_val) else int(255 - 30 * col_val))
                    item.setData(QBrush(bkcolor), Qt.BackgroundRole)
                    item.setData("trbl", BorderRole)
                    item.setToolTip("actual: {}\npredicted: {}".format(
                        self.headers[i], self.headers[j]))
                    item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
                    item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self._set_item(i + 2, j + 2, item)

            model = self.tablemodel
            font = model.invisibleRootItem().font()
            bold_font = QFont(font)
            bold_font.setBold(True)

            def sum_item(value, border=""):
                item = QStandardItem()
                item.setData(value, Qt.DisplayRole)
                item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
                item.setFlags(Qt.ItemIsEnabled)
                item.setFont(bold_font)
                item.setData(border, BorderRole)
                item.setData(QColor(192, 192, 192), BorderColorRole)
                return item

            N = len(colsum)
            for i in range(N):
                model.setItem(N + 2, i + 2, sum_item(int(colsum[i]), "t"))
                model.setItem(i + 2, N + 2, sum_item(int(rowsum[i]), "l"))

            model.setItem(N + 2, N + 2, sum_item(int(total)))

    def send_report(self):
        if self.results is not None and self.selected_learner:
            index = self.selected_learner[0]
            self.report_table(
                "Confusion matrix for {} (showing {})".format(
                    self.learners[index],
                    self.quantities[self.selected_quantity].lower()),
                self.tablemodel)
Exemplo n.º 54
0
class QtWidgetRegistry(QObject, WidgetRegistry):
    """
    A QObject wrapper for `WidgetRegistry`

    A QStandardItemModel instance containing the widgets in
    a tree (of depth 2). The items in a model can be quaries using standard
    roles (DisplayRole, BackgroundRole, DecorationRole ToolTipRole).
    They also have QtWidgetRegistry.CATEGORY_DESC_ROLE,
    QtWidgetRegistry.WIDGET_DESC_ROLE, which store Category/WidgetDescription
    respectfully. Furthermore QtWidgetRegistry.WIDGET_ACTION_ROLE stores an
    default QAction which can be used for widget creation action.

    """

    CATEGORY_DESC_ROLE = Qt.UserRole + 1
    """Category Description Role"""

    WIDGET_DESC_ROLE = Qt.UserRole + 2
    """Widget Description Role"""

    WIDGET_ACTION_ROLE = Qt.UserRole + 3
    """Widget Action Role"""

    BACKGROUND_ROLE = Qt.UserRole + 4
    """Background color for widget/category in the canvas
    (different from Qt.BackgroundRole)
    """

    category_added = Signal(str, CategoryDescription)
    """signal: category_added(name: str, desc: CategoryDescription)
    """

    widget_added = Signal(str, str, WidgetDescription)
    """signal widget_added(category_name: str, widget_name: str,
                           desc: WidgetDescription)
    """

    reset = Signal()
    """signal: reset()
    """
    def __init__(self, other_or_parent=None, parent=None):
        if isinstance(other_or_parent, QObject) and parent is None:
            parent, other_or_parent = other_or_parent, None
        QObject.__init__(self, parent)
        WidgetRegistry.__init__(self, other_or_parent)

        # Should  the QStandardItemModel be subclassed?
        self.__item_model = QStandardItemModel(self)

        for i, desc in enumerate(self.categories()):
            cat_item = self._cat_desc_to_std_item(desc)
            self.__item_model.insertRow(i, cat_item)

            for j, wdesc in enumerate(self.widgets(desc.name)):
                widget_item = self._widget_desc_to_std_item(wdesc, desc)
                cat_item.insertRow(j, widget_item)

    def model(self):
        """
        Return the widget descriptions in a Qt Item Model instance
        (QStandardItemModel).

        .. note:: The model should not be modified outside of the registry.

        """
        return self.__item_model

    def item_for_widget(self, widget):
        """Return the QStandardItem for the widget.
        """
        if isinstance(widget, str):
            widget = self.widget(widget)
        cat = self.category(widget.category)
        cat_ind = self.categories().index(cat)
        cat_item = self.model().item(cat_ind)
        widget_ind = self.widgets(cat).index(widget)
        return cat_item.child(widget_ind)

    def action_for_widget(self, widget):
        """
        Return the QAction instance for the widget (can be a string or
        a WidgetDescription instance).

        """
        item = self.item_for_widget(widget)
        return item.data(self.WIDGET_ACTION_ROLE)

    def create_action_for_item(self, item):
        """
        Create a QAction instance for the widget description item.
        """
        name = item.text()
        tooltip = item.toolTip()
        whatsThis = item.whatsThis()
        icon = item.icon()
        if icon:
            action = QAction(icon,
                             name,
                             self,
                             toolTip=tooltip,
                             whatsThis=whatsThis,
                             statusTip=name)
        else:
            action = QAction(name,
                             self,
                             toolTip=tooltip,
                             whatsThis=whatsThis,
                             statusTip=name)

        widget_desc = item.data(self.WIDGET_DESC_ROLE)
        action.setData(widget_desc)
        action.setProperty("item", item)
        return action

    def _insert_category(self, desc):
        """
        Override to update the item model and emit the signals.
        """
        priority = desc.priority
        priorities = [c.priority for c, _ in self.registry]
        insertion_i = bisect.bisect_right(priorities, priority)

        WidgetRegistry._insert_category(self, desc)

        cat_item = self._cat_desc_to_std_item(desc)
        self.__item_model.insertRow(insertion_i, cat_item)

        self.category_added.emit(desc.name, desc)

    def _insert_widget(self, category, desc):
        """
        Override to update the item model and emit the signals.
        """
        assert (isinstance(category, CategoryDescription))
        categories = self.categories()
        cat_i = categories.index(category)
        _, widgets = self._categories_dict[category.name]
        priorities = [w.priority for w in widgets]
        insertion_i = bisect.bisect_right(priorities, desc.priority)

        WidgetRegistry._insert_widget(self, category, desc)

        cat_item = self.__item_model.item(cat_i)
        widget_item = self._widget_desc_to_std_item(desc, category)

        cat_item.insertRow(insertion_i, widget_item)

        self.widget_added.emit(category.name, desc.name, desc)

    def _cat_desc_to_std_item(self, desc):
        """
        Create a QStandardItem for the category description.
        """
        item = QStandardItem()
        item.setText(desc.name)

        if desc.icon:
            icon = desc.icon
        else:
            icon = "icons/default-category.svg"

        icon = icon_loader.from_description(desc).get(icon)
        item.setIcon(icon)

        if desc.background:
            background = desc.background
        else:
            background = DEFAULT_COLOR

        background = NAMED_COLORS.get(background, background)

        brush = QBrush(QColor(background))
        item.setData(brush, self.BACKGROUND_ROLE)

        tooltip = desc.description if desc.description else desc.name

        item.setToolTip(tooltip)
        item.setFlags(Qt.ItemIsEnabled)
        item.setData(desc, self.CATEGORY_DESC_ROLE)
        return item

    def _widget_desc_to_std_item(self, desc, category):
        """
        Create a QStandardItem for the widget description.
        """
        item = QStandardItem(desc.name)
        item.setText(desc.name)

        if desc.icon:
            icon = desc.icon
        else:
            icon = "icons/default-widget.svg"

        icon = icon_loader.from_description(desc).get(icon)
        item.setIcon(icon)

        # This should be inherited from the category.
        background = None
        if desc.background:
            background = desc.background
        elif category.background:
            background = category.background
        else:
            background = DEFAULT_COLOR

        if background is not None:
            background = NAMED_COLORS.get(background, background)
            brush = QBrush(QColor(background))
            item.setData(brush, self.BACKGROUND_ROLE)

        tooltip = tooltip_helper(desc)
        style = "ul { margin-top: 1px; margin-bottom: 1px; }"
        tooltip = TOOLTIP_TEMPLATE.format(style=style, tooltip=tooltip)
        item.setToolTip(tooltip)
        item.setWhatsThis(whats_this_helper(desc))
        item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
        item.setData(desc, self.WIDGET_DESC_ROLE)

        # Create the action for the widget_item
        action = self.create_action_for_item(item)
        item.setData(action, self.WIDGET_ACTION_ROLE)
        return item
Exemplo n.º 55
0
class ClusterWidget(QSplitter):
    def __init__(self, peaks, parent=None):
        QSplitter.__init__(self, Qt.Vertical, parent)
        self.peaks = peaks
        self.choosenOne = [pe for pe in self.peaks if pe is not None][0]
        #self.peakModel = QStandardItemModel()
        self.identificationModel = QStandardItemModel()
        self.setupUi()
        self.setModel()
        self.connect(self.calcCorr, SIGNAL('pressed()'), self.setRankValue)
        #self.setRankValue()

    def setupUi(self):
        self.widget = MSView(
            MSQtCanvas(self.peaks,
                       "peaks@%s" % str(self.peaks[0]),
                       labels={
                           'bottom': 'RT(s)',
                           'left': 'INTENSITY'
                       },
                       flags='peak'))
        self.tableView = QTableView()
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.setSortingEnabled(True)

        self.corr = QLabel("Nan")
        self.calcCorr = QPushButton("r_coef:")
        #v = QVBoxLayout(self)
        self.addWidget(self.widget)

        self.wid = QWidget()
        vb = QVBoxLayout()
        vb.addWidget(self.calcCorr)
        vb.addWidget(self.corr)
        hb = QHBoxLayout(self.wid)
        #if self.choosenOne.formulas:
        hb.addWidget(self.tableView)
        #else:
        #    hb.addWidget(QLabel("Identification not performed yet..."))
        hb.addLayout(vb)
        self.addWidget(self.wid)

    def setModel(self):
        from gui.MetBaseGui import MSStandardItem
        #we assume that the different peaks have the same identifiers
        #TODO: may have to merge several stuffs later
        if self.choosenOne.formulas:
            self.identificationModel.setHorizontalHeaderLabels(
                ["score", "formula", "diff mass", "names"])
            for i, f in enumerate(self.choosenOne.formulas.iterkeys()):

                self.identificationModel.setItem(
                    i, 0,
                    MSStandardItem(str(self.choosenOne.formulas[f]["score"])))
                self.identificationModel.setItem(i, 1, QStandardItem(str(f)))
                self.identificationModel.setItem(
                    i, 2,
                    MSStandardItem(str(
                        self.choosenOne.formulas[f]["diffmass"])))
                self.identificationModel.setItem(
                    i, 3, QStandardItem(self.choosenOne.formulas[f]["names"]))
                if self.choosenOne.formulas[f]["names"] != 'Not Found':
                    for j in xrange(4):
                        self.identificationModel.item(i, j).setBackground(
                            QBrush(Qt.green))
                else:
                    for j in xrange(4):
                        self.identificationModel.item(i, j).setBackground(
                            QBrush(Qt.red))
            self.tableView.setModel(self.identificationModel)

    def setRankValue(self):
        #m = qApp.instance().model
        #m.pearsonIntraCalculation()
        #peaks =[]
        #for spl in m:
        #    peaks+=[p.r_coef for p in spl.mappedPeaks if p.r_coef]
        #if not self.choosenOne.r_coef:
        self.choosenOne.pCalcBasedOnPeakShape()
        #from _bisect import bisect_left
        #x = bisect_left(sorted(peaks), self.choosenOne.r_coef)
        s = '<br><b>%f</b></br>' % np.round(self.choosenOne.r_coef, 4)
        #s+='<br><b>Rank: </b>%d</br>'%abs(len(peaks)-x)
        self.corr.setText(s)
Exemplo n.º 56
0
class SubPowerWidget(QWidget):
    """
	@brief Zeigt alle Unterkräfte in einer Baumstruktur an.
	"""
    def __init__(self, template, character, parent=None):
        super(SubPowerWidget, self).__init__(parent)

        self.__storage = template
        self.__character = character

        self.__model = QStandardItemModel()
        # Das ungenutzte Model dient dazu, alle Unterkräfte aufzunehmen, die ich nicht darstellen möchte. Ist einfacher, als diese im View zu verstecken.
        self.__modelUnused = QStandardItemModel()

        self._layout = QVBoxLayout()
        self.setLayout(self._layout)

        self.__view = QTreeView()
        self.__view.setHeaderHidden(True)
        self.__view.setModel(self.__model)

        self._layout.addWidget(self.__view)

        self._typ = "Subpower"
        categories = self.__storage.categories(self._typ)

        self.__items = {}

        self.__rootItem = QStandardItem()
        self.__rootItem = self.__model.invisibleRootItem()

        self.__rootItemUnused = QStandardItem()
        self.__rootItemUnused = self.__modelUnused.invisibleRootItem()

        for item in categories:
            categoryItem = QStandardItem(item)
            self.__rootItem.appendRow(categoryItem)

            ## Ich benötige diese Items auch im ungenutzten Model.
            categoryItemUnused = QStandardItem(item)
            self.__rootItemUnused.appendRow(categoryItemUnused)

            traitList = list(self.__character.traits[self._typ][item].items())
            traitList.sort()
            for trait in traitList:
                traitItem = QStandardItem(trait[1].name)
                traitItem.setCheckable(True)
                ## Unhashable Type
                self.__items[trait[1]] = traitItem
                categoryItem.appendRow(traitItem)

                ## Funktioniert mit PySide nicht:
                #trait[1].availableChanged.connect(traitItem.setEnabled)
                ## Funktioniert auch mit PySide:
                trait[1].availableChanged.connect(
                    lambda enable, item=traitItem: item.setEnabled(enable))
                trait[1].valueChanged.connect(lambda val, trait=trait[
                    1], item=traitItem: self.__setItemValue(trait, item))

        self.__model.itemChanged.connect(self.__getItemValue)
        self.__character.speciesChanged.connect(self.hideOrShowToolPage)
        self.__character.breedChanged.connect(self.hideOrShowToolPage)
        self.__character.factionChanged.connect(self.hideOrShowToolPage)

    def __setItemValue(self, trait, item):
        """
		Setzt den Wert der Angezeigten Items.
		"""

        if trait.value == 0:
            item.setCheckState(Qt.Unchecked)
        elif trait.value == 1:
            item.setCheckState(Qt.PartiallyChecked)
        else:
            item.setCheckState(Qt.Checked)

    def __getItemValue(self, item):
        """
		Setzt den Wert der Eigenschaft im Speicher.
		"""

        for trait in self.__items.items():
            if id(trait[1]) == id(item):
                trait[0].value = item.checkState()
                break

    def hideOrShowToolPage(self, res):
        """
		Alle Eigenschaften, die nicht zur Verfügung stehen, werden verborgen, indem sie in ein anderes Model verschoben werden.

		\bug Möglicher Fehler in PySide: Der Aufruf von QStandardItem.model() führt beim Beenden des Programms zu einem Segmentation Fault.
		"""

        # Versteckt alle Unterkräfte, die zu gewähltem Charakter nicht passen.
        for item in self.__items.items():
            if ((item[0].species
                 and item[0].species != self.__character.species) or
                (item[0].only and self.__character.breed not in item[0].only
                 and self.__character.faction not in item[0].only)):
                #self.__view.setRowHidden(item[1].index().row(), item[1].parent().index(), True)
                #Debug.debug(item[1].model())
                ## Hier wird beispielsweise besagter Aufruf getätigt, der zu einem segfault führt.
                if item[1].model() == self.__model:
                    parent = item[1].parent()
                    itemUnused = parent.takeRow(item[1].index().row())
                    parentUnused = self.__modelUnused.findItems(
                        parent.text())[0]
                    parentUnused.appendRow(itemUnused)
            else:
                #self.__view.setRowHidden(item[1].index().row(), item[1].parent().index(), False)
                if item[1].model() == self.__modelUnused:
                    parent = item[1].parent()
                    itemUsed = parent.takeRow(item[1].index().row())
                    parentUsed = self.__model.findItems(parent.text())[0]
                    parentUsed.appendRow(itemUsed)

        ## Versteckt alle Elternzeilen, wenn sie keine Kinder enthalten.
        for i in range(self.__model.rowCount()):
            categoryItem = self.__model.item(i)
            if categoryItem.hasChildren():
                self.__view.setRowHidden(categoryItem.index().row(),
                                         self.__rootItem.index(), False)
            else:
                self.__view.setRowHidden(categoryItem.index().row(),
                                         self.__rootItem.index(), True)
Exemplo n.º 57
0
class OWTestLearners(widget.OWWidget):
    name = "Test Learners"
    description = "Cross-validation accuracy estimation."
    icon = "icons/TestLearners1.svg"
    priority = 100

    inputs = [("Learner", Orange.classification.Learner,
               "set_learner", widget.Multiple),
              ("Data", Orange.data.Table, "set_train_data", widget.Default),
              ("Test Data", Orange.data.Table, "set_test_data")]

    outputs = [("Evaluation Results", Orange.evaluation.Results)]

    settingsHandler = settings.ClassValuesContextHandler()

    #: Resampling/testing types
    KFold, LeaveOneOut, Bootstrap, TestOnTrain, TestOnTest = 0, 1, 2, 3, 4

    #: Selected resampling type
    resampling = settings.Setting(0)
    #: Number of folds for K-fold cross validation
    k_folds = settings.Setting(10)
    #: Number of repeats for bootstrap sampling
    n_repeat = settings.Setting(10)
    #: Bootstrap sampling p
    sample_p = settings.Setting(75)

    class_selection = settings.ContextSetting("(None)")

    def __init__(self, parent=None):
        super().__init__(parent)

        self.train_data = None
        self.test_data = None

        #: An Ordered dictionary with current inputs and their testing
        #: results.
        self.learners = OrderedDict()

        sbox = gui.widgetBox(self.controlArea, "Sampling")
        rbox = gui.radioButtons(
            sbox, self, "resampling", callback=self._param_changed
        )
        gui.appendRadioButton(rbox, "Cross validation")
        ibox = gui.indentedBox(rbox)
        gui.spin(ibox, self, "k_folds", 2, 50, label="Number of folds:",
                 callback=self.kfold_changed)
        gui.appendRadioButton(rbox, "Leave one out")
        gui.appendRadioButton(rbox, "Random sampling")
        ibox = gui.indentedBox(rbox)
        gui.spin(ibox, self, "n_repeat", 2, 50, label="Repeat train/test",
                 callback=self.bootstrap_changed)
        gui.widgetLabel(ibox, "Relative training set size:")
        gui.hSlider(ibox, self, "sample_p", minValue=1, maxValue=100,
                    ticks=20, vertical=False, labelFormat="%d %%",
                    callback=self.bootstrap_changed)

        gui.appendRadioButton(rbox, "Test on train data")
        gui.appendRadioButton(rbox, "Test on test data")

        rbox.layout().addSpacing(5)
        gui.button(rbox, self, "Apply", callback=self.apply)

        self.cbox = gui.widgetBox(self.controlArea, "Target class")
        self.class_selection_combo = gui.comboBox(self.cbox, self, "class_selection",
             items=[],
             callback=self._select_class,
             sendSelectedValue=True, valueType=str)

        gui.rubber(self.controlArea)


        self.view = QTreeView(
            rootIsDecorated=False,
            uniformRowHeights=True,
            wordWrap=True,
            editTriggers=QTreeView.NoEditTriggers
        )
        header = self.view.header()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setDefaultAlignment(Qt.AlignCenter)
        header.setStretchLastSection(False)

        self.result_model = QStandardItemModel()
        self.view.setModel(self.result_model)
        self.view.setItemDelegate(ItemDelegate())
        self._update_header()
        box = gui.widgetBox(self.mainArea, "Evaluation Results")
        box.layout().addWidget(self.view)

    def set_learner(self, learner, key):
        if key in self.learners and learner is None:
            del self.learners[key]
        else:
            self.learners[key] = Input(learner, None, ())
        self._update_stats_model()

    def set_train_data(self, data):
        self.error(0)
        if data and not data.domain.class_var:
            self.error(0, "Train data input requires a class variable")
            data = None

        self.train_data = data
        self.closeContext()
        if data is not None:
            self.openContext(data.domain.class_var)
            self._update_header()
        self._update_class_selection()
        self._invalidate()

    def set_test_data(self, data):
        self.error(1)
        if data and not data.domain.class_var:
            self.error(1, "Test data input requires a class variable")
            data = None

        self.test_data = data
        if self.resampling == OWTestLearners.TestOnTest:
            self._invalidate()

    def handleNewSignals(self):
        self.update_results()
        self.commit()

    def kfold_changed(self):
        self.resampling = OWTestLearners.KFold
        self._param_changed()

    def bootstrap_changed(self):
        self.resampling = OWTestLearners.Bootstrap
        self._param_changed()

    def _param_changed(self):
        self._invalidate()

    def update_results(self):
        self.warning([1, 2])
        self.error(2)

        if self.train_data is None:
            return

        if self.resampling == OWTestLearners.TestOnTest:
            if self.test_data is None:
                self.warning(2, "Missing separate test data input")
                return

            elif self.test_data.domain.class_var != \
                    self.train_data.domain.class_var:
                self.error(2, ("Inconsistent class variable between test " +
                               "and train data sets"))
                return

        # items in need of an update
        items = [(key, input) for key, input in self.learners.items()
                 if input.results is None]
        learners = [input.learner for _, input in items]

        self.setStatusMessage("Running")
        if self.test_data is not None and \
                self.resampling != OWTestLearners.TestOnTest:
            self.warning(1, "Test data is present but unused. "
                            "Select 'Test on test data' to use it.")

        # TODO: Test each learner individually
        try:
            if self.resampling == OWTestLearners.KFold:
                results = Orange.evaluation.CrossValidation(
                    self.train_data, learners, k=self.k_folds, store_data=True
                )
            elif self.resampling == OWTestLearners.LeaveOneOut:
                results = Orange.evaluation.LeaveOneOut(
                    self.train_data, learners, store_data=True
                )
            elif self.resampling == OWTestLearners.Bootstrap:
                p = self.sample_p / 100.0
                results = Orange.evaluation.Bootstrap(
                    self.train_data, learners, n_resamples=self.n_repeat, p=p,
                    store_data=True
                )
            elif self.resampling == OWTestLearners.TestOnTrain:
                results = Orange.evaluation.TestOnTrainingData(
                    self.train_data, learners, store_data=True
                )
            elif self.resampling == OWTestLearners.TestOnTest:
                if self.test_data is None:
                    return
                results = Orange.evaluation.TestOnTestData(
                    self.train_data, self.test_data, learners, store_data=True
                )
            else:
                assert False
        except Exception as e:
            self.error(2, str(e))
            return

        self.results = results
        results = list(split_by_model(results))

        class_var = self.train_data.domain.class_var

        if class_var.is_discrete:
            stats = [classification_stats(self.one_vs_rest(res)) for res in results]
        else:
            stats = [regression_stats(res) for res in results]

        self._update_header()

        for (key, input), res, stat in zip(items, results, stats):
            self.learners[key] = input._replace(results=res, stats=stat)

        self.setStatusMessage("")

        self._update_stats_model()


    def _update_header(self):
        headers = ["Method"]
        if self.train_data is not None:
            if self.train_data.domain.class_var.is_discrete:
                headers.extend(classification_stats.headers)
            else:
                headers.extend(regression_stats.headers)
        for i in reversed(range(len(headers),
                                self.result_model.columnCount())):
            self.result_model.takeColumn(i)

        self.result_model.setHorizontalHeaderLabels(headers)

    def _update_stats_model(self):
        model = self.view.model()

        for r in reversed(range(model.rowCount())):
            model.takeRow(r)

        for input in self.learners.values():
            name = learner_name(input.learner)
            row = []
            head = QStandardItem()
            head.setData(name, Qt.DisplayRole)
            row.append(head)
            for stat in input.stats:
                item = QStandardItem()
                item.setData(" {:.3f} ".format(stat[0]), Qt.DisplayRole)
                row.append(item)
            model.appendRow(row)

    def _update_class_selection(self):
        self.class_selection_combo.clear()
        if not self.train_data:
            return
        if self.train_data.domain.class_var.is_discrete:
            self.cbox.setVisible(True)
            values = self.train_data.domain.class_var.values
            self.class_selection_combo.addItem("(None)")
            self.class_selection_combo.addItems(values)

            class_index = 0
            if self.class_selection in self.train_data.domain.class_var.values:
                    class_index = self.train_data.domain.class_var.values.index(self.class_selection)+1
            else:
                self.class_selection = '(None)'

            self.class_selection_combo.setCurrentIndex(class_index)
            self.previous_class_selection = "(None)"
        else:
            self.cbox.setVisible(False)

    def one_vs_rest(self, res):
        if self.class_selection != '(None)' and self.class_selection != 0:
            class_ = self.train_data.domain.class_var.values.index(self.class_selection)
            actual = res.actual == class_
            predicted = res.predicted == class_
            return Results(
                nmethods=1, domain=self.train_data.domain,
                actual=actual, predicted=predicted)
        else:
            return res

    def _select_class(self):
        if self.previous_class_selection == self.class_selection:
            return

        results = list(split_by_model(self.results))

        items = [(key, input) for key, input in self.learners.items()]
        learners = [input.learner for _, input in items]

        class_var = self.train_data.domain.class_var
        if class_var.is_discrete:
            stats = [classification_stats(self.one_vs_rest(res)) for res in results]
        else:
            stats = [regression_stats(res) for res in results]

        for (key, input), res, stat in zip(items, results, stats):
            self.learners[key] = input._replace(results=res, stats=stat)

        self.setStatusMessage("")

        self._update_stats_model()
        self.previous_class_selection = self.class_selection

    def _invalidate(self, which=None):
        if which is None:
            which = self.learners.keys()

        all_keys = list(self.learners.keys())
        model = self.view.model()

        for key in which:
            self.learners[key] = \
                self.learners[key]._replace(results=None, stats=None)

            if key in self.learners:
                row = all_keys.index(key)
                for c in range(1, model.columnCount()):
                    item = model.item(row, c)
                    if item is not None:
                        item.setData(None, Qt.DisplayRole)

    def apply(self):
        self.update_results()
        self.commit()

    def commit(self):
        results = [val.results for val in self.learners.values()
                   if val.results is not None]
        if results:
            combined = results_merge(results)
            combined.learner_names = [learner_name(val.learner)
                                     for val in self.learners.values()]
        else:
            combined = None
        self.send("Evaluation Results", combined)
Exemplo n.º 58
0
class OWKMeans(widget.OWWidget):
    name = "k-Means"
    description = "k-Means clustering algorithm with silhouette-based " \
                  "quality estimation."
    icon = "icons/KMeans.svg"
    priority = 2100

    inputs = [("Data", Table, "set_data")]

    outputs = [("Annotated Data", Table, widget.Default), ("Centroids", Table)]

    INIT_KMEANS, INIT_RANDOM = range(2)
    INIT_METHODS = "Initialize with KMeans++", "Random initialization"

    SILHOUETTE, INTERCLUSTER, DISTANCES = range(3)
    SCORING_METHODS = [("Silhouette", lambda km: km.silhouette, False),
                       ("Inter-cluster distance", lambda km: km.inter_cluster,
                        True),
                       ("Distance to centroids", lambda km: km.inertia, True)]

    OUTPUT_CLASS, OUTPUT_ATTRIBUTE, OUTPUT_META = range(3)
    OUTPUT_METHODS = ("Class", "Feature", "Meta")

    resizing_enabled = False

    k = Setting(3)
    k_from = Setting(2)
    k_to = Setting(8)
    optimize_k = Setting(False)
    max_iterations = Setting(300)
    n_init = Setting(10)
    smart_init = Setting(INIT_KMEANS)
    scoring = Setting(SILHOUETTE)
    append_cluster_ids = Setting(True)
    place_cluster_ids = Setting(OUTPUT_CLASS)
    output_name = Setting("Cluster")
    auto_run = Setting(True)

    def __init__(self):
        super().__init__()

        self.data = None
        self.km = None
        self.optimization_runs = []

        box = gui.vBox(self.controlArea, "Number of Clusters")
        layout = QGridLayout()
        self.n_clusters = bg = gui.radioButtonsInBox(box,
                                                     self,
                                                     "optimize_k", [],
                                                     orientation=layout,
                                                     callback=self.update)
        layout.addWidget(
            gui.appendRadioButton(bg, "Fixed:", addToLayout=False), 1, 1)
        sb = gui.hBox(None, margin=0)
        self.fixedSpinBox = gui.spin(sb,
                                     self,
                                     "k",
                                     minv=2,
                                     maxv=30,
                                     controlWidth=60,
                                     alignment=Qt.AlignRight,
                                     callback=self.update_k)
        gui.rubber(sb)
        layout.addWidget(sb, 1, 2)

        layout.addWidget(
            gui.appendRadioButton(bg, "Optimized from", addToLayout=False), 2,
            1)
        ftobox = gui.hBox(None)
        ftobox.layout().setContentsMargins(0, 0, 0, 0)
        layout.addWidget(ftobox)
        gui.spin(ftobox,
                 self,
                 "k_from",
                 minv=2,
                 maxv=29,
                 controlWidth=60,
                 alignment=Qt.AlignRight,
                 callback=self.update_from)
        gui.widgetLabel(ftobox, "to")
        self.fixedSpinBox = gui.spin(ftobox,
                                     self,
                                     "k_to",
                                     minv=3,
                                     maxv=30,
                                     controlWidth=60,
                                     alignment=Qt.AlignRight,
                                     callback=self.update_to)
        gui.rubber(ftobox)

        layout.addWidget(gui.widgetLabel(None, "Scoring: "), 5, 1,
                         Qt.AlignRight)
        layout.addWidget(
            gui.comboBox(None,
                         self,
                         "scoring",
                         label="Scoring",
                         items=list(zip(*self.SCORING_METHODS))[0],
                         callback=self.update), 5, 2)

        box = gui.vBox(self.controlArea, "Initialization")
        gui.comboBox(box,
                     self,
                     "smart_init",
                     items=self.INIT_METHODS,
                     callback=self.update)

        layout = QGridLayout()
        box2 = gui.widgetBox(box, orientation=layout)
        box2.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        layout.addWidget(gui.widgetLabel(None, "Re-runs: "), 0, 0,
                         Qt.AlignLeft)
        sb = gui.hBox(None, margin=0)
        layout.addWidget(sb, 0, 1)
        gui.lineEdit(sb,
                     self,
                     "n_init",
                     controlWidth=60,
                     valueType=int,
                     validator=QIntValidator(),
                     callback=self.update)
        layout.addWidget(gui.widgetLabel(None, "Maximal iterations: "), 1, 0,
                         Qt.AlignLeft)
        sb = gui.hBox(None, margin=0)
        layout.addWidget(sb, 1, 1)
        gui.lineEdit(sb,
                     self,
                     "max_iterations",
                     controlWidth=60,
                     valueType=int,
                     validator=QIntValidator(),
                     callback=self.update)

        box = gui.vBox(self.controlArea, "Output")
        gui.comboBox(box,
                     self,
                     "place_cluster_ids",
                     label="Append cluster ID as:",
                     orientation=Qt.Horizontal,
                     callback=self.send_data,
                     items=self.OUTPUT_METHODS)
        gui.lineEdit(box,
                     self,
                     "output_name",
                     label="Name:",
                     orientation=Qt.Horizontal,
                     callback=self.send_data)

        gui.separator(self.buttonsArea, 30)
        self.apply_button = gui.auto_commit(self.buttonsArea,
                                            self,
                                            "auto_run",
                                            "Apply",
                                            box=None)
        gui.rubber(self.controlArea)

        self.table_model = QStandardItemModel(self)
        self.table_model.setHorizontalHeaderLabels(["k", "Score"])
        self.table_model.setColumnCount(2)

        self.table_box = gui.vBox(self.mainArea,
                                  "Optimization Report",
                                  addSpace=0)
        table = self.table_view = QTableView(self.table_box)
        table.setHorizontalScrollMode(QTableView.ScrollPerPixel)
        table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        table.setSelectionMode(QTableView.SingleSelection)
        table.setSelectionBehavior(QTableView.SelectRows)
        table.verticalHeader().hide()
        table.setItemDelegateForColumn(1, gui.TableBarItem(self))
        table.setModel(self.table_model)
        table.selectionModel().selectionChanged.connect(
            self.table_item_selected)
        table.setColumnWidth(0, 40)
        table.setColumnWidth(1, 120)
        table.horizontalHeader().setStretchLastSection(True)

        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.mainArea.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
        self.table_box.setSizePolicy(QSizePolicy.Fixed,
                                     QSizePolicy.MinimumExpanding)
        self.table_view.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.MinimumExpanding)
        self.table_box.layout().addWidget(self.table_view)
        self.hide_show_opt_results()

    def adjustSize(self):
        self.ensurePolished()
        s = self.sizeHint()
        self.resize(s)

    def hide_show_opt_results(self):
        [self.mainArea.hide, self.mainArea.show][self.optimize_k]()
        QTimer.singleShot(100, self.adjustSize)

    def sizeHint(self):
        s = self.controlArea.sizeHint()
        if self.optimize_k and not self.mainArea.isHidden():
            s.setWidth(s.width() + self.mainArea.sizeHint().width() +
                       4 * self.childrenRect().x())
        return s

    def update_k(self):
        self.optimize_k = False
        self.update()

    def update_from(self):
        self.k_to = max(self.k_from + 1, self.k_to)
        self.optimize_k = True
        self.update()

    def update_to(self):
        self.k_from = min(self.k_from, self.k_to - 1)
        self.optimize_k = True
        self.update()

    def set_optimization(self):
        self.updateOptimizationGui()
        self.update()

    def check_data_size(self, n, msg_group):
        msg_group.add_message(
            "not_enough_data",
            "Too few ({}) unique data instances for {} clusters")
        if n > len(self.data):
            msg_group.not_enough_data(len(self.data), n)
            return False
        else:
            msg_group.not_enough_data.clear()
            return True

    def run_optimization(self):
        # Disabling is needed since this function is not reentrant
        # Fast clicking on, say, "To: " causes multiple calls
        try:
            self.controlArea.setDisabled(True)
            self.optimization_runs = []
            if not self.check_data_size(self.k_from, self.Error):
                return
            self.check_data_size(self.k_to, self.Warning)
            k_to = min(self.k_to, len(self.data))
            kmeans = KMeans(
                init=['random', 'k-means++'][self.smart_init],
                n_init=self.n_init,
                max_iter=self.max_iterations,
                compute_silhouette_score=self.scoring == self.SILHOUETTE)
            with self.progressBar(k_to - self.k_from + 1) as progress:
                for k in range(self.k_from, k_to + 1):
                    progress.advance()
                    kmeans.params["n_clusters"] = k
                    self.optimization_runs.append((k, kmeans(self.data)))
        finally:
            self.controlArea.setDisabled(False)
        self.show_results()
        self.send_data()

    def cluster(self):
        if not self.check_data_size(self.k, self.Error):
            return
        self.km = KMeans(n_clusters=self.k,
                         init=['random', 'k-means++'][self.smart_init],
                         n_init=self.n_init,
                         max_iter=self.max_iterations)(self.data)
        self.send_data()

    def run(self):
        self.clear_messages()
        if not self.data:
            return
        if self.optimize_k:
            self.run_optimization()
        else:
            self.cluster()

    commit = run

    def show_results(self):
        minimize = self.SCORING_METHODS[self.scoring][2]
        k_scores = [(k, self.SCORING_METHODS[self.scoring][1](run))
                    for k, run in self.optimization_runs]
        scores = list(zip(*k_scores))[1]
        if minimize:
            best_score, worst_score = min(scores), max(scores)
        else:
            best_score, worst_score = max(scores), min(scores)

        best_run = scores.index(best_score)
        score_span = (best_score - worst_score) or 1
        max_score = max(scores)
        nplaces = min(5, np.floor(abs(math.log(max(max_score, 1e-10)))) + 2)
        fmt = "{{:.{}f}}".format(int(nplaces))
        model = self.table_model
        model.setRowCount(len(k_scores))
        for i, (k, score) in enumerate(k_scores):
            item = model.item(i, 0)
            if item is None:
                item = QStandardItem()
            item.setData(k, Qt.DisplayRole)
            item.setTextAlignment(Qt.AlignCenter)
            model.setItem(i, 0, item)
            item = model.item(i, 1)
            if item is None:
                item = QStandardItem()
            item.setData(
                fmt.format(score) if not np.isnan(score) else
                'out-of-memory error', Qt.DisplayRole)
            bar_ratio = 0.95 * (score - worst_score) / score_span
            item.setData(bar_ratio, gui.TableBarItem.BarRole)
            model.setItem(i, 1, item)
        self.table_view.resizeRowsToContents()

        self.table_view.selectRow(best_run)
        self.table_view.show()
        if minimize:
            self.table_box.setTitle("Scoring (smaller is better)")
        else:
            self.table_box.setTitle("Scoring (bigger is better)")
        QTimer.singleShot(0, self.adjustSize)

    def update(self):
        self.hide_show_opt_results()
        self.run()

    def selected_row(self):
        indices = self.table_view.selectedIndexes()
        rows = {ind.row() for ind in indices}
        if len(rows) == 1:
            return rows.pop()

    def table_item_selected(self):
        row = self.selected_row()
        if row is not None:
            self.send_data(row)

    def send_data(self, row=None):
        if self.optimize_k:
            if row is None:
                row = self.selected_row()
            km = self.optimization_runs[row][1]
        else:
            km = self.km
        if not self.data or not km:
            self.send("Annotated Data", None)
            self.send("Centroids", None)
            return

        clust_var = DiscreteVariable(
            self.output_name, values=["C%d" % (x + 1) for x in range(km.k)])
        clust_ids = km(self.data)
        domain = self.data.domain
        attributes, classes = domain.attributes, domain.class_vars
        meta_attrs = domain.metas
        if self.place_cluster_ids == self.OUTPUT_CLASS:
            if classes:
                meta_attrs += classes
            classes = [clust_var]
        elif self.place_cluster_ids == self.OUTPUT_ATTRIBUTE:
            attributes += (clust_var, )
        else:
            meta_attrs += (clust_var, )

        domain = Domain(attributes, classes, meta_attrs)
        new_table = Table.from_table(domain, self.data)
        new_table.get_column_view(clust_var)[0][:] = clust_ids.X.ravel()

        centroids = Table(Domain(km.pre_domain.attributes), km.centroids)

        self.send("Annotated Data", new_table)
        self.send("Centroids", centroids)

    @check_sql_input
    def set_data(self, data):
        self.data = data
        if data is None:
            self.table_model.setRowCount(0)
        else:
            self.data = data
            self.run()

    def send_report(self):
        k_clusters = self.k
        if self.optimize_k and self.optimization_runs and self.selected_row(
        ) is not None:
            k_clusters = self.optimization_runs[self.selected_row()][1].k
        self.report_items(
            (("Number of clusters",
              k_clusters), ("Optimization", self.optimize_k != 0
                            and "{}, {} re-runs limited to {} steps".format(
                                self.INIT_METHODS[self.smart_init].lower(),
                                self.n_init, self.max_iterations)),
             ("Cluster ID in output", self.append_cluster_ids
              and "'{}' (as {})".format(
                  self.output_name,
                  self.OUTPUT_METHODS[self.place_cluster_ids].lower()))))
        if self.data:
            self.report_data("Data", self.data)
            if self.optimize_k:
                self.report_table(
                    "Scoring by {}".format(
                        self.SCORING_METHODS[self.scoring][0]),
                    self.table_view)
Exemplo n.º 59
0
Arquivo: tree.py Projeto: vertrex/DFF
    def data(self, index, role):
        """
    \reimp

    Nodes' pointers are encapsulated in QStandardItem (role : Qt.UserRole + 1). Most
    of the data can only be retrieved only if the node is retrieved:

    * The node name
    * The node icon
    * ...

    To do so, the TreeModel.data() method calls the QStandardItemModel.data() method by passing
    the `index` parameter and `Qt.UserRole + 1` or `Qt.UserRole + 2` to it. In the second case, it
    retrieves a boolean used to know if the node is already expended and returns directly.

    \param index the index of the data we want to get
    \param role the role of the data we want to retrieve

    \return a QVariant containing the data, or an invalid QVariant if the data could not be retrieved.
    """
        if not index.isValid():
            return QVariant()
        # Qt.UserRole + 2 contain a boolean indicating if the node has already been expanded
        # in the tree.
        if role == Qt.UserRole + 3:
            return QStandardItemModel.data(self, index, role)
        if role == Qt.UserRole + 2:
            return QStandardItemModel.data(self, index, role)
        # call QStandardItemModel.data method with a Qt.UserRole + 1 to get the pointer on the node
        # (returns a invalid QVariant if the node or the data is None)
        data = QStandardItemModel.data(self, index, Qt.UserRole + 1)
        if not data.isValid():
            return data
        # getting the node or returning an invalid QVariant() if the node is not valid
        uid, valid = data.toULongLong()
        if not valid:
            return QVariant()
        node = self.VFS.getNodeById(uid)
        if node is None:
            return QVariant()
        # if role == UserRole + 1, it means that the node itself must be returned (the pointer
        # on the node, encapsulated in a QVariant()
        if role == (Qt.UserRole + 1):
            return data
        # in other cases, returns the requires data  : icon, color, etc. or an invalid QVariant()
        # if the role does not correpond to anything.
        if role == Qt.DisplayRole:
            display = QString.fromUtf8(node.name())
            if self.displayCount:
                display += QString("  (" + str(node.totalChildrenCount()) +
                                   ")")
            return QVariant(display)
        if role == Qt.DecorationRole:
            pixmap = QPixmap(node.icon())
            if node.hasChildren():
                try:
                    pfsobj = node.children()[0].fsobj(
                    ).this  #XXX fsobj have uid now
                except AttributeError:
                    pfsobj = None
                try:
                    nfsobj = node.fsobj().this
                except AttributeError:
                    nfsobj = None
                if pfsobj != nfsobj:
                    pixmap = pixmap.scaled(QSize(128, 128), Qt.KeepAspectRatio)
                    painter = QPainter(pixmap)
                    rootPixmap = QPixmap(":root")
                    painter.drawPixmap(0, 0, rootPixmap)
                    painter.end()
            return QVariant(QIcon(pixmap))
        if role == Qt.BackgroundRole:
            if index == self.currentIndex:
                palette = QPalette().color(QPalette.Highlight)
                return QVariant(QColor(palette))
        if role == Qt.ForegroundRole:
            if (index == self.currentIndex) and not node.isDeleted():
                palette = QPalette().color(QPalette.HighlightedText)
                return QVariant(QColor(palette))
            if node.isDeleted():
                return QVariant(QColor(Qt.red))
        if self.ch == True:
            if role == Qt.CheckStateRole:
                if index.column() == 0:
                    if node.uid() in self.selection.get():
                        return Qt.Checked
                    else:
                        return Qt.Unchecked

        return QVariant()
Exemplo n.º 60
0
 def __init__(self, header, editable=False, parent=None):
     self.header = header
     self.editable = editable
     QStandardItemModel.__init__(self, 0, len(self.header), parent)