Skip to content

sanpyPlugin

Bases: QWidget

Base class for all SanPy plugins.

Provides general purpose API to build plugings including:

  • Open PyQt and Matplotlib plots
  • Set up signal/slots to communicate with the main SanPy app:

    • file is changed
    • detection is run
    • spike is selected
    • axis is changed

Users derive from this class to create new plugins.

Examples:

Run a plugin with the following code

import sys
from PyQt5 import QtCore, QtWidgets, QtGui
import sanpy
import sanpy.interface

# load sample data
path = '../../../data/19114001.abf'
ba = sanpy.bAnalysis(path)

# get presets detection parameters for 'SA Node'
_dDict = sanpy.bDetection().getDetectionDict('SA Node')

# spike detect
ba.spikeDetect(_dDict)

# create a PyQt application
app = QtWidgets.QApplication([])

# open the interface for the 'plotScatter' plugin.
sa = sanpy.interface.plugins.plotScatter(ba=ba, startStop=None)

sys.exit(app.exec_())

Attributes:

Name Type Description
signalCloseWindow pyqtSignal

Signal emitted when the plugin window is closed.

signalSelectSpikeList pyqtSignal

Signal emitted when spikes are selected in the plugin.

ba
Source code in sanpy/interface/plugins/sanpyPlugin.py
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
class sanpyPlugin(QtWidgets.QWidget):
    """Base class for all SanPy plugins.

    Provides general purpose API to build plugings including:

    - Open PyQt and Matplotlib plots
    - Set up signal/slots to communicate with the main SanPy app:

        - file is changed
        - detection is run
        - spike is selected
        - axis is changed

    Users derive from this class to create new plugins.

    Examples
    --------
    Run a plugin with the following code

    ```python
    import sys
    from PyQt5 import QtCore, QtWidgets, QtGui
    import sanpy
    import sanpy.interface

    # load sample data
    path = '../../../data/19114001.abf'
    ba = sanpy.bAnalysis(path)

    # get presets detection parameters for 'SA Node'
    _dDict = sanpy.bDetection().getDetectionDict('SA Node')

    # spike detect
    ba.spikeDetect(_dDict)

    # create a PyQt application
    app = QtWidgets.QApplication([])

    # open the interface for the 'plotScatter' plugin.
    sa = sanpy.interface.plugins.plotScatter(ba=ba, startStop=None)

    sys.exit(app.exec_())
    ```

    Attributes
    ----------
    signalCloseWindow : QtCore.pyqtSignal
        Signal emitted when the plugin window is closed.
    signalSelectSpikeList : QtCore.pyqtSignal
        Signal emitted when spikes are selected in the plugin.
    ba
    """

    signalCloseWindow = QtCore.pyqtSignal(object)
    """Emit signal on window close."""

    # signalSelectSpike = QtCore.pyqtSignal(object)
    """Emit signal on spike selection."""

    signalSelectSpikeList = QtCore.pyqtSignal(object)
    """Emit signal on spike selection."""

    signalDetect = QtCore.pyqtSignal(object)
    """Emit signal on spike selection."""

    myHumanName = "UNDEFINED-PLUGIN-NAME"
    """Each derived class needs to define this."""

    #signalSetSpikeStat = QtCore.Signal(dict)
    signalUpdateAnalysis = QtCore.Signal(dict)
    """Set stats (columns) for a list of spikes."""

    # mar 11, if True then show in menus
    showInMenu = True

    responseTypes = ResponseType
    """Defines how a plugin will response to interface changes. Includes (switchFile, analysisChange, selectSpike, setAxis)."""

    def __init__(
        self,
        ba: Optional[sanpy.bAnalysis] = None,
        # bPlugin: Optional["sanpy.interface.bPlugin"] = None,
        sanPyWindow: Optional["sanpy.interface.SanPyWindow"] = None,
        startStop: Optional[List[float]] = None,
        options=None,
        parent=None,
    ):
        """
        Parameters
        ----------
        ba : sanpy.bAnalysis
            Object representing one file.
        bPlugin : "sanpy.interface.bPlugin"
            Used in PyQt to get SanPy App and to setup signal/slot.
        startStop : list(float)
            Start and stop (s) of x-axis.
        options : dict
            Depreciated.
            Dictionary of optional plugins.
                Used by 'plot tool' to plot a pool using app analysisDir dfMaster.
        """
        super().__init__(parent)

        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        # does not work, key press gets called first?
        # self._closeAction = QtWidgets.QAction("Exit Application", self)
        # self._closeAction.setShortcut('Ctrl+W')
        # self._closeAction.triggered.connect(self.close)

        # derived classes will set this in init (see kymographPlugin)
        self._initError: bool = False

        # underlying bAnalaysis
        self._ba: sanpy.bAnalysis = ba

        # the sweep number of the sanpy.bAnalaysis
        self._sweepNumber: Union[int, str] = "All"
        self._epochNumber: Union[int, str] = "All"

        self._sanPyWindow = sanPyWindow
        # self._bPlugins: "sanpy.interface.bPlugin" = bPlugin
        # pointer to object, send signal back on close

        self.darkTheme = True
        if self.getSanPyApp() is not None:
            _useDarkStyle = self.getSanPyApp().useDarkStyle
            self.darkTheme = _useDarkStyle

        # to show as a widget
        self._showSelf: bool = True

        self._blockSlots = False

        # the start and stop secinds to display
        self._startSec: Optional[float] = None
        self._stopSec: Optional[float] = None
        if startStop is not None:
            self._startSec = startStop[0]
            self._stopSec = startStop[1]

        # keep track of spike selection
        self._selectedSpikeList: List[int] = []

        # build a dict of boolean from ResponseType enum class
        # Things to respond to like switch file, set sweep, etc
        self._responseOptions: dict = {}
        for option in self.responseTypes:
            # print(type(option))
            self._responseOptions[option.name] = True

        # mar 26 2023 was this
        # doDark = self.getSanPyApp().useDarkStyle
        # if doDark and qdarkstyle is not None:
        #     self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt5'))
        # else:
        #     self.setStyleSheet("")

        # created in mplWindow2()
        # these are causing really freaking annoying failures on GitHub !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        # self.fig : "matplotlib.figure.Figure" = None
        # self.axs : "matplotlib.axes._axes.Axes" = None
        # self.mplToolbar : "matplotlib.backends.backend_qt.NavigationToolbar2QT" = None
        self.fig = None
        self.axs = None
        self.mplToolbar = None

        self.keyIsDown = None

        self.winWidth_inches = 4  # used by mpl
        self.winHeight_inches = 4

        # connect self to main app with signals/slots
        self._installSignalSlot()

        self._mySetWindowTitle()

        # all plugin widgets always have a single QtWidgetQVBoxLayout
        # both widget and layouts can be added to this
        self._vBoxLayout = self.makeVLayout()

        # the top toolbar is always present
        self._blockComboBox: bool = False
        self._topToolbarWidget = self._buildTopToolbarWidget()

        # if ba has > 1 sweep or > 2 epochs then show top toolbar
        _showTop = False
        if self.ba is not None:
            _numEpochs = self.ba.fileLoader.numEpochs  # can be None
            _showTop = self.ba.fileLoader.numSweeps>1
            _numEpoch = (_numEpochs is not None) and _numEpochs>2
            _showTop = _showTop | _numEpoch
        self.toggleTopToobar(_showTop)  # initially hidden

        self._updateTopToolbar()
        self._vBoxLayout.addWidget(self._topToolbarWidget)

    def getStatList(self) -> dict:
        """Get all analysis results.
        """
        return self._sanPyWindow.getStatList()

    def _myClassName(self):
        return self.__class__.__name__

    def getPenColor(self) -> str:
        """Get pen color for pyqtgraph traces based on dark theme."""
        if self.darkTheme:
            return "w"
        else:
            return "k"

    def getStat(self, stat: str, getFullList : bool = False) -> list:
        """Convenianece function to get a stat from underling sanpy.bAnalysis.

        Parameters
        ----------
        stat : str
            Stat to get, corresponds to a column in sanpy.bAnalysis
        """
        return self.ba.getStat(
            stat, sweepNumber=self.sweepNumber,
            epochNumber=self.epochNumber,
            getFullList=getFullList
        )

    @property
    def responseOptions(self):
        return self._responseOptions

    def toggleTopToobar(self, visible: bool = None):
        """Toggle or set the top toolbar.

        Parameters
        ----------
        visible : bool or None
            If None then toggle, otherwise set to `visible`.
        """
        if visible is None:
            visible = not self._topToolbarWidget.isVisible()
        self._topToolbarWidget.setVisible(visible)

    def getVBoxLayout(self):
        """Get the main PyQt.QWidgets.QVBoxLayout

        Derived plugins can add to this with addWidget() and addLayout()
        """
        return self._vBoxLayout

    def getSelectedSpikes(self) -> List[int]:
        """Get the currently selected spikes."""
        return self._selectedSpikeList

    def setSelectedSpikes(self, spikes: List[int]):
        """Set the currently selected spikes.

        Parameters
        ----------
        spikes : list of int
        """
        self._selectedSpikeList = spikes

    def getHumanName(self):
        """Get the human readable name for the plugin.

        Each plugin needs a unique name specified in the static property `myHumanName`.

        This is used to display the plugin in the menus.
        """
        return self.myHumanName

    def getInitError(self):
        return self._initError

    def getWidget(self):
        """Over-ride if plugin makes its own PyQt widget.

        By default, all plugins inherit from PyQt.QWidgets.QWidget
        """
        return self

    def getShowSelf(self):
        return self._showSelf

    def setShowSelf(self, show: bool):
        self._showSelf = show

    @property
    def sweepNumber(self):
        """Get the current sweep number, can be 'All'."""
        return self._sweepNumber

    @property
    def epochNumber(self):
        """Get the current epoch number, can be 'All'."""
        return self._epochNumber

    def getSweep(self, type: str):
        """Get the raw data from a sweep.

        Parameters
        ----------
        type : str
            The sweep type from ('X', 'Y', 'C', 'filteredDeriv', 'filteredVm')
        """
        theRet = None
        type = type.upper()
        if self.ba is None:
            return theRet
        if type == "X":
            theRet = self.ba.fileLoader.sweepX
        elif type == "Y":
            theRet = self.ba.fileLoader.sweepY
        elif type == "C":
            theRet = self.ba.fileLoader.sweepC
        elif type == "filteredDeriv":
            theRet = self.ba.fileLoader.filteredDeriv
        elif type == "filteredVm":
            theRet = self.ba.fileLoader.sweepY_filtered
        else:
            logger.error(f'Did not understand type: "{type}"')

        return theRet

    @property
    def ba(self):
        """Get the current sanpy.bAnalysis object.

        Returns
        -------
        sanpy.bAnalysis
            The underlying bAnalysis object
        """
        return self._ba

    def _old_get_bPlugins(self) -> "sanpy.interface.bPlugins":
        """Get the SanPy app bPlugin object.

        Returns
        -------
        sanpy.interface.bPlugins
        """
        return self._bPlugins

    def getSanPyApp(self) -> "sanpy.interface.SanPyApp":
        """Return underlying SanPy app.

        Only exists if running in SanPy Qt Gui

        Returns
        -------
        sanpy.interface.sanpy_app
        """
        if self._sanPyWindow is not None:
            return self._sanPyWindow.getSanPyApp()

    def getSanPyWindow(self):
        return self._sanPyWindow

    def _installSignalSlot(self):
        """Set up PyQt signals/slots.

        Be sure to call _disconnectSignalSlot() on plugin destruction.
        """
        app = self.getSanPyWindow()
        if app is not None:
            # receive spike selection
            app.signalSelectSpikeList.connect(self.slot_selectSpikeList)

            # receive update analysis (both file change and detect)
            app.signalUpdateAnalysis.connect(self.slot_updateAnalysis)
            self.signalUpdateAnalysis.connect(app.slot_updateAnalysis)

            app.signalSwitchFile.connect(self.slot_switchFile)

            # recieve set sweep
            app.signalSelectSweep.connect(self.slot_setSweep)

            # recieve set x axis
            app.signalSetXAxis.connect(self.slot_set_x_axis)

            # emit when we spike detect (used in detectionParams plugin)
            self.signalDetect.connect(app.slot_detect)

            self.signalSelectSpikeList.connect(app.slot_selectSpikeList)

        sanPyWindow = self.getSanPyWindow()
        if sanPyWindow is not None:
            # emit spike selection
            # self.signalSelectSpike.connect(bPlugins.slot_selectSpike)

            # removed april 29
            #self.signalSelectSpikeList.connect(bPlugins.slot_selectSpikeList)

            # emit on close window
            self.signalCloseWindow.connect(sanPyWindow.slot_closeWindow)

        # connect to self
        # self.signalSelectSpike.connect(self.slot_selectSpike)
        # self.signalSelectSpikeList.connect(self.slot_selectSpikeList)

    def _disconnectSignalSlot(self):
        """Disconnect PyQt signal/slot on destruction."""
        app = self.getSanPyWindow()
        if app is not None:
            # receive spike selection
            # app.signalSelectSpike.disconnect(self.slot_selectSpike)
            # receive update analysis (both file change and detect)
            app.signalSwitchFile.disconnect(self.slot_switchFile)
            app.signalUpdateAnalysis.disconnect(self.slot_updateAnalysis)
            # recieve set sweep
            app.signalSelectSweep.disconnect(self.slot_setSweep)
            # recieve set x axis
            app.signalSetXAxis.disconnect(self.slot_set_x_axis)

    def toggleResponseOptions(self, thisOption: ResponseType, newValue: bool = None):
        """Set underlying responseOptions based on name of thisOption.

        Parameters
        ----------
        thisOption : ResponseType
        newValue : Optional[bool]
            If boolean then set, if None then toggle.
        """
        # logger.info(f'{thisOption} {newValue}')
        if newValue is None:
            newValue = not self.responseOptions[thisOption.name]
        self.responseOptions[thisOption.name] = newValue

    def _getResponseOption(self, thisOption: ResponseType) -> str:
        """Get the state of a plot option from responseOptions.

        Parameters
        ----------
        thisOption : ResponseType
        """
        return self.responseOptions[thisOption.name]

    def plot(self):
        """Derived class adds code to plot."""
        pass

    def replot(self):
        """Derived class adds code to replot."""
        pass

    def _old_selectSpike(self, sDict=None):
        """Derived class adds code to select spike from sDict."""
        pass

    def selectSpikeList(self):
        """Derived class adds code to select spike from sDict.

        Get selected spike list with getSelectedSpikes()
        """
        pass

    def getStartStop(self):
        """Get current start stop of interface.

        Returns:
            tuple: (start, stop) in seconds. Can be None
        """
        return self._startSec, self._stopSec

    def keyReleaseEvent(self, event):
        self.keyIsDown = None

    def keyPressEvent(self, event):
        """Handle key press events.

        On 'ctrl+c' will copy-to-clipboard.

        On 'esc' emits signalSelectSpikeList.

        Parameters
        ----------
        event : Union[QtGui.QKeyEvent, matplotlib.backend_bases.KeyEvent]
            Either a PyQt or matplotlib key press event.
        """
        isQt = isinstance(event, QtGui.QKeyEvent)
        isMpl = isinstance(event, mpl.backend_bases.KeyEvent)

        key = None
        text = None
        doCopy = False
        doClose = False
        if isQt:
            key = event.key()
            text = event.text()
            doCopy = event.matches(QtGui.QKeySequence.Copy)
            doClose = event.matches(QtGui.QKeySequence.Close)
        elif isMpl:
            # q will quit !!!!
            text = event.key
            doCopy = text in ["ctrl+c", "cmd+c"]
            doClose = text in ["ctrl+w", "cmd+w"]
            logger.info(f'mpl key: "{text}"')
        else:
            logger.warning(f"Unknown event type: {type(event)}")
            return

        self.keyIsDown = text

        if doCopy:
            self.copyToClipboard()
        elif doClose:
            self.close()
        elif key == QtCore.Qt.Key_Escape or text == "esc" or text == "escape":
            # single spike
            # sDict = {
            #     'spikeNumber': None,
            #     'doZoom': False,
            #     'ba': self.ba,

            # }
            # self.signalSelectSpike.emit(sDict)
            # spike list
            sDict = {
                "spikeList": [],
                "doZoom": False,
                "ba": self.ba,
            }
            self.signalSelectSpikeList.emit(sDict)
        elif key == QtCore.Qt.Key_T or text == "t":
            self.toggleTopToobar()
        elif text == "":
            pass

        # critical difference between mpl and qt
        if isMpl:
            return text
        else:
            # return event
            return

    def copyToClipboard(self, df=None):
        """Derived classes add code to copy plugin to clipboard."""
        if df is None:
            return

        logger.info("")
        if self.ba is None:
            return

        fileName = self.ba.fileLoader.filename
        fileName += ".csv"
        savePath = fileName
        options = QtWidgets.QFileDialog.Options()
        fileName, _ = QtWidgets.QFileDialog.getSaveFileName(
            self, "Save .csv file", savePath, "CSV Files (*.csv)", options=options
        )
        if not fileName:
            return

        logger.info(f'Saving: "{fileName}"')
        df.to_csv(fileName, index=False)

    def saveResultsFigure(self, pgPlot=None):
        """In derived, add code to save main figure to file.

        In derived, pass in a pg plot from a view and we will save it.
        """
        if pgPlot is None:
            return

        exporter = pg.exporters.ImageExporter(pgPlot)
        # print(f'exporter: {type(exporter)}')
        # print('getSupportedImageFormats:', exporter.getSupportedImageFormats())
        # set export parameters if needed

        # (width, height, antialias, background, invertvalue)
        exporter.parameters()[
            "width"
        ] = 1000  # (note this also affects height parameter)

        # ask user for file
        fileName = self.ba.fileLoader.filename
        fileName += ".png"
        savePath = fileName
        options = QtWidgets.QFileDialog.Options()
        fileName, _ = QtWidgets.QFileDialog.getSaveFileName(
            self, "Save .png file", savePath, "CSV Files (*.png)", options=options
        )
        if not fileName:
            return

        # save to file
        logger.info(f"Saving to: {fileName}")
        exporter.export(fileName)

    def bringToFront(self):
        """Bring the widget to the front."""
        if not self._showSelf:
            return

        # Qt
        self.getWidget().show()
        self.getWidget().activateWindow()

        # Matplotlib
        if self.fig is not None:
            FigureManagerQT = self.fig.canvas.manager
            FigureManagerQT.window.activateWindow()
            FigureManagerQT.window.raise_()

    def makeVLayout(self):
        """Make a PyQt QVBoxLayout."""
        vBoxLayout = QtWidgets.QVBoxLayout()
        self.setLayout(vBoxLayout)
        return vBoxLayout

    def mplWindow2(self, numRow=1, numCol=1, addToLayout: bool = True):
        """Make a matplotlib figure, canvas, and axis.

        Parameters
        ----------
        numRow : int
        numCol : int
        addToLayout : bool
            If true then add widget to main `getVBoxLayou()`.

        Returns
        -------
        self.static_canvas, self.mplToolbar

        """
        # plt.style.use('dark_background')
        if self.darkTheme:
            plt.style.use("dark_background")
        else:
            plt.rcParams.update(plt.rcParamsDefault)

        # this is dangerous, collides with self.mplWindow()
        # these are causing really freaking annoying failures on GitHub !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        # self.fig : "matplotlib.figure.Figure" = mpl.figure.Figure()
        self.fig = mpl.figure.Figure()

        # not working
        # self.fig.canvas.mpl_connect('key_press_event', self.keyPressEvent)

        self.static_canvas = backend_qt5agg.FigureCanvas(self.fig)
        self.static_canvas.setFocusPolicy(
            QtCore.Qt.ClickFocus
        )  # this is really triccky and annoying
        self.static_canvas.setFocus()
        self.fig.canvas.mpl_connect("key_press_event", self.keyPressEvent)

        self.axs = [None] * numRow  # empty list
        if numRow == 1 and numCol == 1:
            _static_ax = self.static_canvas.figure.subplots()
            self.axs = _static_ax
            # print('self.axs:', type(self.axs))
        else:
            for idx in range(numRow):
                plotNum = idx + 1
                # print('mplWindow2()', idx)
                self.axs[idx] = self.static_canvas.figure.add_subplot(
                    numRow, 1, plotNum
                )

        # does not work
        # self.static_canvas.mpl_connect('key_press_event', self.keyPressEvent)

        # pick_event assumes 'picker=5' in any .plot()
        # does this need to be a member? I think so?
        self._cid = self.static_canvas.mpl_connect("pick_event", self.spike_pick_event)

        # matplotlib plot tools toolbar (zoom, pan, save, etc)
        # from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
        self.mplToolbar = mpl.backends.backend_qt5agg.NavigationToolbar2QT(
            self.static_canvas, self.static_canvas
        )

        # layout = QtWidgets.QVBoxLayout()
        if addToLayout:
            layout = self.getVBoxLayout()
            layout.addWidget(self.static_canvas)
            layout.addWidget(self.mplToolbar)
        else:
            return self.static_canvas, self.mplToolbar

    def _mySetWindowTitle(self):
        """Set the window title based on ba."""
        if self.ba is not None:
            fileName = self.ba.fileLoader.filename
        else:
            fileName = ""
        _windowTitle = self.myHumanName + ":" + fileName

        # mpl
        if self.fig is not None:
            if self.fig.canvas.manager is not None:
                self.fig.canvas.manager.set_window_title(_windowTitle)

        # pyqt
        # self.mainWidget._mySetWindowTitle(self.windowTitle)
        self.getWidget().setWindowTitle(_windowTitle)

    def spike_pick_event(self, event):
        """Respond to user clicks in mpl plot

        Assumes plot(..., picker=5)

        Parameters
        ----------
        event : matplotlib.backend_bases.PickEvent
            PickEvent with plot indices in ind[]
        """
        if len(event.ind) < 1:
            return

        # logger.info(f'{event.ind}')

        spikeNumber = event.ind[0]

        doZoom = False
        modifiers = QtWidgets.QApplication.keyboardModifiers()
        if modifiers == QtCore.Qt.ShiftModifier:
            doZoom = True

        logger.info(
            f"got {len(event.ind)} candidates, first is spike:{spikeNumber} doZoom:{doZoom}"
        )

        # propagate a signal to parent
        # TODO: use class SpikeSelectEvent()
        sDict = {
            "spikeList": [spikeNumber],
            "doZoom": doZoom,
            "ba": self.ba,
        }
        self.signalSelectSpikeList.emit(sDict)

    def closeEvent(self, event):
        """Called when window is closed.

        Signal close event back to parent bPlugin object.

        Parameters
        ----------
        event Union[matplotlib.backend_bases.CloseEvent, PyQt5.QtGui.QCloseEvent]
            The close event from either PyQt or matplotlib
        """
        logger.info(f"  -->> emit signalCloseWindow(self)")
        self.signalCloseWindow.emit(self)

    def slot_switchFile(
        self, ba: sanpy.bAnalysis, rowDict: Optional[dict] = None, replot: bool = True
    ):
        """Respond to switch file.

        Parameters
        ----------
        rowDict : dict
            Optional, assumes rowDict has keys ['Start(s)', 'Stop(s)']
        ba : sanpy.bAnalysis
            The new bAnalysis file to switch to
        replot : bool
            If true then call replot()
        """
        if not self._getResponseOption(self.responseTypes.switchFile):
            return

        if ba is None:
            return

        # don't respond if we are already using ba
        if self._ba == ba:
            return

        self._ba = ba
        # self.fileRowDict = rowDict  # for detectionParams plugin

        # rest sweep and epoch
        self._sweepNumber = 0
        self._epochNumber = 'All'

        # reset start/stop
        startSec = None
        stopSec = None
        if rowDict is not None:
            startSec = rowDict["Start(s)"]
            stopSec = rowDict["Stop(s)"]
            if math.isnan(startSec):
                startSec = None
            if math.isnan(stopSec):
                stopSec = None
        self._startSec = startSec
        self._stopSec = stopSec

        # reset spike and spike list selection
        self._selectedSpikeList = []
        self.selectedSpike = None

        # inform derived classes of change
        # self.old_selectSpike()
        self.selectSpikeList()

        # set pyqt window title
        self._mySetWindowTitle()

        self._updateTopToolbar()

        if replot:
            self.replot()

    def slot_updateAnalysis(self, sDict : dict):
        """Respond to new spike detection.

        Parameters
        ----------
        sDict : dict
        """
        logger.info("")
        if not self._getResponseOption(self.responseTypes.analysisChange):
            return

        ba = sDict['ba']

        if ba is None:
            return

        # don't update analysis if we are showing different ba
        if self._ba != ba:
            return

        self.replot()

    def slot_setSweep(self, ba: sanpy.bAnalysis, sweepNumber: int):
        """Respond to user selecting a sweep."""

        if not self._getResponseOption(self.responseTypes.setSweep):
            return

        logger.info(f"{self._myClassName()} sweepNumber:{sweepNumber}")

        if ba is None:
            return

        # don't respond if we are showing different ba
        if self._ba != ba:
            return

        self._sweepNumber = sweepNumber

        # reset selection
        self._selectedSpikeList = []
        self.selectedSpike = None

        # update toolbar
        self._updateTopToolbar()

        self.replot()

    def slot_selectSpikeList(self, eDict: dict):
        """Respond to spike selection.

        TODO: convert dict to class spikeSelection
        """

        if self._blockSlots:
            return

        logger.info(f"{self._myClassName()} num spikes:{len(eDict['spikeList'])}")

        # don't respond if we are showing a different ba (bAnalysis)
        ba = eDict["ba"]
        if self.ba != ba:
            return

        spikeList = eDict["spikeList"]
        self._selectedSpikeList = spikeList  # [] on no selection

        self.selectSpikeList()

    def old_slot_selectSpike(self, eDict):
        """Respond to spike selection."""

        # don't respond if user/code has turned this off
        if not self._getResponseOption(self.responseTypes.selectSpike):
            return

        # don't respond if we are showing a different ba (bAnalysis)
        ba = eDict["ba"]
        if self.ba != ba:
            return

        self.selectedSpike = eDict["spikeNumber"]

        self.old_selectSpike(eDict)

    def slot_set_x_axis(self, startStopList: List[float]):
        """Respond to changes in x-axis.

        Parameters
        ----------
        startStopList : list(float)
            Two element list with [start, stop] in seconds
        """
        if not self._getResponseOption(self.responseTypes.setAxis):
            return

        # don't set axis if we are showing different ba
        app = self.getSanPyWindow()
        if app is not None:
            ba = app.get_bAnalysis()
            if self._ba != ba:
                return

        if startStopList is None:
            self._startSec = None
            self._stopSec = None
        else:
            self._startSec = startStopList[0]
            self._stopSec = startStopList[1]
        #
        # we do not always want to replot on set axis
        self.setAxis()
        self.replot()

    def setAxis(self):
        """Respond to set axis.

        Some plugins want to replot() when x-axis changes.
        """
        pass

    def _turnOffAllSignalSlot(self):
        """Make plugin not respond to any changes in interface."""
        # turn off all signal/slot
        switchFile = self.responseTypes.switchFile
        self.toggleResponseOptions(switchFile, newValue=False)

        setSweep = self.responseTypes.setSweep
        self.toggleResponseOptions(setSweep, newValue=False)

        analysisChange = self.responseTypes.analysisChange
        self.toggleResponseOptions(analysisChange, newValue=False)

        selectSpike = self.responseTypes.selectSpike
        self.toggleResponseOptions(selectSpike, newValue=False)

        setAxis = self.responseTypes.setAxis
        self.toggleResponseOptions(setAxis, newValue=False)

    def contextMenuEvent(self, event):
        """Show popup menu (QComboBox) on mouse right-click.

        This is inherited from QWidget
        and should only be modified for advanced usage.

        See `prependMenus` for plugins to add items to this contect menu.

        Parameters
        ----------
        event : QtGui.QContextMenuEvent
            Used to position popup
        """
        if self.mplToolbar is not None:
            state = self.mplToolbar.mode
            if state in ["zoom rect", "pan/zoom"]:
                # don't process right-click when toolbar is active
                return

        logger.info("")

        contextMenu = QtWidgets.QMenu(self)

        # prepend any menu from derived classes
        self.prependMenus(contextMenu)

        switchFile = contextMenu.addAction("Switch File")
        switchFile.setCheckable(True)
        switchFile.setChecked(self.responseOptions["switchFile"])

        setSweep = contextMenu.addAction("Set Sweep")
        setSweep.setCheckable(True)
        setSweep.setChecked(self.responseOptions["setSweep"])

        analysisChange = contextMenu.addAction("Analysis Change")
        analysisChange.setCheckable(True)
        analysisChange.setChecked(self.responseOptions["analysisChange"])

        selectSpike = contextMenu.addAction("Select Spike")
        selectSpike.setCheckable(True)
        selectSpike.setChecked(self.responseOptions["selectSpike"])

        axisChange = contextMenu.addAction("Axis Change")
        axisChange.setCheckable(True)
        axisChange.setChecked(self.responseOptions["setAxis"])

        contextMenu.addSeparator()
        copyTable = contextMenu.addAction("Copy Results")
        saveFigure = contextMenu.addAction("Save Figure")

        contextMenu.addSeparator()
        showTopToolbar = contextMenu.addAction("Toggle Top Toolbar")

        # contextMenu.addSeparator()
        # saveTable = contextMenu.addAction("Save Table")

        #
        # open the menu
        action = contextMenu.exec_(self.mapToGlobal(event.pos()))

        if action is None:
            # no menu selected
            return

        #
        # handle actions in derived plugins
        handled = self.handleContextMenu(action)

        if handled:
            return

        if action == switchFile:
            self.toggleResponseOptions(self.responseTypes.switchFile)
        elif action == setSweep:
            self.toggleResponseOptions(self.responseTypes.setSweep)
        elif action == analysisChange:
            self.toggleResponseOptions(self.responseTypes.analysisChange)
        elif action == selectSpike:
            self.toggleResponseOptions(self.responseTypes.selectSpike)
        elif action == axisChange:
            self.toggleResponseOptions(self.responseTypes.setAxis)
        elif action == copyTable:
            self.copyToClipboard()
        elif action == saveFigure:
            self.saveResultsFigure()
        elif action == showTopToolbar:
            self.toggleTopToobar()
        # elif action == saveTable:
        #    #self.saveToFile()
        #    logger.info('NOT IMPLEMENTED')

        elif action is not None:
            logger.warning(f'Menu action not taken "{action.text}"')

    def prependMenus(self, contextMenu: "QtWidgets.QMenu"):
        """Prepend menus to mouse right-click contect menu.

        Parameters
        ----------
        contextMenu : QtWidgets.QMenu
        """
        pass

    def handleContextMenu(self, action: "QtGui.QAction"):
        """Derived plugins need to define this to handle right-click contect menu actions.

        Only needed if `prependMenus` is used.

        Parameters
        ----------
        action : QtGui.QAction
        """
        pass

    def _updateTopToolbar(self):
        """Update the top toolbar on state change like switch file."""

        if self.ba is None:
            return

        _sweepList = self.ba.fileLoader.sweepList
        self._blockComboBox = True
        self._sweepComboBox.clear()
        self._sweepComboBox.addItem("All")
        for _sweep in _sweepList:
            self._sweepComboBox.addItem(str(_sweep))
        _enabled = len(_sweepList) > 1
        self._sweepComboBox.setEnabled(_enabled)
        if self.sweepNumber == "All":
            self._sweepComboBox.setCurrentIndex(0)
        else:
            self._sweepComboBox.setCurrentIndex(self.sweepNumber + 1)
        self._blockComboBox = False

        # minimum of 2 (never 1 or 0)
        # because of annoying pClamp default short epoch 0
        _numEpochs = self.ba.fileLoader.numEpochs
        if _numEpochs is not None:
            self._blockComboBox = True
            self._epochComboBox.clear()
            self._epochComboBox.addItem("All")
            for _epoch in range(_numEpochs):
                self._epochComboBox.addItem(str(_epoch))
            _enabled = True  # _numEpochs > 2
            self._epochComboBox.setEnabled(_enabled)
            if self.epochNumber == "All":
                self._epochComboBox.setCurrentIndex(0)
            else:
                self._epochComboBox.setCurrentIndex(self.epochNumber + 1)
            self._blockComboBox = False
        else:
            # no epochs defined
            self._epochComboBox.setEnabled(False)

        # filename = self.ba.getFileName()
        # self._fileLabel.setText(filename)

    def _on_sweep_combo_box(self, idx: int):
        """Respond to user selecting sweep combobox.

        Notes
        -----
        idx 0 is 'All', idx 1 is sweep 0
        """
        if self._blockComboBox:
            return

        idx = idx - 1  # first item is always 'All'
        if idx == -1:
            idx = "All"
        logger.info(idx)
        self._sweepNumber = idx

        if self.ba is None:
            return

        self.replot()

    def _on_epoch_combo_box(self, idx: int):
        """Respond to user selecting epoch combobox.

        Notes
        -----
        idx 0 is 'All', idx 1 is epoch 0
        """
        if self._blockComboBox:
            return

        idx = idx - 1  # first item is always 'All'
        if idx == -1:
            idx = "All"
        logger.info(idx)
        self._epochNumber = idx

        if self.ba is None:
            return

        self.replot()

    def _buildTopToolbarWidget(self) -> QtWidgets.QWidget:
        """Top toolbar to show file, toggle responses on/off, etc"""

        # TODO: Super annoying that popups come up blank if using AlignLeft ???

        #
        # first row of controls
        hLayout0 = QtWidgets.QHBoxLayout()

        # sweep popup
        aLabel = QtWidgets.QLabel("Sweeps")
        # hLayout0.addWidget(aLabel, alignment=QtCore.Qt.AlignLeft)
        hLayout0.addWidget(aLabel)
        self._sweepComboBox = QtWidgets.QComboBox()
        self._sweepComboBox.currentIndexChanged.connect(self._on_sweep_combo_box)
        # hLayout0.addWidget(self._sweepComboBox, alignment=QtCore.Qt.AlignLeft)
        hLayout0.addWidget(self._sweepComboBox)

        # hLayout0.addStretch()

        # epoch popup
        aLabel = QtWidgets.QLabel("Epochs")
        hLayout0.addWidget(aLabel, alignment=QtCore.Qt.AlignLeft)
        # hLayout0.addWidget(aLabel)
        self._epochComboBox = QtWidgets.QComboBox()
        self._epochComboBox.currentIndexChanged.connect(self._on_epoch_combo_box)
        # hLayout0.addWidget(self._epochComboBox, alignment=QtCore.Qt.AlignLeft)
        hLayout0.addWidget(self._epochComboBox)

        # update on switch file
        # self._fileLabel = QtWidgets.QLabel('File')
        # hLayout0.addWidget(self._fileLabel, alignment=QtCore.Qt.AlignLeft)

        # update for all response types (switch file, set sweep, analyze, ...)
        # self._numSpikesLabel = QtWidgets.QLabel('unknown spikes')
        # hLayout0.addWidget(self._numSpikesLabel, alignment=QtCore.Qt.AlignLeft)

        # hLayout0.addStretch()

        #
        # second row of controls
        hLayout1 = QtWidgets.QHBoxLayout()

        # a checkbox for each 'respond to' in the ResponseType enum
        for item in ResponseType:
            aCheckbox = QtWidgets.QCheckBox(item.value)
            aCheckbox.setChecked(self.responseOptions[item.name])
            aCheckbox.stateChanged.connect(
                functools.partial(self.toggleResponseOptions, item)
            )
            hLayout1.addWidget(aCheckbox, alignment=QtCore.Qt.AlignLeft)

        hLayout1.addStretch()

        # toolbar layout needs to be in a widget so it can be hidden
        _mainWidget = QtWidgets.QWidget()
        _topToolbarLayout = QtWidgets.QVBoxLayout(_mainWidget)
        _topToolbarLayout.addLayout(hLayout0)
        _topToolbarLayout.addLayout(hLayout1)

        return _mainWidget

    # def __on_checkbox_clicked(self, checkBoxName, checkBoxState):
    #     logger.info(checkBoxName, checkBoxState)

    def getWindowGeometry(self):
        """Get the current window position."""
        myRect = self.geometry()
        left = myRect.left()
        top = myRect.top()
        width = myRect.width()
        height = myRect.height()
        return left, top, width, height

Attributes¤

ba property ¤

Get the current sanpy.bAnalysis object.

Returns:

Type Description
bAnalysis

The underlying bAnalysis object

epochNumber property ¤

Get the current epoch number, can be 'All'.

myHumanName = 'UNDEFINED-PLUGIN-NAME' class-attribute instance-attribute ¤

Each derived class needs to define this.

responseTypes = ResponseType class-attribute instance-attribute ¤

Defines how a plugin will response to interface changes. Includes (switchFile, analysisChange, selectSpike, setAxis).

signalCloseWindow = QtCore.pyqtSignal(object) class-attribute instance-attribute ¤

Emit signal on window close.

signalDetect = QtCore.pyqtSignal(object) class-attribute instance-attribute ¤

Emit signal on spike selection.

signalSelectSpikeList = QtCore.pyqtSignal(object) class-attribute instance-attribute ¤

Emit signal on spike selection.

signalUpdateAnalysis = QtCore.Signal(dict) class-attribute instance-attribute ¤

Set stats (columns) for a list of spikes.

sweepNumber property ¤

Get the current sweep number, can be 'All'.

Functions¤

__init__(ba=None, sanPyWindow=None, startStop=None, options=None, parent=None) ¤

Parameters:

Name Type Description Default
ba bAnalysis

Object representing one file.

None
bPlugin bPlugin

Used in PyQt to get SanPy App and to setup signal/slot.

required
startStop list(float)

Start and stop (s) of x-axis.

None
options dict

Depreciated. Dictionary of optional plugins. Used by 'plot tool' to plot a pool using app analysisDir dfMaster.

None
Source code in sanpy/interface/plugins/sanpyPlugin.py
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
def __init__(
    self,
    ba: Optional[sanpy.bAnalysis] = None,
    # bPlugin: Optional["sanpy.interface.bPlugin"] = None,
    sanPyWindow: Optional["sanpy.interface.SanPyWindow"] = None,
    startStop: Optional[List[float]] = None,
    options=None,
    parent=None,
):
    """
    Parameters
    ----------
    ba : sanpy.bAnalysis
        Object representing one file.
    bPlugin : "sanpy.interface.bPlugin"
        Used in PyQt to get SanPy App and to setup signal/slot.
    startStop : list(float)
        Start and stop (s) of x-axis.
    options : dict
        Depreciated.
        Dictionary of optional plugins.
            Used by 'plot tool' to plot a pool using app analysisDir dfMaster.
    """
    super().__init__(parent)

    self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

    # does not work, key press gets called first?
    # self._closeAction = QtWidgets.QAction("Exit Application", self)
    # self._closeAction.setShortcut('Ctrl+W')
    # self._closeAction.triggered.connect(self.close)

    # derived classes will set this in init (see kymographPlugin)
    self._initError: bool = False

    # underlying bAnalaysis
    self._ba: sanpy.bAnalysis = ba

    # the sweep number of the sanpy.bAnalaysis
    self._sweepNumber: Union[int, str] = "All"
    self._epochNumber: Union[int, str] = "All"

    self._sanPyWindow = sanPyWindow
    # self._bPlugins: "sanpy.interface.bPlugin" = bPlugin
    # pointer to object, send signal back on close

    self.darkTheme = True
    if self.getSanPyApp() is not None:
        _useDarkStyle = self.getSanPyApp().useDarkStyle
        self.darkTheme = _useDarkStyle

    # to show as a widget
    self._showSelf: bool = True

    self._blockSlots = False

    # the start and stop secinds to display
    self._startSec: Optional[float] = None
    self._stopSec: Optional[float] = None
    if startStop is not None:
        self._startSec = startStop[0]
        self._stopSec = startStop[1]

    # keep track of spike selection
    self._selectedSpikeList: List[int] = []

    # build a dict of boolean from ResponseType enum class
    # Things to respond to like switch file, set sweep, etc
    self._responseOptions: dict = {}
    for option in self.responseTypes:
        # print(type(option))
        self._responseOptions[option.name] = True

    # mar 26 2023 was this
    # doDark = self.getSanPyApp().useDarkStyle
    # if doDark and qdarkstyle is not None:
    #     self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt5'))
    # else:
    #     self.setStyleSheet("")

    # created in mplWindow2()
    # these are causing really freaking annoying failures on GitHub !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # self.fig : "matplotlib.figure.Figure" = None
    # self.axs : "matplotlib.axes._axes.Axes" = None
    # self.mplToolbar : "matplotlib.backends.backend_qt.NavigationToolbar2QT" = None
    self.fig = None
    self.axs = None
    self.mplToolbar = None

    self.keyIsDown = None

    self.winWidth_inches = 4  # used by mpl
    self.winHeight_inches = 4

    # connect self to main app with signals/slots
    self._installSignalSlot()

    self._mySetWindowTitle()

    # all plugin widgets always have a single QtWidgetQVBoxLayout
    # both widget and layouts can be added to this
    self._vBoxLayout = self.makeVLayout()

    # the top toolbar is always present
    self._blockComboBox: bool = False
    self._topToolbarWidget = self._buildTopToolbarWidget()

    # if ba has > 1 sweep or > 2 epochs then show top toolbar
    _showTop = False
    if self.ba is not None:
        _numEpochs = self.ba.fileLoader.numEpochs  # can be None
        _showTop = self.ba.fileLoader.numSweeps>1
        _numEpoch = (_numEpochs is not None) and _numEpochs>2
        _showTop = _showTop | _numEpoch
    self.toggleTopToobar(_showTop)  # initially hidden

    self._updateTopToolbar()
    self._vBoxLayout.addWidget(self._topToolbarWidget)

bringToFront() ¤

Bring the widget to the front.

Source code in sanpy/interface/plugins/sanpyPlugin.py
646
647
648
649
650
651
652
653
654
655
656
657
658
659
def bringToFront(self):
    """Bring the widget to the front."""
    if not self._showSelf:
        return

    # Qt
    self.getWidget().show()
    self.getWidget().activateWindow()

    # Matplotlib
    if self.fig is not None:
        FigureManagerQT = self.fig.canvas.manager
        FigureManagerQT.window.activateWindow()
        FigureManagerQT.window.raise_()

closeEvent(event) ¤

Called when window is closed.

Signal close event back to parent bPlugin object.

Parameters:

Name Type Description Default
event

The close event from either PyQt or matplotlib

required
Source code in sanpy/interface/plugins/sanpyPlugin.py
789
790
791
792
793
794
795
796
797
798
799
800
def closeEvent(self, event):
    """Called when window is closed.

    Signal close event back to parent bPlugin object.

    Parameters
    ----------
    event Union[matplotlib.backend_bases.CloseEvent, PyQt5.QtGui.QCloseEvent]
        The close event from either PyQt or matplotlib
    """
    logger.info(f"  -->> emit signalCloseWindow(self)")
    self.signalCloseWindow.emit(self)

contextMenuEvent(event) ¤

Show popup menu (QComboBox) on mouse right-click.

This is inherited from QWidget and should only be modified for advanced usage.

See prependMenus for plugins to add items to this contect menu.

Parameters:

Name Type Description Default
event QContextMenuEvent

Used to position popup

required
Source code in sanpy/interface/plugins/sanpyPlugin.py
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
def contextMenuEvent(self, event):
    """Show popup menu (QComboBox) on mouse right-click.

    This is inherited from QWidget
    and should only be modified for advanced usage.

    See `prependMenus` for plugins to add items to this contect menu.

    Parameters
    ----------
    event : QtGui.QContextMenuEvent
        Used to position popup
    """
    if self.mplToolbar is not None:
        state = self.mplToolbar.mode
        if state in ["zoom rect", "pan/zoom"]:
            # don't process right-click when toolbar is active
            return

    logger.info("")

    contextMenu = QtWidgets.QMenu(self)

    # prepend any menu from derived classes
    self.prependMenus(contextMenu)

    switchFile = contextMenu.addAction("Switch File")
    switchFile.setCheckable(True)
    switchFile.setChecked(self.responseOptions["switchFile"])

    setSweep = contextMenu.addAction("Set Sweep")
    setSweep.setCheckable(True)
    setSweep.setChecked(self.responseOptions["setSweep"])

    analysisChange = contextMenu.addAction("Analysis Change")
    analysisChange.setCheckable(True)
    analysisChange.setChecked(self.responseOptions["analysisChange"])

    selectSpike = contextMenu.addAction("Select Spike")
    selectSpike.setCheckable(True)
    selectSpike.setChecked(self.responseOptions["selectSpike"])

    axisChange = contextMenu.addAction("Axis Change")
    axisChange.setCheckable(True)
    axisChange.setChecked(self.responseOptions["setAxis"])

    contextMenu.addSeparator()
    copyTable = contextMenu.addAction("Copy Results")
    saveFigure = contextMenu.addAction("Save Figure")

    contextMenu.addSeparator()
    showTopToolbar = contextMenu.addAction("Toggle Top Toolbar")

    # contextMenu.addSeparator()
    # saveTable = contextMenu.addAction("Save Table")

    #
    # open the menu
    action = contextMenu.exec_(self.mapToGlobal(event.pos()))

    if action is None:
        # no menu selected
        return

    #
    # handle actions in derived plugins
    handled = self.handleContextMenu(action)

    if handled:
        return

    if action == switchFile:
        self.toggleResponseOptions(self.responseTypes.switchFile)
    elif action == setSweep:
        self.toggleResponseOptions(self.responseTypes.setSweep)
    elif action == analysisChange:
        self.toggleResponseOptions(self.responseTypes.analysisChange)
    elif action == selectSpike:
        self.toggleResponseOptions(self.responseTypes.selectSpike)
    elif action == axisChange:
        self.toggleResponseOptions(self.responseTypes.setAxis)
    elif action == copyTable:
        self.copyToClipboard()
    elif action == saveFigure:
        self.saveResultsFigure()
    elif action == showTopToolbar:
        self.toggleTopToobar()
    # elif action == saveTable:
    #    #self.saveToFile()
    #    logger.info('NOT IMPLEMENTED')

    elif action is not None:
        logger.warning(f'Menu action not taken "{action.text}"')

copyToClipboard(df=None) ¤

Derived classes add code to copy plugin to clipboard.

Source code in sanpy/interface/plugins/sanpyPlugin.py
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def copyToClipboard(self, df=None):
    """Derived classes add code to copy plugin to clipboard."""
    if df is None:
        return

    logger.info("")
    if self.ba is None:
        return

    fileName = self.ba.fileLoader.filename
    fileName += ".csv"
    savePath = fileName
    options = QtWidgets.QFileDialog.Options()
    fileName, _ = QtWidgets.QFileDialog.getSaveFileName(
        self, "Save .csv file", savePath, "CSV Files (*.csv)", options=options
    )
    if not fileName:
        return

    logger.info(f'Saving: "{fileName}"')
    df.to_csv(fileName, index=False)

getHumanName() ¤

Get the human readable name for the plugin.

Each plugin needs a unique name specified in the static property myHumanName.

This is used to display the plugin in the menus.

Source code in sanpy/interface/plugins/sanpyPlugin.py
317
318
319
320
321
322
323
324
def getHumanName(self):
    """Get the human readable name for the plugin.

    Each plugin needs a unique name specified in the static property `myHumanName`.

    This is used to display the plugin in the menus.
    """
    return self.myHumanName

getPenColor() ¤

Get pen color for pyqtgraph traces based on dark theme.

Source code in sanpy/interface/plugins/sanpyPlugin.py
260
261
262
263
264
265
def getPenColor(self) -> str:
    """Get pen color for pyqtgraph traces based on dark theme."""
    if self.darkTheme:
        return "w"
    else:
        return "k"

getSanPyApp() ¤

Return underlying SanPy app.

Only exists if running in SanPy Qt Gui

Returns:

Type Description
sanpy_app
Source code in sanpy/interface/plugins/sanpyPlugin.py
399
400
401
402
403
404
405
406
407
408
409
def getSanPyApp(self) -> "sanpy.interface.SanPyApp":
    """Return underlying SanPy app.

    Only exists if running in SanPy Qt Gui

    Returns
    -------
    sanpy.interface.sanpy_app
    """
    if self._sanPyWindow is not None:
        return self._sanPyWindow.getSanPyApp()

getSelectedSpikes() ¤

Get the currently selected spikes.

Source code in sanpy/interface/plugins/sanpyPlugin.py
304
305
306
def getSelectedSpikes(self) -> List[int]:
    """Get the currently selected spikes."""
    return self._selectedSpikeList

getStartStop() ¤

Get current start stop of interface.

Returns: tuple: (start, stop) in seconds. Can be None

Source code in sanpy/interface/plugins/sanpyPlugin.py
512
513
514
515
516
517
518
def getStartStop(self):
    """Get current start stop of interface.

    Returns:
        tuple: (start, stop) in seconds. Can be None
    """
    return self._startSec, self._stopSec

getStat(stat, getFullList=False) ¤

Convenianece function to get a stat from underling sanpy.bAnalysis.

Parameters:

Name Type Description Default
stat str

Stat to get, corresponds to a column in sanpy.bAnalysis

required
Source code in sanpy/interface/plugins/sanpyPlugin.py
267
268
269
270
271
272
273
274
275
276
277
278
279
def getStat(self, stat: str, getFullList : bool = False) -> list:
    """Convenianece function to get a stat from underling sanpy.bAnalysis.

    Parameters
    ----------
    stat : str
        Stat to get, corresponds to a column in sanpy.bAnalysis
    """
    return self.ba.getStat(
        stat, sweepNumber=self.sweepNumber,
        epochNumber=self.epochNumber,
        getFullList=getFullList
    )

getStatList() ¤

Get all analysis results.

Source code in sanpy/interface/plugins/sanpyPlugin.py
252
253
254
255
def getStatList(self) -> dict:
    """Get all analysis results.
    """
    return self._sanPyWindow.getStatList()

getSweep(type) ¤

Get the raw data from a sweep.

Parameters:

Name Type Description Default
type str

The sweep type from ('X', 'Y', 'C', 'filteredDeriv', 'filteredVm')

required
Source code in sanpy/interface/plugins/sanpyPlugin.py
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
def getSweep(self, type: str):
    """Get the raw data from a sweep.

    Parameters
    ----------
    type : str
        The sweep type from ('X', 'Y', 'C', 'filteredDeriv', 'filteredVm')
    """
    theRet = None
    type = type.upper()
    if self.ba is None:
        return theRet
    if type == "X":
        theRet = self.ba.fileLoader.sweepX
    elif type == "Y":
        theRet = self.ba.fileLoader.sweepY
    elif type == "C":
        theRet = self.ba.fileLoader.sweepC
    elif type == "filteredDeriv":
        theRet = self.ba.fileLoader.filteredDeriv
    elif type == "filteredVm":
        theRet = self.ba.fileLoader.sweepY_filtered
    else:
        logger.error(f'Did not understand type: "{type}"')

    return theRet

getVBoxLayout() ¤

Get the main PyQt.QWidgets.QVBoxLayout

Derived plugins can add to this with addWidget() and addLayout()

Source code in sanpy/interface/plugins/sanpyPlugin.py
297
298
299
300
301
302
def getVBoxLayout(self):
    """Get the main PyQt.QWidgets.QVBoxLayout

    Derived plugins can add to this with addWidget() and addLayout()
    """
    return self._vBoxLayout

getWidget() ¤

Over-ride if plugin makes its own PyQt widget.

By default, all plugins inherit from PyQt.QWidgets.QWidget

Source code in sanpy/interface/plugins/sanpyPlugin.py
329
330
331
332
333
334
def getWidget(self):
    """Over-ride if plugin makes its own PyQt widget.

    By default, all plugins inherit from PyQt.QWidgets.QWidget
    """
    return self

getWindowGeometry() ¤

Get the current window position.

Source code in sanpy/interface/plugins/sanpyPlugin.py
1265
1266
1267
1268
1269
1270
1271
1272
def getWindowGeometry(self):
    """Get the current window position."""
    myRect = self.geometry()
    left = myRect.left()
    top = myRect.top()
    width = myRect.width()
    height = myRect.height()
    return left, top, width, height

handleContextMenu(action) ¤

Derived plugins need to define this to handle right-click contect menu actions.

Only needed if prependMenus is used.

Parameters:

Name Type Description Default
action QAction
required
Source code in sanpy/interface/plugins/sanpyPlugin.py
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
def handleContextMenu(self, action: "QtGui.QAction"):
    """Derived plugins need to define this to handle right-click contect menu actions.

    Only needed if `prependMenus` is used.

    Parameters
    ----------
    action : QtGui.QAction
    """
    pass

keyPressEvent(event) ¤

Handle key press events.

On 'ctrl+c' will copy-to-clipboard.

On 'esc' emits signalSelectSpikeList.

Parameters:

Name Type Description Default
event Union[QKeyEvent, KeyEvent]

Either a PyQt or matplotlib key press event.

required
Source code in sanpy/interface/plugins/sanpyPlugin.py
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
def keyPressEvent(self, event):
    """Handle key press events.

    On 'ctrl+c' will copy-to-clipboard.

    On 'esc' emits signalSelectSpikeList.

    Parameters
    ----------
    event : Union[QtGui.QKeyEvent, matplotlib.backend_bases.KeyEvent]
        Either a PyQt or matplotlib key press event.
    """
    isQt = isinstance(event, QtGui.QKeyEvent)
    isMpl = isinstance(event, mpl.backend_bases.KeyEvent)

    key = None
    text = None
    doCopy = False
    doClose = False
    if isQt:
        key = event.key()
        text = event.text()
        doCopy = event.matches(QtGui.QKeySequence.Copy)
        doClose = event.matches(QtGui.QKeySequence.Close)
    elif isMpl:
        # q will quit !!!!
        text = event.key
        doCopy = text in ["ctrl+c", "cmd+c"]
        doClose = text in ["ctrl+w", "cmd+w"]
        logger.info(f'mpl key: "{text}"')
    else:
        logger.warning(f"Unknown event type: {type(event)}")
        return

    self.keyIsDown = text

    if doCopy:
        self.copyToClipboard()
    elif doClose:
        self.close()
    elif key == QtCore.Qt.Key_Escape or text == "esc" or text == "escape":
        # single spike
        # sDict = {
        #     'spikeNumber': None,
        #     'doZoom': False,
        #     'ba': self.ba,

        # }
        # self.signalSelectSpike.emit(sDict)
        # spike list
        sDict = {
            "spikeList": [],
            "doZoom": False,
            "ba": self.ba,
        }
        self.signalSelectSpikeList.emit(sDict)
    elif key == QtCore.Qt.Key_T or text == "t":
        self.toggleTopToobar()
    elif text == "":
        pass

    # critical difference between mpl and qt
    if isMpl:
        return text
    else:
        # return event
        return

makeVLayout() ¤

Make a PyQt QVBoxLayout.

Source code in sanpy/interface/plugins/sanpyPlugin.py
661
662
663
664
665
def makeVLayout(self):
    """Make a PyQt QVBoxLayout."""
    vBoxLayout = QtWidgets.QVBoxLayout()
    self.setLayout(vBoxLayout)
    return vBoxLayout

mplWindow2(numRow=1, numCol=1, addToLayout=True) ¤

Make a matplotlib figure, canvas, and axis.

Parameters:

Name Type Description Default
numRow int
1
numCol int
1
addToLayout bool

If true then add widget to main getVBoxLayou().

True

Returns:

Type Description
(static_canvas, mplToolbar)
Source code in sanpy/interface/plugins/sanpyPlugin.py
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
def mplWindow2(self, numRow=1, numCol=1, addToLayout: bool = True):
    """Make a matplotlib figure, canvas, and axis.

    Parameters
    ----------
    numRow : int
    numCol : int
    addToLayout : bool
        If true then add widget to main `getVBoxLayou()`.

    Returns
    -------
    self.static_canvas, self.mplToolbar

    """
    # plt.style.use('dark_background')
    if self.darkTheme:
        plt.style.use("dark_background")
    else:
        plt.rcParams.update(plt.rcParamsDefault)

    # this is dangerous, collides with self.mplWindow()
    # these are causing really freaking annoying failures on GitHub !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # self.fig : "matplotlib.figure.Figure" = mpl.figure.Figure()
    self.fig = mpl.figure.Figure()

    # not working
    # self.fig.canvas.mpl_connect('key_press_event', self.keyPressEvent)

    self.static_canvas = backend_qt5agg.FigureCanvas(self.fig)
    self.static_canvas.setFocusPolicy(
        QtCore.Qt.ClickFocus
    )  # this is really triccky and annoying
    self.static_canvas.setFocus()
    self.fig.canvas.mpl_connect("key_press_event", self.keyPressEvent)

    self.axs = [None] * numRow  # empty list
    if numRow == 1 and numCol == 1:
        _static_ax = self.static_canvas.figure.subplots()
        self.axs = _static_ax
        # print('self.axs:', type(self.axs))
    else:
        for idx in range(numRow):
            plotNum = idx + 1
            # print('mplWindow2()', idx)
            self.axs[idx] = self.static_canvas.figure.add_subplot(
                numRow, 1, plotNum
            )

    # does not work
    # self.static_canvas.mpl_connect('key_press_event', self.keyPressEvent)

    # pick_event assumes 'picker=5' in any .plot()
    # does this need to be a member? I think so?
    self._cid = self.static_canvas.mpl_connect("pick_event", self.spike_pick_event)

    # matplotlib plot tools toolbar (zoom, pan, save, etc)
    # from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
    self.mplToolbar = mpl.backends.backend_qt5agg.NavigationToolbar2QT(
        self.static_canvas, self.static_canvas
    )

    # layout = QtWidgets.QVBoxLayout()
    if addToLayout:
        layout = self.getVBoxLayout()
        layout.addWidget(self.static_canvas)
        layout.addWidget(self.mplToolbar)
    else:
        return self.static_canvas, self.mplToolbar

old_slot_selectSpike(eDict) ¤

Respond to spike selection.

Source code in sanpy/interface/plugins/sanpyPlugin.py
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
def old_slot_selectSpike(self, eDict):
    """Respond to spike selection."""

    # don't respond if user/code has turned this off
    if not self._getResponseOption(self.responseTypes.selectSpike):
        return

    # don't respond if we are showing a different ba (bAnalysis)
    ba = eDict["ba"]
    if self.ba != ba:
        return

    self.selectedSpike = eDict["spikeNumber"]

    self.old_selectSpike(eDict)

plot() ¤

Derived class adds code to plot.

Source code in sanpy/interface/plugins/sanpyPlugin.py
493
494
495
def plot(self):
    """Derived class adds code to plot."""
    pass

prependMenus(contextMenu) ¤

Prepend menus to mouse right-click contect menu.

Parameters:

Name Type Description Default
contextMenu QMenu
required
Source code in sanpy/interface/plugins/sanpyPlugin.py
1095
1096
1097
1098
1099
1100
1101
1102
def prependMenus(self, contextMenu: "QtWidgets.QMenu"):
    """Prepend menus to mouse right-click contect menu.

    Parameters
    ----------
    contextMenu : QtWidgets.QMenu
    """
    pass

replot() ¤

Derived class adds code to replot.

Source code in sanpy/interface/plugins/sanpyPlugin.py
497
498
499
def replot(self):
    """Derived class adds code to replot."""
    pass

saveResultsFigure(pgPlot=None) ¤

In derived, add code to save main figure to file.

In derived, pass in a pg plot from a view and we will save it.

Source code in sanpy/interface/plugins/sanpyPlugin.py
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
def saveResultsFigure(self, pgPlot=None):
    """In derived, add code to save main figure to file.

    In derived, pass in a pg plot from a view and we will save it.
    """
    if pgPlot is None:
        return

    exporter = pg.exporters.ImageExporter(pgPlot)
    # print(f'exporter: {type(exporter)}')
    # print('getSupportedImageFormats:', exporter.getSupportedImageFormats())
    # set export parameters if needed

    # (width, height, antialias, background, invertvalue)
    exporter.parameters()[
        "width"
    ] = 1000  # (note this also affects height parameter)

    # ask user for file
    fileName = self.ba.fileLoader.filename
    fileName += ".png"
    savePath = fileName
    options = QtWidgets.QFileDialog.Options()
    fileName, _ = QtWidgets.QFileDialog.getSaveFileName(
        self, "Save .png file", savePath, "CSV Files (*.png)", options=options
    )
    if not fileName:
        return

    # save to file
    logger.info(f"Saving to: {fileName}")
    exporter.export(fileName)

selectSpikeList() ¤

Derived class adds code to select spike from sDict.

Get selected spike list with getSelectedSpikes()

Source code in sanpy/interface/plugins/sanpyPlugin.py
505
506
507
508
509
510
def selectSpikeList(self):
    """Derived class adds code to select spike from sDict.

    Get selected spike list with getSelectedSpikes()
    """
    pass

setAxis() ¤

Respond to set axis.

Some plugins want to replot() when x-axis changes.

Source code in sanpy/interface/plugins/sanpyPlugin.py
976
977
978
979
980
981
def setAxis(self):
    """Respond to set axis.

    Some plugins want to replot() when x-axis changes.
    """
    pass

setSelectedSpikes(spikes) ¤

Set the currently selected spikes.

Parameters:

Name Type Description Default
spikes list of int
required
Source code in sanpy/interface/plugins/sanpyPlugin.py
308
309
310
311
312
313
314
315
def setSelectedSpikes(self, spikes: List[int]):
    """Set the currently selected spikes.

    Parameters
    ----------
    spikes : list of int
    """
    self._selectedSpikeList = spikes

slot_selectSpikeList(eDict) ¤

Respond to spike selection.

TODO: convert dict to class spikeSelection

Source code in sanpy/interface/plugins/sanpyPlugin.py
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
def slot_selectSpikeList(self, eDict: dict):
    """Respond to spike selection.

    TODO: convert dict to class spikeSelection
    """

    if self._blockSlots:
        return

    logger.info(f"{self._myClassName()} num spikes:{len(eDict['spikeList'])}")

    # don't respond if we are showing a different ba (bAnalysis)
    ba = eDict["ba"]
    if self.ba != ba:
        return

    spikeList = eDict["spikeList"]
    self._selectedSpikeList = spikeList  # [] on no selection

    self.selectSpikeList()

slot_setSweep(ba, sweepNumber) ¤

Respond to user selecting a sweep.

Source code in sanpy/interface/plugins/sanpyPlugin.py
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
def slot_setSweep(self, ba: sanpy.bAnalysis, sweepNumber: int):
    """Respond to user selecting a sweep."""

    if not self._getResponseOption(self.responseTypes.setSweep):
        return

    logger.info(f"{self._myClassName()} sweepNumber:{sweepNumber}")

    if ba is None:
        return

    # don't respond if we are showing different ba
    if self._ba != ba:
        return

    self._sweepNumber = sweepNumber

    # reset selection
    self._selectedSpikeList = []
    self.selectedSpike = None

    # update toolbar
    self._updateTopToolbar()

    self.replot()

slot_set_x_axis(startStopList) ¤

Respond to changes in x-axis.

Parameters:

Name Type Description Default
startStopList list(float)

Two element list with [start, stop] in seconds

required
Source code in sanpy/interface/plugins/sanpyPlugin.py
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
def slot_set_x_axis(self, startStopList: List[float]):
    """Respond to changes in x-axis.

    Parameters
    ----------
    startStopList : list(float)
        Two element list with [start, stop] in seconds
    """
    if not self._getResponseOption(self.responseTypes.setAxis):
        return

    # don't set axis if we are showing different ba
    app = self.getSanPyWindow()
    if app is not None:
        ba = app.get_bAnalysis()
        if self._ba != ba:
            return

    if startStopList is None:
        self._startSec = None
        self._stopSec = None
    else:
        self._startSec = startStopList[0]
        self._stopSec = startStopList[1]
    #
    # we do not always want to replot on set axis
    self.setAxis()
    self.replot()

slot_switchFile(ba, rowDict=None, replot=True) ¤

Respond to switch file.

Parameters:

Name Type Description Default
rowDict dict

Optional, assumes rowDict has keys ['Start(s)', 'Stop(s)']

None
ba bAnalysis

The new bAnalysis file to switch to

required
replot bool

If true then call replot()

True
Source code in sanpy/interface/plugins/sanpyPlugin.py
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
def slot_switchFile(
    self, ba: sanpy.bAnalysis, rowDict: Optional[dict] = None, replot: bool = True
):
    """Respond to switch file.

    Parameters
    ----------
    rowDict : dict
        Optional, assumes rowDict has keys ['Start(s)', 'Stop(s)']
    ba : sanpy.bAnalysis
        The new bAnalysis file to switch to
    replot : bool
        If true then call replot()
    """
    if not self._getResponseOption(self.responseTypes.switchFile):
        return

    if ba is None:
        return

    # don't respond if we are already using ba
    if self._ba == ba:
        return

    self._ba = ba
    # self.fileRowDict = rowDict  # for detectionParams plugin

    # rest sweep and epoch
    self._sweepNumber = 0
    self._epochNumber = 'All'

    # reset start/stop
    startSec = None
    stopSec = None
    if rowDict is not None:
        startSec = rowDict["Start(s)"]
        stopSec = rowDict["Stop(s)"]
        if math.isnan(startSec):
            startSec = None
        if math.isnan(stopSec):
            stopSec = None
    self._startSec = startSec
    self._stopSec = stopSec

    # reset spike and spike list selection
    self._selectedSpikeList = []
    self.selectedSpike = None

    # inform derived classes of change
    # self.old_selectSpike()
    self.selectSpikeList()

    # set pyqt window title
    self._mySetWindowTitle()

    self._updateTopToolbar()

    if replot:
        self.replot()

slot_updateAnalysis(sDict) ¤

Respond to new spike detection.

Parameters:

Name Type Description Default
sDict dict
required
Source code in sanpy/interface/plugins/sanpyPlugin.py
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
def slot_updateAnalysis(self, sDict : dict):
    """Respond to new spike detection.

    Parameters
    ----------
    sDict : dict
    """
    logger.info("")
    if not self._getResponseOption(self.responseTypes.analysisChange):
        return

    ba = sDict['ba']

    if ba is None:
        return

    # don't update analysis if we are showing different ba
    if self._ba != ba:
        return

    self.replot()

spike_pick_event(event) ¤

Respond to user clicks in mpl plot

Assumes plot(..., picker=5)

Parameters:

Name Type Description Default
event PickEvent

PickEvent with plot indices in ind[]

required
Source code in sanpy/interface/plugins/sanpyPlugin.py
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
def spike_pick_event(self, event):
    """Respond to user clicks in mpl plot

    Assumes plot(..., picker=5)

    Parameters
    ----------
    event : matplotlib.backend_bases.PickEvent
        PickEvent with plot indices in ind[]
    """
    if len(event.ind) < 1:
        return

    # logger.info(f'{event.ind}')

    spikeNumber = event.ind[0]

    doZoom = False
    modifiers = QtWidgets.QApplication.keyboardModifiers()
    if modifiers == QtCore.Qt.ShiftModifier:
        doZoom = True

    logger.info(
        f"got {len(event.ind)} candidates, first is spike:{spikeNumber} doZoom:{doZoom}"
    )

    # propagate a signal to parent
    # TODO: use class SpikeSelectEvent()
    sDict = {
        "spikeList": [spikeNumber],
        "doZoom": doZoom,
        "ba": self.ba,
    }
    self.signalSelectSpikeList.emit(sDict)

toggleResponseOptions(thisOption, newValue=None) ¤

Set underlying responseOptions based on name of thisOption.

Parameters:

Name Type Description Default
thisOption ResponseType
required
newValue Optional[bool]

If boolean then set, if None then toggle.

None
Source code in sanpy/interface/plugins/sanpyPlugin.py
470
471
472
473
474
475
476
477
478
479
480
481
482
def toggleResponseOptions(self, thisOption: ResponseType, newValue: bool = None):
    """Set underlying responseOptions based on name of thisOption.

    Parameters
    ----------
    thisOption : ResponseType
    newValue : Optional[bool]
        If boolean then set, if None then toggle.
    """
    # logger.info(f'{thisOption} {newValue}')
    if newValue is None:
        newValue = not self.responseOptions[thisOption.name]
    self.responseOptions[thisOption.name] = newValue

toggleTopToobar(visible=None) ¤

Toggle or set the top toolbar.

Parameters:

Name Type Description Default
visible bool or None

If None then toggle, otherwise set to visible.

None
Source code in sanpy/interface/plugins/sanpyPlugin.py
285
286
287
288
289
290
291
292
293
294
295
def toggleTopToobar(self, visible: bool = None):
    """Toggle or set the top toolbar.

    Parameters
    ----------
    visible : bool or None
        If None then toggle, otherwise set to `visible`.
    """
    if visible is None:
        visible = not self._topToolbarWidget.isVisible()
    self._topToolbarWidget.setVisible(visible)

Bases: Enum

Enum representing the types of events a Plugin will respond to.

Source code in sanpy/interface/plugins/sanpyPlugin.py
25
26
27
28
29
30
31
32
class ResponseType(enum.Enum):
    """Enum representing the types of events a Plugin will respond to."""

    switchFile = "Switch File"
    setSweep = "Set Sweep"
    analysisChange = "Analysis Change"
    selectSpike = "Select Spike"
    setAxis = "Set Axis"
All material is Copyright 2011-2023 Robert H. Cudmore