1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
|
import fractions
from collections import namedtuple, OrderedDict
from typing import Tuple, List, Optional, Dict
import numpy as np
from AnyQt.QtCore import QPointF, QRectF, Qt, QSizeF, QEvent, Signal
from AnyQt.QtGui import (
QPainterPath, QPen, QBrush, QPalette, QPainterPathStroker, QColor,
QTransform, QFontMetrics, QPolygonF
)
from AnyQt.QtWidgets import (
QGraphicsWidget, QGraphicsPathItem, QGraphicsItemGroup,
QGraphicsSimpleTextItem
)
from Orange.clustering.hierarchical import Tree, postorder, preorder, leaves
from Orange.widgets.utils import colorpalettes
__all__ = [
"DendrogramWidget"
]
def dendrogram_layout(tree, expand_leaves=False):
# type: (Tree, bool) -> List[Tuple[Tree, Tuple[float, float, float]]]
coords = []
cluster_geometry = {}
leaf_idx = 0
for node in postorder(tree):
cluster = node.value
if node.is_leaf:
if expand_leaves:
start = float(cluster.first) + 0.5
end = float(cluster.last - 1) + 0.5
else:
start = end = leaf_idx + 0.5
leaf_idx += 1
center = (start + end) / 2.0
cluster_geometry[node] = (start, center, end)
coords.append((node, (start, center, end)))
else:
left = node.left
right = node.right
left_center = cluster_geometry[left][1]
right_center = cluster_geometry[right][1]
start, end = left_center, right_center
center = (start + end) / 2.0
cluster_geometry[node] = (start, center, end)
coords.append((node, (start, center, end)))
return coords
Point = namedtuple("Point", ["x", "y"])
Element = namedtuple("Element", ["anchor", "path"])
def path_toQtPath(geom):
p = QPainterPath()
anchor, points = geom
if len(points) > 1:
p.moveTo(*points[0])
for (x, y) in points[1:]:
p.lineTo(x, y)
elif len(points) == 1:
r = QRectF(0, 0, 1e-0, 1e-9)
r.moveCenter(*points[0])
p.addRect(r)
elif len(points) == 0:
r = QRectF(0, 0, 1e-16, 1e-16)
r.moveCenter(QPointF(*anchor))
p.addRect(r)
return p
#: Dendrogram orientation flags
Left, Top, Right, Bottom = 1, 2, 3, 4
def dendrogram_path(tree, orientation=Left, scaleh=1):
layout = dendrogram_layout(tree)
T = {}
paths = {}
rootdata = tree.value
base = scaleh * rootdata.height
if orientation == Bottom:
transform = lambda x, y: (x, y)
if orientation == Top:
transform = lambda x, y: (x, base - y)
elif orientation == Left:
transform = lambda x, y: (base - y, x)
elif orientation == Right:
transform = lambda x, y: (y, x)
for node, (start, center, end) in layout:
if node.is_leaf:
x, y = transform(center, 0)
anchor = Point(x, y)
paths[node] = Element(anchor, ())
else:
left, right = paths[node.left], paths[node.right]
lines = (left.anchor,
Point(*transform(start, scaleh * node.value.height)),
Point(*transform(end, scaleh * node.value.height)),
right.anchor)
anchor = Point(*transform(center, scaleh * node.value.height))
paths[node] = Element(anchor, lines)
T[node] = Tree((node, paths[node]),
tuple(T[ch] for ch in node.branches))
return T[tree]
def make_pen(brush=Qt.black, width=1, style=Qt.SolidLine,
cap_style=Qt.SquareCap, join_style=Qt.BevelJoin,
cosmetic=False):
pen = QPen(brush)
pen.setWidth(width)
pen.setStyle(style)
pen.setCapStyle(cap_style)
pen.setJoinStyle(join_style)
pen.setCosmetic(cosmetic)
return pen
def update_pen(pen, brush=None, width=None, style=None,
cap_style=None, join_style=None,
cosmetic=None):
pen = QPen(pen)
if brush is not None:
pen.setBrush(QBrush(brush))
if width is not None:
pen.setWidth(width)
if style is not None:
pen.setStyle(style)
if cap_style is not None:
pen.setCapStyle(cap_style)
if join_style is not None:
pen.setJoinStyle(join_style)
if cosmetic is not None:
pen.setCosmetic(cosmetic)
return pen
def path_stroke(path, width=1, join_style=Qt.RoundJoin):
stroke = QPainterPathStroker()
stroke.setWidth(width)
stroke.setJoinStyle(join_style)
stroke.setMiterLimit(1.0)
return stroke.createStroke(path)
def path_outline(path, width=1, join_style=Qt.RoundJoin):
stroke = path_stroke(path, width, join_style)
return stroke.united(path)
class DendrogramWidget(QGraphicsWidget):
"""A Graphics Widget displaying a dendrogram."""
class ClusterGraphicsItem(QGraphicsPathItem):
#: The untransformed source path in 'dendrogram' logical coordinate
#: system
sourcePath = QPainterPath() # type: QPainterPath
sourceAreaShape = QPainterPath() # type: QPainterPath
__shape = None # type: Optional[QPainterPath]
__boundingRect = None # type: Optional[QRectF]
#: An extended path describing the full mouse hit area
#: (extends all the way to the base of the dendrogram)
__mouseAreaShape = QPainterPath() # type: QPainterPath
def setGeometryData(self, path, hitArea):
# type: (QPainterPath, QPainterPath) -> None
"""
Set the geometry (path) and the mouse hit area (hitArea) for this
item.
"""
super().setPath(path)
self.prepareGeometryChange()
self.__boundingRect = self.__shape = None
self.__mouseAreaShape = hitArea
def shape(self):
# type: () -> QPainterPath
if self.__shape is None:
path = super().shape() # type: QPainterPath
self.__shape = path.united(self.__mouseAreaShape)
return self.__shape
def boundingRect(self):
# type: () -> QRectF
if self.__boundingRect is None:
sh = self.shape()
pw = self.pen().widthF() / 2.0
self.__boundingRect = sh.boundingRect().adjusted(-pw, -pw, pw, pw)
return self.__boundingRect
class _SelectionItem(QGraphicsItemGroup):
def __init__(self, parent, path, unscaled_path, label=""):
super().__init__(parent)
self.path = QGraphicsPathItem(path, self)
self.path.setPen(make_pen(width=1, cosmetic=True))
self.addToGroup(self.path)
self.label = QGraphicsSimpleTextItem(label)
self._update_label_pos()
self.addToGroup(self.label)
self.unscaled_path = unscaled_path
def set_path(self, path):
self.path.setPath(path)
self._update_label_pos()
def set_label(self, label):
self.label.setText(label)
self._update_label_pos()
def set_color(self, color):
self.path.setBrush(QColor(color))
def _update_label_pos(self):
path = self.path.path()
elements = (path.elementAt(i) for i in range(path.elementCount()))
points = ((p.x, p.y) for p in elements)
p1, p2, *rest = sorted(points)
x, y = p1[0], (p1[1] + p2[1]) / 2
brect = self.label.boundingRect()
# leaf nodes' paths are 4 pixels higher; leafs are `len(rest) == 3`
self.label.setPos(x - brect.width() - 4,
y - brect.height() + 4 * (len(rest) == 3))
#: Orientation
Left, Top, Right, Bottom = 1, 2, 3, 4
#: Selection flags
NoSelection, SingleSelection, ExtendedSelection = 0, 1, 2
#: Emitted when a user clicks on the cluster item.
itemClicked = Signal(ClusterGraphicsItem)
#: Signal emitted when the selection changes.
selectionChanged = Signal()
#: Signal emitted when the selection was changed by the user.
selectionEdited = Signal()
def __init__(self, parent=None, root=None, orientation=Left,
hoverHighlightEnabled=True, selectionMode=ExtendedSelection,
*, pen_width=1,
**kwargs):
super().__init__(None, **kwargs)
# Filter all events from children (`ClusterGraphicsItem`s)
self.setFiltersChildEvents(True)
self.orientation = orientation
self._root = None
#: A tree with dendrogram geometry
self._layout = None
self._highlighted_item = None
#: a list of selected items
self._selection = OrderedDict()
#: a {node: item} mapping
self._items = {} # type: Dict[Tree, DendrogramWidget.ClusterGraphicsItem]
#: container for all cluster items.
self._itemgroup = QGraphicsWidget(self)
self._itemgroup.setGeometry(self.contentsRect())
#: Transform mapping from 'dendrogram' to widget local coordinate
#: system
self._transform = QTransform()
self._cluster_parent = {}
self.__hoverHighlightEnabled = hoverHighlightEnabled
self.__selectionMode = selectionMode
self._pen_width = pen_width
self.setContentsMargins(0, 0, 0, 0)
self.setRoot(root)
if parent is not None:
self.setParentItem(parent)
def setSelectionMode(self, mode):
"""
Set the selection mode.
"""
assert mode in [DendrogramWidget.NoSelection,
DendrogramWidget.SingleSelection,
DendrogramWidget.ExtendedSelection]
if self.__selectionMode != mode:
self.__selectionMode = mode
if self.__selectionMode == DendrogramWidget.NoSelection and \
self._selection:
self.setSelectedClusters([])
elif self.__selectionMode == DendrogramWidget.SingleSelection and \
len(self._selection) > 1:
self.setSelectedClusters([self.selected_nodes()[-1]])
def selectionMode(self):
"""
Return the current selection mode.
"""
return self.__selectionMode
def setHoverHighlightEnabled(self, enabled):
if self.__hoverHighlightEnabled != bool(enabled):
self.__hoverHighlightEnabled = bool(enabled)
if self._highlighted_item is not None:
self._set_hover_item(None)
def isHoverHighlightEnabled(self):
return self.__hoverHighlightEnabled
def clear(self):
"""
Clear the widget.
"""
scene = self.scene()
if scene is not None:
scene.removeItem(self._itemgroup)
else:
self._itemgroup.setParentItem(None)
self._itemgroup = QGraphicsWidget(self)
self._itemgroup.setGeometry(self.contentsRect())
self._items.clear()
for item in self._selection.values():
if scene is not None:
scene.removeItem(item)
else:
item.setParentItem(None)
self._root = None
self._items = {}
self._selection = OrderedDict()
self._highlighted_item = None
self._cluster_parent = {}
self.updateGeometry()
def setRoot(self, root):
# type: (Tree) -> None
"""
Set the root cluster tree node for display.
Parameters
----------
root : Tree
The tree root node.
"""
self.clear()
self._root = root
if root is not None:
foreground = self.palette().color(QPalette.WindowText)
pen = make_pen(foreground, width=self._pen_width, cosmetic=True)
for node in postorder(root):
item = DendrogramWidget.ClusterGraphicsItem(self._itemgroup)
item.setAcceptHoverEvents(True)
item.setPen(pen)
item.node = node
for branch in node.branches:
assert branch in self._items
self._cluster_parent[branch] = node
self._items[node] = item
self._relayout()
self._rescale()
self.updateGeometry()
set_root = setRoot
def root(self):
# type: () -> Tree
"""
Return the cluster tree root node.
Returns
-------
root : Tree
"""
return self._root
def item(self, node):
# type: (Tree) -> DendrogramWidget.ClusterGraphicsItem
"""
Return the ClusterGraphicsItem instance representing the cluster `node`.
"""
return self._items.get(node)
def heightAt(self, point):
# type: (QPointF) -> float
"""
Return the cluster height at the point in widget local coordinates.
"""
if not self._root:
return 0
tinv, ok = self._transform.inverted()
if not ok:
return 0
tpoint = tinv.map(point)
if self.orientation in [self.Left, self.Right]:
height = tpoint.x()
else:
height = tpoint.y()
# Undo geometry prescaling
base = self._root.value.height
scale = self._height_scale_factor()
# Use better better precision then double provides.
Fr = fractions.Fraction
if scale > 0:
height = Fr(height) / Fr(scale)
else:
height = 0
if self.orientation in [self.Left, self.Bottom]:
height = Fr(base) - Fr(height)
return float(height)
height_at = heightAt
def posAtHeight(self, height):
# type: (float) -> float
"""
Return a point in local coordinates for `height` (in cluster
"""
if not self._root:
return QPointF()
scale = self._height_scale_factor()
base = self._root.value.height
height = scale * height
if self.orientation in [self.Left, self.Bottom]:
height = scale * base - height
if self.orientation in [self.Left, self.Right]:
p = QPointF(height, 0)
else:
p = QPointF(0, height)
return self._transform.map(p)
pos_at_height = posAtHeight
def _set_hover_item(self, item):
"""Set the currently highlighted item."""
if self._highlighted_item is item:
return
def set_pen(item, pen):
def branches(item):
return [self._items[ch] for ch in item.node.branches]
for it in postorder(item, branches):
it.setPen(pen)
if self._highlighted_item:
# Restore the previous item
highlight = self.palette().color(QPalette.WindowText)
set_pen(self._highlighted_item,
make_pen(highlight, width=self._pen_width, cosmetic=True))
self._highlighted_item = item
if item:
hpen = make_pen(self.palette().color(QPalette.Highlight),
width=self._pen_width + 1, cosmetic=True)
set_pen(item, hpen)
def leafItems(self):
"""Iterate over the dendrogram leaf items (:class:`QGraphicsItem`).
"""
if self._root:
return (self._items[leaf] for leaf in leaves(self._root))
else:
return iter(())
leaf_items = leafItems
def leafAnchors(self):
"""Iterate over the dendrogram leaf anchor points (:class:`QPointF`).
The points are in the widget local coordinates.
"""
for item in self.leafItems():
anchor = QPointF(item.element.anchor)
yield self.mapFromItem(item, anchor)
leaf_anchors = leafAnchors
def selectedNodes(self):
"""
Return the selected cluster nodes.
"""
return [item.node for item in self._selection]
selected_nodes = selectedNodes
def setSelectedItems(self, items: List[ClusterGraphicsItem]):
"""Set the item selection."""
to_remove = set(self._selection) - set(items)
to_add = set(items) - set(self._selection)
for sel in to_remove:
self._remove_selection(sel)
for sel in to_add:
self._add_selection(sel)
if to_add or to_remove:
self._re_enumerate_selections()
self.selectionChanged.emit()
set_selected_items = setSelectedItems
def setSelectedClusters(self, clusters: List[Tree]) -> None:
"""Set the selected clusters.
"""
self.setSelectedItems(list(map(self.item, clusters)))
set_selected_clusters = setSelectedClusters
def isItemSelected(self, item: ClusterGraphicsItem) -> bool:
"""Is `item` selected (is a root of a selection)."""
return item in self._selection
def isItemIncludedInSelection(self, item: ClusterGraphicsItem) -> bool:
"""Is item included in any selection."""
return self._selected_super_item(item) is not None
is_included = isItemIncludedInSelection
def setItemSelected(self, item, state):
# type: (ClusterGraphicsItem, bool) -> None
"""Set the `item`s selection state to `state`."""
if state is False and item not in self._selection or \
state is True and item in self._selection:
return # State unchanged
if item in self._selection:
if state is False:
self._remove_selection(item)
self._re_enumerate_selections()
self.selectionChanged.emit()
else:
# If item is already inside another selected item,
# remove that selection
super_selection = self._selected_super_item(item)
if super_selection:
self._remove_selection(super_selection)
# Remove selections this selection will override.
sub_selections = self._selected_sub_items(item)
for sub in sub_selections:
self._remove_selection(sub)
if state:
self._add_selection(item)
elif item in self._selection:
self._remove_selection(item)
self._re_enumerate_selections()
self.selectionChanged.emit()
select_item = setItemSelected
@staticmethod
def _create_path(item, path):
ppath = QPainterPath()
if item.node.is_leaf:
ppath.addRect(path.boundingRect().adjusted(-8, -4, 0, 4))
else:
ppath.addPolygon(path)
ppath = path_outline(ppath, width=-8)
return ppath
@staticmethod
def _create_label(i):
return f"C{i + 1}"
def _add_selection(self, item):
"""Add selection rooted at item
"""
outline = self._selection_poly(item)
path = self._transform.map(outline)
ppath = self._create_path(item, path)
label = self._create_label(len(self._selection))
selection_item = self._SelectionItem(self, ppath, outline, label)
selection_item.label.setBrush(self.palette().color(QPalette.Link))
selection_item.setPos(self.contentsRect().topLeft())
self._selection[item] = selection_item
def _remove_selection(self, item):
"""Remove selection rooted at item."""
selection_item = self._selection[item]
selection_item.hide()
selection_item.setParentItem(None)
if self.scene():
self.scene().removeItem(selection_item)
del self._selection[item]
def _selected_sub_items(self, item):
"""Return all selected subclusters under item."""
def branches(item):
return [self._items[ch] for ch in item.node.branches]
res = []
for item in list(preorder(item, branches))[1:]:
if item in self._selection:
res.append(item)
return res
def _selected_super_item(self, item):
"""Return the selected super item if it exists."""
def branches(item):
return [self._items[ch] for ch in item.node.branches]
for selected_item in self._selection:
if item in set(preorder(selected_item, branches)):
return selected_item
return None
def _re_enumerate_selections(self):
"""Re enumerate the selection items and update the colors."""
# Order the clusters
items = sorted(self._selection.items(),
key=lambda item: item[0].node.value.first)
palette = colorpalettes.LimitedDiscretePalette(len(items))
for i, (item, selection_item) in enumerate(items):
# delete and then reinsert to update the ordering
del self._selection[item]
self._selection[item] = selection_item
selection_item.set_label(self._create_label(i))
color = palette[i]
color.setAlpha(150)
selection_item.set_color(color)
def _selection_poly(self, item):
# type: (Tree) -> QPolygonF
"""
Return an selection geometry covering item and all its children.
"""
def left(item):
return [self._items[ch] for ch in item.node.branches[:1]]
def right(item):
return [self._items[ch] for ch in item.node.branches[-1:]]
itemsleft = list(preorder(item, left))[::-1]
itemsright = list(preorder(item, right))
# itemsleft + itemsright walks from the leftmost leaf up to the root
# and down to the rightmost leaf
assert itemsleft[0].node.is_leaf
assert itemsright[-1].node.is_leaf
if item.node.is_leaf:
# a single anchor point
vert = [itemsleft[0].element.anchor]
else:
vert = []
for it in itemsleft[1:]:
vert.extend([it.element.path[0], it.element.path[1],
it.element.anchor])
for it in itemsright[:-1]:
vert.extend([it.element.anchor,
it.element.path[-2], it.element.path[-1]])
# close the polygon
vert.append(vert[0])
def isclose(a, b, rel_tol=1e-6):
return abs(a - b) < rel_tol * max(abs(a), abs(b))
def isclose_p(p1, p2, rel_tol=1e-6):
return isclose(p1.x, p2.x, rel_tol) and \
isclose(p1.y, p2.y, rel_tol)
# merge consecutive vertices that are (too) close
acc = [vert[0]]
for v in vert[1:]:
if not isclose_p(v, acc[-1]):
acc.append(v)
vert = acc
return QPolygonF([QPointF(*p) for p in vert])
def _update_selection_items(self):
"""Update the shapes of selection items after a scale change.
"""
transform = self._transform
for item, selection in self._selection.items():
path = transform.map(selection.unscaled_path)
ppath = self._create_path(item, path)
selection.set_path(ppath)
def _height_scale_factor(self):
# Internal dendrogram height scale factor. The dendrogram geometry is
# scaled by this factor to better condition the geometry
if self._root is None:
return 1
base = self._root.value.height
# implicitly scale the geometry to 0..1 scale or flush to 0 for fuzz
if base >= np.finfo(base).eps:
return 1 / base
else:
return 0
def _relayout(self):
if self._root is None:
return
scale = self._height_scale_factor()
base = scale * self._root.value.height
self._layout = dendrogram_path(self._root, self.orientation,
scaleh=scale)
for node_geom in postorder(self._layout):
node, geom = node_geom.value
item = self._items[node]
item.element = geom
# the untransformed source path
item.sourcePath = path_toQtPath(geom)
r = item.sourcePath.boundingRect()
if self.orientation == Left:
r.setRight(base)
elif self.orientation == Right:
r.setLeft(0)
elif self.orientation == Top:
r.setBottom(base)
else:
r.setTop(0)
hitarea = QPainterPath()
hitarea.addRect(r)
item.sourceAreaShape = hitarea
item.setGeometryData(item.sourcePath, item.sourceAreaShape)
item.setZValue(-node.value.height)
def _rescale(self):
if self._root is None:
return
scale = self._height_scale_factor()
base = scale * self._root.value.height
crect = self.contentsRect()
leaf_count = len(list(leaves(self._root)))
if self.orientation in [Left, Right]:
drect = QSizeF(base, leaf_count)
else:
drect = QSizeF(leaf_count, base)
eps = np.finfo(np.float64).eps
if abs(drect.width()) < eps:
sx = 1.0
else:
sx = crect.width() / drect.width()
if abs(drect.height()) < eps:
sy = 1.0
else:
sy = crect.height() / drect.height()
transform = QTransform().scale(sx, sy)
self._transform = transform
self._itemgroup.setPos(crect.topLeft())
self._itemgroup.setGeometry(crect)
for node_geom in postorder(self._layout):
node, _ = node_geom.value
item = self._items[node]
item.setGeometryData(
transform.map(item.sourcePath),
transform.map(item.sourceAreaShape)
)
self._selection_items = None
self._update_selection_items()
def sizeHint(self, which: Qt.SizeHint, constraint=QSizeF()) -> QSizeF:
# reimplemented
fm = QFontMetrics(self.font())
spacing = fm.lineSpacing()
mleft, mtop, mright, mbottom = self.getContentsMargins()
if self._root and which == Qt.PreferredSize:
nleaves = len([node for node in self._items.keys()
if not node.branches])
base = max(10, min(spacing * 16, 250))
if self.orientation in [self.Left, self.Right]:
return QSizeF(base, spacing * nleaves + mleft + mright)
else:
return QSizeF(spacing * nleaves + mtop + mbottom, base)
elif which == Qt.MinimumSize:
return QSizeF(mleft + mright + 10, mtop + mbottom + 10)
else:
return QSizeF()
def sceneEventFilter(self, obj, event):
if isinstance(obj, DendrogramWidget.ClusterGraphicsItem):
if event.type() == QEvent.GraphicsSceneHoverEnter and \
self.__hoverHighlightEnabled:
self._set_hover_item(obj)
event.accept()
return True
elif event.type() == QEvent.GraphicsSceneMousePress and \
event.button() == Qt.LeftButton:
is_selected = self.isItemSelected(obj)
is_included = self.is_included(obj)
current_selection = list(self._selection)
if self.__selectionMode == DendrogramWidget.SingleSelection:
if event.modifiers() & Qt.ControlModifier:
self.setSelectedItems(
[obj] if not is_selected else [])
elif event.modifiers() & Qt.AltModifier:
self.setSelectedItems([])
elif event.modifiers() & Qt.ShiftModifier:
if not is_included:
self.setSelectedItems([obj])
elif current_selection != [obj]:
self.setSelectedItems([obj])
elif self.__selectionMode == DendrogramWidget.ExtendedSelection:
if event.modifiers() & Qt.ControlModifier:
self.setItemSelected(obj, not is_selected)
elif event.modifiers() & Qt.AltModifier:
self.setItemSelected(self._selected_super_item(obj), False)
elif event.modifiers() & Qt.ShiftModifier:
if not is_included:
self.setItemSelected(obj, True)
elif current_selection != [obj]:
self.setSelectedItems([obj])
if current_selection != self._selection:
self.selectionEdited.emit()
self.itemClicked.emit(obj)
event.accept()
return True
if event.type() == QEvent.GraphicsSceneHoverLeave:
self._set_hover_item(None)
return super().sceneEventFilter(obj, event)
def changeEvent(self, event):
# reimplemented
super().changeEvent(event)
if event.type() == QEvent.FontChange:
self.updateGeometry()
elif event.type() == QEvent.PaletteChange:
self._update_colors()
elif event.type() == QEvent.ContentsRectChange:
self._rescale()
def resizeEvent(self, event):
# reimplemented
super().resizeEvent(event)
self._rescale()
def mousePressEvent(self, event):
# reimplemented
super().mousePressEvent(event)
# A mouse press on an empty widget part
if event.modifiers() == Qt.NoModifier and self._selection:
self.set_selected_clusters([])
def _update_colors(self):
def set_color(item: DendrogramWidget.ClusterGraphicsItem, color: QColor):
def branches(item):
return [self._items[ch] for ch in item.node.branches]
for it in postorder(item, branches):
it.setPen(update_pen(it.pen(), brush=color))
if self._root is not None:
foreground = self.palette().color(QPalette.WindowText)
item = self.item(self._root)
set_color(item, foreground)
highlight = self.palette().color(QPalette.Highlight)
if self._highlighted_item is not None:
set_color(self._highlighted_item, highlight)
accent = self.palette().color(QPalette.Link)
for item in self._selection.values():
item.label.setBrush(accent)
|