Skip to content

analysisDir

Class to manage a list of files loaded from a folder.

Source code in sanpy/analysisDir.py
 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
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
class analysisDir:
    """Class to manage a list of files loaded from a folder.
    """

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

    # 20231230, get this from sanpyapp fileloader keys
    # theseFileTypes = [".abf", ".atf", ".sanpy", ".tif"]  # .dat .czi
    # File types to load.

    def __init__(
        self,
        path: str = None,
        filePath : str = None,
        sanPyWindow : "sanpy.interface.SanPyWindow" = None,
        fileLoaderDict : dict = None,
        autoLoad: bool = False,
        folderDepth: Optional[int] = None,
    ):
        """Load and manage a list of files in a folder path.

        Use this as the main pandasModel for file list myTableView.

        TODO: extend to link to folder in cloud (start with box and/or github)

        Parameters
        ----------
        path (str):
            Path to folder
        filePath (str):
            Path to one file
        sanPyWindow (sanpy.interface.SanPyWindow)
            PyQt, used to signal progress on loading
        fileLoaderDict (dict):
            Dict with file extension keys (no dot)
        autoLoad (bool):
            If True then 
        folderDepth (int):
            Folder depth to recurse if loading folder path.

        Notes
        -----
        - Some functions are so self can mimic a pandas dataframe used by pandasModel.
            (shape, loc, loc_setter, iloc, iLoc_setter, columns, append, drop, sort_values, copy)
        - 202312 adding filepath to load just one file
        """

        self._filePath = filePath
        if filePath is not None and os.path.isfile(filePath):
            self._filePath = filePath
            path = os.path.split(filePath)[0]

        logger.info(f'{path} self._filePath:{self._filePath}')

        self.path: str = path

        self._sanPyWindow = sanPyWindow
        # used to signal on building initial db

        self._fileLoaderDict = fileLoaderDict
        # dist with file extension keys

        self.autoLoad = autoLoad
        # not used

        self.folderDepth = folderDepth

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

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

        # keys are full path to file, if from cloud, key is 'cloud/<filename>'
        # holds bAnalysisObjects
        # needs to be a list so we can have files more than one
        # self.fileList = [] #OrderedDict()

        # 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"

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

        # if we have a filePath and not in df then add it
        if self._filePath is not None:

            logger.info('self._df')
            print(self._df)

        # self._df = self.loadFolder(loadData=autoLoad)

        #
        self._checkColumns()
        self._updateLoadedAnalyzed()

    @property
    def theseFileTypes(self):
        """Get list of file extensions we will load.
        """
        if self._fileLoaderDict is not None:
            return list(self._fileLoaderDict.keys())

    def findFileRow(self, filename):
        # filename = os.path.split(filePath)[1]
        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):
        self._iterIdx = -1
        return self

        # self._iterIdx = 0
        # logger.info(f'making iter for bAnalysisDir')
        # print(self._df)
        # x = self._df.loc[self._iterIdx]["_ba"]
        # return x

    def __next__(self):
        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"]

        # if self._iterIdx < self.numFiles:
        #     x = self._df.loc[self._iterIdx]["_ba"]
        #     self._iterIdx += 1
        #     return x
        # else:
        #     raise StopIteration

    def __str__(self):
        totalDurSec = self._df["Dur(s)"].sum()
        theStr = f"analysisDir Num Files: {len(self)} Total Dur(s): {totalDurSec}"
        return theStr

    @property
    def isDirty(self):
        return self._isDirty

    def __len__(self):
        return len(self._df)

    @property
    def numFiles(self):
        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 iat(self):
        # mimic pandas df.iat[]
        return self._df.iat

    @iat.setter
    def iat_setter(self, rowIdx, colStr, value):
        self._df.iat[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):
        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):
        """Get the underlying pandas DataFrame."""
        return self._df

    @property
    def numFiles(self):
        """Get the number of files. same as len()."""
        return len(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)

        """
        print('xxx', self.path)
        print('xxx', relPath)
        print('xxx', fullFilePath)
        """

        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 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
                    # print('xxx SETTING dir uuid')
                    df.at[row, "uuid"] = ba.uuid

        # 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, dbKey)

        #
        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)

        # list the keys in the file
        # sanpy.h5Util.listKeys(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 analy anlysis 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, uuid=None, allowAutoLoad=True, verbose=False):
        """Load one bAnalysis either from original file path or uuid of h5 file.

        If from h5, we still need to reload sweeps !!!
        They are binary and fast, saving to h5 (in this case) is slow.
        """
        if verbose:
            logger.info(f'path:"{path}" uuid:"{uuid}" allowAutoLoad:"{allowAutoLoad}"')

        hdfPath = self._getHdfFile()

        # grab the fileLoaderDict from our app
        # if it is None then bAnalysis will load this (from disk)
        # if self.mySanPyWindow is not None:
        #     _fileLoaderDict = self.mySanPyWindow.getSanPyApp().getFileLoaderDict()
        # else:
        #     _fileLoaderDict = None

        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)

            # 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}")
        #
        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=None, loadData=False) -> pd.DataFrame:
        """Parse a folder and load all (abf, csv, ...).

        Only called if no h5 file.

        TODO: get rid of loading database from .csv (it is replaced by .h5 file)
        TODO: extend the logic to load from cloud (after we were instantiated)
        """
        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):

            self.signalWindow(
                f'Loading file {rowIdx+1} of {_numFilesToLoad} "{fullFilePath}"'
            )

            # 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):
        """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 not col in loadedColumns:
                # loaded is missing expected, add it
                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
                startSec = ba.getDetectionDict()["startSeconds"]
                stopSec = ba.getDetectionDict()["stopSeconds"]
                self._df.loc[rowIdx, "Start(s)"] = startSec
                self._df.loc[rowIdx, "Stop(s)"] = stopSec

                dvdtThreshold = ba.getDetectionDict()["dvdtThreshold"]
                mvThreshold = ba.getDetectionDict()["mvThreshold"]
                self._df.loc[rowIdx, "dvdtThreshold"] = dvdtThreshold
                self._df.loc[rowIdx, "mvThreshold"] = mvThreshold

                #
                # TODO: remove start of ba._path that corresponds to our current folder path
                # will allow our save db to be modular

                # relPth 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

            # kymograph interface
            # 20230602, don't show rect in interface
            # if ba is not None and ba.fileLoader.isKymograph():
            #     kRect = ba.fileLoader.getKymographRect()

            #     # print(kRect)
            #     # sys.exit(1)

            #     if kRect is None:
            #         logger.error(f"Got None kymograph rect")
            #     else:
            #         self._df.loc[rowIdx, "kLeft"] = kRect[0]
            #         self._df.loc[rowIdx, "kTop"] = kRect[1]
            #         self._df.loc[rowIdx, "kRight"] = kRect[2]
            #         self._df.loc[rowIdx, "kBottom"] = kRect[3]
            #
            # 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 setCellValue(self, rowIdx, colStr, value):
        self._df.loc[rowIdx, colStr] = value
    """

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

    def isAnalyzed(self, rowIdx):
        isAnalyzed = False
        ba = self._df.loc[rowIdx, "_ba"]
        # print('isAnalyzed()', rowIdx, ba)
        # if ba is not None:
        # print('qqq', rowIdx, ba, type(ba))
        # sanpy.bAnalysis_.bAnalysis
        # if isinstance(ba, sanpy.bAnalysis):
        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
        # filePath = os.path.join(self.path, file)
        # logger.info(f'Found _ba in file db with ba:"{ba}" {type(ba)}')
        # logger.info(f'rowIdx: {rowIdx} ba:{ba}')

        if ba is None or ba == "":
            # logger.info('did not find _ba ... loading from abf file ...')
            # working on kymograph
            #                 relPath = self.getPathFromRelPath(ba._path)
            relPath = self._df.loc[rowIdx, "relPath"]
            filePath = self.getPathFromRelPath(relPath)

            ba = self.loadOneAnalysis(
                filePath, uuid, allowAutoLoad=allowAutoLoad, verbose=verbose
            )
            # load
            """
            logger.info(f'Loading bAnalysis from row {rowIdx} "{filePath}"')
            ba = sanpy.bAnalysis(filePath)
            """
            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}")

                # kymograph, set ba rect from table
                # if ba is not None and ba.fileLoader.isKymograph():
                #     left = self._df.loc[rowIdx, "kLeft"]
                #     top = self._df.loc[rowIdx, "kTop"]
                #     right = self._df.loc[rowIdx, "kRight"]
                #     bottom = self._df.loc[rowIdx, "kBottom"]

                #     # on first load, these will be empty
                #     # grab rect from ba (in _updateLoadedAnalyzed())
                #     if left == "" or top == "" or right == "" or bottom == "":
                #         pass
                #     else:
                #         theRect = [left, top, right, bottom]
                #         logger.info(f"  theRect:{theRect}")
                #         ba.fileLoader._updateTifRoi(theRect)

                #
                # 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 not col in self.sanpyColumns:
                logger.warning(f'Column "{col}" is not in sanpyColumns -->> ignoring')
                continue
            colType = self.sanpyColumns[col]["type"]
            # print(f'  _setColumnType() for "{col}" is type "{colType}"')
            # print(f'    df[col]:', 'len:', len(df[col]))
            # print(df[col])
            if colType == str:
                df[col] = df[col].replace(np.nan, "", regex=True)
                df[col] = df[col].astype(str)
            elif colType == int:
                pass
                # print('!!! df[col]:', df[col])
                # df[col] = df[col].astype(int)
            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:
        #     fileType = fileType[1:]  # [1:] to strip period
        if fileType not in self.theseFileTypes:  
            logger.warning(f'Did not load file type "{fileType}"')
            return None, None

        # grab the fileLoaderDict from our app
        # if it is None then bAnalysis will load this (from disk)
        # if self.mySanPyWindow is not None:
        #     _fileLoaderDict = self.mySanPyWindow.getSanPyApp().getFileLoaderDict()
        # else:
        #     _fileLoaderDict = None

        # load bAnalysis
        # logger.info(f'Loading bAnalysis "{path}"')
        # loadData is false, load header
        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 rowIdx is not None:
        #    rowDict['Idx'] = rowIdx

        """
        if ba.loadError:
            rowDict['I'] = 0
        else:
            rowDict['I'] = 2 # need 2 because checkbox value is in (0,2)
        """

        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

        # TODO: 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

        # rowDict['dvdtThreshold'] = 20
        # rowDict['mvThreshold'] = -20
        if ba.isAnalyzed():
            dDict = ba.getDetectionDict()
            # rowDict['I'] = dDict.getValue('include')
            rowDict["dvdtThreshold"] = dDict.getValue("dvdtThreshold")
            rowDict["mvThreshold"] = dDict.getValue("mvThreshold")
            rowDict["Start(s)"] = dDict.getValue("startSeconds")
            rowDict["Stop(s)"] = dDict.getValue("stopSeconds")

        # 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
        relPath = path.replace(self.path, "")

        # logger.info(f'xxx self.path: "{self.path}"')
        # logger.info(f'xxx path: "{path}"')
        # logger.info(f'xxx relPath: "{relPath}"')

        if relPath.startswith("/"):
            # so we can use os.path.join()
            relPath = relPath[1:]
        # added 20230505 working with johnson in 1313 to fix windows bug ???
        if relPath.startswith("\\"):
            # so we can use os.path.join()
            relPath = relPath[1:]

        rowDict["relPath"] = relPath

        #logger.info(f'2) xxx relPath: "{relPath}"')
        # logger.info('qqq')
        # print(rowDict)

        return ba, rowDict

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

        Uses self.theseFileTypes

        """

        # to open just one file
        # if forceFolder:
        #     # we are forcing reload of an entire folder
        #     self._filePath = None

        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)
        if santanaTif:
            fileList = stripSantanaTif(fileList)
        return fileList

        logger.warning("Remember: MODIFIED TO LOAD TIF FILES IN SUBFOLDERS")
        count = 1
        tmpFileList = []
        folderDepth = self.folderDepth  # if none then all depths
        excludeFolders = ["analysis", "hide"]
        for root, subdirs, files in os.walk(path):
            subdirs[:] = [d for d in subdirs if d not in excludeFolders]

            print(f'count:{count} folderDepth:{folderDepth}')
            print('  root:', root)
            print('  subdirs:', subdirs)
            print('  files:', files)

            # strip out folders that start with __
            # _parentFolder = os.path.split(root)[1]
            # print('root:', root)
            # print('  parentFolder:', _parentFolder)
            # if _parentFolder.startswith('__'):
            if "__" in root:
                logger.info(f"SKIPPING based on path root:{root}")
                continue

            if os.path.split(root)[1] == "analysis":
                # don't load from analysis/ folder, we save analysis there
                continue

            # if os.path.split(root)[1] == 'hide':
            #     # special case/convention, don't load from 'hide' folders
            #     continue

            for file in files:
                # TODO (cudmore) parse all our fileLoader(s) for a list
                _, _ext = os.path.splitext(file)
                if _ext in self.theseFileTypes:
                    oneFile = os.path.join(root, file)
                    tmpFileList.append(oneFile)

            count += 1
            if folderDepth is not None and count > folderDepth:
                break

        fileList = []
        for file in sorted(tmpFileList):
            if file.startswith("."):
                continue
            # ignore our database file
            if file == self.dbFile:
                continue

            # tmpExt is like .abf, .csv, etc
            tmpFileName, tmpExt = os.path.splitext(file)
            if tmpExt in self.theseFileTypes:
                # if getFullPath:
                #     #file = os.path.join(path, file)
                #     file = pathlib.Path(path) / file
                #     file = str(file)  # return List[str] NOT List[PosixPath]
                fileList.append(file)
        #
        logger.info(f"found {len(fileList)} files ...")
        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."""

        # logger.info('')
        # print('    rowDict:', rowDict)
        # print('    ba:', ba)

        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
        # logger.warning(f"need to replace append with concat")
        #df = df.append(rowSeries, ignore_index=True)

        logger.info('concat this rowSeries')
        print(rowSeries)
        print('to this df')
        print(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

        print('')
        logger.info('=== after concat')
        print(df)

        #
        self._df = df

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

    def removeRowFromDatabase(self, rowIdx):
        # 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

        # 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 _old_duplicateRow(self, rowIdx):
        """Depreciated, Was used to have different conditions within a recording,
        this is now handled by condiiton column.
        """
        # duplicate rowIdx
        newIdx = rowIdx + 0.5

        rowDict = self.getRowDict(rowIdx)

        # CRITICAL: Need to make a deep copy of the _ba pointer to bAnalysis object
        logger.info(f"copying {type(rowDict['_ba'])} {rowDict['_ba']}")
        baNew = copy.deepcopy(rowDict["_ba"])

        # copy of bAnalysis needs a new uuid
        new_uuid = (
            sanpy._util.getNewUuid()
        )  # 't' + str(uuid.uuid4())   #.replace('-', '_')
        logger.info(f"assigning new uuid {new_uuid} to {baNew}")

        if baNew.uuid == new_uuid:
            logger.error("!!!!!!!!!!!!!!!!!!!!!!!!!CRITICAL, new uuid is same as old")

        baNew.uuid = new_uuid

        rowDict["_ba"] = baNew
        rowDict["uuid"] = baNew.uuid  # new row can never have same uuid as old

        dfRow = pd.DataFrame(rowDict, index=[newIdx])

        df = self._df
        df = df.append(dfRow, ignore_index=True)
        df = df.sort_values(by=["File"], axis="index", ascending=True, inplace=False)
        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.
        """

        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 pool_build(self, uniqueColumn=None, allowAutoLoad=False, includeNo=True, verbose=False):
        """Build one df with all analysis. Use this in plot tool plugin.

        Parameters
        ----------
        uniqueColumn : str
            Name of column to prepend to File column to make a unique name.
            Use 'parant2' for Kymograph tif files exported from Olympus.
        includeNo : boolean
            if True then include files with metadata 'Include' of no.
        """
        if verbose:
            logger.info("")

        masterDf = None

        # for row in range(self.numFiles):
        for rowIdx, rowDict in self._df.iterrows():
            if (not includeNo) and (rowDict['Include'] == 'no'):
                if verbose:
                    logger.info(f'  rowIdx:{rowIdx} Include is "no"')
                continue

            ba = self.getAnalysis(rowIdx, allowAutoLoad=allowAutoLoad)
            if ba is None:
                continue

            if not ba.isAnalyzed():
                if verbose:
                    logger.info(f"  rowIdx:{rowIdx} not analyzed")
                continue

            oneDf = ba.asDataFrame(regenerateAnalysisDataFrame=True)

            if oneDf is not None:

                self.signalWindow(f'Adding "{ba.fileLoader.filename}"', verbose=verbose)

                oneDf["File Number"] = int(rowIdx)

                # 20240114
                oneDf['File Path'] = ba.fileLoader.filepath

                uniqueName = os.path.splitext(ba.fileLoader.filename)[0]
                if uniqueColumn is not None:
                    uniqueName = rowDict[uniqueColumn] + '-' + uniqueName
                oneDf["Unique Name"] = uniqueName

                # logger.warning('TEMPORARY WHILE WORKING ON KYM POOLING !!!!!!!!!!!!!!!!!!!!!!!!!')
                # logger.warning('randomly assigning sex to male, female, unknown')
                # sexList = ['male', 'female', 'unknown']
                # oneDf['Sex'] = random.choice(sexList)
                oneDf_thresholdVal = oneDf['thresholdVal'].to_numpy()  # take off potential
                oneDf_thresholdVal_mean = np.nanmean(oneDf_thresholdVal)
                if oneDf_thresholdVal_mean > 0.5685522031727147:  # mean of all thresholdVal
                    # print(f'oneDf_thresholdVal_mean:{oneDf_thresholdVal_mean} male')
                    oneDf['Sex'] ='male'  # pandas dataframe columns are Capitalized !!!!!
                else:
                    oneDf['Sex'] = 'female'
                    # print(f'oneDf_thresholdVal_mean:{oneDf_thresholdVal_mean} female')

                # print('FINAL SEX IS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
                # print(oneDf['sex'])
                # drop some redundant analysis results (not in file metadata)

                if masterDf is None:
                    masterDf = oneDf
                else:
                    masterDf = pd.concat([masterDf, oneDf], ignore_index=True)
        #
        if masterDf is None:
            if verbose:
                logger.error("Did not find any analysis.")
        else:
            # add an index column (for plotting)
            masterDf['index'] = [x for x in range(len(masterDf))]
            if verbose:
                logger.info(f"final num spikes {len(masterDf)}")

            # # randomly assign sex based on mena +/- STD of take of potential
            # _thresholdVal = masterDf['thresholdVal'].to_numpy()  # take off potential
            # _thresholdVal_mean = np.nanmean(_thresholdVal)
            # # _thresholdVal_mean: 0.5685522031727147
            # logger.error(f'  remember, setting rows based on takeoff potential _thresholdVal_mean: {_thresholdVal_mean}')
            # for _idx, _row in masterDf.iterrows():
            #     logger.error(f' _idx:{_idx} thresholdVal:{_row["thresholdVal"]}')
            #     if _row['thresholdVal'] > _thresholdVal_mean:
            #         print('  -->> male')
            #         masterDf.at[_idx, 'sex'] = 'male'
            #     else:
            #         masterDf.at[_idx, 'sex'] = 'female'
            #         print('  -->> male')

        # print(masterDf.head())
        #self._poolDf = masterDf

        return masterDf

    def signalWindow(self, str, verbose=True):
        """Update status bar of SanPy window.

        TODO make this a signal and connect app to it.
            Will not be able to do this, we need to run outside Qt
        """
        if self._sanPyWindow is not None:
            self._sanPyWindow.slot_updateStatus(str)
        elif verbose:
            logger.info(str)

    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¤

loc property ¤

Mimic pandas df.loc[]

numFiles property ¤

Get the number of files. same as len().

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 ¤

Get list of file extensions we will load.

Functions¤

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

Load and manage a list of files in a folder path.

Use this as the main pandasModel for file list myTableView.

TODO: extend to link to folder in cloud (start with box and/or github)

Parameters:

Name Type Description Default
path str

Path to folder

None
filePath str

Path to one file

None
sanPyWindow SanPyWindow

PyQt, used to signal progress on loading

None
fileLoaderDict dict

Dict with file extension keys (no dot)

None
autoLoad bool

If True then

False
folderDepth Optional[int]

Folder depth to recurse if loading folder path.

None
Notes¤
  • Some functions are so self can mimic a pandas dataframe used by pandasModel. (shape, loc, loc_setter, iloc, iLoc_setter, columns, append, drop, sort_values, copy)
  • 202312 adding filepath to load just one file
Source code in sanpy/analysisDir.py
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
def __init__(
    self,
    path: str = None,
    filePath : str = None,
    sanPyWindow : "sanpy.interface.SanPyWindow" = None,
    fileLoaderDict : dict = None,
    autoLoad: bool = False,
    folderDepth: Optional[int] = None,
):
    """Load and manage a list of files in a folder path.

    Use this as the main pandasModel for file list myTableView.

    TODO: extend to link to folder in cloud (start with box and/or github)

    Parameters
    ----------
    path (str):
        Path to folder
    filePath (str):
        Path to one file
    sanPyWindow (sanpy.interface.SanPyWindow)
        PyQt, used to signal progress on loading
    fileLoaderDict (dict):
        Dict with file extension keys (no dot)
    autoLoad (bool):
        If True then 
    folderDepth (int):
        Folder depth to recurse if loading folder path.

    Notes
    -----
    - Some functions are so self can mimic a pandas dataframe used by pandasModel.
        (shape, loc, loc_setter, iloc, iLoc_setter, columns, append, drop, sort_values, copy)
    - 202312 adding filepath to load just one file
    """

    self._filePath = filePath
    if filePath is not None and os.path.isfile(filePath):
        self._filePath = filePath
        path = os.path.split(filePath)[0]

    logger.info(f'{path} self._filePath:{self._filePath}')

    self.path: str = path

    self._sanPyWindow = sanPyWindow
    # used to signal on building initial db

    self._fileLoaderDict = fileLoaderDict
    # dist with file extension keys

    self.autoLoad = autoLoad
    # not used

    self.folderDepth = folderDepth

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

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

    # keys are full path to file, if from cloud, key is 'cloud/<filename>'
    # holds bAnalysisObjects
    # needs to be a list so we can have files more than one
    # self.fileList = [] #OrderedDict()

    # 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"

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

    # if we have a filePath and not in df then add it
    if self._filePath is not None:

        logger.info('self._df')
        print(self._df)

    # self._df = self.loadFolder(loadData=autoLoad)

    #
    self._checkColumns()
    self._updateLoadedAnalyzed()

analysisIsDirty(rowIdx) ¤

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

Source code in sanpy/analysisDir.py
1129
1130
1131
1132
1133
1134
1135
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
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
def appendRow(self, rowDict=None, ba=None):
    """Append an empty row."""

    # logger.info('')
    # print('    rowDict:', rowDict)
    # print('    ba:', ba)

    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
    # logger.warning(f"need to replace append with concat")
    #df = df.append(rowSeries, ignore_index=True)

    logger.info('concat this rowSeries')
    print(rowSeries)
    print('to this df')
    print(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

    print('')
    logger.info('=== after concat')
    print(df)

    #
    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
695
696
697
698
699
700
701
702
703
704
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

copyToClipboard() ¤

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

Source code in sanpy/analysisDir.py
715
716
717
718
719
720
721
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")

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
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
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
    # filePath = os.path.join(self.path, file)
    # logger.info(f'Found _ba in file db with ba:"{ba}" {type(ba)}')
    # logger.info(f'rowIdx: {rowIdx} ba:{ba}')

    if ba is None or ba == "":
        # logger.info('did not find _ba ... loading from abf file ...')
        # working on kymograph
        #                 relPath = self.getPathFromRelPath(ba._path)
        relPath = self._df.loc[rowIdx, "relPath"]
        filePath = self.getPathFromRelPath(relPath)

        ba = self.loadOneAnalysis(
            filePath, uuid, allowAutoLoad=allowAutoLoad, verbose=verbose
        )
        # load
        """
        logger.info(f'Loading bAnalysis from row {rowIdx} "{filePath}"')
        ba = sanpy.bAnalysis(filePath)
        """
        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}")

            # kymograph, set ba rect from table
            # if ba is not None and ba.fileLoader.isKymograph():
            #     left = self._df.loc[rowIdx, "kLeft"]
            #     top = self._df.loc[rowIdx, "kTop"]
            #     right = self._df.loc[rowIdx, "kRight"]
            #     bottom = self._df.loc[rowIdx, "kBottom"]

            #     # on first load, these will be empty
            #     # grab rect from ba (in _updateLoadedAnalyzed())
            #     if left == "" or top == "" or right == "" or bottom == "":
            #         pass
            #     else:
            #         theRect = [left, top, right, bottom]
            #         logger.info(f"  theRect:{theRect}")
            #         ba.fileLoader._updateTifRoi(theRect)

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

    return ba

getDataFrame() ¤

Get the underlying pandas DataFrame.

Source code in sanpy/analysisDir.py
706
707
708
def getDataFrame(self):
    """Get the underlying pandas DataFrame."""
    return self._df

getFileList(path=None, santanaTif=False) ¤

Get file paths from path.

Uses self.theseFileTypes

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
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
def getFileList(self,
                path: str = None,
                santanaTif=False
                ) -> List[str]:
    """Get file paths from path.

    Uses self.theseFileTypes

    """

    # to open just one file
    # if forceFolder:
    #     # we are forcing reload of an entire folder
    #     self._filePath = None

    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)
    if santanaTif:
        fileList = stripSantanaTif(fileList)
    return fileList

    logger.warning("Remember: MODIFIED TO LOAD TIF FILES IN SUBFOLDERS")
    count = 1
    tmpFileList = []
    folderDepth = self.folderDepth  # if none then all depths
    excludeFolders = ["analysis", "hide"]
    for root, subdirs, files in os.walk(path):
        subdirs[:] = [d for d in subdirs if d not in excludeFolders]

        print(f'count:{count} folderDepth:{folderDepth}')
        print('  root:', root)
        print('  subdirs:', subdirs)
        print('  files:', files)

        # strip out folders that start with __
        # _parentFolder = os.path.split(root)[1]
        # print('root:', root)
        # print('  parentFolder:', _parentFolder)
        # if _parentFolder.startswith('__'):
        if "__" in root:
            logger.info(f"SKIPPING based on path root:{root}")
            continue

        if os.path.split(root)[1] == "analysis":
            # don't load from analysis/ folder, we save analysis there
            continue

        # if os.path.split(root)[1] == 'hide':
        #     # special case/convention, don't load from 'hide' folders
        #     continue

        for file in files:
            # TODO (cudmore) parse all our fileLoader(s) for a list
            _, _ext = os.path.splitext(file)
            if _ext in self.theseFileTypes:
                oneFile = os.path.join(root, file)
                tmpFileList.append(oneFile)

        count += 1
        if folderDepth is not None and count > folderDepth:
            break

    fileList = []
    for file in sorted(tmpFileList):
        if file.startswith("."):
            continue
        # ignore our database file
        if file == self.dbFile:
            continue

        # tmpExt is like .abf, .csv, etc
        tmpFileName, tmpExt = os.path.splitext(file)
        if tmpExt in self.theseFileTypes:
            # if getFullPath:
            #     #file = os.path.join(path, file)
            #     file = pathlib.Path(path) / file
            #     file = str(file)  # return List[str] NOT List[PosixPath]
            fileList.append(file)
    #
    logger.info(f"found {len(fileList)} files ...")
    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
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
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:
    #     fileType = fileType[1:]  # [1:] to strip period
    if fileType not in self.theseFileTypes:  
        logger.warning(f'Did not load file type "{fileType}"')
        return None, None

    # grab the fileLoaderDict from our app
    # if it is None then bAnalysis will load this (from disk)
    # if self.mySanPyWindow is not None:
    #     _fileLoaderDict = self.mySanPyWindow.getSanPyApp().getFileLoaderDict()
    # else:
    #     _fileLoaderDict = None

    # load bAnalysis
    # logger.info(f'Loading bAnalysis "{path}"')
    # loadData is false, load header
    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 rowIdx is not None:
    #    rowDict['Idx'] = rowIdx

    """
    if ba.loadError:
        rowDict['I'] = 0
    else:
        rowDict['I'] = 2 # need 2 because checkbox value is in (0,2)
    """

    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

    # TODO: 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

    # rowDict['dvdtThreshold'] = 20
    # rowDict['mvThreshold'] = -20
    if ba.isAnalyzed():
        dDict = ba.getDetectionDict()
        # rowDict['I'] = dDict.getValue('include')
        rowDict["dvdtThreshold"] = dDict.getValue("dvdtThreshold")
        rowDict["mvThreshold"] = dDict.getValue("mvThreshold")
        rowDict["Start(s)"] = dDict.getValue("startSeconds")
        rowDict["Stop(s)"] = dDict.getValue("stopSeconds")

    # 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
    relPath = path.replace(self.path, "")

    # logger.info(f'xxx self.path: "{self.path}"')
    # logger.info(f'xxx path: "{path}"')
    # logger.info(f'xxx relPath: "{relPath}"')

    if relPath.startswith("/"):
        # so we can use os.path.join()
        relPath = relPath[1:]
    # added 20230505 working with johnson in 1313 to fix windows bug ???
    if relPath.startswith("\\"):
        # so we can use os.path.join()
        relPath = relPath[1:]

    rowDict["relPath"] = relPath

    #logger.info(f'2) xxx relPath: "{relPath}"')
    # logger.info('qqq')
    # print(rowDict)

    return ba, rowDict

getPathFromRelPath(relPath) ¤

Get full path to file from relPath.

Uses analysisDir folder path.

Source code in sanpy/analysisDir.py
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
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)

    """
    print('xxx', self.path)
    print('xxx', relPath)
    print('xxx', fullFilePath)
    """

    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
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
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

hasDirty() ¤

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

Source code in sanpy/analysisDir.py
1137
1138
1139
1140
1141
1142
1143
1144
1145
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) ¤

Parse a folder and load all (abf, csv, ...).

Only called if no h5 file.

TODO: get rid of loading database from .csv (it is replaced by .h5 file) TODO: extend the logic to load from cloud (after we were instantiated)

Source code in sanpy/analysisDir.py
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
def loadFolder(self, path=None, loadData=False) -> pd.DataFrame:
    """Parse a folder and load all (abf, csv, ...).

    Only called if no h5 file.

    TODO: get rid of loading database from .csv (it is replaced by .h5 file)
    TODO: extend the logic to load from cloud (after we were instantiated)
    """
    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):

        self.signalWindow(
            f'Loading file {rowIdx+1} of {_numFilesToLoad} "{fullFilePath}"'
        )

        # 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 analy anlysis until user clicks on row, see loadOneAnalysis()

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

    We do not load analy anlysis 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 bAnalysis either from original file path or uuid of h5 file.

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

Source code in sanpy/analysisDir.py
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
def loadOneAnalysis(self, path, uuid=None, allowAutoLoad=True, verbose=False):
    """Load one bAnalysis either from original file path or uuid of h5 file.

    If from h5, we still need to reload sweeps !!!
    They are binary and fast, saving to h5 (in this case) is slow.
    """
    if verbose:
        logger.info(f'path:"{path}" uuid:"{uuid}" allowAutoLoad:"{allowAutoLoad}"')

    hdfPath = self._getHdfFile()

    # grab the fileLoaderDict from our app
    # if it is None then bAnalysis will load this (from disk)
    # if self.mySanPyWindow is not None:
    #     _fileLoaderDict = self.mySanPyWindow.getSanPyApp().getFileLoaderDict()
    # else:
    #     _fileLoaderDict = None

    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)

        # 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}")
    #
    return ba

pool_build(uniqueColumn=None, allowAutoLoad=False, includeNo=True, verbose=False) ¤

Build one df with all analysis. Use this in plot tool plugin.

Parameters:

Name Type Description Default
uniqueColumn str

Name of column to prepend to File column to make a unique name. Use 'parant2' for Kymograph tif files exported from Olympus.

None
includeNo boolean

if True then include files with metadata 'Include' of no.

True
Source code in sanpy/analysisDir.py
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
def pool_build(self, uniqueColumn=None, allowAutoLoad=False, includeNo=True, verbose=False):
    """Build one df with all analysis. Use this in plot tool plugin.

    Parameters
    ----------
    uniqueColumn : str
        Name of column to prepend to File column to make a unique name.
        Use 'parant2' for Kymograph tif files exported from Olympus.
    includeNo : boolean
        if True then include files with metadata 'Include' of no.
    """
    if verbose:
        logger.info("")

    masterDf = None

    # for row in range(self.numFiles):
    for rowIdx, rowDict in self._df.iterrows():
        if (not includeNo) and (rowDict['Include'] == 'no'):
            if verbose:
                logger.info(f'  rowIdx:{rowIdx} Include is "no"')
            continue

        ba = self.getAnalysis(rowIdx, allowAutoLoad=allowAutoLoad)
        if ba is None:
            continue

        if not ba.isAnalyzed():
            if verbose:
                logger.info(f"  rowIdx:{rowIdx} not analyzed")
            continue

        oneDf = ba.asDataFrame(regenerateAnalysisDataFrame=True)

        if oneDf is not None:

            self.signalWindow(f'Adding "{ba.fileLoader.filename}"', verbose=verbose)

            oneDf["File Number"] = int(rowIdx)

            # 20240114
            oneDf['File Path'] = ba.fileLoader.filepath

            uniqueName = os.path.splitext(ba.fileLoader.filename)[0]
            if uniqueColumn is not None:
                uniqueName = rowDict[uniqueColumn] + '-' + uniqueName
            oneDf["Unique Name"] = uniqueName

            # logger.warning('TEMPORARY WHILE WORKING ON KYM POOLING !!!!!!!!!!!!!!!!!!!!!!!!!')
            # logger.warning('randomly assigning sex to male, female, unknown')
            # sexList = ['male', 'female', 'unknown']
            # oneDf['Sex'] = random.choice(sexList)
            oneDf_thresholdVal = oneDf['thresholdVal'].to_numpy()  # take off potential
            oneDf_thresholdVal_mean = np.nanmean(oneDf_thresholdVal)
            if oneDf_thresholdVal_mean > 0.5685522031727147:  # mean of all thresholdVal
                # print(f'oneDf_thresholdVal_mean:{oneDf_thresholdVal_mean} male')
                oneDf['Sex'] ='male'  # pandas dataframe columns are Capitalized !!!!!
            else:
                oneDf['Sex'] = 'female'
                # print(f'oneDf_thresholdVal_mean:{oneDf_thresholdVal_mean} female')

            # print('FINAL SEX IS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
            # print(oneDf['sex'])
            # drop some redundant analysis results (not in file metadata)

            if masterDf is None:
                masterDf = oneDf
            else:
                masterDf = pd.concat([masterDf, oneDf], ignore_index=True)
    #
    if masterDf is None:
        if verbose:
            logger.error("Did not find any analysis.")
    else:
        # add an index column (for plotting)
        masterDf['index'] = [x for x in range(len(masterDf))]
        if verbose:
            logger.info(f"final num spikes {len(masterDf)}")

        # # randomly assign sex based on mena +/- STD of take of potential
        # _thresholdVal = masterDf['thresholdVal'].to_numpy()  # take off potential
        # _thresholdVal_mean = np.nanmean(_thresholdVal)
        # # _thresholdVal_mean: 0.5685522031727147
        # logger.error(f'  remember, setting rows based on takeoff potential _thresholdVal_mean: {_thresholdVal_mean}')
        # for _idx, _row in masterDf.iterrows():
        #     logger.error(f' _idx:{_idx} thresholdVal:{_row["thresholdVal"]}')
        #     if _row['thresholdVal'] > _thresholdVal_mean:
        #         print('  -->> male')
        #         masterDf.at[_idx, 'sex'] = 'male'
        #     else:
        #         masterDf.at[_idx, 'sex'] = 'female'
        #         print('  -->> male')

    # print(masterDf.head())
    #self._poolDf = masterDf

    return masterDf

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
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
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 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
                # print('xxx SETTING dir uuid')
                df.at[row, "uuid"] = ba.uuid

    # 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, dbKey)

    #
    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)

    # list the keys in the file
    # sanpy.h5Util.listKeys(hdfFilePath)

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

signalWindow(str, verbose=True) ¤

Update status bar of SanPy window.

TODO make this a signal and connect app to it. Will not be able to do this, we need to run outside Qt

Source code in sanpy/analysisDir.py
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
def signalWindow(self, str, verbose=True):
    """Update status bar of SanPy window.

    TODO make this a signal and connect app to it.
        Will not be able to do this, we need to run outside Qt
    """
    if self._sanPyWindow is not None:
        self._sanPyWindow.slot_updateStatus(str)
    elif verbose:
        logger.info(str)

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
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
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.
    """

    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()
All material is Copyright 2011-2023 Robert H. Cudmore