GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — PlotPy/plotpy/plot/base.py at master · PlotPyStack/PlotPy Expand file tree/ Copy pathbase.pyMore file actions 2692 lines (2307 loc) · 94.4 KB / Copy pathbase.pyFile metadata and controls2692 lines (2307 loc) · 94.4 KB 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 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 # -*- coding: utf-8 -*- # # Licensed under the terms of the BSD 3-Clause # (see plotpy/LICENSE for details) # pylint: disable=C0103 """ Plotting widget base class -------------------------- The `base` module provides the :mod:`plotpy` plotting widget base class: :py:class:`.base.BasePlot`. """ from __future__ import annotations import dataclasses import pickle import sys import warnings import weakref from datetime import datetime from math import fabs from typing import TYPE_CHECKING, Any import numpy as np import qwt from guidata.configtools import get_font from guidata.qthelpers import is_qobject_valid from qtpy import QtCore as QC from qtpy import QtGui as QG from qtpy import QtWidgets as QW from qtpy.QtPrintSupport import QPrinter from plotpy import constants as cst from plotpy import io from plotpy.config import CONF, _ from plotpy.constants import PARAMETERS_TITLE_ICON, PlotType from plotpy.events import StatefulEventFilter from plotpy.interfaces import items as itf from plotpy.items import ( AnnotatedCircle, AnnotatedEllipse, AnnotatedObliqueRectangle, AnnotatedPoint, AnnotatedPolygon, AnnotatedRectangle, AnnotatedSegment, BaseImageItem, CurveItem, GridItem, Marker, PolygonMapItem, PolygonShape, QuiverItem, ) from plotpy.mathutils.colormap import LogScaleColorMap from plotpy.styles.axes import AxesParam, AxeStyleParam, AxisParam, ImageAxesParam from plotpy.styles.base import GridParam, ItemParameters if TYPE_CHECKING: from typing import IO from qwt.scale_widget import QwtScaleWidget from plotpy.plot.manager import PlotManager TrackableItem = CurveItem | BaseImageItem import guidata.io @dataclasses.dataclass class BasePlotOptions: """Base plot options Args: title: The plot title xlabel: (bottom axis title, top axis title) or bottom axis title only ylabel: (left axis title, right axis title) or left axis title only zlabel: The Z-axis label xunit: (bottom axis unit, top axis unit) or bottom axis unit only yunit: (left axis unit, right axis unit) or left axis unit only zunit: The Z-axis unit yreverse: If True, the Y-axis is reversed aspect_ratio: The plot aspect ratio lock_aspect_ratio: If True, the aspect ratio is locked curve_antialiasing: If True, the curve antialiasing is enabled gridparam: The grid parameters section: The plot configuration section name ("plot", by default) type: The plot type ("auto", "manual", "curve" or "image") axes_synchronised: If True, the axes are synchronised force_colorbar_enabled: If True, the colorbar is always enabled show_axes_tab: If True, the axes tab is shown in the parameters dialog autoscale_margin_percent: The percentage margin added when autoscaling (0.2% by default) """ title: str | None = None xlabel: str | tuple[str, str] | None = None ylabel: str | tuple[str, str] | None = None zlabel: str | None = None xunit: str | tuple[str, str] | None = None yunit: str | tuple[str, str] | None = None zunit: str | None = None yreverse: bool | None = None aspect_ratio: float = 1.0 lock_aspect_ratio: bool | None = None curve_antialiasing: bool | None = None gridparam: GridParam | None = None section: str = "plot" type: str | PlotType = "auto" axes_synchronised: bool = False force_colorbar_enabled: bool = False show_axes_tab: bool = True autoscale_margin_percent: float = 0.2 def __post_init__(self) -> None: """Check arguments""" # Check type if isinstance(self.type, str): if self.type not in ["auto", "manual", "curve", "image"]: raise ValueError("type must be 'auto', 'manual', 'curve' or 'image'") self.type = PlotType[self.type.upper()] elif not isinstance(self.type, PlotType): raise TypeError("type must be a string or a PlotType") # Check aspect ratio if self.aspect_ratio <= 0: raise ValueError("aspect_ratio must be strictly positive") # Check autoscale margin percentage if self.autoscale_margin_percent < 0: raise ValueError("autoscale_margin_percent must be non-negative") if self.autoscale_margin_percent > 50: raise ValueError("autoscale_margin_percent must be <= 50%") # Show a warning if force_colorbar_enabled is True and type is "curve" if self.force_colorbar_enabled and self.type == "curve": warnings.warn( "force_colorbar_enabled is True but type is 'curve', " "so the colorbar will not be displayed", RuntimeWarning, ) def copy(self, other_options: dict[str, Any]) -> BasePlotOptions: """Copy the options and replace some of them with the given dictionary Args: other_options: The dictionary Returns: BasePlotOptions: The new options """ return dataclasses.replace(self, **other_options) class BasePlot(qwt.QwtPlot): """Enhanced QwtPlot class providing methods for handling items and axes better It distinguishes activatable items from basic QwtPlotItems. Activatable items must support IBasePlotItem interface and should be added to the plot using add_item methods. Args: parent: parent widget options: plot options """ Y_LEFT, Y_RIGHT, X_BOTTOM, X_TOP = cst.Y_LEFT, cst.Y_RIGHT, cst.X_BOTTOM, cst.X_TOP AXIS_IDS = (Y_LEFT, Y_RIGHT, X_BOTTOM, X_TOP) AXIS_NAMES = {"left": Y_LEFT, "right": Y_RIGHT, "bottom": X_BOTTOM, "top": X_TOP} AXIS_TYPES = { "lin": qwt.QwtLinearScaleEngine, "log": qwt.QwtLogScaleEngine, "datetime": qwt.QwtDateTimeScaleEngine, } AXIS_CONF_OPTIONS = ("axis", "axis", "axis", "axis") DEFAULT_ACTIVE_XAXIS = X_BOTTOM DEFAULT_ACTIVE_YAXIS = Y_LEFT AUTOSCALE_TYPES = (CurveItem, BaseImageItem, PolygonMapItem, QuiverItem) #: Number of calls to :meth:`replot` and :meth:`invalidate`, by which image items #: tell whether their rendering may have changed (see :meth:`replot_overlays`) _replot_count = 0 #: Signal emitted by plot when an IBasePlotItem object was moved #: #: Args: #: item: the moved item #: x0 (float): the old x position #: y0 (float): the old y position #: x1 (float): the new x position #: y1 (float): the new y position SIG_ITEM_MOVED = QC.Signal(object, float, float, float, float) #: Signal emitted by plot when an IBasePlotItem handle was moved #: #: Args: #: item: the moved item SIG_ITEM_HANDLE_MOVED = QC.Signal(object) #: Signal emitted by plot when an IBasePlotItem object was resized #: #: Args: #: item: the resized item #: zoom_dx (float): the zoom factor along the x axis #: zoom_dy (float): the zoom factor along the y axis SIG_ITEM_RESIZED = QC.Signal(object, float, float) #: Signal emitted by plot when an IBasePlotItem object was rotated #: #: Args: #: item: the rotated item #: angle (float): the new angle (in radians) SIG_ITEM_ROTATED = QC.Signal(object, float) #: Signal emitted by plot when a shape.Marker position changes #: #: Args: #: marker: the moved marker SIG_MARKER_CHANGED = QC.Signal(object) #: Signal emitted by plot when a shape.Axes position (or the angle) changes #: #: Args: #: axes: the moved axes SIG_AXES_CHANGED = QC.Signal(object) #: Signal emitted by plot when an annotation.AnnotatedShape position changes #: #: Args: #: annotation: the moved annotation SIG_ANNOTATION_CHANGED = QC.Signal(object) #: Signal emitted by plot when the a shape.XRangeSelection range changes #: #: Args: #: selection: the selection item #: xmin (float): the new minimum x value #: xmax (float): the new maximum x value SIG_RANGE_CHANGED = QC.Signal(object, float, float) #: Signal emitted by plot when item list has changed (item removed, added, ...) #: #: Args: #: plot: the plot SIG_ITEMS_CHANGED = QC.Signal(object) #: Signal emitted by plot when item parameters have changed (through the item's #: parameters dialog, or when setting colormap using the dedicated tool) #: #: Args: #: item: the item SIG_ITEM_PARAMETERS_CHANGED = QC.Signal(object) #: Signal emitted by plot when axis parameters have changed (through the axis #: parameters dialog) #: #: Args: #: axis_id: the axis id (0: left, 1: right, 2: bottom, 3: top) SIG_AXIS_PARAMETERS_CHANGED = QC.Signal(int) #: Signal emitted by plot when selected item has changed #: #: Args: #: plot: the plot SIG_ACTIVE_ITEM_CHANGED = QC.Signal(object) #: Signal emitted by plot when an item was deleted from the item list or using the #: delete item tool #: #: Args: #: item: the deleted item SIG_ITEM_REMOVED = QC.Signal(object) #: Signal emitted by plot when an item is selected #: #: Args: #: item: the selected item SIG_ITEM_SELECTION_CHANGED = QC.Signal(object) #: Signal emitted by plot when plot's title or any axis label has changed #: #: Args: #: plot: the plot SIG_PLOT_LABELS_CHANGED = QC.Signal(object) #: Signal emitted by plot when any plot axis direction has changed #: #: Args: #: plot: the plot #: axis_id: the axis id ("left", "right", "bottom", "top") SIG_AXIS_DIRECTION_CHANGED = QC.Signal(object, object) #: Signal emitted by plot when LUT has been changed by the user #: #: Args: #: plot: the plot SIG_LUT_CHANGED = QC.Signal(object) #: Signal emitted by plot when image mask has changed #: #: Args: #: plot: the plot SIG_MASK_CHANGED = QC.Signal(object) #: Signal emitted by cross section plot when cross section curve data has changed #: #: Args: #: plot: the plot SIG_CS_CURVE_CHANGED = QC.Signal(object) #: Signal emitted by plot when plot axis has changed, e.g. when panning/zooming #: #: Args: #: plot: the plot SIG_PLOT_AXIS_CHANGED = QC.Signal(object) EPSILON_ASPECT_RATIO = 1e-6 def __init__( self, parent: QW.QWidget | None = None, options: BasePlotOptions | dict[str, Any] | None = None, ) -> None: super().__init__(parent) if isinstance(options, dict): options = BasePlotOptions(**options) self.options = options = options if options is not None else BasePlotOptions() self.__autoscale_excluded_items: list[itf.IBasePlotItem] = [] self.autoscale_margin_percent = options.autoscale_margin_percent self._axis_autoscale_strategy: dict[ int, tuple[str, float | None, float | None] ] = {axis_id: ("auto", None, None) for axis_id in self.AXIS_IDS} self.lock_aspect_ratio = options.lock_aspect_ratio self.__autoLockAspectRatio = False if self.lock_aspect_ratio is None: if self.options.type == PlotType.IMAGE: self.lock_aspect_ratio = True elif self.options.type in (PlotType.CURVE, PlotType.MANUAL): self.lock_aspect_ratio = False else: # PlotType.AUTO self.lock_aspect_ratio = False self.__autoLockAspectRatio = True self.__autoYReverse = False if options.yreverse is None: if self.options.type == PlotType.IMAGE: options.yreverse = True elif self.options.type in (PlotType.CURVE, PlotType.MANUAL): options.yreverse = False else: # PlotType.AUTO options.yreverse = False self.__autoYReverse = True self.colormap_axis = cst.Y_RIGHT self.__autoColorBarEnabled = False if options.force_colorbar_enabled or self.options.type == PlotType.IMAGE: self.enableAxis(self.colormap_axis) self.axisWidget(self.colormap_axis).setColorBarEnabled(True) elif self.options.type == PlotType.AUTO: self.__autoColorBarEnabled = True if options.zlabel is not None: if options.ylabel is not None and not isinstance(options.ylabel, str): options.ylabel = options.ylabel[0] options.ylabel = (options.ylabel, options.zlabel) if options.zunit is not None: if options.yunit is not None and not isinstance(options.yunit, str): options.yunit = options.yunit[0] options.yunit = (options.yunit, options.zunit) self._start_autoscaled = True self.setSizePolicy(QW.QSizePolicy.Expanding, QW.QSizePolicy.Expanding) self.manager = None self.plot_id = None # id assigned by it's manager self.filter = StatefulEventFilter(self) self.items: list[itf.IBasePlotItem] = [] self.active_item: qwt.QwtPlotItem = None self.last_selected = {} # a mapping from item type to last selected item self.axes_styles = [ AxeStyleParam(_("Left")), AxeStyleParam(_("Right")), AxeStyleParam(_("Bottom")), AxeStyleParam(_("Top")), ] self._active_xaxis = self.DEFAULT_ACTIVE_XAXIS self._active_yaxis = self.DEFAULT_ACTIVE_YAXIS self.read_axes_styles(options.section, self.AXIS_CONF_OPTIONS) self.font_title = get_font(CONF, options.section, "title") canvas: qwt.QwtPlotCanvas = self.canvas() canvas.setFocusPolicy(QC.Qt.FocusPolicy.StrongFocus) canvas.setFocusIndicator(qwt.QwtPlotCanvas.ItemFocusIndicator) self.SIG_ITEM_MOVED.connect(self._move_selected_items_together) self.SIG_ITEM_RESIZED.connect(self._resize_selected_items_together) self.SIG_ITEM_ROTATED.connect(self._rotate_selected_items_together) self.legendDataChanged.connect( lambda item, _legdata: item.update_item_parameters() ) self.axes_reverse = [False] * 4 self.set_titles( title=options.title, xlabel=options.xlabel, ylabel=options.ylabel, xunit=options.xunit, yunit=options.yunit, ) self.antialiased = False antial = options.curve_antialiasing or CONF.get(options.section, "antialiasing") self.set_antialiasing(antial) self.axes_synchronised = options.axes_synchronised # Installing our own event filter: # (qwt's event filter does not fit our needs) canvas.installEventFilter(self.filter) canvas.setMouseTracking(True) self.cross_marker = Marker() self.curve_marker = Marker( label_cb=self.get_coordinates_str, constraint_cb=self.on_active_curve ) self.__marker_stay_visible = False self.cross_marker.set_style(options.section, "marker/cross") self.curve_marker.set_style(options.section, "marker/curve") self.cross_marker.setVisible(False) self.curve_marker.setVisible(False) self.cross_marker.attach(self) self.curve_marker.attach(self) # Background color self.setCanvasBackground(QC.Qt.GlobalColor.white) self.curve_pointer = False self.canvas_pointer = False # Setting up grid if options.gridparam is None: options.gridparam = GridParam(title=_("Grid"), icon="grid.svg") options.gridparam.read_config(CONF, options.section, "grid") self.grid = GridItem(options.gridparam) self.add_item(self.grid, z=-1) self.__aspect_ratio = None self.set_axis_direction("left", options.yreverse) self.set_aspect_ratio(options.aspect_ratio, options.lock_aspect_ratio) self.replot() # Workaround for the empty image widget bug # ---- Private API ---------------------------------------------------------- def __del__(self): # Sometimes, an obscure exception happens when we quit an application # because if we don't remove the eventFilter it can still be called # after the filter object has been destroyed by Python. # Note: PySide6 segfaults instead of raising RuntimeError when accessing # a deleted C++ object, so we must check validity before calling methods. if not is_qobject_valid(self): return canvas: qwt.QwtPlotCanvas = self.canvas() if canvas and is_qobject_valid(canvas) and is_qobject_valid(self.filter): try: canvas.removeEventFilter(self.filter) except (RuntimeError, ValueError): # Widget/filter may have already been deleted pass def update_color_mode(self) -> None: """Color mode was updated, update plot widget accordingly""" self.grid.gridparam.read_config(CONF, self.options.section, "grid") self.grid.gridparam.update_grid(self.grid) self.replot() def on_active_curve(self, x: float, y: float) -> tuple[float, float]: """ Callback called when the active curve is moved Args: x (float): the x position y (float): the y position """ curve: CurveItem = self.get_last_active_item(itf.ICurveItemType) if curve: x, y = curve.get_closest_coordinates(x, y) return x, y def get_coordinates_str(self, x: float, y: float) -> str: """ Return the coordinates string Args: x (float): the x position y (float): the y position Returns: str: the coordinates string """ title = _("Grid") item: TrackableItem = self.get_last_active_item(itf.ITrackableItemType) if item: return item.get_coordinates_label(x, y) return self.format_coordinate_values(x, y, "bottom", "left", title) def format_coordinate_values( self, x: float, y: float, xaxis: str | int, yaxis: str | int, title: str ) -> str: """Format coordinate values with axis-aware formatting Args: x: The x coordinate value y: The y coordinate value xaxis: The x axis name ("bottom", "top") or axis ID yaxis: The y axis name ("left", "right") or axis ID title: The title to display in the coordinate string Returns: str: Formatted coordinate string with HTML markup """ x_formatted = self.format_coordinate_value(x, xaxis) y_formatted = self.format_coordinate_value(y, yaxis) return f"<b>{title}</b><br>x = {x_formatted}<br>y = {y_formatted}" def format_coordinate_value(self, value: float, axis_id: str | int) -> str: """Format a coordinate value based on the axis scale type Args: value: The coordinate value to format axis_id: The axis name ("bottom", "top", "left", "right") or axis ID Returns: str: Formatted coordinate value """ axis_id = self.get_axis_id(axis_id) # Check if this axis is using datetime scale if self.get_axis_scale(axis_id) == "datetime": try: scale_draw: qwt.QwtDateTimeScaleDraw = self.axisScaleDraw(axis_id) dt = datetime.fromtimestamp(value) return dt.strftime(scale_draw.get_format()) except (ValueError, OSError, OverflowError): # Handle invalid timestamps, fall back to numeric display return f"{value:g}" else: # Standard numeric formatting return f"{value:g}" def set_marker_axes(self) -> None: """ Set the axes of the markers """ item: TrackableItem = self.get_last_active_item(itf.ITrackableItemType) if item: self.cross_marker.setAxes(item.xAxis(), item.yAxis()) self.curve_marker.setAxes(item.xAxis(), item.yAxis()) def do_move_marker(self, event: QG.QMouseEvent) -> None: """ Move the marker Args: event (QMouseEvent): the event """ pos = event.pos() self.set_marker_axes() if ( event.modifiers() & QC.Qt.KeyboardModifier.ShiftModifier or self.curve_pointer ): self.curve_marker.setZ(self.get_max_z() + 1) self.cross_marker.setVisible(False) self.curve_marker.setVisible(True) self.curve_marker.move_local_point_to(0, pos) self.replot() self.__marker_stay_visible = event.modifiers() & QC.Qt.ControlModifier elif ( event.modifiers() & QC.Qt.KeyboardModifier.AltModifier or self.canvas_pointer ): self.cross_marker.setZ(self.get_max_z() + 1) self.cross_marker.setVisible(True) self.curve_marker.setVisible(False) self.cross_marker.move_local_point_to(0, pos) self.replot() self.__marker_stay_visible = event.modifiers() & QC.Qt.ControlModifier else: vis_cross = self.cross_marker.isVisible() vis_curve = self.curve_marker.isVisible() self.cross_marker.setVisible(False) self.curve_marker.setVisible(self.__marker_stay_visible) if vis_cross or vis_curve: self.replot() def __get_axes_to_update( self, dx: tuple[float, float, float, float], dy: tuple[float, float, float, float], ) -> list[tuple[float, float, float, float], int]: """ Return the axes to update Args: dx (tuple[float, float, float, float]): the x axis 'state' tuple dy (tuple[float, float, float, float]): the y axis 'state' tuple Returns: list[tuple[float, float, float, float], int]: the axes to update """ if self.axes_synchronised: axes = [] for axis_name in self.AXIS_NAMES: if axis_name in ("left", "right"): d = dy else: d = dx axes.append((d, self.get_axis_id(axis_name))) return axes else: xaxis, yaxis = self.get_active_axes() return [(dx, xaxis), (dy, yaxis)] def do_pan_view( self, dx: tuple[float, float, float, float], dy: tuple[float, float, float, float], replot: bool = True, ) -> None: """ Translate the active axes according to dx, dy axis 'state' tuples Args: dx (tuple[float, float, float, float]): the x axis 'state' tuple dy (tuple[float, float, float, float]): the y axis 'state' tuple replot: if True, do a full replot else just update the axes to avoid a redraw (default: True) """ # dx and dy are the output of the "DragHandler.get_move_state" method # (see module ``plotpy.events``) auto = self.autoReplot() self.setAutoReplot(False) axes_to_update = self.__get_axes_to_update(dx, dy) for (x1, x0, _start, _width), axis_id in axes_to_update: lbound, hbound = self.get_axis_limits(axis_id) i_lbound = self.transform(axis_id, lbound) i_hbound = self.transform(axis_id, hbound) delta = x1 - x0 vmin = self.invTransform(axis_id, i_lbound - delta) vmax = self.invTransform(axis_id, i_hbound - delta) self.set_axis_limits(axis_id, vmin, vmax) self.setAutoReplot(auto) if replot: self.replot() else: self.updateAxes() # the signal MUST be emitted after replot, otherwise # we receiver won't see the new bounds (don't know why?) self.SIG_PLOT_AXIS_CHANGED.emit(self) def do_zoom_view( self, dx: tuple[float, float, float, float], dy: tuple[float, float, float, float], lock_aspect_ratio: bool | None = None, replot: bool = True, ) -> None: """ Change the scale of the active axes (zoom/dezoom) according to dx, dy axis 'state' tuples We try to keep initial pos fixed on the canvas as the scale changes Args: dx (tuple[float, float, float, float]): the x axis 'state' tuple dy (tuple[float, float, float, float]): the y axis 'state' tuple lock_aspect_ratio: if True, the aspect ratio is locked replot: if True, do a full replot else just update the axes to avoid a redraw (default: True) """ # dx and dy are the output of the "DragHandler.get_move_state" method # (see module ``plotpy.events``): # dx = (pos.x(), self.last.x(), self.start.x(), rct.width()) # dy = (pos.y(), self.last.y(), self.start.y(), rct.height()) # where: # * self.last is the mouse position seen during last event # * self.start is the first mouse position (here, this is the # coordinate of the point which is at the center of the zoomed area) # * rct is the plot rect contents # * pos is the current mouse cursor position if lock_aspect_ratio is None: lock_aspect_ratio = self.lock_aspect_ratio auto = self.autoReplot() self.setAutoReplot(False) dx = (-1,) + dx # adding direction to tuple dx dy = (1,) + dy # adding direction to tuple dy if lock_aspect_ratio: direction, x1, x0, start, width = dx F = 1 + 3 * direction * float(x1 - x0) / width axes_to_update = self.__get_axes_to_update(dx, dy) for (direction, x1, x0, start, width), axis_id in axes_to_update: lbound, hbound = self.get_axis_limits(axis_id) if not lock_aspect_ratio: F = 1 + 3 * direction * float(x1 - x0) / width if F * (hbound - lbound) == 0: continue if self.get_axis_scale(axis_id) in ("lin", "datetime"): orig = self.invTransform(axis_id, start) vmin = orig - F * (orig - lbound) vmax = orig + F * (hbound - orig) else: # log scale i_lbound = self.transform(axis_id, lbound) i_hbound = self.transform(axis_id, hbound) imin = start - F * (start - i_lbound) imax = start + F * (i_hbound - start) vmin = self.invTransform(axis_id, imin) vmax = self.invTransform(axis_id, imax) self.set_axis_limits(axis_id, vmin, vmax) self.setAutoReplot(auto) if replot: self.replot() else: self.updateAxes() # the signal MUST be emitted after replot, otherwise # we receiver won't see the new bounds (don't know why?) self.SIG_PLOT_AXIS_CHANGED.emit(self) def do_zoom_rect_view(self, start: QC.QPointF, end: QC.QPointF) -> None: """ Zoom to rectangle defined by start and end points Args: start (QPointF): the start point end (QPointF): the end point """ # TODO: Implement the case when axes are synchronised x1, y1 = start.x(), start.y() x2, y2 = end.x(), end.y() xaxis, yaxis = self.get_active_axes() active_axes = [(x1, x2, xaxis), (y1, y2, yaxis)] for h1, h2, k in active_axes: o1 = self.invTransform(k, h1) o2 = self.invTransform(k, h2) if o1 > o2: o1, o2 = o2, o1 if o1 == o2: continue if self.get_axis_direction(k): o1, o2 = o2, o1 self.setAxisScale(k, o1, o2) self.replot() self.SIG_PLOT_AXIS_CHANGED.emit(self) if self.lock_aspect_ratio: self.apply_aspect_ratio() def get_default_item(self) -> itf.IBasePlotItem | None: """Return default item, depending on plot's default item type (e.g. for a curve plot, this is a curve item type). Return nothing if there is more than one item matching the default item type. Returns: IBasePlotItem: the default item """ if self.options.type == PlotType.IMAGE: items = self.get_items(item_type=itf.IImageItemType) elif self.options.type == PlotType.CURVE: items = self.get_items(item_type=itf.ICurveItemType) else: items = [ item for item in self.items if itf.IImageItemType in item.types() or itf.ICurveItemType in item.types() ] if len(items) == 1: return items[0] # ---- QWidget API --------------------------------------------------------- def mouseDoubleClickEvent(self, event: QG.QMouseEvent) -> None: """Reimplement QWidget method""" for axis_id in self.AXIS_IDS: widget = self.axisWidget(axis_id) if widget.geometry().contains(event.pos()): self.edit_axis_parameters(axis_id) break else: qwt.QwtPlot.mouseDoubleClickEvent(self, event) # ---- QwtPlot API --------------------------------------------------------- def showEvent(self, event) -> None: """Reimplement Qwt method""" if self.lock_aspect_ratio: self._start_autoscaled = True qwt.QwtPlot.showEvent(self, event) if self._start_autoscaled: self.do_autoscale() def resizeEvent(self, event): """Reimplement Qt method to resize widget""" qwt.QwtPlot.resizeEvent(self, event) if self.lock_aspect_ratio: self.apply_aspect_ratio() self.replot() # ---- Public API ---------------------------------------------------------- def _move_selected_items_together( self, item: itf.IBasePlotItem, x0: float, y0: float, x1: float, y1: float ) -> None: """Selected items move together Args: item (IBasePlotItem): the item x0 (float): the old x position y0 (float): the old y position x1 (float): the new x position y1 (float): the new y position """ for selitem in self.get_selected_items(): if selitem is not item and selitem.can_move(): selitem.move_with_selection(x1 - x0, y1 - y0) def _resize_selected_items_together( self, item: itf.IBasePlotItem, zoom_dx: float, zoom_dy: float ) -> None: """Selected items resize together Args: item (IBasePlotItem): the item zoom_dx (float): the zoom factor along the x axis zoom_dy (float): the zoom factor along the y axis """ for selitem in self.get_selected_items(): if ( selitem is not item and selitem.can_resize() and itf.IBaseImageItem in selitem.__implements__ ): if zoom_dx != 0 or zoom_dy != 0: selitem.resize_with_selection(zoom_dx, zoom_dy) def _rotate_selected_items_together( self, item: itf.IBasePlotItem, angle: float ) -> None: """Selected items rotate together Args: item (IBasePlotItem): the item angle (float): the new angle (in radians) """ for selitem in self.get_selected_items(): if ( selitem is not item and selitem.can_rotate() and itf.IBaseImageItem in selitem.__implements__ ): selitem.rotate_with_selection(angle) def set_manager(self, manager: PlotManager, plot_id: int) -> None: """Set the associated :py:class:`.plot.manager.PlotManager` instance Args: manager (PlotManager): the manager plot_id (int): the plot id """ self.manager = manager self.plot_id = plot_id def sizeHint(self) -> QC.QSize: """Preferred size""" return QC.QSize(400, 300) def get_title(self) -> str: """Get plot title""" return str(self.title().text()) def set_title(self, title: str) -> None: """Set plot title Args: title (str): the title """ current = self.title() if current.text() == title and current.font().key() == self.font_title.key(): # Nothing changed: setting the title would lay out the plot again return text = qwt.QwtText(title) text.setFont(self.font_title) self.setTitle(text) self.SIG_PLOT_LABELS_CHANGED.emit(self) def get_show_axes_tab(self) -> bool: """Get whether the axes tab is shown in the parameters dialog Returns: bool: True if the axes tab is shown """ return self.options.show_axes_tab def set_show_axes_tab(self, show: bool) -> None: """Set whether the axes tab is shown in the parameters dialog Args: show (bool): True to show the axes tab """ self.options.show_axes_tab = show def get_axis_id(self, axis_name: str | int) -> int: """Return axis ID from axis name If axis ID is passed directly, check the ID Args: axis_name (str | int): the axis name or ID Returns: int: the axis ID """ assert axis_name in self.AXIS_NAMES or axis_name in self.AXIS_IDS return self.AXIS_NAMES.get(axis_name, axis_name) def read_axes_styles(self, section: str, options: list[str, str, str, str]) -> None: """ Read axes styles from section and options (one option for each axis in the order left, right, bottom, top) Skip axis if option is None Args: section (str): the section options (list[str, str, str, str]): the options """ for prm, option in zip(self.axes_styles, options): if option is None: continue prm.read_config(CONF, section, option) self.update_all_axes_styles() def get_axis_title(self, axis_id: int) -> str: """Get axis title Args: axis_id (int): the axis id Returns: str: the axis title """ axis_id = self.get_axis_id(axis_id) return self.axes_styles[axis_id].title def set_axis_title(self, axis_id: int, text: str) -> None: """Set axis title Args: axis_id (int): the axis id text (str): the axis title """ axis_id = self.get_axis_id(axis_id) self.axes_styles[axis_id].title = text self.update_axis_style(axis_id) def get_axis_unit(self, axis_id: int) -> str: """Get axis unit Args: axis_id (int): the axis id Returns: str: the axis unit """ axis_id = self.get_axis_id(axis_id) return self.axes_styles[axis_id].unit def set_axis_unit(self, axis_id: int, text: str) -> None: """Set axis unit Args: axis_id (int): the axis id text (str): the axis unit """ axis_id = self.get_axis_id(axis_id) self.axes_styles[axis_id].unit = text self.update_axis_style(axis_id) def get_axis_font(self, axis_id: int) -> QG.QFont: """Get axis font Args: axis_id (int): the axis id |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |