Skip to content

analysisDir

Manage folder-backed collections of SanPy recording analyses.

Classes¤

analysisDir ¤

Manage a folder-backed collection of SanPy recordings and analyses.

The file table is loaded from the folder's SanPy HDF5 database when one is present. Otherwise, the folder is scanned for supported recording files. Recordings can be loaded eagerly with autoLoad=True or on demand with get_analysis_for_file_key() or getAnalysis().

Source code in sanpy/analysisDir.py
 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
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
class analysisDir:
    """Manage a folder-backed collection of SanPy recordings and analyses.

    The file table is loaded from the folder's SanPy HDF5 database when one is
    present. Otherwise, the folder is scanned for supported recording files.
    Recordings can be loaded eagerly with ``autoLoad=True`` or on demand with
    ``get_analysis_for_file_key()`` or ``getAnalysis()``.
    """

    sanpyColumns = _sanpyColumns
    # Dict of dict of column names and bookkeeping info.

    def __init__(
        self,
        path: str | None = None,
        fileLoaderDict: dict[str, dict[str, object]] | None = None,
        autoLoad: bool = False,
        folderDepth: Optional[int] = None,
        status_callback: Callable[[str], None] | None = None,
    ) -> None:
        """Load a folder catalog and optionally load its recordings.

        Args:
            path: Path to a recording or folder.
            fileLoaderDict: File-loader definitions keyed by extension. SanPy's
                registered loaders are used when omitted.
            autoLoad: Whether to load each recording while scanning a folder.
            folderDepth: Maximum folder depth to scan. Use ``1`` for only the
                selected folder or ``None`` for unlimited recursion.
            status_callback: Optional callback for construction progress.

        Note:
            Passing a recording path creates a one-file collection rooted in that
            recording's parent folder.
        """

        self._filePath = None
        if os.path.isfile(path):
            self._filePath = path
            folderPath = os.path.split(path)[0]
        else:
            folderPath = path

        logger.info(f'{path}')

        self.path: str = folderPath  # path to folder

        self._fileLoaderDict = fileLoaderDict

        self.autoLoad = autoLoad

        self.folderDepth = folderDepth
        self._pool_frame_cache: dict[str, tuple[str, pd.DataFrame]] = {}

        self._isDirty = False
        # keep track if analysis was changed and prompt on quit

        # self._poolDf = None
        """See pool_ functions"""

        # TODO: refactor, we are not using the csv parth of this, just the filename
        # name of database file created/loaded from folder path
        self.dbFile = "sanpy_recording_db.csv"  # old but still critical to keep

        self._df = self.loadHdf()
        if self._df is None:
            # did not load h5 file
            self._df = self.loadFolder(
                loadData=autoLoad,
                status_callback=status_callback,
            )
            self._updateLoadedAnalyzed()
        elif self._fileLoaderDict is not None:
            logger.info(f'sync existing df with filePath: {self._filePath}')
            self.syncDfWithPath()

        #
        self._checkColumns()
        self._normalize_file_keys()
        self._updateLoadedAnalyzed()

    def _normalize_file_keys(self) -> None:
        """Normalize and validate every recording key in the file table.

        Raises:
            ValueError: If a key is missing, outside the directory, or duplicated.
        """
        keys: list[str] = []
        available_paths: list[str] | None = None
        for row_index in self._df.index:
            value = self._df.at[row_index, "relPath"]
            if not isinstance(value, str) or not value:
                value = str(self._df.at[row_index, "File"])
            try:
                key = _normalized_file_key(self.path, value)
            except ValueError:
                if available_paths is None:
                    available_paths = self.getFileList()
                filename = pathlib.PureWindowsPath(value).name
                matches = [
                    path
                    for path in available_paths
                    if os.path.basename(path) == filename
                ]
                if len(matches) != 1:
                    raise ValueError(
                        f'Cannot uniquely resolve legacy recording path "{value}"'
                    ) from None
                key = _normalized_file_key(self.path, matches[0])
            self._df.at[row_index, "relPath"] = key
            keys.append(key)
        duplicates = sorted({key for key in keys if keys.count(key) > 1})
        if duplicates:
            raise ValueError(f"Duplicate analysis file keys: {duplicates}")

    def get_file_key(self, row_idx: int) -> str:
        """Return the stable file key for one table row.

        Args:
            row_idx: File-table row index.

        Returns:
            Normalized path relative to the analysis directory.
        """
        return str(self._df.at[row_idx, "relPath"])

    def get_row_for_file_key(self, file_key: str) -> int | None:
        """Return the table row for a normalized file key.

        Args:
            file_key: Recording identity relative to the analysis directory.

        Returns:
            Matching row index, or ``None`` when the key is unknown.
        """
        try:
            normalized = _normalized_file_key(self.path, file_key)
        except ValueError:
            return None
        rows = self._df.index[self._df["relPath"] == normalized].tolist()
        return int(rows[0]) if rows else None

    def get_analysis_for_file_key(
        self,
        file_key: str,
        allow_auto_load: bool = True,
    ) -> Optional[sanpy.bAnalysis]:
        """Resolve and optionally load an analysis by stable file key.

        Args:
            file_key: Recording identity relative to the analysis directory.
            allow_auto_load: Whether the recording may be loaded on demand.

        Returns:
            Resolved analysis, or ``None`` when the key is unknown or cannot load.
        """
        row_index = self.get_row_for_file_key(file_key)
        if row_index is None:
            return None
        return self.getAnalysis(row_index, allowAutoLoad=allow_auto_load)

    def detect_file_keys(
        self,
        file_keys: Sequence[str],
        detection: Mapping[str, object],
        *,
        should_continue: Callable[[int, int, str], bool] | None = None,
        after_file: Callable[[str], None] | None = None,
    ) -> tuple[int, tuple[str, ...]]:
        """Detect spikes across recordings identified by stable file keys.

        Each recording receives an independent detection dictionary covering
        its complete duration. Failures do not prevent later recordings from
        being processed.

        Args:
            file_keys: Recording identities relative to this analysis directory.
            detection: Detection preset and threshold values to apply.
            should_continue: Optional callback before each recording. Arguments
                are one-based position, total count, and file key. Returning
                ``False`` cancels before that recording.
            after_file: Optional callback after one recording finishes.

        Returns:
            Number of detected recordings and the keys that failed.
        """
        detected = 0
        failed: list[str] = []
        total = len(file_keys)
        for position, file_key in enumerate(file_keys, start=1):
            if should_continue is not None and not should_continue(
                position, total, file_key
            ):
                break
            row = self.get_row_for_file_key(file_key)
            analysis = self.get_analysis_for_file_key(file_key)
            if row is None or analysis is None or analysis.loadError:
                failed.append(file_key)
                continue
            try:
                detection_for_file = copy.deepcopy(dict(detection))
                detection_for_file["startSeconds"] = 0
                detection_for_file["stopSeconds"] = analysis.fileLoader.recordingDur
                analysis.spikeDetect(detection_for_file)
                self._updateLoadedAnalyzed(row)
            except Exception:
                logger.exception(f'Batch detection failed for "{file_key}"')
                failed.append(file_key)
                continue
            detected += 1
            if after_file is not None:
                after_file(file_key)
        return detected, tuple(failed)

    def set_metadata_for_file_keys(
        self,
        file_keys: Sequence[str],
        key: str,
        value: str,
        *,
        should_continue: Callable[[int, int, str], bool] | None = None,
        after_file: Callable[[str], None] | None = None,
    ) -> tuple[int, tuple[str, ...]]:
        """Set one experimental metadata value across recordings.

        Analyses are loaded when necessary and left dirty for the existing save
        workflow. This method never persists changes.

        Args:
            file_keys: Recording identities relative to this analysis directory.
            key: Canonical experimental-metadata key.
            value: New string value.
            should_continue: Optional callback before each recording. Arguments
                are one-based position, total count, and file key. Returning
                ``False`` cancels before that recording.
            after_file: Optional callback after one recording is processed.

        Returns:
            Number of changed recordings and the keys that failed.

        Raises:
            ValueError: If ``key`` is not canonical experimental metadata.
        """
        if key not in MetaData.getMetaDataDict():
            raise ValueError(f'Unknown experimental metadata key: "{key}"')
        changed = 0
        failed: list[str] = []
        total = len(file_keys)
        for position, file_key in enumerate(file_keys, start=1):
            if should_continue is not None and not should_continue(
                position, total, file_key
            ):
                break
            row = self.get_row_for_file_key(file_key)
            analysis = self.get_analysis_for_file_key(file_key)
            if row is None or analysis is None or analysis.loadError:
                failed.append(file_key)
                continue
            try:
                previous = analysis.metaData.getMetaData(key)
                analysis.metaData.setMetaData(key, value)
                self._updateLoadedAnalyzed(row)
            except Exception:
                logger.exception(f'Batch metadata update failed for "{file_key}"')
                failed.append(file_key)
                continue
            if previous != value:
                changed += 1
            if after_file is not None:
                after_file(file_key)
        return changed, tuple(failed)

    @property
    def theseFileTypes(self) -> list[str]:
        """Return the recording extensions available for folder scanning.

        Returns:
            Extensions from the caller-supplied loader definitions, or from
            SanPy's registered loaders when no definitions were supplied.
        """
        if self._fileLoaderDict is None:
            return list(sanpy.fileloaders.getFileLoaders().keys())
        return list(self._fileLoaderDict.keys())

    def findFileRow(self, filename):
        """Find the row index of a file in the file table.

        Args:
            filename: The name of the file to find.

        Returns:
            The row index of the file in the file table, or None if the file is not found.
        """
        fileIndexList = self._df.index[self._df['File'] == filename].tolist()
        if fileIndexList:
            rowIdx = fileIndexList[0]
            return rowIdx
        else:
            logger.warning(f"Did not find file {filename} in {self._df['File'].tolist()}")

    def __iter__(self):
        """Iterate over the bAnalysis objects in the file table."""
        self._iterIdx = -1
        return self

    def __next__(self):
        """Get the next bAnalysis object in the file table."""
        self._iterIdx += 1
        if self._iterIdx >= self.numFiles:
            self._iterIdx = -1  # reset to initial value
            raise StopIteration
        else:
            return self._df.loc[self._iterIdx]["_ba"]

    def __str__(self) -> str:
        """Return a concise folder summary.

        Returns:
            Summary containing the number of files and their total duration.
        """
        totalDurSec = self._df["Dur(s)"].sum()
        theStr = f"analysisDir Num Files: {len(self)} Total Dur(s): {totalDurSec}"
        return theStr

    @property
    def isDirty(self):
        """Get the dirty state of the analysisDir.

        Returns:
            True if the analysisDir is dirty, False otherwise.
        """
        return self._isDirty

    def __len__(self) -> int:
        """Return the number of files in the collection.

        Returns:
            Number of file-table rows.
        """
        return len(self._df)

    @property
    def numFiles(self) -> int:
        """Return the number of files in the collection.

        Returns:
            Number of file-table rows.
        """
        return len(self._df)

    @property
    def shape(self):
        """
        Can't just return shape of _df, columns (like 'ba') may have been added
        Number of columns is based on self.columns
        """
        # return self._df.shape
        numRows = self._df.shape[0]
        numCols = len(self.columns)
        return (numRows, numCols)

    @property
    def loc(self):
        """Mimic pandas df.loc[]"""
        return self._df.loc

    @loc.setter
    def loc_setter(self, rowIdx, colStr, value):
        self._df.loc[rowIdx, colStr] = value

    @property
    def iloc(self):
        # mimic pandas df.iloc[]
        return self._df.iloc

    @iloc.setter
    def iLoc_setter(self, rowIdx, colIdx, value):
        self._df.iloc[rowIdx, colIdx] = value
        self._isDirty = True

    @property
    def at(self):
        # mimic pandas df.at[]
        return self._df.at

    @at.setter
    def at_setter(self, rowIdx, colStr, value):
        self._df.at[rowIdx, colStr] = value
        self._isDirty = True

    @property
    def index(self):
        return self._df.index

    @property
    def columns(self):
        # return list of column names
        return list(self.sanpyColumns.keys())

    def copy(self) -> pd.DataFrame:
        """Return an independent copy of the folder's file table.

        Returns:
            Copy of the file table, including recording metadata and status.
        """
        return self._df.copy()

    def sort_values(self, Ncol, order):
        logger.info(f"sorting by column {self.columns[Ncol]} with order:{order}")
        self._df = self._df.sort_values(self.columns[Ncol], ascending=not order)
        # print(self._df)

    @property
    def columnsDict(self):
        return self.sanpyColumns

    def columnIsEditable(self, colName):
        return self.sanpyColumns[colName]["isEditable"]

    def columnIsCheckBox(self, colName):
        """All bool columns are checkbox

        TODO: problems with using type=bool and isinstance(). Kust using str 'bool'
        """
        type = self.sanpyColumns[colName]["type"]
        # isBool = isinstance(type, bool)
        isBool = type == "bool"
        # logger.info(f'{colName} {type(type)}, type:{type} {isBool}')
        return isBool

    def getDataFrame(self) -> pd.DataFrame:
        """Return the mutable file table used by this collection.

        Returns:
            Internal file table. Use ``copy()`` when mutations should not affect
            the collection.
        """
        return self._df

    def copyToClipboard(self):
        """
        TODO: Is this used or is copy to clipboard in pandas model?
        """
        if self.getDataFrame() is not None:
            self.getDataFrame().to_clipboard(sep="\t", index=False)
            logger.info("Copied to clipboard")

    def getPathFromRelPath(self, relPath):
        """Get full path to file from relPath.

        Uses analysisDir folder path.
        """
        if relPath.startswith("/"):
            relPath = relPath[1:]

        fullFilePath = os.path.join(self.path, relPath)

        return fullFilePath

    def saveHdf(self):
        """Save file table and any number of loaded and analyzed bAnalysis.

        Set file table 'uuid' column when we actually save a bAnalysis

        Important: Order matters
            (1) Save bAnalysis first, it updates uuid in file table.
            (2) Save file table with updated uuid
        """
        start = time.time()

        df = self.getDataFrame()

        # the compressed version from the last save
        hdfFile = os.path.splitext(self.dbFile)[0] + ".h5"
        hdfFilePath = pathlib.Path(self.path) / hdfFile

        logger.info(f"Saving h5 db (will be compressed) {hdfFilePath}")

        # save each bAnalysis
        for row in range(len(df)):
            ba = df.at[row, "_ba"]
            if ba is not None:
                didSave = ba._saveHdf_pytables(hdfFilePath)
                if didSave:
                    # we are now saved into h5 file, remember uuid to load
                    df.at[row, "uuid"] = ba.uuid
                    self._pool_frame_cache.pop(self.get_file_key(row), None)

        # rebuild (L, A, S) columns
        self._updateLoadedAnalyzed()

        #
        # save file database
        logger.info(f"    saving file db with {len(df)} rows")
        # print(df)

        dbKey = os.path.splitext(self.dbFile)[0]
        df = df.drop("_ba", axis=1)  # don't ever save _ba, use it for runtime

        # hdfStore[dbKey] = df  # save it
        df.to_hdf(hdfFilePath, key=dbKey)
        with pd.HDFStore(hdfFilePath) as hdfStore:
            hdfStore.get_storer(dbKey).attrs.sanpy_format_version = SANPY_H5_FORMAT_VERSION

        #
        self._isDirty = False  # if true, prompt to save on quit

        # rebuild the file to remove old changes and reduce size
        # self._rebuildHdf()
        sanpy.h5Util._repackHdf(hdfFilePath)

        stop = time.time()
        logger.info(f"    Saving took {round(stop-start,2)} seconds")

    def loadHdf(self, path=None, verbose=False):
        """Load the database key from an h5 file.

        We do not load analysis until user clicks on row, see loadOneAnalysis()
        """
        if path is None:
            path = self.path
        self.path = path

        df = None
        hdfFile = os.path.splitext(self.dbFile)[0] + ".h5"
        hdfPath = pathlib.Path(self.path) / hdfFile
        if not hdfPath.is_file():
            return

        # logger.info(f"Loading existing folder h5 file {hdfPath}")
        # sanpy.h5Util.listKeys(hdfPath)

        _start = time.time()
        dbKey = os.path.splitext(self.dbFile)[0]

        try:
            df = pd.read_hdf(hdfPath, dbKey)
        except KeyError as e:
            # file is corrupt !!!
            logger.error(f'    Load h5 failed, did not find dbKey:"{dbKey}" {e}')

        if df is not None:
            # _ba is for runtime, assign after loading from either (abf or h5)
            df["_ba"] = None

            # fix bug during dev of ba metadata
            # df['Sex'] = 'unknown'

            if verbose:
                logger.info("    loaded db df")

            _stop = time.time()
            # logger.info(f"Loading took {round(_stop-_start,2)} seconds")

            # if we are one file then make sure file is in df

        return df

    def loadOneAnalysis(
        self,
        path: str,
        uuid: Optional[str] = None,
        allowAutoLoad: bool = True,
        verbose: bool = False,
    ) -> Optional[sanpy.bAnalysis]:
        """Load one analysis from its recording and optional HDF5 data.

        If from h5, we still need to reload sweeps !!!
        They are binary and fast, saving to h5 (in this case) is slow.

        Args:
            path: Recording path.
            uuid: Optional analysis identifier in the folder HDF5 file.
            allowAutoLoad: Load directly from the recording when HDF5 data is
                unavailable.
            verbose: Emit detailed loading messages.

        Returns:
            A valid loaded analysis, or ``None`` when the recording cannot be
            loaded.
        """
        if verbose:
            logger.info(f'path:"{path}" uuid:"{uuid}" allowAutoLoad:"{allowAutoLoad}"')

        hdfPath = self._getHdfFile()

        ba = None
        if uuid is not None and uuid:
            # load from h5
            if verbose:
                logger.info(f"    Retreiving uuid from hdf file {uuid}")

            # load from abf
            # ba = sanpy.bAnalysis(path, fileLoaderDict=self._fileLoaderDict, verbose=verbose)
            ba = sanpy.bAnalysis(path, loadData=allowAutoLoad, fileLoaderDict=self._fileLoaderDict, verbose=verbose)

            if ba.loadError:
                logger.error('Unable to load recording "%s"', path)
                return None

            # load analysis from h5 file, will fail if uuid is not in file
            ba._loadHdf_pytables(hdfPath, uuid)

        if allowAutoLoad and ba is None:
            # load from path
            ba = sanpy.bAnalysis(path, fileLoaderDict=self._fileLoaderDict, verbose=verbose)
            if verbose:
                logger.info(f"    Loaded ba from path {path} and now ba:{ba}")

        if ba is not None and ba.loadError:
            logger.error('Unable to load recording "%s"', path)
            return None
        #
        return ba

    def _getHdfFile(self):
        hdfFile = os.path.splitext(self.dbFile)[0] + ".h5"
        hdfPath = os.path.join(self.path, hdfFile)
        return hdfPath

    def _deleteFromHdf(self, uuid):
        """Delete uuid from h5 file.

        Each bAnalysis detection get a unique uuid.
        """
        if uuid is None or not uuid:
            return
        logger.info(f"deleting from h5 file uuid:{uuid}")

        _hdfFile = os.path.splitext(self.dbFile)[0] + ".h5"
        hdfPath = pathlib.Path(self.path) / _hdfFile

        # tmpHdfPath = self._getTmpHdfFile()

        removed = False
        with pd.HDFStore(hdfPath) as hdfStore:
            try:
                hdfStore.remove(uuid)
                removed = True
            except KeyError:
                logger.error(f"Did not find uuid {uuid} in h5 file {hdfPath}")

        #
        if removed:
            # will rebuild on next save
            # self._rebuildHdf()
            self._updateLoadedAnalyzed()
            self._isDirty = True  # if true, prompt to save on quit

    def loadFolder(
        self,
        path: str | None = None,
        loadData: bool = False,
        status_callback: Callable[[str], None] | None = None,
    ) -> pd.DataFrame:
        """Parse a folder and build its recording table.

        Args:
            path: Folder to scan. The configured directory is used when omitted.
            loadData: Whether to retain each loaded analysis in memory.
            status_callback: Optional callback for per-file progress messages.

        Returns:
            Dataframe containing one row for each supported recording.
        """
        logger.info("Loading folder from scratch (no h5 file)")

        start = time.time()
        if path is None:
            path = self.path
        self.path = path

        df = pd.DataFrame(columns=self.sanpyColumns.keys())
        df = self._setColumnType(df)

        # get list of all abf/csv/tif files
        fileList = self.getFileList(path)
        _numFilesToLoad = len(fileList)
        start = time.time()
        # build new db dataframe
        listOfDict = []
        for rowIdx, fullFilePath in enumerate(fileList):
            status_message = (
                f'Loading file {rowIdx+1} of {_numFilesToLoad} "{_normalized_file_key(self.path, fullFilePath)}"'
            )
            if status_callback is None:
                logger.info(status_message)
            else:
                status_callback(status_message)

            # rowDict is what we are showing in the file table
            # abb debug vue, set loadData=True
            # loads bAnalysis
            ba, rowDict = self.getFileRow(fullFilePath, loadData=loadData)

            if rowDict is None:
                logger.warning(f'error loading file {fullFilePath}')
                continue

            # as we parse the folder, don't load ALL files (will run out of memory)
            if loadData:
                rowDict["_ba"] = ba
            else:
                rowDict["_ba"] = None  # ba

            # do not assign uuid until bAnalysis is saved in h5 file
            # rowDict['uuid'] = ''

            # logger.info(f'    row:{rowIdx} relPath:{relPath} fullFilePath:{fullFilePath}')

            listOfDict.append(rowDict)

        stop = time.time()
        logger.info(f"Loading {len(listOfDict)} files took {round(stop-start,3)} seconds.")

        df = pd.DataFrame(listOfDict)
        df = self._setColumnType(df)

        return df

    def _checkColumns(self, verbose = False):
        """Check columns in loaded vs sanpyColumns (and vica versa).
        """
        if self._df is None:
            return

        # verbose = True
        loadedColumns = self._df.columns
        for col in loadedColumns:
            if col not in self.sanpyColumns.keys():
                # loaded has unexpected column, leave it
                if verbose:
                    logger.info(
                        f'did not find loaded col: "{col}" in sanpyColumns.keys() ... ignore it'
                    )
        for col in self.sanpyColumns.keys():
            if col not in loadedColumns:
                # loaded is missing expected, add it
                if verbose:
                    logger.info(
                        f'did not find sanpyColumns.keys() col: "{col}" in loadedColumns ... adding col'
                    )
                self._df[col] = ""

    def _updateLoadedAnalyzed(self, theRowIdx=None):
        """Refresh Loaded (L) and Analyzed (A) columns.

        Arguments:
            theRowIdx (int): Update just one row

        TODO: For kymograph, add rows (left, top, right, bottom) and update
        """
        if self._df is None:
            return
        for rowIdx in range(len(self._df)):
            if theRowIdx is not None and theRowIdx != rowIdx:
                continue

            ba = self._df.loc[rowIdx, "_ba"]  # Can be None

            # uuid = self._df.at[rowIdx, 'uuid']
            #
            # loaded
            if self.isLoaded(rowIdx):
                theChar = "\u2022"  # FILLED BULLET
            # elif uuid:
            #    #theChar = '\u25CB'  # open circle
            #    theChar = '\u25e6'  # white bullet
            else:
                theChar = ""
            # self._df.iloc[rowIdx, loadedCol] = theChar
            self._df.loc[rowIdx, "L"] = theChar
            #
            # analyzed
            if self.isAnalyzed(rowIdx):
                theChar = "\u2022"  # FILLED BULLET
                self._df.loc[rowIdx, "N"] = ba.numSpikes
                _numErrors = ba.numErrors
                if _numErrors is None:
                    _numErrors = ''
                # logger.warning(f'setting E to _numErrors {_numErrors}')
                self._df.loc[rowIdx, "E"] = _numErrors
            # elif uuid:
            #    #theChar = '\u25CB'
            #    theChar = '\u25e6'  # white bullet
            else:
                theChar = ""
                self._df.loc[rowIdx, "A"] = ""
            # self._df.iloc[rowIdx, analyzedCol] = theChar
            self._df.loc[rowIdx, "A"] = theChar
            #
            # saved
            if self.isSaved(rowIdx):
                theChar = "\u2022"  # FILLED BULLET
            else:
                theChar = ""
            # self._df.iloc[rowIdx, savedCol] = theChar
            self._df.loc[rowIdx, "S"] = theChar
            #
            # start(s) and stop(s) from ba detectionDict
            if self.isAnalyzed(rowIdx):
                # set table to values we just detected with

                # relPath should usually be filled in ???
                """
                relPath = self.getPathFromRelPath(ba._path)
                self._df.loc[rowIdx, 'relPath'] = relPath
                """

                # logger.info('maybe put back in')
                # print(f'    self._df.loc[rowIdx, "relPath"] is "{self._df.loc[rowIdx, "relPath"]}"')

            # aug 2023, update meta data columns
            if ba is not None:
                for k,v in ba.metaData.items():
                    self._df.loc[rowIdx, k] = v

            # TODO: remove start of ba._path that corresponds to our current folder path
            # will allow our save db to be modular
            # self._df.loc[rowIdx, 'path'] = ba._path

    def isLoaded(self, rowIdx):
        isLoaded = self._df.loc[rowIdx, "_ba"] is not None
        return isLoaded

    def isAnalyzed(self, rowIdx):
        isAnalyzed = False
        # abb 20261012 type hinting
        ba : sanpy.bAnalysis = self._df.loc[rowIdx, "_ba"]
        if ba is not None:
            try:
                isAnalyzed = ba.isAnalyzed()
            except(AttributeError) as e:
                logger.error(f'rowIdx {rowIdx} ba is "{ba}" but expecting bAnalysis_')
                logger.error('self._df:')
                print(self._df)
                return False
        return isAnalyzed

    def analysisIsDirty(self, rowIdx):
        """Analysis is dirty when there has been detection but not saved to h5."""
        isDirty = False
        ba = self._df.loc[rowIdx, "_ba"]
        if isinstance(ba, sanpy.bAnalysis):
            isDirty = ba.isDirty()
        return isDirty

    def hasDirty(self):
        """Return true if any bAnalysis in list has been analyzed but not saved (e.g. is dirty).
        """
        haveDirty = False
        numRows = len(self._df)
        for rowIdx in range(numRows):
            if self.analysisIsDirty(rowIdx):
                haveDirty = True

        return haveDirty

    def isSaved(self, rowIdx):
        uuid = self._df.at[rowIdx, "uuid"]
        return len(uuid) > 0

    def getAnalysis(self, rowIdx, allowAutoLoad=True, verbose=False) -> sanpy.bAnalysis:
        """Get bAnalysis object, will load if necc.

        Args:
            rowIdx (int): Row index from table, corresponds to row in self._df
            allowAutoLoad (bool)
        Return:
            bAnalysis
        """
        file = self._df.loc[rowIdx, "File"]
        ba = self._df.loc[rowIdx, "_ba"]
        uuid = self._df.loc[rowIdx, "uuid"]  # if we have a uuid bAnalysis is saved in h5f

        if ba is None or ba == "":
            relPath = self._df.loc[rowIdx, "relPath"]
            filePath = self.getPathFromRelPath(relPath)

            ba = self.loadOneAnalysis(
                filePath, uuid, allowAutoLoad=allowAutoLoad, verbose=verbose
            )
            # load
            if ba is None:
                logger.warning(
                    f'Did not load row {rowIdx} path: "{filePath}". Analysis was probably not saved'
                )
            else:
                self._df.at[rowIdx, "_ba"] = ba
                # does not get a uuid until save into h5
                if uuid:
                    # there was an original uuid (in table), means we are saved into h5
                    self._df.at[rowIdx, "uuid"] = uuid
                    if uuid != ba.uuid:
                        logger.error(
                            "Loaded uuid does not match existing in file table"
                        )
                        logger.error(f"  Loaded {ba.uuid}")
                        logger.error(f"  Existing {uuid}")

                #
                # update stats of table load/analyzed columns
                self._updateLoadedAnalyzed()

        return ba

    def _setColumnType(self, df):
        """Needs to be called every time a df is created.
        Ensures proper type of columns following sanpyColumns[key]['type']
        """
        # print('columns are:', df.columns)
        for col in df.columns:
            # when loading from csv, 'col' may not be in sanpyColumns
            if col not in self.sanpyColumns:
                # logger.warning(f'Column "{col}" is not in sanpyColumns -->> ignoring')
                continue
            colType = self.sanpyColumns[col]["type"]
            if colType == str:
                df[col] = df[col].replace(np.nan, "", regex=True)
                df[col] = df[col].astype(str)
            elif colType == int:
                pass
            elif colType == float:
                # error if ''
                df[col] = df[col].astype(float)
            elif colType == bool:
                df[col] = df[col].astype(bool)
            else:
                logger.warning(f'Did not parse col "{col}" with type "{colType}"')
        #
        return df

    def getFileRow(self, path, loadData=False):
        """Get dict representing one file (row in table). Loads bAnalysis to get headers.

        On load error of proper file type (abf, csv), ba.loadError==True

        Args:
            path (Str): Full path to file.
            #rowIdx (int): Optional row index to assign in column 'Idx'

        Return:
            (tuple): tuple containing:

            - ba (bAnalysis): [sanpy.bAnalysis](/api/bAnalysis).
            - rowDict (dict): On success, otherwise None.
                    fails when path does not lead to valid bAnalysis file.
        """
        if not os.path.isfile(path):
            logger.warning(f'Did not find file "{path}"')
            return None, None

        fileType = os.path.splitext(path)[1]

        if fileType not in self.theseFileTypes:  
            logger.warning(f'Did not load file type "{fileType}"')
            return None, None

        ba = sanpy.bAnalysis(path,
                             loadData=loadData,
                             fileLoaderDict=self._fileLoaderDict)

        if ba.loadError:
            logger.error(f'Error loading bAnalysis file "{path}"')
            # return None, None

        # not sufficient to default everything to empty str ''
        # sanpyColumns can only have type in ('float', 'str')
        rowDict = dict.fromkeys(self.sanpyColumns.keys(), "")
        for k in rowDict.keys():
            if self.sanpyColumns[k]["type"] == str:
                rowDict[k] = ""
            elif self.sanpyColumns[k]["type"] == float:
                rowDict[k] = np.nan

        if ba.loadError:
            return None, None

        rowDict["File"] = ba.fileLoader.filename  # os.path.split(ba.path)[1]
        rowDict["Dur(s)"] = ba.fileLoader.recordingDur
        rowDict["Channels"] = ba.fileLoader.numChannels  # Theanne
        rowDict["Sweeps"] = ba.fileLoader.numSweeps

        # here, we do not get an epoch table until the file is loaded !!!
        rowDict["Epochs"] = ba.fileLoader.numEpochs  # Theanne, data has to be loaded

        rowDict["kHz"] = ba.fileLoader.recordingFrequency
        rowDict["Mode"] = ba.fileLoader.recordingMode.value

        # add parent1, parent2, parent3
        _path, _file = os.path.split(path)
        _path, _parent1 = os.path.split(_path)
        _path, _parent2 = os.path.split(_path)
        _path, _parent3 = os.path.split(_path)
        rowDict['parent1'] = _parent1
        rowDict['parent2'] = _parent2
        rowDict['parent3'] = _parent3

        # aug 2023,  adding bAnalysis metadata columns
        for k,v in ba.metaData.items():
            rowDict[k] = v

        # remove the path to the folder we have loaded
        rowDict["relPath"] = _normalized_file_key(self.path, path)

        return ba, rowDict

    def getFileList(self,
                    path: str = None,
                    ) -> List[str]:
        """Get file paths from path.

        Uses self.theseFileTypes

        """

        if self._filePath is not None:
            logger.info(f'returning one file {self._filePath}')
            return [self._filePath]

        if path is None:
            path = self.path

        fileList = getFileList(path, self.theseFileTypes, self.folderDepth)
        return fileList

    def getRowDict(self, rowIdx):
        """
        Return a dict with selected row as dict (includes detection parameters).

        Important to return a copy as our '_ba' is a pointer to bAnalysis.

        Returns:
            theRet (dict): Be sure to make a deep copy of ['_ba'] if neccessary.
        """
        theRet = {}
        # use columns in main sanpyColumns, not in df
        # for colStr in self.columns:
        for colStr in self._df.columns:
            # theRet[colStr] = self._df.loc[rowIdx, colStr]
            theRet[colStr] = self._df.loc[rowIdx, colStr]
        # theRet['_ba'] = theRet['_ba'].copy()
        return theRet

    def appendRow(self, rowDict=None, ba=None):
        """Append an empty row."""

        rowSeries = pd.Series()
        if rowDict is not None:
            # rowSeries = pd.Series(rowDict)
            rowSeries = pd.DataFrame([rowDict])

            # self._data.iloc[row] = rowSeries
            # self._data = self._data.reset_index(drop=True)

        newRowIdx = len(self._df)  # append this row

        df = self._df
        df = pd.concat([df, rowSeries], axis=0, ignore_index=True)

        # df = pd.concat([df,rowSeries], ignore_index=True, axis=1)
        df = df.reset_index(drop=True)

        if ba is not None:
            df.loc[newRowIdx, "_ba"] = ba

        #
        self._df = df

    def unloadRow(self, rowIdx):
        self._pool_frame_cache.pop(self.get_file_key(rowIdx), None)
        self._df.loc[rowIdx, "_ba"] = None
        self._updateLoadedAnalyzed()

    def removeRowFromDatabase(self, rowIdx):
        self._pool_frame_cache.pop(self.get_file_key(rowIdx), None)
        # delete from h5 file
        uuid = self._df.at[rowIdx, "uuid"]
        self._deleteFromHdf(uuid)

        # clear uuid
        self._df.at[rowIdx, "uuid"] = ""

        self._updateLoadedAnalyzed()

    def deleteRow(self, rowIdx):
        df = self._df
        self._pool_frame_cache.pop(self.get_file_key(rowIdx), None)

        # delete from h5 file
        uuid = df.at[rowIdx, "uuid"]
        self._deleteFromHdf(uuid)

        # delete from df/model
        df = df.drop([rowIdx])
        df = df.reset_index(drop=True)
        self._df = df

        self._updateLoadedAnalyzed()

    def syncDfWithPath(self):
        """Sync path with existing df. Used to detect new/removed files.

        If we currently have just one file (self._filePath) we will trash it and load a folder

        Notes
        -----
        20231230, trying to use this to open a one file window with an exiting h5 file.
        """
        self._pool_frame_cache.clear()

        pathFileList = self.getFileList()

        # our currently loaded files
        dfFileList = self._df["File"].tolist()

        # logger.info(f'dfFileList: {dfFileList}')
        # print('    === pathFileList (on drive):')
        # print('    ', pathFileList)
        # print('    === dfFileList (in table):')
        # print('    ', dfFileList)

        addedToDf = False

        # look for files in path not in df
        for pathFile in pathFileList:
            fileName = os.path.split(pathFile)[1]
            if fileName not in dfFileList:
                logger.info(f'   Found file in path "{fileName}" not in df')

                # load bAnalysis and get df column values
                addedToDf = True

                ba, rowDict = self.getFileRow(pathFile)  # loads bAnalysis

                if rowDict is not None:
                    # listOfDict.append(rowDict)

                    # TODO: get this into getFileROw()
                    # logger.warning("bug 20220718, not sure we need this ???")
                    # print(rowDict)

                    # rowDict['relPath'] = pathFile
                    rowDict["_ba"] = None

                    self.appendRow(rowDict=rowDict, ba=None)

        # look for files in df not in path
        # for dfFile in dfFileList:
        #     if not dfFile in pathFileList:
        #         logger.info(f'Found file in df "{dfFile}" not in path')

        if addedToDf:
            df = self._df
            df = df.sort_values(
                by=["File"], axis="index", ascending=True, inplace=False
            )
            df = df.reset_index(drop=True)
            self._df = df

        self._updateLoadedAnalyzed()

    def spike_dataframe_for_row(self, row_idx: int) -> pd.DataFrame | None:
        """Return pooled spike results for one file-table row.

        A loaded analysis is always authoritative. For an unloaded row, a
        matching cached frame is reused or the saved spike results and file
        metadata are read from the folder HDF5 file without opening the
        recording.

        Args:
            row_idx: File-table row index.

        Returns:
            Copied spike results with pooled identity columns, or ``None`` when
            the row has no saved analyzed spikes.

        Raises:
            ValueError: If analyzed results have no ``spikeNumber`` column.
        """
        file_key = self.get_file_key(row_idx)
        uuid = str(self._df.at[row_idx, "uuid"])
        ba = self._df.at[row_idx, "_ba"]
        cache_result = ba is None or ba == ""

        if not cache_result:
            self._pool_frame_cache.pop(file_key, None)
            if not ba.isAnalyzed():
                return None
            one_df = ba.asDataFrame(regenerateAnalysisDataFrame=True)
        else:
            cached = self._pool_frame_cache.get(file_key)
            if cached is not None:
                if cached[0] == uuid:
                    cached_frame = cached[1]
                    return None if cached_frame.empty else cached_frame.copy()
                self._pool_frame_cache.pop(file_key, None)
            if not uuid:
                return None
            with pd.HDFStore(self._getHdfFile(), mode="r") as store:
                analysis_key = f"/{uuid}/analysisList"
                if analysis_key not in store:
                    return None
                spikes = sanpy.bAnalysisResults.analysisResultList()
                spikes.setFromListDict(store[analysis_key].to_dict("records"))
                metadata = MetaData()
                metadata_key = f"/{uuid}/metaDataDict"
                if metadata_key in store:
                    saved = store[metadata_key].to_dict("records")[0]
                    metadata.fromDict(
                        {k: v for k, v in saved.items() if k in metadata},
                        triggerDirty=False,
                    )
            one_df = sanpy.bAnalysis_.analysis_dataframe(
                spikes.asDataFrame(), metadata
            )

        if one_df is None or one_df.empty:
            if cache_result:
                self._pool_frame_cache[file_key] = (uuid, pd.DataFrame())
            return None
        if "spikeNumber" not in one_df.columns:
            raise ValueError(
                "SanPy spike results are missing the spikeNumber column"
            )

        one_df = one_df.copy()
        one_df["file_number"] = int(row_idx)
        one_df["file_key"] = file_key
        one_df["row_id"] = (
            one_df["file_number"].astype(int).astype(str)
            + ":"
            + one_df["spikeNumber"].astype(int).astype(str)
        )
        if cache_result:
            self._pool_frame_cache[file_key] = (uuid, one_df.copy())
        return one_df

    def pool_spike_dataframe(
        self,
        status_callback: Callable[[str], None] | None = None,
    ) -> pd.DataFrame | None:
        """Concatenate spike results for every analyzed file.

        Reuses per-file cached results or loads a saved analysis without raw
        sweep arrays when that file is not already in memory.

        Args:
            status_callback: Optional callback for per-file progress messages.

        Returns:
            The concatenated spike table, or ``None`` when no file has spikes.

        Raises:
            ValueError: If an analyzed file has no ``spikeNumber`` column.

        """
        frames: list[pd.DataFrame] = []
        row_indices = list(self._df.index)
        total = len(row_indices)
        for position, row_idx in enumerate(row_indices, start=1):
            file_key = self.get_file_key(int(row_idx))
            status_message = (
                f'Pooling file {position} of {total} "{file_key}"'
            )
            if status_callback is None:
                logger.info(status_message)
            else:
                status_callback(status_message)
            one_df = self.spike_dataframe_for_row(int(row_idx))
            if one_df is not None:
                frames.append(one_df)
        if not frames:
            return None
        return pd.concat(frames, ignore_index=True)

    def api_getFileHeaders(self):
        headerList = []
        df = self.getDataFrame()
        for row in range(len(df)):
            # ba = self.getAnalysis(row)  # do not call this, it will load
            ba = df.at[row, "_ba"]
            if ba is not None:
                headerDict = ba.api_getHeader()
                headerList.append(headerDict)
        #
        return headerList

Attributes¤

isDirty property ¤

Get the dirty state of the analysisDir.

Returns: True if the analysisDir is dirty, False otherwise.

loc property ¤

Mimic pandas df.loc[]

numFiles property ¤

Return the number of files in the collection.

Returns: Number of file-table rows.

shape property ¤

Can't just return shape of _df, columns (like 'ba') may have been added Number of columns is based on self.columns

theseFileTypes property ¤

Return the recording extensions available for folder scanning.

Returns: Extensions from the caller-supplied loader definitions, or from SanPy's registered loaders when no definitions were supplied.

Methods:¤

__init__(path=None, fileLoaderDict=None, autoLoad=False, folderDepth=None, status_callback=None) ¤

Load a folder catalog and optionally load its recordings.

Args: path: Path to a recording or folder. fileLoaderDict: File-loader definitions keyed by extension. SanPy's registered loaders are used when omitted. autoLoad: Whether to load each recording while scanning a folder. folderDepth: Maximum folder depth to scan. Use 1 for only the selected folder or None for unlimited recursion. status_callback: Optional callback for construction progress.

Note: Passing a recording path creates a one-file collection rooted in that recording's parent folder.

Source code in sanpy/analysisDir.py
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
def __init__(
    self,
    path: str | None = None,
    fileLoaderDict: dict[str, dict[str, object]] | None = None,
    autoLoad: bool = False,
    folderDepth: Optional[int] = None,
    status_callback: Callable[[str], None] | None = None,
) -> None:
    """Load a folder catalog and optionally load its recordings.

    Args:
        path: Path to a recording or folder.
        fileLoaderDict: File-loader definitions keyed by extension. SanPy's
            registered loaders are used when omitted.
        autoLoad: Whether to load each recording while scanning a folder.
        folderDepth: Maximum folder depth to scan. Use ``1`` for only the
            selected folder or ``None`` for unlimited recursion.
        status_callback: Optional callback for construction progress.

    Note:
        Passing a recording path creates a one-file collection rooted in that
        recording's parent folder.
    """

    self._filePath = None
    if os.path.isfile(path):
        self._filePath = path
        folderPath = os.path.split(path)[0]
    else:
        folderPath = path

    logger.info(f'{path}')

    self.path: str = folderPath  # path to folder

    self._fileLoaderDict = fileLoaderDict

    self.autoLoad = autoLoad

    self.folderDepth = folderDepth
    self._pool_frame_cache: dict[str, tuple[str, pd.DataFrame]] = {}

    self._isDirty = False
    # keep track if analysis was changed and prompt on quit

    # self._poolDf = None
    """See pool_ functions"""

    # TODO: refactor, we are not using the csv parth of this, just the filename
    # name of database file created/loaded from folder path
    self.dbFile = "sanpy_recording_db.csv"  # old but still critical to keep

    self._df = self.loadHdf()
    if self._df is None:
        # did not load h5 file
        self._df = self.loadFolder(
            loadData=autoLoad,
            status_callback=status_callback,
        )
        self._updateLoadedAnalyzed()
    elif self._fileLoaderDict is not None:
        logger.info(f'sync existing df with filePath: {self._filePath}')
        self.syncDfWithPath()

    #
    self._checkColumns()
    self._normalize_file_keys()
    self._updateLoadedAnalyzed()
__iter__() ¤

Iterate over the bAnalysis objects in the file table.

Source code in sanpy/analysisDir.py
515
516
517
518
def __iter__(self):
    """Iterate over the bAnalysis objects in the file table."""
    self._iterIdx = -1
    return self
__len__() ¤

Return the number of files in the collection.

Returns: Number of file-table rows.

Source code in sanpy/analysisDir.py
548
549
550
551
552
553
554
def __len__(self) -> int:
    """Return the number of files in the collection.

    Returns:
        Number of file-table rows.
    """
    return len(self._df)
__next__() ¤

Get the next bAnalysis object in the file table.

Source code in sanpy/analysisDir.py
520
521
522
523
524
525
526
527
def __next__(self):
    """Get the next bAnalysis object in the file table."""
    self._iterIdx += 1
    if self._iterIdx >= self.numFiles:
        self._iterIdx = -1  # reset to initial value
        raise StopIteration
    else:
        return self._df.loc[self._iterIdx]["_ba"]
__str__() ¤

Return a concise folder summary.

Returns: Summary containing the number of files and their total duration.

Source code in sanpy/analysisDir.py
529
530
531
532
533
534
535
536
537
def __str__(self) -> str:
    """Return a concise folder summary.

    Returns:
        Summary containing the number of files and their total duration.
    """
    totalDurSec = self._df["Dur(s)"].sum()
    theStr = f"analysisDir Num Files: {len(self)} Total Dur(s): {totalDurSec}"
    return theStr
analysisIsDirty(rowIdx) ¤

Analysis is dirty when there has been detection but not saved to h5.

Source code in sanpy/analysisDir.py
1054
1055
1056
1057
1058
1059
1060
def analysisIsDirty(self, rowIdx):
    """Analysis is dirty when there has been detection but not saved to h5."""
    isDirty = False
    ba = self._df.loc[rowIdx, "_ba"]
    if isinstance(ba, sanpy.bAnalysis):
        isDirty = ba.isDirty()
    return isDirty
appendRow(rowDict=None, ba=None) ¤

Append an empty row.

Source code in sanpy/analysisDir.py
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
def appendRow(self, rowDict=None, ba=None):
    """Append an empty row."""

    rowSeries = pd.Series()
    if rowDict is not None:
        # rowSeries = pd.Series(rowDict)
        rowSeries = pd.DataFrame([rowDict])

        # self._data.iloc[row] = rowSeries
        # self._data = self._data.reset_index(drop=True)

    newRowIdx = len(self._df)  # append this row

    df = self._df
    df = pd.concat([df, rowSeries], axis=0, ignore_index=True)

    # df = pd.concat([df,rowSeries], ignore_index=True, axis=1)
    df = df.reset_index(drop=True)

    if ba is not None:
        df.loc[newRowIdx, "_ba"] = ba

    #
    self._df = df
columnIsCheckBox(colName) ¤

All bool columns are checkbox

TODO: problems with using type=bool and isinstance(). Kust using str 'bool'

Source code in sanpy/analysisDir.py
634
635
636
637
638
639
640
641
642
643
def columnIsCheckBox(self, colName):
    """All bool columns are checkbox

    TODO: problems with using type=bool and isinstance(). Kust using str 'bool'
    """
    type = self.sanpyColumns[colName]["type"]
    # isBool = isinstance(type, bool)
    isBool = type == "bool"
    # logger.info(f'{colName} {type(type)}, type:{type} {isBool}')
    return isBool
copy() ¤

Return an independent copy of the folder's file table.

Returns: Copy of the file table, including recording metadata and status.

Source code in sanpy/analysisDir.py
614
615
616
617
618
619
620
def copy(self) -> pd.DataFrame:
    """Return an independent copy of the folder's file table.

    Returns:
        Copy of the file table, including recording metadata and status.
    """
    return self._df.copy()
copyToClipboard() ¤

TODO: Is this used or is copy to clipboard in pandas model?

Source code in sanpy/analysisDir.py
654
655
656
657
658
659
660
def copyToClipboard(self):
    """
    TODO: Is this used or is copy to clipboard in pandas model?
    """
    if self.getDataFrame() is not None:
        self.getDataFrame().to_clipboard(sep="\t", index=False)
        logger.info("Copied to clipboard")
detect_file_keys(file_keys, detection, *, should_continue=None, after_file=None) ¤

Detect spikes across recordings identified by stable file keys.

Each recording receives an independent detection dictionary covering its complete duration. Failures do not prevent later recordings from being processed.

Args: file_keys: Recording identities relative to this analysis directory. detection: Detection preset and threshold values to apply. should_continue: Optional callback before each recording. Arguments are one-based position, total count, and file key. Returning False cancels before that recording. after_file: Optional callback after one recording finishes.

Returns: Number of detected recordings and the keys that failed.

Source code in sanpy/analysisDir.py
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
def detect_file_keys(
    self,
    file_keys: Sequence[str],
    detection: Mapping[str, object],
    *,
    should_continue: Callable[[int, int, str], bool] | None = None,
    after_file: Callable[[str], None] | None = None,
) -> tuple[int, tuple[str, ...]]:
    """Detect spikes across recordings identified by stable file keys.

    Each recording receives an independent detection dictionary covering
    its complete duration. Failures do not prevent later recordings from
    being processed.

    Args:
        file_keys: Recording identities relative to this analysis directory.
        detection: Detection preset and threshold values to apply.
        should_continue: Optional callback before each recording. Arguments
            are one-based position, total count, and file key. Returning
            ``False`` cancels before that recording.
        after_file: Optional callback after one recording finishes.

    Returns:
        Number of detected recordings and the keys that failed.
    """
    detected = 0
    failed: list[str] = []
    total = len(file_keys)
    for position, file_key in enumerate(file_keys, start=1):
        if should_continue is not None and not should_continue(
            position, total, file_key
        ):
            break
        row = self.get_row_for_file_key(file_key)
        analysis = self.get_analysis_for_file_key(file_key)
        if row is None or analysis is None or analysis.loadError:
            failed.append(file_key)
            continue
        try:
            detection_for_file = copy.deepcopy(dict(detection))
            detection_for_file["startSeconds"] = 0
            detection_for_file["stopSeconds"] = analysis.fileLoader.recordingDur
            analysis.spikeDetect(detection_for_file)
            self._updateLoadedAnalyzed(row)
        except Exception:
            logger.exception(f'Batch detection failed for "{file_key}"')
            failed.append(file_key)
            continue
        detected += 1
        if after_file is not None:
            after_file(file_key)
    return detected, tuple(failed)
findFileRow(filename) ¤

Find the row index of a file in the file table.

Args: filename: The name of the file to find.

Returns: The row index of the file in the file table, or None if the file is not found.

Source code in sanpy/analysisDir.py
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
def findFileRow(self, filename):
    """Find the row index of a file in the file table.

    Args:
        filename: The name of the file to find.

    Returns:
        The row index of the file in the file table, or None if the file is not found.
    """
    fileIndexList = self._df.index[self._df['File'] == filename].tolist()
    if fileIndexList:
        rowIdx = fileIndexList[0]
        return rowIdx
    else:
        logger.warning(f"Did not find file {filename} in {self._df['File'].tolist()}")
getAnalysis(rowIdx, allowAutoLoad=True, verbose=False) ¤

Get bAnalysis object, will load if necc.

Args: rowIdx (int): Row index from table, corresponds to row in self._df allowAutoLoad (bool) Return: bAnalysis

Source code in sanpy/analysisDir.py
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
def getAnalysis(self, rowIdx, allowAutoLoad=True, verbose=False) -> sanpy.bAnalysis:
    """Get bAnalysis object, will load if necc.

    Args:
        rowIdx (int): Row index from table, corresponds to row in self._df
        allowAutoLoad (bool)
    Return:
        bAnalysis
    """
    file = self._df.loc[rowIdx, "File"]
    ba = self._df.loc[rowIdx, "_ba"]
    uuid = self._df.loc[rowIdx, "uuid"]  # if we have a uuid bAnalysis is saved in h5f

    if ba is None or ba == "":
        relPath = self._df.loc[rowIdx, "relPath"]
        filePath = self.getPathFromRelPath(relPath)

        ba = self.loadOneAnalysis(
            filePath, uuid, allowAutoLoad=allowAutoLoad, verbose=verbose
        )
        # load
        if ba is None:
            logger.warning(
                f'Did not load row {rowIdx} path: "{filePath}". Analysis was probably not saved'
            )
        else:
            self._df.at[rowIdx, "_ba"] = ba
            # does not get a uuid until save into h5
            if uuid:
                # there was an original uuid (in table), means we are saved into h5
                self._df.at[rowIdx, "uuid"] = uuid
                if uuid != ba.uuid:
                    logger.error(
                        "Loaded uuid does not match existing in file table"
                    )
                    logger.error(f"  Loaded {ba.uuid}")
                    logger.error(f"  Existing {uuid}")

            #
            # update stats of table load/analyzed columns
            self._updateLoadedAnalyzed()

    return ba
getDataFrame() ¤

Return the mutable file table used by this collection.

Returns: Internal file table. Use copy() when mutations should not affect the collection.

Source code in sanpy/analysisDir.py
645
646
647
648
649
650
651
652
def getDataFrame(self) -> pd.DataFrame:
    """Return the mutable file table used by this collection.

    Returns:
        Internal file table. Use ``copy()`` when mutations should not affect
        the collection.
    """
    return self._df
getFileList(path=None) ¤

Get file paths from path.

Uses self.theseFileTypes

Source code in sanpy/analysisDir.py
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
def getFileList(self,
                path: str = None,
                ) -> List[str]:
    """Get file paths from path.

    Uses self.theseFileTypes

    """

    if self._filePath is not None:
        logger.info(f'returning one file {self._filePath}')
        return [self._filePath]

    if path is None:
        path = self.path

    fileList = getFileList(path, self.theseFileTypes, self.folderDepth)
    return fileList
getFileRow(path, loadData=False) ¤

Get dict representing one file (row in table). Loads bAnalysis to get headers.

On load error of proper file type (abf, csv), ba.loadError==True

Args: path (Str): Full path to file. #rowIdx (int): Optional row index to assign in column 'Idx'

Return: (tuple): tuple containing:

- ba (bAnalysis): [sanpy.bAnalysis](/api/bAnalysis).
- rowDict (dict): On success, otherwise None.
        fails when path does not lead to valid bAnalysis file.
Source code in sanpy/analysisDir.py
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
def getFileRow(self, path, loadData=False):
    """Get dict representing one file (row in table). Loads bAnalysis to get headers.

    On load error of proper file type (abf, csv), ba.loadError==True

    Args:
        path (Str): Full path to file.
        #rowIdx (int): Optional row index to assign in column 'Idx'

    Return:
        (tuple): tuple containing:

        - ba (bAnalysis): [sanpy.bAnalysis](/api/bAnalysis).
        - rowDict (dict): On success, otherwise None.
                fails when path does not lead to valid bAnalysis file.
    """
    if not os.path.isfile(path):
        logger.warning(f'Did not find file "{path}"')
        return None, None

    fileType = os.path.splitext(path)[1]

    if fileType not in self.theseFileTypes:  
        logger.warning(f'Did not load file type "{fileType}"')
        return None, None

    ba = sanpy.bAnalysis(path,
                         loadData=loadData,
                         fileLoaderDict=self._fileLoaderDict)

    if ba.loadError:
        logger.error(f'Error loading bAnalysis file "{path}"')
        # return None, None

    # not sufficient to default everything to empty str ''
    # sanpyColumns can only have type in ('float', 'str')
    rowDict = dict.fromkeys(self.sanpyColumns.keys(), "")
    for k in rowDict.keys():
        if self.sanpyColumns[k]["type"] == str:
            rowDict[k] = ""
        elif self.sanpyColumns[k]["type"] == float:
            rowDict[k] = np.nan

    if ba.loadError:
        return None, None

    rowDict["File"] = ba.fileLoader.filename  # os.path.split(ba.path)[1]
    rowDict["Dur(s)"] = ba.fileLoader.recordingDur
    rowDict["Channels"] = ba.fileLoader.numChannels  # Theanne
    rowDict["Sweeps"] = ba.fileLoader.numSweeps

    # here, we do not get an epoch table until the file is loaded !!!
    rowDict["Epochs"] = ba.fileLoader.numEpochs  # Theanne, data has to be loaded

    rowDict["kHz"] = ba.fileLoader.recordingFrequency
    rowDict["Mode"] = ba.fileLoader.recordingMode.value

    # add parent1, parent2, parent3
    _path, _file = os.path.split(path)
    _path, _parent1 = os.path.split(_path)
    _path, _parent2 = os.path.split(_path)
    _path, _parent3 = os.path.split(_path)
    rowDict['parent1'] = _parent1
    rowDict['parent2'] = _parent2
    rowDict['parent3'] = _parent3

    # aug 2023,  adding bAnalysis metadata columns
    for k,v in ba.metaData.items():
        rowDict[k] = v

    # remove the path to the folder we have loaded
    rowDict["relPath"] = _normalized_file_key(self.path, path)

    return ba, rowDict
getPathFromRelPath(relPath) ¤

Get full path to file from relPath.

Uses analysisDir folder path.

Source code in sanpy/analysisDir.py
662
663
664
665
666
667
668
669
670
671
672
def getPathFromRelPath(self, relPath):
    """Get full path to file from relPath.

    Uses analysisDir folder path.
    """
    if relPath.startswith("/"):
        relPath = relPath[1:]

    fullFilePath = os.path.join(self.path, relPath)

    return fullFilePath
getRowDict(rowIdx) ¤

Return a dict with selected row as dict (includes detection parameters).

Important to return a copy as our '_ba' is a pointer to bAnalysis.

Returns: theRet (dict): Be sure to make a deep copy of ['_ba'] if neccessary.

Source code in sanpy/analysisDir.py
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
def getRowDict(self, rowIdx):
    """
    Return a dict with selected row as dict (includes detection parameters).

    Important to return a copy as our '_ba' is a pointer to bAnalysis.

    Returns:
        theRet (dict): Be sure to make a deep copy of ['_ba'] if neccessary.
    """
    theRet = {}
    # use columns in main sanpyColumns, not in df
    # for colStr in self.columns:
    for colStr in self._df.columns:
        # theRet[colStr] = self._df.loc[rowIdx, colStr]
        theRet[colStr] = self._df.loc[rowIdx, colStr]
    # theRet['_ba'] = theRet['_ba'].copy()
    return theRet
get_analysis_for_file_key(file_key, allow_auto_load=True) ¤

Resolve and optionally load an analysis by stable file key.

Args: file_key: Recording identity relative to the analysis directory. allow_auto_load: Whether the recording may be loaded on demand.

Returns: Resolved analysis, or None when the key is unknown or cannot load.

Source code in sanpy/analysisDir.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def get_analysis_for_file_key(
    self,
    file_key: str,
    allow_auto_load: bool = True,
) -> Optional[sanpy.bAnalysis]:
    """Resolve and optionally load an analysis by stable file key.

    Args:
        file_key: Recording identity relative to the analysis directory.
        allow_auto_load: Whether the recording may be loaded on demand.

    Returns:
        Resolved analysis, or ``None`` when the key is unknown or cannot load.
    """
    row_index = self.get_row_for_file_key(file_key)
    if row_index is None:
        return None
    return self.getAnalysis(row_index, allowAutoLoad=allow_auto_load)
get_file_key(row_idx) ¤

Return the stable file key for one table row.

Args: row_idx: File-table row index.

Returns: Normalized path relative to the analysis directory.

Source code in sanpy/analysisDir.py
330
331
332
333
334
335
336
337
338
339
def get_file_key(self, row_idx: int) -> str:
    """Return the stable file key for one table row.

    Args:
        row_idx: File-table row index.

    Returns:
        Normalized path relative to the analysis directory.
    """
    return str(self._df.at[row_idx, "relPath"])
get_row_for_file_key(file_key) ¤

Return the table row for a normalized file key.

Args: file_key: Recording identity relative to the analysis directory.

Returns: Matching row index, or None when the key is unknown.

Source code in sanpy/analysisDir.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def get_row_for_file_key(self, file_key: str) -> int | None:
    """Return the table row for a normalized file key.

    Args:
        file_key: Recording identity relative to the analysis directory.

    Returns:
        Matching row index, or ``None`` when the key is unknown.
    """
    try:
        normalized = _normalized_file_key(self.path, file_key)
    except ValueError:
        return None
    rows = self._df.index[self._df["relPath"] == normalized].tolist()
    return int(rows[0]) if rows else None
hasDirty() ¤

Return true if any bAnalysis in list has been analyzed but not saved (e.g. is dirty).

Source code in sanpy/analysisDir.py
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
def hasDirty(self):
    """Return true if any bAnalysis in list has been analyzed but not saved (e.g. is dirty).
    """
    haveDirty = False
    numRows = len(self._df)
    for rowIdx in range(numRows):
        if self.analysisIsDirty(rowIdx):
            haveDirty = True

    return haveDirty
loadFolder(path=None, loadData=False, status_callback=None) ¤

Parse a folder and build its recording table.

Args: path: Folder to scan. The configured directory is used when omitted. loadData: Whether to retain each loaded analysis in memory. status_callback: Optional callback for per-file progress messages.

Returns: Dataframe containing one row for each supported recording.

Source code in sanpy/analysisDir.py
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
def loadFolder(
    self,
    path: str | None = None,
    loadData: bool = False,
    status_callback: Callable[[str], None] | None = None,
) -> pd.DataFrame:
    """Parse a folder and build its recording table.

    Args:
        path: Folder to scan. The configured directory is used when omitted.
        loadData: Whether to retain each loaded analysis in memory.
        status_callback: Optional callback for per-file progress messages.

    Returns:
        Dataframe containing one row for each supported recording.
    """
    logger.info("Loading folder from scratch (no h5 file)")

    start = time.time()
    if path is None:
        path = self.path
    self.path = path

    df = pd.DataFrame(columns=self.sanpyColumns.keys())
    df = self._setColumnType(df)

    # get list of all abf/csv/tif files
    fileList = self.getFileList(path)
    _numFilesToLoad = len(fileList)
    start = time.time()
    # build new db dataframe
    listOfDict = []
    for rowIdx, fullFilePath in enumerate(fileList):
        status_message = (
            f'Loading file {rowIdx+1} of {_numFilesToLoad} "{_normalized_file_key(self.path, fullFilePath)}"'
        )
        if status_callback is None:
            logger.info(status_message)
        else:
            status_callback(status_message)

        # rowDict is what we are showing in the file table
        # abb debug vue, set loadData=True
        # loads bAnalysis
        ba, rowDict = self.getFileRow(fullFilePath, loadData=loadData)

        if rowDict is None:
            logger.warning(f'error loading file {fullFilePath}')
            continue

        # as we parse the folder, don't load ALL files (will run out of memory)
        if loadData:
            rowDict["_ba"] = ba
        else:
            rowDict["_ba"] = None  # ba

        # do not assign uuid until bAnalysis is saved in h5 file
        # rowDict['uuid'] = ''

        # logger.info(f'    row:{rowIdx} relPath:{relPath} fullFilePath:{fullFilePath}')

        listOfDict.append(rowDict)

    stop = time.time()
    logger.info(f"Loading {len(listOfDict)} files took {round(stop-start,3)} seconds.")

    df = pd.DataFrame(listOfDict)
    df = self._setColumnType(df)

    return df
loadHdf(path=None, verbose=False) ¤

Load the database key from an h5 file.

We do not load analysis until user clicks on row, see loadOneAnalysis()

Source code in sanpy/analysisDir.py
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
def loadHdf(self, path=None, verbose=False):
    """Load the database key from an h5 file.

    We do not load analysis until user clicks on row, see loadOneAnalysis()
    """
    if path is None:
        path = self.path
    self.path = path

    df = None
    hdfFile = os.path.splitext(self.dbFile)[0] + ".h5"
    hdfPath = pathlib.Path(self.path) / hdfFile
    if not hdfPath.is_file():
        return

    # logger.info(f"Loading existing folder h5 file {hdfPath}")
    # sanpy.h5Util.listKeys(hdfPath)

    _start = time.time()
    dbKey = os.path.splitext(self.dbFile)[0]

    try:
        df = pd.read_hdf(hdfPath, dbKey)
    except KeyError as e:
        # file is corrupt !!!
        logger.error(f'    Load h5 failed, did not find dbKey:"{dbKey}" {e}')

    if df is not None:
        # _ba is for runtime, assign after loading from either (abf or h5)
        df["_ba"] = None

        # fix bug during dev of ba metadata
        # df['Sex'] = 'unknown'

        if verbose:
            logger.info("    loaded db df")

        _stop = time.time()
        # logger.info(f"Loading took {round(_stop-_start,2)} seconds")

        # if we are one file then make sure file is in df

    return df
loadOneAnalysis(path, uuid=None, allowAutoLoad=True, verbose=False) ¤

Load one analysis from its recording and optional HDF5 data.

If from h5, we still need to reload sweeps !!! They are binary and fast, saving to h5 (in this case) is slow.

Args: path: Recording path. uuid: Optional analysis identifier in the folder HDF5 file. allowAutoLoad: Load directly from the recording when HDF5 data is unavailable. verbose: Emit detailed loading messages.

Returns: A valid loaded analysis, or None when the recording cannot be loaded.

Source code in sanpy/analysisDir.py
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
def loadOneAnalysis(
    self,
    path: str,
    uuid: Optional[str] = None,
    allowAutoLoad: bool = True,
    verbose: bool = False,
) -> Optional[sanpy.bAnalysis]:
    """Load one analysis from its recording and optional HDF5 data.

    If from h5, we still need to reload sweeps !!!
    They are binary and fast, saving to h5 (in this case) is slow.

    Args:
        path: Recording path.
        uuid: Optional analysis identifier in the folder HDF5 file.
        allowAutoLoad: Load directly from the recording when HDF5 data is
            unavailable.
        verbose: Emit detailed loading messages.

    Returns:
        A valid loaded analysis, or ``None`` when the recording cannot be
        loaded.
    """
    if verbose:
        logger.info(f'path:"{path}" uuid:"{uuid}" allowAutoLoad:"{allowAutoLoad}"')

    hdfPath = self._getHdfFile()

    ba = None
    if uuid is not None and uuid:
        # load from h5
        if verbose:
            logger.info(f"    Retreiving uuid from hdf file {uuid}")

        # load from abf
        # ba = sanpy.bAnalysis(path, fileLoaderDict=self._fileLoaderDict, verbose=verbose)
        ba = sanpy.bAnalysis(path, loadData=allowAutoLoad, fileLoaderDict=self._fileLoaderDict, verbose=verbose)

        if ba.loadError:
            logger.error('Unable to load recording "%s"', path)
            return None

        # load analysis from h5 file, will fail if uuid is not in file
        ba._loadHdf_pytables(hdfPath, uuid)

    if allowAutoLoad and ba is None:
        # load from path
        ba = sanpy.bAnalysis(path, fileLoaderDict=self._fileLoaderDict, verbose=verbose)
        if verbose:
            logger.info(f"    Loaded ba from path {path} and now ba:{ba}")

    if ba is not None and ba.loadError:
        logger.error('Unable to load recording "%s"', path)
        return None
    #
    return ba
pool_spike_dataframe(status_callback=None) ¤

Concatenate spike results for every analyzed file.

Reuses per-file cached results or loads a saved analysis without raw sweep arrays when that file is not already in memory.

Args: status_callback: Optional callback for per-file progress messages.

Returns: The concatenated spike table, or None when no file has spikes.

Raises: ValueError: If an analyzed file has no spikeNumber column.

Source code in sanpy/analysisDir.py
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
def pool_spike_dataframe(
    self,
    status_callback: Callable[[str], None] | None = None,
) -> pd.DataFrame | None:
    """Concatenate spike results for every analyzed file.

    Reuses per-file cached results or loads a saved analysis without raw
    sweep arrays when that file is not already in memory.

    Args:
        status_callback: Optional callback for per-file progress messages.

    Returns:
        The concatenated spike table, or ``None`` when no file has spikes.

    Raises:
        ValueError: If an analyzed file has no ``spikeNumber`` column.

    """
    frames: list[pd.DataFrame] = []
    row_indices = list(self._df.index)
    total = len(row_indices)
    for position, row_idx in enumerate(row_indices, start=1):
        file_key = self.get_file_key(int(row_idx))
        status_message = (
            f'Pooling file {position} of {total} "{file_key}"'
        )
        if status_callback is None:
            logger.info(status_message)
        else:
            status_callback(status_message)
        one_df = self.spike_dataframe_for_row(int(row_idx))
        if one_df is not None:
            frames.append(one_df)
    if not frames:
        return None
    return pd.concat(frames, ignore_index=True)
saveHdf() ¤

Save file table and any number of loaded and analyzed bAnalysis.

Set file table 'uuid' column when we actually save a bAnalysis

Important: Order matters (1) Save bAnalysis first, it updates uuid in file table. (2) Save file table with updated uuid

Source code in sanpy/analysisDir.py
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
def saveHdf(self):
    """Save file table and any number of loaded and analyzed bAnalysis.

    Set file table 'uuid' column when we actually save a bAnalysis

    Important: Order matters
        (1) Save bAnalysis first, it updates uuid in file table.
        (2) Save file table with updated uuid
    """
    start = time.time()

    df = self.getDataFrame()

    # the compressed version from the last save
    hdfFile = os.path.splitext(self.dbFile)[0] + ".h5"
    hdfFilePath = pathlib.Path(self.path) / hdfFile

    logger.info(f"Saving h5 db (will be compressed) {hdfFilePath}")

    # save each bAnalysis
    for row in range(len(df)):
        ba = df.at[row, "_ba"]
        if ba is not None:
            didSave = ba._saveHdf_pytables(hdfFilePath)
            if didSave:
                # we are now saved into h5 file, remember uuid to load
                df.at[row, "uuid"] = ba.uuid
                self._pool_frame_cache.pop(self.get_file_key(row), None)

    # rebuild (L, A, S) columns
    self._updateLoadedAnalyzed()

    #
    # save file database
    logger.info(f"    saving file db with {len(df)} rows")
    # print(df)

    dbKey = os.path.splitext(self.dbFile)[0]
    df = df.drop("_ba", axis=1)  # don't ever save _ba, use it for runtime

    # hdfStore[dbKey] = df  # save it
    df.to_hdf(hdfFilePath, key=dbKey)
    with pd.HDFStore(hdfFilePath) as hdfStore:
        hdfStore.get_storer(dbKey).attrs.sanpy_format_version = SANPY_H5_FORMAT_VERSION

    #
    self._isDirty = False  # if true, prompt to save on quit

    # rebuild the file to remove old changes and reduce size
    # self._rebuildHdf()
    sanpy.h5Util._repackHdf(hdfFilePath)

    stop = time.time()
    logger.info(f"    Saving took {round(stop-start,2)} seconds")
set_metadata_for_file_keys(file_keys, key, value, *, should_continue=None, after_file=None) ¤

Set one experimental metadata value across recordings.

Analyses are loaded when necessary and left dirty for the existing save workflow. This method never persists changes.

Args: file_keys: Recording identities relative to this analysis directory. key: Canonical experimental-metadata key. value: New string value. should_continue: Optional callback before each recording. Arguments are one-based position, total count, and file key. Returning False cancels before that recording. after_file: Optional callback after one recording is processed.

Returns: Number of changed recordings and the keys that failed.

Raises: ValueError: If key is not canonical experimental metadata.

Source code in sanpy/analysisDir.py
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
def set_metadata_for_file_keys(
    self,
    file_keys: Sequence[str],
    key: str,
    value: str,
    *,
    should_continue: Callable[[int, int, str], bool] | None = None,
    after_file: Callable[[str], None] | None = None,
) -> tuple[int, tuple[str, ...]]:
    """Set one experimental metadata value across recordings.

    Analyses are loaded when necessary and left dirty for the existing save
    workflow. This method never persists changes.

    Args:
        file_keys: Recording identities relative to this analysis directory.
        key: Canonical experimental-metadata key.
        value: New string value.
        should_continue: Optional callback before each recording. Arguments
            are one-based position, total count, and file key. Returning
            ``False`` cancels before that recording.
        after_file: Optional callback after one recording is processed.

    Returns:
        Number of changed recordings and the keys that failed.

    Raises:
        ValueError: If ``key`` is not canonical experimental metadata.
    """
    if key not in MetaData.getMetaDataDict():
        raise ValueError(f'Unknown experimental metadata key: "{key}"')
    changed = 0
    failed: list[str] = []
    total = len(file_keys)
    for position, file_key in enumerate(file_keys, start=1):
        if should_continue is not None and not should_continue(
            position, total, file_key
        ):
            break
        row = self.get_row_for_file_key(file_key)
        analysis = self.get_analysis_for_file_key(file_key)
        if row is None or analysis is None or analysis.loadError:
            failed.append(file_key)
            continue
        try:
            previous = analysis.metaData.getMetaData(key)
            analysis.metaData.setMetaData(key, value)
            self._updateLoadedAnalyzed(row)
        except Exception:
            logger.exception(f'Batch metadata update failed for "{file_key}"')
            failed.append(file_key)
            continue
        if previous != value:
            changed += 1
        if after_file is not None:
            after_file(file_key)
    return changed, tuple(failed)
spike_dataframe_for_row(row_idx) ¤

Return pooled spike results for one file-table row.

A loaded analysis is always authoritative. For an unloaded row, a matching cached frame is reused or the saved spike results and file metadata are read from the folder HDF5 file without opening the recording.

Args: row_idx: File-table row index.

Returns: Copied spike results with pooled identity columns, or None when the row has no saved analyzed spikes.

Raises: ValueError: If analyzed results have no spikeNumber column.

Source code in sanpy/analysisDir.py
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
def spike_dataframe_for_row(self, row_idx: int) -> pd.DataFrame | None:
    """Return pooled spike results for one file-table row.

    A loaded analysis is always authoritative. For an unloaded row, a
    matching cached frame is reused or the saved spike results and file
    metadata are read from the folder HDF5 file without opening the
    recording.

    Args:
        row_idx: File-table row index.

    Returns:
        Copied spike results with pooled identity columns, or ``None`` when
        the row has no saved analyzed spikes.

    Raises:
        ValueError: If analyzed results have no ``spikeNumber`` column.
    """
    file_key = self.get_file_key(row_idx)
    uuid = str(self._df.at[row_idx, "uuid"])
    ba = self._df.at[row_idx, "_ba"]
    cache_result = ba is None or ba == ""

    if not cache_result:
        self._pool_frame_cache.pop(file_key, None)
        if not ba.isAnalyzed():
            return None
        one_df = ba.asDataFrame(regenerateAnalysisDataFrame=True)
    else:
        cached = self._pool_frame_cache.get(file_key)
        if cached is not None:
            if cached[0] == uuid:
                cached_frame = cached[1]
                return None if cached_frame.empty else cached_frame.copy()
            self._pool_frame_cache.pop(file_key, None)
        if not uuid:
            return None
        with pd.HDFStore(self._getHdfFile(), mode="r") as store:
            analysis_key = f"/{uuid}/analysisList"
            if analysis_key not in store:
                return None
            spikes = sanpy.bAnalysisResults.analysisResultList()
            spikes.setFromListDict(store[analysis_key].to_dict("records"))
            metadata = MetaData()
            metadata_key = f"/{uuid}/metaDataDict"
            if metadata_key in store:
                saved = store[metadata_key].to_dict("records")[0]
                metadata.fromDict(
                    {k: v for k, v in saved.items() if k in metadata},
                    triggerDirty=False,
                )
        one_df = sanpy.bAnalysis_.analysis_dataframe(
            spikes.asDataFrame(), metadata
        )

    if one_df is None or one_df.empty:
        if cache_result:
            self._pool_frame_cache[file_key] = (uuid, pd.DataFrame())
        return None
    if "spikeNumber" not in one_df.columns:
        raise ValueError(
            "SanPy spike results are missing the spikeNumber column"
        )

    one_df = one_df.copy()
    one_df["file_number"] = int(row_idx)
    one_df["file_key"] = file_key
    one_df["row_id"] = (
        one_df["file_number"].astype(int).astype(str)
        + ":"
        + one_df["spikeNumber"].astype(int).astype(str)
    )
    if cache_result:
        self._pool_frame_cache[file_key] = (uuid, one_df.copy())
    return one_df
syncDfWithPath() ¤

Sync path with existing df. Used to detect new/removed files.

If we currently have just one file (self._filePath) we will trash it and load a folder

Notes

20231230, trying to use this to open a one file window with an exiting h5 file.

Source code in sanpy/analysisDir.py
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
def syncDfWithPath(self):
    """Sync path with existing df. Used to detect new/removed files.

    If we currently have just one file (self._filePath) we will trash it and load a folder

    Notes
    -----
    20231230, trying to use this to open a one file window with an exiting h5 file.
    """
    self._pool_frame_cache.clear()

    pathFileList = self.getFileList()

    # our currently loaded files
    dfFileList = self._df["File"].tolist()

    # logger.info(f'dfFileList: {dfFileList}')
    # print('    === pathFileList (on drive):')
    # print('    ', pathFileList)
    # print('    === dfFileList (in table):')
    # print('    ', dfFileList)

    addedToDf = False

    # look for files in path not in df
    for pathFile in pathFileList:
        fileName = os.path.split(pathFile)[1]
        if fileName not in dfFileList:
            logger.info(f'   Found file in path "{fileName}" not in df')

            # load bAnalysis and get df column values
            addedToDf = True

            ba, rowDict = self.getFileRow(pathFile)  # loads bAnalysis

            if rowDict is not None:
                # listOfDict.append(rowDict)

                # TODO: get this into getFileROw()
                # logger.warning("bug 20220718, not sure we need this ???")
                # print(rowDict)

                # rowDict['relPath'] = pathFile
                rowDict["_ba"] = None

                self.appendRow(rowDict=rowDict, ba=None)

    # look for files in df not in path
    # for dfFile in dfFileList:
    #     if not dfFile in pathFileList:
    #         logger.info(f'Found file in df "{dfFile}" not in path')

    if addedToDf:
        df = self._df
        df = df.sort_values(
            by=["File"], axis="index", ascending=True, inplace=False
        )
        df = df.reset_index(drop=True)
        self._df = df

    self._updateLoadedAnalyzed()

Functions:¤

getFileList(path, theseFileTypes, depth=1) ¤

Get a list of files from a path.

Source code in sanpy/analysisDir.py
210
211
212
213
def getFileList(path, theseFileTypes, depth=1):
    """Get a list of files from a path."""
    fileList = [filePath for filePath in _walk(path, theseFileTypes, depth)]
    return fileList
All material is Copyright 2019-2026 Robert H. Cudmore