コード例 #1
0
    def setList(self, data):
        self.colorCombo.clear()
        self.sizeCombo.clear()
        self.shapeCombo.clear()
        self.nameCombo.clear()
        for name in ["Same color", "strain"]:
            self.colorCombo.addItem(name)
        for name in ["No name", "name", "strain"]:
            self.nameCombo.addItem(name)

        self.colors = [[Qt.black] * 3 for i in range(len(data))]
        self.shapes = [[QwtSymbol.Ellipse] for i in range(len(data))]
        self.sizes = [[5] for i in range(len(data))]
        self.selectedInput = [False] * len(data)

        if type(data[0]) in [str, unicode]:
            self.names = [("", di, "", "") for di in data]
        else:
            self.names = [[""] * 4 for i in range(len(data))]
            try:
                strains = list(set([d.strain for d in data]))
                c = OWColorPalette.ColorPaletteHSV(len(strains))
                for i, d in enumerate(data):
                    self.colors[i][1] = c[strains.index(d.strain)]
                    self.names[i][1] = " " + d.name
                    self.names[i][2] = " " + d.strain
            except Exception, val:
                print val
コード例 #2
0
    def computePotentials(self):
        import orangeom
        #rx = self.transform(QwtPlot.xBottom, 1) - self.transform(QwtPlot.xBottom, 0)
        #ry = self.transform(QwtPlot.yLeft, 0) - self.transform(QwtPlot.yLeft, 1)

        rx = self.transform(QwtPlot.xBottom, 1) - self.transform(QwtPlot.xBottom, -1)
        ry = self.transform(QwtPlot.yLeft, -1) - self.transform(QwtPlot.yLeft, 1)
        ox = self.transform(QwtPlot.xBottom, 0) - self.transform(QwtPlot.xBottom, -1)
        oy = self.transform(QwtPlot.yLeft, -1) - self.transform(QwtPlot.yLeft, 0)

        rx -= rx % self.squareGranularity
        ry -= ry % self.squareGranularity

        if not getattr(self, "potentialsImage", None) \
           or getattr(self, "potentialContext", None) != (rx, ry, self.shownAttributes, self.trueScaleFactor, self.squareGranularity, self.jitterSize, self.jitterContinuous, self.spaceBetweenCells):
            if self.potentialsClassifier.classVar.varType == orange.VarTypes.Continuous:
                imagebmp = orangeom.potentialsBitmap(self.potentialsClassifier, rx, ry, ox, oy, self.squareGranularity, self.trueScaleFactor/2, self.spaceBetweenCells)
                palette = [qRgb(255.*i/255., 255.*i/255., 255-(255.*i/255.)) for i in range(255)] + [qRgb(255, 255, 255)]
            else:
                imagebmp, nShades = orangeom.potentialsBitmap(self.potentialsClassifier, rx, ry, ox, oy, self.squareGranularity, self.trueScaleFactor/2, self.spaceBetweenCells) # the last argument is self.trueScaleFactor (in LinProjGraph...)
                palette = []
                sortedClasses = getVariableValuesSorted(self.potentialsClassifier.domain.classVar)
                for cls in self.potentialsClassifier.classVar.values:
                    color = self.discPalette.getRGB(sortedClasses.index(cls))
                    towhite = [255-c for c in color]
                    for s in range(nShades):
                        si = 1-float(s)/nShades
                        palette.append(qRgb(*tuple([color[i]+towhite[i]*si for i in (0, 1, 2)])))
                palette.extend([qRgb(255, 255, 255) for i in range(256-len(palette))])

            self.potentialsImage = QImage(imagebmp, rx, ry, QImage.Format_Indexed8)
            self.potentialsImage.setColorTable(OWColorPalette.signedPalette(palette))
            self.potentialsImage.setNumColors(256)
            self.potentialContext = (rx, ry, self.shownAttributes, self.trueScaleFactor, self.squareGranularity, self.jitterSize, self.jitterContinuous, self.spaceBetweenCells)
コード例 #3
0
    def computePotentials(self):
        import orangeom
        #rx = self.transform(xBottom, 1) - self.transform(xBottom, 0)
        #ry = self.transform(yLeft, 0) - self.transform(yLeft, 1)

        rx = self.transform(xBottom, 1) - self.transform(xBottom, -1)
        ry = self.transform(yLeft, -1) - self.transform(yLeft, 1)
        ox = self.transform(xBottom, 0) - self.transform(xBottom, -1)
        oy = self.transform(yLeft, -1) - self.transform(yLeft, 0)

        rx -= rx % self.squareGranularity
        ry -= ry % self.squareGranularity

        if not getattr(self, "potentialsImage", None) \
           or getattr(self, "potentialContext", None) != (rx, ry, self.shownAttributes, self.trueScaleFactor, self.squareGranularity, self.jitterSize, self.jitterContinuous, self.spaceBetweenCells):
            if self.potentialsClassifier.classVar.varType == orange.VarTypes.Continuous:
                imagebmp = orangeom.potentialsBitmap(self.potentialsClassifier, rx, ry, ox, oy, self.squareGranularity, self.trueScaleFactor/2, self.spaceBetweenCells)
                palette = [qRgb(255.*i/255., 255.*i/255., 255-(255.*i/255.)) for i in range(255)] + [qRgb(255, 255, 255)]
            else:
                imagebmp, nShades = orangeom.potentialsBitmap(self.potentialsClassifier, rx, ry, ox, oy, self.squareGranularity, self.trueScaleFactor/2, self.spaceBetweenCells) # the last argument is self.trueScaleFactor (in LinProjGraph...)
                palette = []
                sortedClasses = getVariableValuesSorted(self.potentialsClassifier.domain.classVar)
                for cls in self.potentialsClassifier.classVar.values:
                    color = self.discPalette.getRGB(sortedClasses.index(cls))
                    towhite = [255-c for c in color]
                    for s in range(nShades):
                        si = 1-float(s)/nShades
                        palette.append(qRgb(*tuple([color[i]+towhite[i]*si for i in (0, 1, 2)])))
                palette.extend([qRgb(255, 255, 255) for i in range(256-len(palette))])

            self.potentialsImage = QImage(imagebmp, rx, ry, QImage.Format_Indexed8)
            self.potentialsImage.setColorTable(OWColorPalette.signedPalette(palette) if qVersion() < "4.5" else palette)
            self.potentialsImage.setNumColors(256)
            self.potentialContext = (rx, ry, self.shownAttributes, self.trueScaleFactor, self.squareGranularity, self.jitterSize, self.jitterContinuous, self.spaceBetweenCells)
            self.potentialsImageFromClassifier = self.potentialsClassifier
コード例 #4
0
    def paint(self, painter, option, index):
        dist = index.data(Qt.DisplayRole)  #.toPyObject()
        rect = option.rect
        rect_w = rect.width() - len([c for c in dist if c]) - 2
        rect_h = rect.height() - 2
        colors = OWColorPalette.ColorPaletteHSV(len(dist))
        abs = dist.abs
        dist_sum = 0

        painter.save()
        qApp.style().drawPrimitive(QStyle.PE_PanelItemViewRow, option, painter)

        showText = getattr(self, "showDistText", True)
        metrics = QFontMetrics(option.font)
        drect_h = metrics.height()
        lineSpacing = metrics.lineSpacing()
        distText = self.displayText(index.data(Qt.DisplayRole), QLocale())
        if showText:
            textPos = QPoint(rect.topLeft().x(),
                             rect.center().y() - lineSpacing)
            painter.drawText(QRect(textPos, QSize(rect.width(), lineSpacing)),
                             Qt.AlignCenter, distText)

        painter.translate(
            QPoint(rect.topLeft().x(),
                   rect.center().y() - (drect_h / 2 if not showText else -2)))
        for i, count in enumerate(dist):
            if count:
                color = colors[i]
                painter.setBrush(color)
                width = round(rect_w * float(count) / abs)
                painter.drawRect(QRect(1, 1, width, drect_h))
                painter.translate(width, 0)

        painter.restore()
コード例 #5
0
 def createColorDialog(self):
     c = OWColorPalette.ColorPaletteDlg(self, "Color Palette")
     c.createDiscretePalette("discPalette", "Discrete Palette")
     box = c.createBox("otherColors", "Other Colors")
     c.createColorButton(box, "Default", "Default color", QColor(Qt.white))
     c.setColorSchemas(self.colorSettings, self.selectedSchemaIndex)
     return c
コード例 #6
0
    def addSelection(self, obj):
        vertList = []
        ptr = obj
        while ptr:  #construct upper part of the polygon
            rect = ptr.rect()
            ptr = ptr.left
            vertList.append(
                QPointF(rect.left() - polyOffset,
                        rect.top() - polyOffset))
            if ptr:
                vertList.append(
                    QPointF(ptr.rect().left() - polyOffset,
                            rect.top() - polyOffset))
            else:
                vertList.append(
                    QPointF(rect.right() + 3,
                            rect.top() - polyOffset))

        tmpList = []
        ptr = obj
        while ptr:  #construct lower part of the polygon
            rect = ptr.rect()
            ptr = ptr.right
            tmpList.append(
                QPointF(rect.left() - polyOffset,
                        rect.bottom() + polyOffset))
            if ptr:
                tmpList.append(
                    QPointF(ptr.rect().left() - polyOffset,
                            rect.bottom() + polyOffset))
            else:
                tmpList.append(
                    QPointF(rect.right() + 3,
                            rect.bottom() + polyOffset))
        tmpList.reverse()
        vertList.extend(tmpList)
        new = SelectionPoly(QPolygonF(vertList))
        self.addItem(new)
        new.rootCluster = obj.cluster
        new.rootGraphics = obj
        self.selectionList.append(new)
        c = float(self.parent.Brightness) / 10
        colorPalette = OWColorPalette.ColorPaletteHSV(len(self.selectionList))
        #color=[(a.red()+(255-a.red())*c, a.green()+(255-a.green())*c,
        #                 a.blue()+(255-a.blue())*c) for a in colorPalette]
        #colorPalette=[QColor(a[0],a[1],a[2]) for a in color]
        colorPalette = [
            colorPalette.getColor(i, 150)
            for i in range(len(self.selectionList))
        ]
        for el, col in zip(self.selectionList, colorPalette):
            brush = QBrush(col, Qt.SolidPattern)
            el.setBrush(brush)
        new.setZValue(self.gZPos - 2)
        #new.setZValue(2)
        ##
        new.show()
        #self.parent.updateSelection(self.selectionList)
        self.update()
コード例 #7
0
 def __init__(self, var, parent=None, **kwargs):
     PyListModel.__init__(self, [], parent, **kwargs)
     self.wrap(var.values)
     self.colorPalette = OWColorPalette.ColorPaletteHSV(len(self))
     self.connect(self, SIGNAL("columnsInserted(QModelIndex, int, int)"),
                  self.updateColors)
     self.connect(self, SIGNAL("columnsRemoved(QModelIndex, int, int)"),
                  self.updateColors)
コード例 #8
0
 def createColorDialog(self):
     c = OWColorPalette.ColorPaletteDlg(self, "Color palette")
     c.createDiscretePalette("discPalette", "Discrete Palette")
     c.createContinuousPalette("contPalette", "Continuous Palette")
     box = c.createBox("otherColors", "Other Colors")
     c.createColorButton(box, "Canvas", "Canvas color",
                         self.graph.color(OWPalette.Canvas))
     c.setColorSchemas(self.colorSettings, self.selectedSchemaIndex)
     return c
コード例 #9
0
ファイル: OWCN2RulesViewer.py プロジェクト: yisuax11/orange2
    def paint(self, painter, option, index):
        dist = index.data(Qt.DisplayRole).toPyObject()
        rect = option.rect.adjusted(4, 4, -4, -4)
        rect_w = rect.width() - len([
            c for c in dist if c
        ])  # This is for the separators in the distribution bar
        rect_h = rect.height()
        colors = OWColorPalette.ColorPaletteHSV(len(dist))
        abs = dist.abs
        dist_sum = 0

        painter.save()
        painter.setFont(option.font)

        qApp.style().drawPrimitive(QStyle.PE_PanelItemViewRow, option, painter)
        qApp.style().drawPrimitive(QStyle.PE_PanelItemViewItem, option,
                                   painter)

        showText = getattr(self, "showDistText", True)
        metrics = QFontMetrics(option.font)
        drect_h = metrics.height()
        lineSpacing = metrics.lineSpacing()
        leading = metrics.leading()
        distText = self.displayText(index.data(Qt.DisplayRole), QLocale())

        if option.state & QStyle.State_Selected:
            color = option.palette.highlightedText().color()
        else:
            color = option.palette.text().color()


#        painter.setBrush(QBrush(color))
        painter.setPen(QPen(color))

        if showText:
            textPos = rect.topLeft()
            textRect = QRect(textPos,
                             QSize(rect.width(),
                                   rect.height() / 2 - leading))
            painter.drawText(textRect, Qt.AlignHCenter | Qt.AlignBottom,
                             distText)

        painter.setPen(QPen(Qt.black))
        painter.translate(
            QPoint(rect.topLeft().x(),
                   rect.center().y() - (drect_h / 2 if not showText else 0)))
        for i, count in enumerate(dist):
            if count:
                color = colors[i]
                painter.setBrush(color)
                painter.setRenderHint(QPainter.Antialiasing)
                width = round(rect_w * float(count) / abs)
                painter.drawRoundedRect(QRect(1, 3, width, 5), 1, 2)
                painter.translate(width, 0)
        painter.restore()
コード例 #10
0
    def updateGraph(self):
        if self.data is None:
            return

        xInd, yInd, zInd = self.getAxesIndices()
        X, Y, Z, mask = self.getAxisData(xInd, yInd, zInd)

        if self.colorAttr > 0:
            colorAttr = self.axisCandidateAttrs[self.colorAttr - 1]
            C = self.dataArray[:, self.colorAttr - 1]

            if colorAttr.varType == orange.VarTypes.Discrete:
                palette = OWColorPalette.ColorPaletteHSV(len(colorAttr.values))
                colors = [palette[int(value)] for value in C.ravel()]
                colors = [[c.red() / 255.,
                           c.green() / 255.,
                           c.blue() / 255.] for c in colors]
            else:
                palette = OWColorPalette.ColorPaletteBW()
                maxC, minC = numpy.max(C), numpy.min(C)
                C = (C - minC) / (maxC - minC)
                colors = [palette[value] for value in C.ravel()]
                colors = [[c.red() / 255.,
                           c.green() / 255.,
                           c.blue() / 255.] for c in colors]
        else:
            colors = "b"

        if self.sizeAttr > 0:
            sizeAttr = self.axisCandidateAttrs[self.sizeAttr - 1]
            S = self.dataArray[:, self.sizeAttr - 1]
            if sizeAttr.varType == orange.VarTypes.Discrete:
                sizes = [(v + 1) * len(sizeAttr.values) / (11 - self.pointSize)
                         for v in S]
            else:
                min, max = numpy.min(S), numpy.max(S)
                sizes = [(v - min) * self.pointSize / (max - min) for v in S]
        else:
            sizes = 1

        self.graph.clear()
        self.graph.scatter(X, Y, Z, colors, sizes)
コード例 #11
0
 def createColorDialog(self):
     c = OWColorPalette.ColorPaletteDlg(self, "Color Palette")
     c.createDiscretePalette("discPalette", "Discrete Palette")
     c.createContinuousPalette("contPalette", "Continuous Palette")
     box = c.createBox("otherColors", "Other Colors")
     c.createColorButton(box, "Canvas", "Canvas color", Qt.white)
     box.layout().addSpacing(5)
     c.createColorButton(box, "Grid", "Grid color", QColor(215,215,215))
     box.layout().addSpacing(5)
     c.setColorSchemas(self.colorSettings, self.selectedSchemaIndex)
     return c
コード例 #12
0
 def createColorDialog(self):
     c = OWColorPalette.ColorPaletteDlg(self, "Color palette")
     c.createDiscretePalette("discPalette", "Discrete palette")
     c.createContinuousPalette("contPalette", "Continuous palette")
     box = c.createBox("otherColors", "Other colors")
     c.createColorButton(box, "Canvas", "Canvas color", QColor(Qt.white))
     #        box.addSpace(5)
     c.createColorButton(box, "Grid", "Grid color", QColor(Qt.black))
     #        box.addSpace(5)
     box.adjustSize()
     c.setColorSchemas(self.colorSettings)
     return c
コード例 #13
0
ファイル: OWCN2RulesViewer.py プロジェクト: stefie10/slu_hri
 def fixGeom(self, width):
     distText = self.distText.strip("<>")
     dist = [float(f) for f in distText.split(",")]
     distSum = sum(dist)
     classColor = OWColorPalette.ColorPaletteHSV(len(dist))
     m = max(dist)
     for i in range(len(dist)):
         r = QGraphicsRectItem(None, self.canvas)
         r.setRect(self.x(), self.y(), dist[i] / distSum * width, barHeight)
         r.setPen(QPen(QColor(classColor[i]), 2))
         if dist[i] == m:
             r.setBrush(QBrush(classColor[i]))
         self.rect.append(r)
コード例 #14
0
ファイル: OWSOMVisualizer.py プロジェクト: stefie10/slu_hri
    def updateHistogramColors(self):
        if self.parent().drawPies():
            return
        attr = self.somMap.examples.domain.variables[self.parent().attribute]
        for n in self.canvasObj:
            if n.hasNode:
                if attr.varType == orange.VarTypes.Discrete:
                    if self.parent().inputSet:
                        dist = orange.Distribution(attr, n.node.mappedExamples)
                    else:
                        dist = orange.Distribution(attr, n.node.examples)
                    colors = OWColorPalette.ColorPaletteHSV(len(dist))
                    maxProb = max(dist)
                    majValInd = filter(lambda i: dist[i] == maxProb,
                                       range(len(dist)))[0]
                    if self.parent().discHistMode == 1:
                        n.histObj[0].setBrush(QBrush(colors[majValInd]))
                    elif self.parent().discHistMode == 2:
                        light = 180 - 80 * float(dist[majValInd]) / max(
                            sum(dist), 1)
                        n.histObj[0].setBrush(
                            QBrush(colors[majValInd].light(light)))
                else:
                    if self.parent().inputSet:
                        dist = orange.Distribution(attr, n.node.mappedExamples)
                        fullDist = orange.Distribution(attr,
                                                       self.parent().examples)
                    else:
                        dist = orange.Distribution(attr, n.node.examples)
                        fullDist = orange.Distribution(attr,
                                                       self.somMap.examples)
                    if len(dist) == 0:
                        continue

                    if self.parent().contHistMode == 0:
                        n.histObj[0].setBrush(QBrush(DefColor))
                    if self.parent().contHistMode == 1:
                        std = (dist.average() - fullDist.average()) / max(
                            fullDist.dev(), 1)
                        std = min(max(std, -1), 1)
                        #print std
                        n.histObj[0].setBrush(
                            QBrush(
                                QColor(70 * (std + 1) + 50,
                                       70 * (std + 1) + 50, 0)))
                    if self.parent().contHistMode == 2:
                        light = 300 - 200 * dist.var() / fullDist.var()
                        n.histObj[0].setBrush(
                            QBrush(QColor(0, 0, 20).light(light)))
コード例 #15
0
ファイル: OWSOMVisualizer.py プロジェクト: stefie10/slu_hri
 def setPie(self, attrIndex, size):
     for e in self.histObj:
         self.scene().removeItem(e)
     self.histObj = []
     if len(self.node.examples) < 0:
         return
     dist = orange.Distribution(attrIndex, self.node.examples)
     colors = OWColorPalette.ColorPaletteHSV(len(dist))
     distSum = max(sum(dist), 1)
     startAngle = 0
     for i in range(len(dist)):
         angle = 360 / distSum * dist[i] * 16
         c = QGraphicsEllipseItem(-size / 2, -size / 2, size, size, self,
                                  self.scene())
         c.setStartAngle(startAngle)
         c.setSpanAngle(angle)
         c.setBrush(QBrush(colors[i]))
         c.show()
         startAngle += angle
         self.histObj.append(c)
コード例 #16
0
 def setVarList(self, data):
     self.colorCombo.clear()
     self.sizeCombo.clear()
     self.shapeCombo.clear()
     self.nameCombo.clear()
     for name in ["Same color", "Variable"]:
         self.colorCombo.addItem(name)
     for name in ["No name", "Var name"]:
         self.nameCombo.addItem(name)
     self.colors = [[Qt.black] * 3 for i in range(len(data))]
     self.shapes = [[QwtSymbol.Ellipse] for i in range(len(data))]
     self.sizes = [[5] for i in range(len(data))]
     self.names = [[""] * 4 for i in range(len(data))]
     self.selectedInput = [False] * len(data)
     try:
         c = OWColorPalette.ColorPaletteHSV(len(data))
         for i, d in enumerate(data):
             self.colors[i][1] = c[i]
             self.names[i][1] = " " + str(d.name)
     except Exception, val:
         print val
コード例 #17
0
ファイル: OWSOMVisualizer.py プロジェクト: stefie10/slu_hri
    def buildToolTip(self):
        if self.node and self.scene().showToolTip:
            node = self.node
            text = "Items: %i" % len(self.node.examples)
            if self.scene().includeCodebook:
                text += "<hr><b>Codebook vector:</b><br>" + "<br>".join(\
                    [a.variable.name + ": " + str(a) for a in node.referenceExample \
                     if a.variable != node.referenceExample.domain.classVar])

            if node.examples.domain.classVar and len(node.examples):
                dist = orange.Distribution(node.examples.domain.classVar,
                                           node.examples)
                if node.examples.domain.classVar.varType == orange.VarTypes.Continuous:
                    text += "<hr>Avg " + node.examples.domain.classVar.name + ":" + (
                        "%.3f" % dist.average())
                else:
                    colors = OWColorPalette.ColorPaletteHSV(
                        len(node.examples.domain.classVar.values))
                    text += "<hr>" + "<br>".join(["<span style=\"color:%s\">%s</span>" %(colors[i].name(), str(value) + ": " + str(dist[i])) \
                                                 for i, value in enumerate(node.examples.domain.classVar.values)])
            self.setToolTip(text)
        else:
            self.setToolTip("")
コード例 #18
0
    def createColorDialog(self):
        c = OWColorPalette.ColorPaletteDlg(self, "Color Palette")
        c.createExtendedContinuousPalette("palette",
                                          "Continuous Palette",
                                          initialColor1=QColor(Qt.blue),
                                          initialColor2=QColor(255, 255,
                                                               0).rgb())
        box = c.createBox("otherColors", "Other Colors")

        c.createColorButton(box, "unknown", "Unknown", Qt.gray)
        box.layout().addSpacing(5)
        c.createColorButton(box, "overflow", "Overflow", Qt.black)
        box.layout().addSpacing(5)
        c.createColorButton(box, "underflow", "Underflow", Qt.white)

        box = c.createBox("cellColors", "Cell colors")
        c.createColorButton(box, "background", "Background", Qt.white)
        box.layout().addSpacing(5)
        c.createColorButton(box, "cellOutline", "Cell outline", Qt.gray)
        box.layout().addSpacing(5)
        c.createColorButton(box, "selection", "Selection", Qt.black)

        c.setColorSchemas(self.colorSettings, self.selectedSchemaIndex)
        return c
コード例 #19
0
 def createColorDialog(self):
     c = OWColorPalette.ColorPaletteDlg(self, "Color Palette")
     c.createDiscretePalette("discPalette", "Discrete Palette", OWColorPalette.defaultRGBColors) #defaultColorBrewerPalette)
     c.setColorSchemas(self.colorSettings, self.selectedSchemaIndex)
     return c
コード例 #20
0
    def setExampleTable(self, data):
        self.colorCombo.clear()
        self.sizeCombo.clear()
        self.shapeCombo.clear()
        self.nameCombo.clear()
        attributes=[attr for attr in data.domain.variables+list(data.domain.getmetas().values()) or [] ]
        discAttributes=[a for a in attributes if a.varType==orange.VarTypes.Discrete]
        contAttributes=[a for a in attributes if a.varType==orange.VarTypes.Continuous]
        attrName=[attr.name for attr in attributes]
        for name in ["Same color"]+attrName:
            self.colorCombo.addItem(name)
        for name in ["Same size"]+[a.name for a in contAttributes]:
            self.sizeCombo.addItem(name)
        for name in ["Same shape"]+[a.name for a in discAttributes]:
            self.shapeCombo.addItem(name)
        for name in ["No name"]+attrName:
            self.nameCombo.addItem(name)

#        if data.domain.classVar:
#            if data.domain.classVar.varType == orange.VarTypes.Discrete:
#                self.graph.ColorAttr = len(data.domain.variables) # index 0 is Same color!
#            elif data.domain.classVar.varType == orange.VarTypes.Continuous:
#                self.graph.SizeAttr = len(data.domain.variables) # index 0 is Same color!
        try:
            self.graph.NameAttr = 1 + [name.lower() for name in attrName].index("name")
        except:
            pass
        
        self.attributes=attributes
        self.discAttributes=discAttributes
        self.contAttributes=contAttributes

        self.colors=[[Qt.black]*(len(attributes)+1) for i in range(len(data))]
        self.shapes=[[QwtSymbol.Ellipse]*(len(discAttributes)+1) for i in range(len(data))]
        self.sizes=[[5]*(len(contAttributes)+1) for i in range(len(data))]
        self.names=[[""]*(len(attributes)+1) for i in range(len(data))]
        try:
            selectedInput=self.selectedInputExamples.select(data.domain)
        except:
            selectedInput=[]
        self.selectedInput=[selectedInput and (d in selectedInput) or not selectedInput for d in data]
        contI=discI=attrI=1
        def check(ex, a):
            try:
                ex[a]
            except:
                return False
            return not ex[a].isSpecial()
        
        for j, attr in enumerate(attributes):
            if attr.varType==orange.VarTypes.Discrete:
                c=OWColorPalette.ColorPaletteHSV(len(attr.values))
                for i in range(len(data)):
                    self.colors[i][attrI]= check(data[i],attr)  and c[int(data[i][attr])] or Qt.black
##                    self.shapes[i][discI]= data[i][attr].isSpecial() and self.graph.shapeList[0] or self.graph.shapeList[int(data[i][attr])%len(self.graph.shapeList)]
                    self.shapes[i][discI]= check(data[i],attr) and self.graph.shapeList[int(data[i][attr])%len(self.graph.shapeList)] or self.graph.shapeList[0]
                    self.names[i][attrI]= check(data[i],attr) and " "+str(data[i][attr]) or ""
                    #self.sizes[i][contI]=5
                attrI+=1
                discI+=1
            elif attr.varType==orange.VarTypes.Continuous:
                c=OWColorPalette.ColorPaletteBW(-1)
                #val=[e[attr] for e in data if not e[attr].isSpecial()]
                val=[e[attr] for e in data if check(e, attr)]
                minVal=min(val or [0])
                maxVal=max(val or [1])
                for i in range(len(data)):
                    self.colors[i][attrI]=check(data[i],attr) and c.getColor((data[i][attr]-minVal)/max(maxVal-minVal, 1e-6)) or Qt.black 
                    #self.shapes[i][discI]=self.graph.shapeList[0]
                    self.names[i][attrI]=check(data[i],attr) and " "+str(data[i][attr]) or ""
                    self.sizes[i][contI]=check(data[i],attr) and int(self.data[i][attr]/maxVal*9)+1 or 5
                contI+=1
                attrI+=1
            else:
                for i in range(len(data)):
                    self.colors[i][attrI]=Qt.black
                    #self.shapes[i][j+1]=self.graph.shapeList[0]
                    self.names[i][attrI]= check(data[i],attr) and " "+str(data[i][attr]) or ""
                    #self.sizes[i][j+1]=5
                attrI+=1
        if data and data.domain.classVar:
            if data.domain.classVar.varType == orange.VarTypes.Discrete:
                self.graph.ColorAttr = len(self.colors[0]) - 1 # index 0 is Same color!
            elif data.domain.classVar.varType == orange.VarTypes.Continuous:
                self.graph.SizeAttr = len(self.sizes[0]) - 1 # index 0 is Same color!
コード例 #21
0
    def clear(self):
        self.commands = []


if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = OWGraph3D()
    w.show()

    from random import random
    rand = lambda: random() - 0.5
    N = 100
    data = orange.ExampleTable("../doc/datasets/iris.tab")
    array, c, _ = data.toNumpyMA()
    import OWColorPalette
    palette = OWColorPalette.ColorPaletteHSV(len(data.domain.classVar.values))
    x = array[:, 0]
    y = array[:, 1]
    z = array[:, 2]
    colors = [palette[int(ex.getclass())] for ex in data]
    colors = [[c.red() / 255.,
               c.green() / 255.,
               c.blue() / 255.] for c in colors]

    #    x = [rand()*2 for i in range(N)]
    #    y = [rand()*2 for i in range(N)]
    #    z = [-3 + rand() for i in range(N)]
    #    colors = "b"
    w.scatter3d(x, y, z, c=colors)
    app.exec_()
コード例 #22
0
 def createColorDialog(self):
     dlg = OWColorPalette.ColorPaletteDlg(self, "Color Palette")
     dlg.createDiscretePalette("discPalette", "Discrete Palette")
     dlg.setColorSchemas(self.colorSettings, self.selectedSchemaIndex)
     return dlg
コード例 #23
0
    def setExampleTable(self, data):
        self.colorCombo.clear()
        self.sizeCombo.clear()
        self.shapeCombo.clear()
        self.nameCombo.clear()
        attributes = list(data.domain.variables) + \
                     data.domain.getmetas().values()
        discAttributes = filter(
            lambda a: a.varType == orange.VarTypes.Discrete, attributes)
        contAttributes = filter(
            lambda a: a.varType == orange.VarTypes.Continuous, attributes)
        attrName = [attr.name for attr in attributes]
        for name in ["Same color"] + attrName:
            self.colorCombo.addItem(name)
        for name in ["Same size"] + map(lambda a: a.name, contAttributes):
            self.sizeCombo.addItem(name)
        for name in ["Same shape"] + map(lambda a: a.name, discAttributes):
            self.shapeCombo.addItem(name)
        for name in ["No name"] + attrName:
            self.nameCombo.addItem(name)

        try:
            self.graph.NameAttr = \
                1 + [name.lower() for name in attrName].index("name")
        except:
            pass

        self.attributes = attributes
        self.discAttributes = discAttributes
        self.contAttributes = contAttributes

        self.colors = [[Qt.black] * (len(attributes) + 1)
                       for i in range(len(data))]
        self.shapes = [[QwtSymbol.Ellipse] * (len(discAttributes) + 1)
                       for i in range(len(data))]
        self.sizes = [[5] * (len(contAttributes) + 1)
                      for i in range(len(data))]
        self.names = [[""] * (len(attributes) + 1) for i in range(len(data))]
        try:
            selectedInput = self.selectedInputExamples.select(data.domain)
        except:
            selectedInput = []
        self.selectedInput = map(
            lambda d: selectedInput and
            (d in selectedInput) or not selectedInput, data)

        contI = discI = attrI = 1

        def check(ex, a):
            try:
                ex[a]
            except Exception:
                return False
            return not ex[a].isSpecial()

        for j, attr in enumerate(attributes):
            if attr.varType == orange.VarTypes.Discrete:
                c = OWColorPalette.ColorPaletteHSV(len(attr.values))
                for i in range(len(data)):
                    if check(data[i], attr):
                        self.colors[i][attrI] = c[int(data[i][attr])]
                        self.shapes[i][discI] = self.graph.shapeList[int(
                            data[i][attr]) % len(self.graph.shapeList)]
                        self.names[i][attrI] = " " + str(data[i][attr])
                    else:
                        self.colors[i][attrI] = Qt.black
                        self.shapes[i][discI] = self.graph.shapeList[0]
                        self.names[i][attrI] = ""
                attrI += 1
                discI += 1
            elif attr.varType == orange.VarTypes.Continuous:
                c = OWColorPalette.ColorPaletteBW(-1)

                val = [e[attr] for e in data if check(e, attr)]
                minVal = min(val or [0])
                maxVal = max(val or [1])
                span = max(maxVal - minVal, 1e-6)
                for i in range(len(data)):
                    if check(data[i], attr):
                        self.colors[i][attrI] = c.getColor(
                            (data[i][attr] - minVal) / span)
                        self.names[i][attrI] = " " + str(data[i][attr])
                        self.sizes[i][contI] = int(
                            self.data[i][attr] / maxVal * 9) + 1
                    else:
                        self.colors[i][attrI] = Qt.black
                        self.names[i][attrI] = ""
                        self.sizes[i][contI] = 5
                contI += 1
                attrI += 1
            else:
                for i in range(len(data)):
                    self.colors[i][attrI] = Qt.black
                    if check(data[i], attr):
                        self.names[i][attrI] = " " + str(data[i][attr])
                    else:
                        self.names[i][attrI] = ""

                attrI += 1

        if data and data.domain.classVar:
            if data.domain.classVar.varType == orange.VarTypes.Discrete:
                self.graph.ColorAttr = len(
                    self.colors[0]) - 1  # index 0 is Same color!
            elif data.domain.classVar.varType == orange.VarTypes.Continuous:
                self.graph.SizeAttr = len(
                    self.sizes[0]) - 1  # index 0 is Same color!
コード例 #24
0
 def updateColors(self, index, start, end):
     self.colorPalette = OWColorPalette.ColorPaletteHSV(len(self))
     self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"),
               self.index(0), self.index(len(self) - 1))
コード例 #25
0
    def __init__(self, parent=None, signalManager=None):
        #        self.callbackDeposit = [] # deposit for OWGUI callback function
        OWWidget.__init__(self,
                          parent,
                          signalManager,
                          'Distance Map',
                          wantGraph=True)

        self.inputs = [("Distance Matrix", orange.SymMatrix, self.setMatrix)]
        self.outputs = [("Examples", ExampleTable),
                        ("Attribute List", orange.VarList)]

        self.clicked = False
        self.offsetX = 5
        self.offsetY = 5
        self.imageWidth = 0
        self.imageHeight = 0
        self.distanceImage = None
        self.legendImage = None
        self.colorSettings = None
        self.selectedSchemaIndex = 0

        self.palette = None

        self.shiftPressed = False

        #set default settings
        self.CellWidth = 15
        self.CellHeight = 15
        self.Merge = 1
        self.savedMerge = self.Merge
        self.Gamma = 1
        self.Grid = 1
        self.savedGrid = 1
        self.CutLow = 0
        self.CutHigh = 0
        self.CutEnabled = 0
        self.Sort = 0
        self.SquareCells = 0
        self.ShowLegend = 1
        self.ShowLabels = 1
        self.ShowBalloon = 1
        self.ShowItemsInBalloon = 1
        self.SendOnRelease = 1

        self.loadSettings()

        self.maxHSize = 30
        self.maxVSize = 30
        self.sorting = [("No sorting", self.sortNone),
                        ("Adjacent distance", self.sortAdjDist),
                        ("Random order", self.sortRandom),
                        ("Clustering", self.sortClustering),
                        ("Clustering with ordered leafs",
                         self.sortClusteringOrdered)]

        self.matrix = self.order = None
        self.rootCluster = None

        # GUI definition
        self.tabs = OWGUI.tabWidget(self.controlArea)

        # SETTINGS TAB
        tab = OWGUI.createTabPage(self.tabs, "Settings")
        box = OWGUI.widgetBox(tab, "Cell Size (Pixels)")
        OWGUI.qwtHSlider(box,
                         self,
                         "CellWidth",
                         label='Width: ',
                         labelWidth=38,
                         minValue=1,
                         maxValue=self.maxHSize,
                         step=1,
                         precision=0,
                         callback=[
                             lambda f="CellWidth", t="CellHeight": self.
                             adjustCellSize(f, t), self.drawDistanceMap,
                             self.manageGrid
                         ])
        OWGUI.qwtHSlider(box,
                         self,
                         "CellHeight",
                         label='Height: ',
                         labelWidth=38,
                         minValue=1,
                         maxValue=self.maxVSize,
                         step=1,
                         precision=0,
                         callback=[
                             lambda f="CellHeight", t="CellWidth": self.
                             adjustCellSize(f, t), self.drawDistanceMap,
                             self.manageGrid
                         ])
        OWGUI.checkBox(box,
                       self,
                       "SquareCells",
                       "Cells as squares",
                       callback=[self.setSquares, self.drawDistanceMap])
        self.gridChkBox = OWGUI.checkBox(
            box,
            self,
            "Grid",
            "Show grid",
            callback=self.createDistanceMap,
            disabled=lambda: min(self.CellWidth, self.CellHeight
                                 ) <= c_smallcell)

        OWGUI.separator(tab)
        OWGUI.qwtHSlider(tab,
                         self,
                         "Merge",
                         box="Merge",
                         label='Elements:',
                         labelWidth=50,
                         minValue=1,
                         maxValue=100,
                         step=1,
                         callback=self.createDistanceMap,
                         ticks=0)

        OWGUI.separator(tab)
        self.labelCombo = OWGUI.comboBox(
            tab,
            self,
            "Sort",
            box="Sort",
            items=[x[0] for x in self.sorting],
            tooltip="Sorting method for items in distance matrix.",
            callback=self.sortItems)
        OWGUI.rubber(tab)

        ##        self.tabs.insertTab(tab, "Settings")

        # FILTER TAB
        tab = OWGUI.createTabPage(self.tabs, "Colors")
        box = OWGUI.widgetBox(tab, "Color settings", addSpace=True)
        OWGUI.widgetLabel(box, "Gamma")
        OWGUI.qwtHSlider(box,
                         self,
                         "Gamma",
                         minValue=0.1,
                         maxValue=1,
                         step=0.1,
                         maxWidth=100,
                         callback=self.drawDistanceMap)

        OWGUI.separator(box)

        OWGUI.checkBox(box,
                       self,
                       'CutEnabled',
                       "Enable thresholds",
                       callback=self.setCutEnabled)
        self.sliderCutLow = OWGUI.qwtHSlider(box,
                                             self,
                                             'CutLow',
                                             label='Low:',
                                             labelWidth=33,
                                             minValue=-100,
                                             maxValue=0,
                                             step=0.1,
                                             precision=1,
                                             ticks=0,
                                             maxWidth=80,
                                             callback=self.drawDistanceMap)
        self.sliderCutHigh = OWGUI.qwtHSlider(box,
                                              self,
                                              'CutHigh',
                                              label='High:',
                                              labelWidth=33,
                                              minValue=0,
                                              maxValue=100,
                                              step=0.1,
                                              precision=1,
                                              ticks=0,
                                              maxWidth=80,
                                              callback=self.drawDistanceMap)
        if not self.CutEnabled:
            self.sliderCutLow.box.setDisabled(1)
            self.sliderCutHigh.box.setDisabled(1)

##        self.colorPalette = ColorPalette(box, self, "",
##                         additionalColors =["Cell outline", "Selected cells"],
##                         callback = self.setColor)
##        box.layout().addWidget(self.colorPalette)
        box = OWGUI.widgetBox(box, "Colors", orientation="horizontal")
        self.colorCombo = OWColorPalette.PaletteSelectorComboBox(self)
        try:
            self.colorCombo.setPalettes("palette", self.createColorDialog())
        except Exception as ex:
            print(
                ex,
                "Error loading saved color palettes!\nCreating new default palette!",
                file=sys.stderr)
            self.colorSettings = None
            self.colorCombo.setPalettes("palette", self.createColorDialog())
        self.colorCombo.setCurrentIndex(self.selectedSchemaIndex)
        self.connect(self.colorCombo, SIGNAL("activated(int)"), self.setColor)
        box.layout().addWidget(self.colorCombo, 2)
        OWGUI.button(box,
                     self,
                     "Edit colors",
                     callback=self.openColorDialog,
                     debuggingEnabled=0)
        OWGUI.rubber(tab)

        self.setColor(self.selectedSchemaIndex)

        ##        self.tabs.insertTab(tab, "Colors")

        # INFO TAB
        tab = OWGUI.createTabPage(self.tabs, "Info")
        box = OWGUI.widgetBox(tab, "Annotation && Legends")
        OWGUI.checkBox(box,
                       self,
                       'ShowLegend',
                       'Show legend',
                       callback=self.drawDistanceMap)
        OWGUI.checkBox(box,
                       self,
                       'ShowLabels',
                       'Show labels',
                       callback=self.drawDistanceMap)

        box = OWGUI.widgetBox(tab, "Balloon")
        OWGUI.checkBox(box, self, 'ShowBalloon', "Show balloon")
        OWGUI.checkBox(box, self, 'ShowItemsInBalloon', "Display item names")

        box = OWGUI.widgetBox(tab, "Select")
        box2 = OWGUI.widgetBox(box, orientation="horizontal")
        self.box2 = box2
        self.buttonUndo = OWToolbars.createButton(box2,
                                                  'Undo',
                                                  self.actionUndo,
                                                  QIcon(OWToolbars.dlg_undo),
                                                  toggle=0)
        self.buttonRemoveAllSelections = OWToolbars.createButton(
            box2,
            'Remove all selections',
            self.actionRemoveAllSelections,
            QIcon(OWToolbars.dlg_clear),
            toggle=0)

        self.buttonSendSelections = OWToolbars.createButton(
            box2,
            'Send selections',
            self.sendOutput,
            QIcon(OWToolbars.dlg_send),
            toggle=0)
        OWGUI.checkBox(box, self, 'SendOnRelease', "Send after mouse release")
        OWGUI.rubber(tab)
        ##        self.tabs.insertTab(tab, "Info")

        self.resize(700, 400)

        self.scene = EventfulGraphicsScene(self)
        self.sceneView = EventfulGraphicsView(self.scene, self.mainArea, self)
        self.mainArea.layout().addWidget(self.sceneView)

        #construct selector
        self.selector = QGraphicsRectItem(0, 0, self.CellWidth,
                                          self.CellHeight, None, self.scene)
        ##        color = self.colorPalette.getCurrentColorSchema().getAdditionalColors()["Cell outline"]
        color = self.cellOutlineColor
        self.selector.setPen(QPen(self.qrgbToQColor(color), v_sel_width))
        self.selector.setZValue(20)

        ##        self.bubble = BubbleInfo(self.scene)
        self.selection = SelectionManager()

        self.selectionLines = []
        self.annotationText = []
        self.clusterItems = []
        self.selectionRects = []

        self.legendText1 = QGraphicsSimpleTextItem(None, self.scene)
        self.legendText2 = QGraphicsSimpleTextItem(None, self.scene)

        self.errorText = QGraphicsSimpleTextItem("Bitmap is too large.", None,
                                                 self.scene)
        self.errorText.setPos(10, 10)

        #        OWGUI.button(self.controlArea, self, "&Save Graph", lambda:OWChooseImageSizeDlg(self.scene).exec_(), debuggingEnabled = 0)
        self.connect(
            self.graphButton, SIGNAL("clicked()"),
            lambda: OWChooseImageSizeDlg(self.scene, parent=self).exec_())
コード例 #26
0
 def createColorDialog(self):
     c = OWColorPalette.ColorPaletteDlg(self, "Color Palette")
     c.createDiscretePalette("colorPalette", "Discrete Palette")
     c.setColorSchemas(self.colorSettings, self.selectedColorSettingsIndex)
     return c