Exemplo n.º 1
0
    def updateTable(self, args):
        cell_color, font_color = self.setTableColor(args[4])

        j = 0
        for data in args:
            item = QTableWidgetItem(data)
            self.table.setItem(self.i, j, item)
            item.setBackground(cell_color)
            item.setForeground(font_color)
            j += 1

        self.i += 1
Exemplo n.º 2
0
    def populate_function_table_1(self):
        """Populate the tblFunctions1 table with available functions."""
        hazards = deepcopy(hazard_all)
        exposures = exposure_all

        self.lblAvailableFunctions1.clear()
        self.tblFunctions1.clear()
        self.tblFunctions1.setColumnCount(len(hazards))
        self.tblFunctions1.setRowCount(len(exposures))
        for i in range(len(hazards)):
            hazard = hazards[i]
            item = QTableWidgetItem()
            item.setIcon(QIcon(get_image_path(hazard)))
            item.setText(hazard['name'].capitalize())
            item.setTextAlignment(Qt.AlignLeft)
            self.tblFunctions1.setHorizontalHeaderItem(i, item)
        for i in range(len(exposures)):
            exposure = exposures[i]
            item = QTableWidgetItem()
            item.setIcon(QIcon(get_image_path(exposure)))
            item.setText(exposure['name'].capitalize())
            self.tblFunctions1.setVerticalHeaderItem(i, item)
        developer_mode = setting('developer_mode', False, bool)
        for hazard in hazards:
            for exposure in exposures:
                item = QTableWidgetItem()
                if (exposure in hazard['disabled_exposures']
                        and not developer_mode):
                    background_colour = unavailable_option_color
                    # Set it disable and un-selectable
                    item.setFlags(item.flags() & ~Qt.ItemIsEnabled
                                  & ~Qt.ItemIsSelectable)
                else:
                    background_colour = available_option_color
                item.setBackground(QBrush(background_colour))
                item.setFont(big_font)
                item.setTextAlignment(Qt.AlignCenter | Qt.AlignHCenter)
                item.setData(RoleHazard, hazard)
                item.setData(RoleExposure, exposure)
                self.tblFunctions1.setItem(exposures.index(exposure),
                                           hazards.index(hazard), item)
        self.parent.pbnNext.setEnabled(False)
Exemplo n.º 3
0
    def create_widgets(self):
        # main/delete/supergroup
        self.set_as_main_button = QPushButton("Set As Main")
        self.create_super_group_button = QPushButton("Create Super Group")
        self.delete_groups_button = QPushButton("Delete Groups")
        self.revert_groups_button = QPushButton("Revert Groups")

        self.show_groups_button = QPushButton("Show Groups")
        self.hide_groups_button = QPushButton("Hide Groups")

        # closing
        self.apply_button = QPushButton("Apply")
        self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Cancel")

        #table
        self.table = QTableWidget()
        self.checks = []
        self.names_text = []

        bold = QtGui.QFont()
        bold.setBold(True)
        bold.setItalic(True)
        bold.setWeight(75)
        anames = array(self.names)
        for iname, name in enumerate(anames[self.inames]):
            check = QTableWidgetItem()
            check.setCheckState(False)

            # TODO: create right click menu ???
            name_text = QTableWidgetItem(str(name))
            if iname == self.imain:
                name_text.setFont(bold)
                self.shown_set.add(iname)
                check.setCheckState(2)
                name_text.setBackground(QtGui.QColor(*self.light_grey))
            elif iname in self.shown_set:
                name_text.setBackground(QtGui.QColor(*self.light_grey))

            self.checks.append(check)
            self.names_text.append(name_text)
Exemplo n.º 4
0
    def create_widgets(self):
        # main/delete/supergroup
        self.set_as_main_button = QPushButton("Set As Main")
        self.create_super_group_button = QPushButton("Create Super Group")
        self.delete_groups_button = QPushButton("Delete Groups")
        self.revert_groups_button = QPushButton("Revert Groups")

        self.show_groups_button = QPushButton("Show Groups")
        self.hide_groups_button = QPushButton("Hide Groups")

        # closing
        self.apply_button = QPushButton("Apply")
        self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Cancel")

        #table
        self.table = QTableWidget()
        self.checks = []
        self.names_text = []

        bold = QtGui.QFont()
        bold.setBold(True)
        bold.setItalic(True)
        bold.setWeight(75)
        anames = array(self.names)
        for iname, name in enumerate(anames[self.inames]):
            check = QTableWidgetItem()
            check.setCheckState(False)

            # TODO: create right click menu ???
            name_text = QTableWidgetItem(str(name))
            if iname == self.imain:
                name_text.setFont(bold)
                self.shown_set.add(iname)
                check.setCheckState(2)
                name_text.setBackground(QtGui.QColor(*self.light_grey))
            elif iname in self.shown_set:
                name_text.setBackground(QtGui.QColor(*self.light_grey))

            self.checks.append(check)
            self.names_text.append(name_text)
Exemplo n.º 5
0
    def load( self, filename ):
        if filename.isEmpty(): return

        self.spec = binary_truth_table()
        read_pla( self.spec, str( filename ), extend = False )

        self.clear()
        self.setColumnCount( self.spec.num_inputs + self.spec.num_outputs )
        self.setRowCount( sum( 1 for _ in self.spec.entries ) )
        self.setHorizontalHeaderLabels( self.spec.inputs + self.spec.outputs )

        for row, entry in enumerate( self.spec.entries ):
            for column, entry in enumerate( entry[0] + entry[1] ):
                item = QTableWidgetItem( "-" if entry is None else str( int( entry ) ) )
                item.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled )
                if column >= self.spec.num_inputs:
                    item.setBackground( Qt.gray )
                self.setItem( row, column, item )

        self.resizeColumnsToContents()
        self.specificationChanged.emit()
Exemplo n.º 6
0
    def load(self, filename):
        if filename.isEmpty(): return

        self.spec = binary_truth_table()
        read_pla(self.spec, str(filename), extend=False)

        self.clear()
        self.setColumnCount(self.spec.num_inputs + self.spec.num_outputs)
        self.setRowCount(sum(1 for _ in self.spec.entries))
        self.setHorizontalHeaderLabels(self.spec.inputs + self.spec.outputs)

        for row, entry in enumerate(self.spec.entries):
            for column, entry in enumerate(entry[0] + entry[1]):
                item = QTableWidgetItem(
                    "-" if entry is None else str(int(entry)))
                item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                if column >= self.spec.num_inputs:
                    item.setBackground(Qt.gray)
                self.setItem(row, column, item)

        self.resizeColumnsToContents()
        self.specificationChanged.emit()
Exemplo n.º 7
0
    def addPlayer(self, player):
        r = self.rowCount()
        self.setRowCount(r + 1)
        name = player.name
        color = player.color
        name = QTableWidgetItem(name)
        name.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        colorItem = QTableWidgetItem()
        colorItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        colorItem.setBackground(QColor(*color))

        cards = QTableWidgetItem()
        cards.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        cards.setTextAlignment(Qt.AlignCenter)
        cards.setData(Qt.DisplayRole, 0)

        troops = QTableWidgetItem()
        troops.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        troops.setTextAlignment(Qt.AlignCenter)
        troops.setData(Qt.DisplayRole, 0)

        territories = QTableWidgetItem()
        territories.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        territories.setTextAlignment(Qt.AlignCenter)
        territories.setData(Qt.DisplayRole, 0)

        troopsPerTurn = QTableWidgetItem()
        troopsPerTurn.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        troopsPerTurn.setTextAlignment(Qt.AlignCenter)
        troopsPerTurn.setData(Qt.DisplayRole, 0)

        self.setItem(r, self.Name, name)
        self.setItem(r, self.Color, colorItem)
        self.setItem(r, self.Cards, cards)
        self.setItem(r, self.NumberOfTroops, troops)
        self.setItem(r, self.NumberOfTerritories, territories)
        self.setItem(r, self.TroopsPerTurn, troopsPerTurn)
    def __init__(self, named_importances, *args, **kwargs):
        super(VariableImportanceDialog, self).__init__(*args, **kwargs)
        self.setWindowTitle("Variable Importance Table")
        self.setMinimumWidth(700)
        self.setMinimumHeight(800)

        layout = QGridLayout() 
        layout.setContentsMargins(10, 10, 10, 10)
               
        if named_importances:
            # Show variable importance table
            rows = len(named_importances.items())
            columns = 5
            table = QTableWidget(rows, columns)   
            table.setHorizontalHeaderLabels(['Variable Name', 'Class #0', 'Class #1', 'Overall', 'Gini'])
            table.verticalHeader().setVisible(False)      
            
            importances_mins = map(min, zip(*named_importances.values()))
            importances_maxs = map(max, zip(*named_importances.values()))
            
            for i, (variable, importances) in enumerate(named_importances.items()):     
                # Remove non-ASCII characters to get rid of the sigma character in the variable names.
                variable = re.sub(r'[^\x00-\x7F]+','s', variable)
                
                item = QTableWidgetItem(variable)
                item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
                table.setItem(i, 0, item)

                for j, importance in enumerate(importances):
                    # Get color based on the importance value
                    val = importances[j]
                    imin = importances_mins[j]
                    imax = importances_maxs[j]
                    range = importances_maxs[j] - importances_mins[j]
                    color = int( 255 - ( (val-imin) * 200) / range )    

                    # Load items as strings
                    item = QTableWidgetItemWithFloatSorting(str("{: .05f}".format(importance)))
                    item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
                    item.setBackground(QColor(color,255,color))
                    table.setItem(i, j+1, item)
                    
            table.resizeColumnsToContents()  
            
            table.setSortingEnabled(True)
            table.sortByColumn(3) # Sort by overall importance

            layout.addWidget(table, 1, 0, 3, 2)  
            
        else:
            # Classifier is not trained. Show warning message.
            msg = ('To enable this feature, you must choose the following classifier type via the menu Advanced > Classifier:\n\n'
                   '"Parallel Random Forest Classifier with Variable Importance (VIGRA)"\n\n'
                   '...and then RETRAIN your classifier (press "Live Update").')
            warningLabel = QLabel(msg)
            warningLabel.setAlignment(Qt.AlignCenter)
            warningLabel.setWordWrap(True) 
            layout.addWidget(warningLabel, 3, 0, 1 ,2)

        # Create and add close button
        closeButton = QPushButton("Close")
        closeButton.clicked.connect(self.close)
        layout.addWidget(closeButton, 4, 1)
        
        self.setLayout(layout)
    def populateLayerTable( self ):
        """
        Fill the table for a given layer type
        """
        # Get parameters for the widget
        lt = self.layersTable
        table = lt['tableWidget']

        attributes = lt['attributes']

        headerData = [ a['key'] for a in attributes ]

        # empty previous content
        for row in range(table.rowCount()):
            table.removeRow(row)
        table.setRowCount(0)

        # create columns and header row
        columns = [ a['key'] for a in attributes ]
        colCount = len( columns )
        table.setColumnCount( colCount )
        table.setHorizontalHeaderLabels( tuple( columns ) )

        # load content from project layers
        lr = QgsMapLayerRegistry.instance()
        for lid in lr.mapLayers():
            layer = lr.mapLayer( lid )

            lineData = []

            # Set row and column count
            twRowCount = table.rowCount()
            # add a new line
            table.setRowCount( twRowCount + 1 )
            table.setColumnCount( colCount )
            i=0

            if layer.customProperty('dynamicDatasourceActive') == 'True':
                bg = QColor(175, 208, 126)
            else:
                bg = Qt.transparent

            # get information
            for attr in attributes:
                newItem = QTableWidgetItem( )

                # Is editable or not
                if( attr['editable'] ):
                    newItem.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled )
                else:
                    newItem.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled  )

                # background
                newItem.setBackground( bg )

                # Item value
                value = self.getLayerProperty( layer, attr['key'] )
                newItem.setData( Qt.EditRole, value )

                # Add cell data to lineData
                # encode it in the file system encoding, only if needed
                if hasattr( value, 'encode' ):
                    value = value.encode( sys.getfilesystemencoding() )
                lineData.append( value )

                # Add item
                table.setItem(twRowCount, i, newItem)
                i+=1
Exemplo n.º 10
0
    def setSnapshotTable(self, data, table, eventid):
        if data:
            length = len(data.values()[0])
        else:
            print ('data is empty, exit.')
            return
        
        for i in range(1, len(data.values())):
            if length != len(data.values()[i]):
                QMessageBox.warning(self,
                                    "Warning",
                                    "Data length are not consistent.")

                return

        if isinstance(data, odict) and isinstance(table, QTableWidget):
            table.setSortingEnabled(False)
            table.clear()
        
            nrows = len(data.values()[0])
            #    ('pv name label',  'dbr_type label', 'string value', 'int value', 'double value', 'status label', 'severity label', 
            #     'ioc time stamp label', 'ioc time stamp nano label', 'is_array', 'array_value'),
            # => (pv_name, status, severity, ioc_timestamp, saved value)
            # ncols = len(data) - 6
            # ncols = ncols + 3  # 2 columns for live data and (live data - saved data), selected restore pv
            ncols = len(data) - 3
            table.setRowCount(nrows)
            table.setColumnCount(ncols)
            
            pvnames = data['PV Name']
            status = data['Status']
            severity = data['Severity']
            ts = data['Time stamp']
            ts_nano = data['Time stamp (nano)']
            dbrtype = data['DBR']
            s_value = data['S_value']
            i_value = data['I_value']
            d_value = data['D_value']
            isConnected = data['isConnected']
            is_array = data['isArray'] 
            array_value = data['arrayValue']
            
            keys = ['Name', 'Status', 'Severity', 'Time Stamp', 'Connection', 'Saved Value', 'Live Value', 'Delta', 'Not Restore']
            table.setHorizontalHeaderLabels(keys)
            
            for i in range(nrows):
                item = table.item(i, 8)
                if item:
                    item.setCheckState(False)
                else:
                    item = QTableWidgetItem()
                    item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable)
                    table.setItem(i, 8, item)
                    item.setCheckState(False)

                if pvnames[i]:
                    self.__setTableItem(table, i, 0, pvnames[i])
                if status[i]:
                    self.__setTableItem(table, i, 1, str(status[i]))
                if severity[i]:
                    self.__setTableItem(table, i, 2, str(severity[i]))
                if ts[i]:
                    dt = str(datetime.datetime.fromtimestamp(ts[i]+ts_nano[i]*1.0e-9))
                    self.__setTableItem(table, i, 3, dt)
                        
                if is_array[i]:
                    self.__setTableItem(table, i, 5, self.__arrayTextFormat(array_value[i]))
                    self.arrayData[pvnames[i]+'_'+str(eventid)] = array_value[i]
                else:
                    if dbrtype[i] in self.epicsDouble:
                        self.__setTableItem(table, i, 5, str(d_value[i]))
                    elif dbrtype[i] in self.epicsLong:
                        self.__setTableItem(table, i, 5, str(i_value[i]))
                    elif dbrtype[i] in self.epicsString:
                        self.__setTableItem(table, i, 5, str(s_value[i]))
                    elif dbrtype[i] in self.epicsNoAccess:
                        # channel are not connected.
                        pass
                    else:
                        print('invalid dbr type (code = %s)'%(dbrtype[i]))
                
                if isConnected[i]:
                    self.__setTableItem(table, i, 4, str(bool(isConnected[i])))
                    item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
                else:
                    self.__setTableItem(table, i, 4, 'False')
                    item.setCheckState(True)
                    item.setSelected(True)
                    # disable user checkable function
                    item.setFlags(item.flags() ^ Qt.ItemIsUserCheckable)
                    for item_idx in range(9):
                        itemtmp = table.item(i, item_idx)
                        if not itemtmp:
                            itemtmp = QTableWidgetItem()
                            table.setItem(i, item_idx, itemtmp)
                        itemtmp.setBackground(self.brushbadpv)

            table.setSortingEnabled(True)
        else:
            raise "Either given data is not an instance of OrderedDict or table is not an instance of QtGui.QTableWidget"
Exemplo n.º 11
0
    def __init__(self, named_importances, *args, **kwargs):
        super(VariableImportanceDialog, self).__init__(*args, **kwargs)
        self.setWindowTitle("Variable Importance Table")
        self.setMinimumWidth(700)
        self.setMinimumHeight(800)

        layout = QGridLayout()
        layout.setContentsMargins(10, 10, 10, 10)

        if named_importances:
            # Show variable importance table
            rows = len(named_importances.items())
            columns = 5
            table = QTableWidget(rows, columns)
            table.setHorizontalHeaderLabels(
                ['Variable Name', 'Class #0', 'Class #1', 'Overall', 'Gini'])
            table.verticalHeader().setVisible(False)

            importances_mins = map(min, zip(*named_importances.values()))
            importances_maxs = map(max, zip(*named_importances.values()))

            for i, (variable,
                    importances) in enumerate(named_importances.items()):
                # Remove non-ASCII characters to get rid of the sigma character in the variable names.
                variable = re.sub(r'[^\x00-\x7F]+', 's', variable)

                item = QTableWidgetItem(variable)
                item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                table.setItem(i, 0, item)

                for j, importance in enumerate(importances):
                    # Get color based on the importance value
                    val = importances[j]
                    imin = importances_mins[j]
                    imax = importances_maxs[j]
                    range = importances_maxs[j] - importances_mins[j]
                    color = int(255 - ((val - imin) * 200) / range)

                    # Load items as strings
                    item = QTableWidgetItemWithFloatSorting(
                        str("{: .05f}".format(importance)))
                    item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                    item.setBackground(QColor(color, 255, color))
                    table.setItem(i, j + 1, item)

            table.resizeColumnsToContents()

            table.setSortingEnabled(True)
            table.sortByColumn(3)  # Sort by overall importance

            layout.addWidget(table, 1, 0, 3, 2)

        else:
            # Classifier is not trained. Show warning message.
            msg = (
                'To enable this feature, you must choose the following classifier type via the menu Advanced > Classifier:\n\n'
                '"Parallel Random Forest Classifier with Variable Importance (VIGRA)"\n\n'
                '...and then RETRAIN your classifier (press "Live Update").')
            warningLabel = QLabel(msg)
            warningLabel.setAlignment(Qt.AlignCenter)
            warningLabel.setWordWrap(True)
            layout.addWidget(warningLabel, 3, 0, 1, 2)

        # Create and add close button
        closeButton = QPushButton("Close")
        closeButton.clicked.connect(self.close)
        layout.addWidget(closeButton, 4, 1)

        self.setLayout(layout)