📄 owlinprojgraph.py
字号:
tempList = []
# for every permutation compute how good it separates different classes
for ind in permutations:
permutation = [attrs[val] for val in ind]
permutationAttributes = [self.attributeNames[i] for i in permutation]
if self.clusterOptimization.isOptimizationCanceled():
secs = time.time() - startTime
self.clusterOptimization.setStatusBarText("Evaluation stopped (evaluated %s projections in %d min, %d sec)" % (orngVisFuncts.createStringFromNumber(self.triedPossibilities), secs/60, secs%60))
self.widget.progressBarFinished()
return
data = self.createProjectionAsExampleTable(permutation, settingsDict = {"validData": validData, "classList": classList, "sum_i": sum_i, "XAnchors": XAnchors, "YAnchors": YAnchors, "domain": domain})
graph, valueDict, closureDict, polygonVerticesDict, enlargedClosureDict, otherDict = self.clusterOptimization.evaluateClusters(data)
classesDict = {}
if not self.onlyOnePerSubset:
allValue = 0.0
for key in valueDict.keys():
addResultFunct(valueDict[key], closureDict[key], polygonVerticesDict[key], permutationAttributes, otherDict[key][OTHER_CLASS], enlargedClosureDict[key], otherDict[key])
classesDict[key] = otherDict[key][OTHER_CLASS]
allValue += valueDict[key]
addResultFunct(allValue, closureDict, polygonVerticesDict, permutationAttributes, classesDict, enlargedClosureDict, otherDict) # add all the clusters
else:
value = 0.0
for val in valueDict.values(): value += val
tempList.append((value, valueDict, closureDict, polygonVerticesDict, permutationAttributes, enlargedClosureDict, otherDict))
self.triedPossibilities += 1
qApp.processEvents() # allow processing of other events
del permutation, data, graph, valueDict, closureDict, polygonVerticesDict, enlargedClosureDict, otherDict, classesDict,
self.widget.progressBarSet(100.0*self.triedPossibilities/float(self.totalPossibilities))
self.clusterOptimization.setStatusBarText("Evaluated %s projections..." % (orngVisFuncts.createStringFromNumber(self.triedPossibilities)))
if self.onlyOnePerSubset:
(value, valueDict, closureDict, polygonVerticesDict, attrs, enlargedClosureDict, otherDict) = max(tempList)
allValue = 0.0
classesDict = {}
for key in valueDict.keys():
addResultFunct(valueDict[key], closureDict[key], polygonVerticesDict[key], attrs, otherDict[key][OTHER_CLASS], enlargedClosureDict[key], otherDict[key])
classesDict[key] = otherDict[key][OTHER_CLASS]
allValue += valueDict[key]
addResultFunct(allValue, closureDict, polygonVerticesDict, attrs, classesDict, enlargedClosureDict, otherDict) # add all the clusters
del validData, classList, selectedData, sum_i, tempList
del combinations
secs = time.time() - startTime
self.clusterOptimization.setStatusBarText("Finished evaluation (evaluated %s projections in %d min, %d sec)" % (orngVisFuncts.createStringFromNumber(self.triedPossibilities), secs/60, secs%60))
self.widget.progressBarFinished()
# update shown data. Set labels, coloring by className ....
def savePicTeX(self):
lastSave = getattr(self, "lastPicTeXSave", "C:\\")
qfileName = QFileDialog.getSaveFileName(lastSave + "graph.pictex","PicTeX (*.pictex);;All files (*.*)", None, "Save to..", "Save to..")
fileName = str(qfileName)
if fileName == "":
return
if not os.path.splitext(fileName)[1][1:]:
fileName = fileName + ".pictex"
self.lastSave = os.path.split(fileName)[0]+"/"
file = open(fileName, "wt")
file.write("\\mbox{\n")
file.write(" \\beginpicture\n")
file.write(" \\setcoordinatesystem units <0.4\columnwidth, 0.4\columnwidth>\n")
file.write(" \\setplotarea x from -1.1 to 1.1, y from -1 to 1.1\n")
if not self.anchorsAsVectors:
file.write("\\circulararc 360 degrees from 1 0 center at 0 0\n")
if self.showAnchors:
if self.hideRadius > 0:
file.write("\\setdashes\n")
file.write("\\circulararc 360 degrees from %5.3f 0 center at 0 0\n" % (self.hideRadius/10.))
file.write("\\setsolid\n")
if self.showAttributeNames:
shownAnchorData = filter(lambda p, r=self.hideRadius**2/100: p[0]**2+p[1]**2>r, self.anchorData)
if self.anchorsAsVectors:
for x,y,l in shownAnchorData:
file.write("\\plot 0 0 %5.3f %5.3f /\n" % (x, y))
file.write("\\put {{\\footnotesize %s}} [b] at %5.3f %5.3f\n" % (l.replace("_", "-"), x*1.07, y*1.04))
else:
file.write("\\multiput {\\small $\\odot$} at %s /\n" % (" ".join(["%5.3f %5.3f" % tuple(i[:2]) for i in shownAnchorData])))
for x,y,l in shownAnchorData:
file.write("\\put {{\\footnotesize %s}} [b] at %5.3f %5.3f\n" % (l.replace("_", "-"), x*1.07, y*1.04))
symbols = ("{\\small $\\circ$}", "{\\tiny $\\times$}", "{\\tiny $+$}", "{\\small $\\star$}",
"{\\small $\\ast$}", "{\\tiny $\\div$}", "{\\small $\\bullet$}", ) + tuple([chr(x) for x in range(97, 123)])
dataSize = len(self.rawdata)
labels = self.widget.getShownAttributeList()
classValueIndices = getVariableValueIndices(self.rawdata, self.rawdata.domain.classVar.name)
indices = [self.attributeNameIndex[label] for label in labels]
selectedData = Numeric.take(self.scaledData, indices)
XAnchors = Numeric.array([a[0] for a in self.anchorData])
YAnchors = Numeric.array([a[1] for a in self.anchorData])
r = Numeric.sqrt(XAnchors*XAnchors + YAnchors*YAnchors) # compute the distance of each anchor from the center of the circle
XAnchors *= r # we need to normalize the anchors by r, otherwise the anchors won't attract points less if they are placed at the center of the circle
YAnchors *= r
x_positions = Numeric.matrixmultiply(XAnchors, selectedData)
y_positions = Numeric.matrixmultiply(YAnchors, selectedData)
if self.normalizeExamples:
sum_i = self._getSum_i(selectedData, useAnchorData = 1, anchorRadius = r)
x_positions /= sum_i
y_positions /= sum_i
if self.scaleFactor:
self.trueScaleFactor = self.scaleFactor
else:
abss = x_positions*x_positions + y_positions*y_positions
self.trueScaleFactor = 1 / sqrt(abss[Numeric.argmax(abss)])
x_positions *= self.trueScaleFactor
y_positions *= self.trueScaleFactor
validData = self.getValidList(indices)
valLen = len(self.rawdata.domain.classVar.values)
pos = [[] for i in range(valLen)]
for i in range(dataSize):
if validData[i]:
pos[classValueIndices[self.rawdata[i].getclass().value]].append((x_positions[i], y_positions[i]))
for i in range(valLen):
file.write("\\multiput {%s} at %s /\n" % (symbols[i], " ".join(["%5.3f %5.3f" % p for p in pos[i]])))
if self.showLegend:
classVariableValues = getVariableValuesSorted(self.rawdata, self.rawdata.domain.classVar.name)
file.write("\\put {%s} [lB] at 0.87 1.06\n" % self.rawdata.domain.classVar.name)
for index in range(len(classVariableValues)):
file.write("\\put {%s} at 1.0 %5.3f\n" % (symbols[index], 0.93 - 0.115*index))
file.write("\\put {%s} [lB] at 1.05 %5.3f\n" % (classVariableValues[index], 0.9 - 0.115*index))
file.write("\\endpicture\n}\n")
file.close()
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, "potentialsBmp", None) \
or getattr(self, "potentialContext", None) != (rx, ry, 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, 1, self.normalizeExamples)
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, self.normalizeExamples)
colors = self.discPalette
palette = []
sortedClasses = getVariableValuesSorted(self.potentialsClassifier, self.potentialsClassifier.domain.classVar.name)
for cls in self.potentialsClassifier.classVar.values:
color = colors[sortedClasses.index(cls)].light(150).rgb()
color = [f(color) for f in [qRed, qGreen, qBlue]]
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))])
# image = QImage(imagebmp, (2*rx + 3) & ~3, 2*ry, 8, palette, 256, QImage.LittleEndian)
image = QImage(imagebmp, (rx + 3) & ~3, ry, 8, palette, 256, QImage.LittleEndian)
self.potentialsBmp = QPixmap()
self.potentialsBmp.convertFromImage(image)
self.potentialContext = (rx, ry, self.trueScaleFactor, self.squareGranularity, self.jitterSize, self.jitterContinuous, self.spaceBetweenCells)
def drawCanvasItems(self, painter, rect, map, pfilter):
if self.showProbabilities and getattr(self, "potentialsClassifier", None):
self.computePotentials()
painter.drawPixmap(QPoint(self.transform(QwtPlot.xBottom, -1), self.transform(QwtPlot.yLeft, 1)), self.potentialsBmp)
OWGraph.drawCanvasItems(self, painter, rect, map, pfilter)
if __name__== "__main__":
#Draw a simple graph
import os
a = QApplication(sys.argv)
graph = OWLinProjGraph(None)
fname = r"..\..\datasets\microarray\brown\brown-selected.tab"
if os.path.exists(fname):
table = orange.ExampleTable(fname)
attrs = [attr.name for attr in table.domain.attributes]
graph.setData(table)
graph.updateData(attrs, 1)
a.setMainWidget(graph)
graph.show()
a.exec_loop()
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -