Skip to content

bAnalysisUtil

Source code in sanpy/bAnalysisUtil.py
 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
class bAnalysisUtil:
    def __init__(self):

        # built in analysis results
        self._statList = self._builStatList()
        self._buildUserStatList()

        self.configDict = self.configDefault()

        # load preferences
        if getattr(sys, "frozen", False):
            # we are running in a bundle (frozen)
            bundle_dir = sys._MEIPASS
        else:
            # we are running in a normal Python environment
            bundle_dir = os.path.dirname(os.path.abspath(__file__))
        self.configFilePath = os.path.join(bundle_dir, "AnalysisApp_Config.json")

        self.configLoad()

        # self.top = None  # used by tkinter interface

    def getStatList(self):
        return self._statList

    def getHumanFromStat(self, statName):
        """Get human readable stat name from backend stat name."""
        ret = ""
        for k, v in self._statList.items():
            name = v["name"]
            if name == statName:
                ret = k
                break
        if ret == "":
            logger.warning(f'Did not find "{statName}"')
        #
        return ret

    def getStatFromHuman(self, humanStat):
        """Get backend stat name from human readable stat."""
        ret = ""
        try:
            ret = self._statList[humanStat]["name"]
        except KeyError as e:
            logger.warning(f'Bad key "{humanStat}"')
        #
        return ret

    # @staticmethod
    # def _old_getStatList():
    #     """20210929 working on extending stat list with sanpy.userAnalysis

    #     We first define stat list in this function as statList
    #     We then ask for user defined stat functions static members xxx
    #     """
    #     coreStatList = statList  # from global withing function

    #     # userStatList = sanpy.userAnalysis.findUserAnalysis()
    #     # userStatList = sanpy.userAnalysis.baseUserAnalysis.findUserAnalysis()
    #     # userStatList = findUserAnalysis()

    #     #logger.warning(f"need to reactivate getting user stats")

    #     """
    #     Each entry in statList looks like:

    #     statList['Spike Time (s)'] = {
    #         'name': 'thresholdSec',
    #         'units': 's',
    #         'yStat': 'thresholdVal',
    #         'yStatUnits': 'mV',
    #         'xStat': 'thresholdSec',
    #         'xStatUnits': 's'
    #         }
    #     """
    #     userStatList: List[
    #         dict
    #     ] = sanpy.user_analysis.baseUserAnalysis.findUserAnalysisStats()
    #     for userStatDict in userStatList:
    #         for k, v in userStatDict.items():
    #             if k in coreStatList.keys():
    #                 logger.error(
    #                     f'user analysis key "{k}" already exists in core stat List'
    #                 )
    #             else:
    #                 # name = v['name']
    #                 # coreStatList[k] = {}
    #                 # coreStatList[k][name] = name
    #                 coreStatList[k] = v

    #     return coreStatList

    #     # 20220630, was this
    #     userStatList = sanpy.user_analysis.baseUserAnalysis.findUserAnalysis()

    #     for k, v in userStatList.items():
    #         # check if key exists !!!
    #         if k in coreStatList.keys():
    #             logger.error(
    #                 f'user analysis key {"k"} already exists in core stat List'
    #             )
    #         else:
    #             name = v["name"]
    #             coreStatList[k] = {}
    #             coreStatList[k][name] = name

    #     return coreStatList

    """
    @staticmethod
    def humanStatToBackend(theStat):
        return ''
    """

    def _buildUserStatList(self):
        """Append user stats to self._statList
        """
        userStatList: List[
            dict
        ] = sanpy.user_analysis.baseUserAnalysis.findUserAnalysisStats()
        for userStatDict in userStatList:
            for k, v in userStatDict.items():
                if k in self._statList.keys():
                    logger.error(
                        f'user analysis key "{k}" already exists in core stat List'
                    )
                else:
                    # name = v['name']
                    # coreStatList[k] = {}
                    # coreStatList[k][name] = name
                    self._statList[k] = v

        # return coreStatList

    def _builStatList(self) -> dict:
        statList = OrderedDict()
        statList["Spike Time (s)"] = {
            "name": "thresholdSec",
            "units": "s",
            "yStat": "thresholdVal",
            "yStatUnits": "mV",
            "xStat": "thresholdSec",
            "xStatUnits": "s",
        }
        statList["Spike Number"] = {
            "name": "spikeNumber",
            "units": "",
            "yStat": "",
            "yStatUnits": "",
            "xStat": "spikeNumber",
            "xStatUnits": "",
        }
        statList["Sweep Spike Number"] = {
            "name": "sweepSpikeNumber",
            "units": "",
            "yStat": "",
            "yStatUnits": "",
            "xStat": "sweepSpikeNumber",
            "xStatUnits": "",
        }
        statList["Sweep Number"] = {
            "name": "sweep",
            "units": "",
            "yStat": "sweep",
            "yStatUnits": "",
            "xStat": "",
            "xStatUnits": "",
        }
        # removed 20230320
        # statList['DAC Command'] = {
        # 'name': 'dacCommand',
        # 'units': '',
        # 'yStat': 'dacCommand',
        # 'yStatUnits': '',
        # 'xStat': '',
        # 'xStatUnits': ''
        # }

        # added 20230320
        # stimulus epoch number a spike is within
        statList["Epoch"] = {
            "name": "epoch",
            "units": "",
            "yStat": "epoch",
            "yStatUnits": "",
            "xStat": "",
            "xStatUnits": "",
        }
        # added 20230320
        # the epoch level (for I-Clamp, corresponds to DAC command)
        statList["Epoch DAC"] = {
            "name": "epochLevel",
            "units": "",
            "yStat": "epochLevel",
            "yStatUnits": "",
            "xStat": "",
            "xStatUnits": "",
        }
        # added 20230320
        # the spike number within the epoch
        # not implemented
        # 20230914 BUG in bAnalysisResults we define 'epoch', not 'epochSpikeNumber'
        # WE need to sync these two interface !!!!
        statList["Epoch Spike Number"] = {
            # "name": "epochSpikeNumber",
            "name": "epoch",
            "units": "",
            # "yStat": "epochSpikeNumber",
            "yStat": "epoch",
            "yStatUnits": "",
            "xStat": "",
            "xStatUnits": "",
        }

        statList["Take Off Potential (mV)"] = {
            "name": "thresholdVal",
            "units": "mV",
            "yStat": "thresholdVal",
            "yStatUnits": "mV",
            "xStat": "thresholdPnt",
            "xStatUnits": "Points",
        }
        statList["Spike Frequency (Hz)"] = {
            "name": "spikeFreq_hz",
            "units": "Hz",
            "yStat": "spikeFreq_hz",
            "yStatUnits": "Hz",
            "xStat": "thresholdPnt",
            "xStatUnits": "Points",
        }
        statList["Inter-Spike-Interval (ms)"] = {
            "name": "isi_ms",
            "units": "ms",
            "yStat": "isi_ms",
            "yStatUnits": "ms",
            "xStat": "thresholdPnt",
            "xStatUnits": "Points",
        }
        statList["Cycle Length (ms)"] = {
            "name": "cycleLength_ms",
            "units": "ms",
            "yStat": "cycleLength_ms",
            "yStatUnits": "ms",
            "xStat": "thresholdPnt",
            "xStatUnits": "Points",
        }
        statList["AP Peak (mV)"] = {
            "name": "peakVal",
            "units": "mV",
            "yStat": "peakVal",
            "yStatUnits": "mV",
            "xStat": "peakPnt",
            "xStatUnits": "Points",
        }
        # spikeDict['peakVal'] - spikeDict['thresholdVal']
        statList["AP Height (mV)"] = {
            "name": "peakHeight",
            "units": "mV",
            "yStat": "peakHeight",
            "yStatUnits": "mV",
            "xStat": "peakPnt",
            "xStatUnits": "Points",
        }
        # new 20220122
        statList["Time To Peak (ms)"] = {
            "name": "timeToPeak_ms",
            "units": "ms",
            "yStat": "peakVal",
            "yStatUnits": "mV",
            "xStat": "peakPnt",
            "xStatUnits": "Points",
        }
        statList["Pre AP Min (mV)"] = {
            "name": "preMinVal",
            "units": "mV",
            "yStat": "preMinVal",
            "yStatUnits": "mV",
            "xStat": "preMinPnt",
            "xStatUnits": "Points",
        }
        statList["Post AP Min (mV)"] = {
            "name": "postMinVal",
            "units": "mV",
            "yStat": "postMinVal",
            "yStatUnits": "mV",
            "xStat": "postMinPnt",
            "xStatUnits": "Points",
        }

        # new 20231201
        statList["Fast AHP (mV)"] = {
            "name": "fastAhpValue",
            "units": "mV",
            "yStat": "fastAhpValue",
            "yStatUnits": "mV",
            "xStat": "fastAhpPnt",
            "xStatUnits": "Points",
        }

        # todo: fix this
        statList["Early Diastolic Depol Rate (dV/s)"] = {
            "name": "earlyDiastolicDurationRate",
            "units": "dV/s",
            "yStat": "earlyDiastolicDurationRate",
            "yStatUnits": "dV/s",
            "xStat": "",
            "xStatUnits": "",
        }
        # todo: fix this
        statList["Early Diastolic Duration (ms)"] = {
            "name": "earlyDiastolicDuration_ms",
            "units": "ms",
            "yStat": "earlyDiastolicDuration_ms",
            "yStatUnits": "dV/s",
            "xStat": "thresholdPnt",
            "xStatUnits": "Points",
        }

        statList["Diastolic Duration (ms)"] = {
            "name": "diastolicDuration_ms",
            "units": "ms",
            "yStat": "diastolicDuration_ms",
            "yStatUnits": "dV/s",
            "xStat": "thresholdPnt",
            "xStatUnits": "Points",
        }
        statList["Max AP Upstroke (mV)"] = {
            "name": "preSpike_dvdt_max_val",
            "units": "mV",
            "yStat": "preSpike_dvdt_max_val",
            "yStatUnits": "dV/s",
            "xStat": "preSpike_dvdt_max_pnt",
            "xStatUnits": "Points",
        }
        statList["Max AP Upstroke (dV/dt)"] = {
            "name": "preSpike_dvdt_max_val2",
            "units": "dV/dt",
            "yStat": "preSpike_dvdt_max_val2",
            "yStatUnits": "dV/dt",
            "xStat": "preSpike_dvdt_max_pnt",
            "xStatUnits": "Points",
        }
        statList["Max AP Repolarization (mV)"] = {
            "name": "postSpike_dvdt_min_val",
            "units": "mV",
            "yStat": "postSpike_dvdt_min_val",
            "yStatUnits": "mV",
            "xStat": "postSpike_dvdt_min_pnt",
            "xStatUnits": "Points",
        }
        # todo: fix this
        statList["AP Duration (ms)"] = {
            "name": "apDuration_ms",
            "units": "ms",
            "yStat": "apDuration_ms",
            "yStatUnits": "ms",
            "xStat": "thresholdPnt",
            "xStatUnits": "Points",
        }

        # new 20210211
        statList["Half Width 10 (ms)"] = {
            "name": "widths_10",
            "yStat": "widths_10",
            "yStatUnits": "ms",
            "xStat": "",
            "xStatUnits": "",
        }
        statList["Half Width 20 (ms)"] = {
            "name": "widths_20",
            "yStat": "widths_20",
            "yStatUnits": "ms",
            "xStat": "",
            "xStatUnits": "",
        }
        statList["Half Width 50 (ms)"] = {
            "name": "widths_50",
            "yStat": "widths_50",
            "yStatUnits": "ms",
            "xStat": "",
            "xStatUnits": "",
        }
        statList["Half Width 80 (ms)"] = {
            "name": "widths_80",
            "yStat": "widths_80",
            "yStatUnits": "ms",
            "xStat": "",
            "xStatUnits": "",
        }
        statList["Half Width 90 (ms)"] = {
            "name": "widths_90",
            "yStat": "widths_90",
            "yStatUnits": "ms",
            "xStat": "",
            "xStatUnits": "",
        }

        statList["User Type"] = {
            "name": "userType",
            "yStat": "userType",
            "yStatUnits": "",
            "xStat": "",
            "xStatUnits": "",
        }

        statList["Condition"] = {
            "name": "condition",
            "yStat": "condition",
            "yStatUnits": "",
            "xStat": "",
            "xStatUnits": "",
        }

        # sa node specific
        """
        statList['Region'] = {
            'yStat': 'Region',
            'yStatUnits': '',
            'xStat': '',
            'xStatUnits': ''
            }
        """
        # kymograph analysis
        if DO_KYMOGRAPH_ANALYSIS:
            statList["Ca++ Delay (s)"] = {
                "yStat": "caDelay_sec",
                "yStatUnits": "s",
                "xStat": "",
                "xStatUnits": "",
            }
            statList["Ca++ Width (ms)"] = {
                "yStat": "caWidth_ms",
                "yStatUnits": "ms",
                "xStat": "",
                "xStatUnits": "",
            }

        return statList

    def prettyPrint(self):
        print(json.dumps(self.configDict, indent=4, sort_keys=True))

    def getDetectionConfig(self):
        return self.config

    def getDetectionParam(self, theParam):
        if theParam in self.configDict["detection"].keys():
            return self.configDict["detection"][theParam]["value"]
        else:
            print(
                "error: bAnalysisUtil.getDetectionParam() detection parameter not found:",
                theParam,
            )
            return None

    def getDetectionDescription(self, theParam):
        if theParam in self.configDict["detection"].keys():
            return self.configDict["detection"][theParam]["meaning"]
        else:
            print(
                "error: bAnalysisUtil.getDetectionDescription() detection parameter not found:",
                theParam,
            )
            return None

    def setDetectionParam(self, theParam, theValue):
        if theParam in self.configDict["detection"].keys():
            self.configDict["detection"][theParam]["value"] = theValue
        else:
            print(
                "error: bAnalysisUtil.setDetectionParam() detection parameter not found:",
                theParam,
            )
            return None

    def configSave(self):
        print("bAnalysisUtil.configSave()")
        with open(self.configFilePath, "w") as outfile:
            json.dump(self.configDict, outfile, indent=4, sort_keys=True)

    def configLoad(self):
        if os.path.isfile(self.configFilePath):
            print(
                "    bAnalysisUtil.configLoad() loading configFile file:",
                self.configFilePath,
            )
            with open(self.configFilePath) as f:
                self.configDict = json.load(f)
        else:
            # print('    bAnalysisUtil.preferencesLoad() using program provided default options')
            self.configDefault()

    def configDefault(self):
        theRet = OrderedDict()

        theRet["detection"] = OrderedDict()

        theRet["detection"]["dvdtThreshold"] = OrderedDict()
        theRet["detection"]["dvdtThreshold"] = {
            "value": 100,
            "meaning": "Threshold crossing in dV/dt",
        }

        theRet["detection"]["minSpikeVm"] = OrderedDict()
        theRet["detection"]["minSpikeVm"] = {
            "value": -20,
            "meaning": "Minimum Vm to accept a detected spike",
        }

        theRet["detection"]["medianFilter"] = OrderedDict()
        theRet["detection"]["medianFilter"] = {
            "value": 5,
            "meaning": "Median filter for Vm (must be odd)",
        }

        theRet["detection"]["minISI_ms"] = OrderedDict()
        theRet["detection"]["minISI_ms"] = {
            "value": 75,
            "meaning": "Minimum allowable inter-spike-interval (ms), anything shorter than this will be rejected",
        }

        return theRet

    def _print(self):
        """Print out human readable detection parameters and convert to markdown table

        This is then pasted as a markdown table into the SanPy docs methods section

        TODO: Add a generation date to the resulting markdown.

        Requires:
            pip install tabulate
        """

        import pandas as pd

        # statList is a dict with keys, one key per stat
        d = self._statList

        dictList = []
        for k, v in d.items():
            stat = k
            oneDict = {
                "Stat": stat,
            }
            for k2, v2 in v.items():
                oneDict[k2] = v2

            dictList.append(oneDict)
        #
        df = pd.DataFrame(dictList)
        str = df.to_markdown()
        print(str)

Functions¤

getHumanFromStat(statName) ¤

Get human readable stat name from backend stat name.

Source code in sanpy/bAnalysisUtil.py
67
68
69
70
71
72
73
74
75
76
77
78
def getHumanFromStat(self, statName):
    """Get human readable stat name from backend stat name."""
    ret = ""
    for k, v in self._statList.items():
        name = v["name"]
        if name == statName:
            ret = k
            break
    if ret == "":
        logger.warning(f'Did not find "{statName}"')
    #
    return ret

getStatFromHuman(humanStat) ¤

Get backend stat name from human readable stat.

Source code in sanpy/bAnalysisUtil.py
80
81
82
83
84
85
86
87
88
def getStatFromHuman(self, humanStat):
    """Get backend stat name from human readable stat."""
    ret = ""
    try:
        ret = self._statList[humanStat]["name"]
    except KeyError as e:
        logger.warning(f'Bad key "{humanStat}"')
    #
    return ret
All material is Copyright 2011-2023 Robert H. Cudmore