Skip to content

map

Classes¤

mmMap ¤

A time-series of :class:pymapmanager.mmStack time-points plus some book-keeping to link corresponding annotations and segments between time-points.

Args: filePath (str): Either: Full path to map folder. Or: Full file path to .txt file for the map. File is inside map folder, for map a5n it is '/a5n/a5n.txt'. urlmap (str): Name of the map to load from a :class:pymapmanager.mmio online repository.

Example::

from pymapmanager import mmMap
myMapPath = 'PyMapManager/examples/exampleMaps/rr30a'
myMap = mmMap(filePath=myMapPath)

# Get the 3rd mmStack using
stack = myMap.stacks[3]

# Retrieve annotations (for a given segmentID) across all time-points in the map
pDist_values = myMap.getMapValues2('pDist', segmentID=[3])
Source code in pymapmanager/mmMap.py
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
class mmMap():
    """
    A time-series of :class:`pymapmanager.mmStack` time-points plus some book-keeping to link corresponding annotations
    and segments between time-points.

    Args:
        filePath (str):
            Either: Full path to map folder.
            Or: Full file path to .txt file for the map. File is inside map folder, for map a5n it is '/a5n/a5n.txt'.
        urlmap (str): Name of the map to load from a :class:`pymapmanager.mmio` online repository.

    Example::

        from pymapmanager import mmMap
        myMapPath = 'PyMapManager/examples/exampleMaps/rr30a'
        myMap = mmMap(filePath=myMapPath)

        # Get the 3rd mmStack using
        stack = myMap.stacks[3]

        # Retrieve annotations (for a given segmentID) across all time-points in the map
        pDist_values = myMap.getMapValues2('pDist', segmentID=[3])
    """

    def getStackPath(self, sessionIdx : int):
        _folder, _file = os.path.split(self.filePath)
        defaultChannel = 2
        # /Users/cudmore/Sites/PyMapManager-Data/maps/rr30a/rr30a_s3_ch2.tif
        stackName = self._getStackName(sessionIdx)
        stackName = f'{stackName}_ch{defaultChannel}.tif'
        stackPath = os.path.join(_folder, stackName)
        return stackPath

    def getStackTimepoint(self, thisStack : pymapmanager.stack) -> int:
        """Given a stack, find the timepoint.
        """ 
        for idx, stack in enumerate(self.stacks):
            if stack == thisStack:
                return idx
        return None

    def getMapName(self):
        _folder, _name = os.path.split(self.filePath)
        _name, _ext = os.path.splitext(_name)
        return _name

    def __init__(self, filePath=None, urlmap=None):
        startTime = time.time()

        self.filePath = ''
        # Full file path to .txt file for the map.

        self._folder = ''
        # Path to enclosing folder, ends in '/'.

        self.name = ''
        # Name of the map. For a map loaded with file a5n.txt, name is a5b. Same as enclosing folder name.
        # If urlmap then this is the name of the map to fetch from a :class:`pymapmanager.mmio` server.

        self.table = None
        # Pandas dataframe loaded from .txt file filePath or 'header' if using :class:`pymapmanager.mmio`.
        # Get values from this dataframe using getValue(name,sessionNumber)

        # removed 20170107, replaced with xxx
        # self.defaultRoiType = 'spineROI'
        #self.defaultRoiTypeID = 0

        self.server = None
        # Pointer to :class:`pymapmanager.mmio` server connection.
        # Only used to load from urlmap.

        self.objMap = None
        # 2D array where each row is a run of annotations.
        # objMap[i][j] gives us a mmStack centric index into mmStack.stackdb.

        self.segMap = None
        # 2D array where each row is a run of segments.
        # segMap[i][j] gives us mmStack centric index into mmStack._line

        self.segRunMap = None # 20180107, why was this not defaulted?

        # if we get a filePath, make sure it exists and decide if it is a folder or a file
        # in the end we will always load from a .txt file
        if filePath is not None:
            if filePath.endswith(os.sep):
                filePath = filePath[0:-1]
            if os.path.exists(filePath):
                if os.path.isdir(filePath):
                    tmpPath, tmpName = os.path.split(filePath)
                    filePath = os.path.join(filePath, tmpName + '.txt')
                    # check if file exists
                    if not os.path.isfile(filePath):
                        raise IOError(ENOENT, 'mmMap got a bad map folder:', filePath)
                else:
                    pass
            else:
                # error
                raise IOError(ENOENT, 'mmMap got a bad map path:', filePath)

        ###############################################################################
        # map nv
        doFile = True
        if filePath is not None:
            if not os.path.isfile(filePath):
                raise IOError(ENOENT, 'mmMap did not find filePath:', filePath)
            self.filePath = filePath #  Path to file used to open map."""
            self._folder = os.path.dirname(filePath) + '/'
            self.name = os.path.basename(filePath).strip('.txt')
            self.table = pd.read_table(filePath, index_col=0)
        elif urlmap is not None:
            doFile = False
            # try loading from url
            self.name = urlmap
            self.server = mmio()
            tmp = self.server.getfile('header', self.name)
            self.table = pd.read_table(io.StringIO(tmp.decode('utf-8')), index_col=0)

        ###############################################################################
        # objMap (3d)
        if doFile:
            objMapFile = self._folder + self.name + '_objMap.txt'
            if not os.path.isfile(objMapFile):
                raise IOError(ENOENT, 'mmMap did not find objMapFile:', objMapFile)
            # with open(objMapFile, 'rU') as f:
            with open(objMapFile, 'r') as f:
                header = f.readline().rstrip()
            self.objMap = np.loadtxt(objMapFile, skiprows=1)
        else:
            tmp = self.server.getfile('objmap', self.name).decode("utf-8")
            header = tmp.split('\n')[0]
            self.objMap = np.loadtxt(tmp.split('\n'), skiprows=1)

        if header.endswith(';'):
            header = header[:-1]
        header = header.split(';')
        d = dict(s.split('=') for s in header)
        numRow = int(d['rows'])
        numCol = int(d['cols'])
        numBlock = int(d['blocks'])

        self.objMap.resize(numBlock,numRow,numCol)
        self.runMap = self._buildRunMap(self.objMap, roiTypeID=self.defaultAnnotationID)

        ###############################################################################
        # segMap (3d)
        header = None
        if doFile:
            segMapFile = self._folder + self.name + '_segMap.txt'
            if os.path.isfile(segMapFile):
                # with open(segMapFile, 'rU') as f:
                with open(segMapFile, 'r') as f:
                    header = f.readline().rstrip()
                self.segMap = np.loadtxt(segMapFile, skiprows=1)
            else:
                #raise IOError(ENOENT, 'mmMap did not find segMapFile:', segMapFile)
                print('did not find segment map file, should be ok')
        else:
            tmp = self.server.getfile('segmap', self.name).decode("utf-8")
            #header = tmp.split('\r')[0] # works when server is running on OSX
            header = tmp.split('\n')[0]
            self.segMap = np.loadtxt(tmp.split('\n'), skiprows=1)

        if header is not None:
            if header.endswith(';'):
                header = header[:-1]
            header = header.split(';')
            d = dict(s.split('=') for s in header)
            numRow = int(d['rows'])
            numCol = int(d['cols'])
            numBlock = int(d['blocks'])

            self.segMap.resize(numBlock,numRow,numCol)
            self.segRunMap = self._buildRunMap(self.segMap, roiTypeID = None)

        ###############################################################################
        #load each stack db
        # this assumes self.objMap has already been loaded
        self._stacks = [] #  A list of mmStack
        for _session in range(0, self.numSessions):
            stackPath = self.getStackPath(_session)
            stack = pymapmanager.stack(stackPath,
                                       loadImageData=False,
                                       mmMap=self,
                                       mmMapSession=_session)
            # if doFile:
            #     stack = mmStack(name=self._getStackName(i), numChannels=self.numChannels, \
            #                     map=self, mapSession=i)
            # else:
            #     stack = mmStack(name=self._getStackName(i), numChannels=self.numChannels, \
            #                     map=self, mapSession=i, urlmap=self.name)
            self.stacks.append(stack)

        stopTime = time.time()
        print('map', self.name, 'loaded in', round(stopTime-startTime,2), 'seconds.')

        # 202402 need to add some columns to stack db
        logger.warning('REMOVE THIS INGEST !!!!!!!!!')
        from pymapmanager.interface2.mapWidgets._mapIngest import addDistance
        addDistance(self)

    def __iter__(self):
        # this along with __next__ allow mmMap to iterate over stacks
        self._iterIdx = 0
        return self

    def __next__(self):
        # this along with __iter__ allow mmMap to iterate over stacks
        if self._iterIdx < self.numSessions:
            x = self.stacks[self._iterIdx]
            self._iterIdx += 1
            return x
        else:
            raise StopIteration

    # def __iter__(self):
    #     i = 0
    #     while i < len(self.stacks):
    #         yield self.stacks[i]
    #         i += 1

    @property
    def numChannels(self):
        """
        Number of image channels in each stack (must be the same for all stacks).
        """
        return int(self.getValue('numChannels', 0))

    @property
    def numSessions(self):
        """
            Number of sessions (timepoints) in the map (time-series).
        """
        return int(self.table.loc['hsStack'].count())

    @property
    def stacks(self):
        """List of :class:`pymapmanager.mmStack` in the map.
        """
        return self._stacks

    @property
    def numMapSegments(self):
        """The number of line segments in the map.
        Corresponding segments are connected together with the segMap.
        """
        if self.segMap is not None:
            numSegments = self.segRunMap.shape[0]
        else:
            numSegments = 0
        return numSegments

    @property
    def defaultAnnotation(self):
        """
        """
        # if defaultAnnotation does not exist then default to 'spineROI'
        if 'defaultAnnotation' in self.table.index:
            theRet = self.table.loc['defaultAnnotation'][0]
            # if empty then we assume 'spineROI'
            if theRet == '':
                theRet = 'spineROI'
        else:
            theRet = 'spineROI'
        return theRet

    @property
    def defaultAnnotationID(self):
        theRet = 0
        defaultAnnotation = self.defaultAnnotation
        if defaultAnnotation == 'spineROI':
            theRet = 0
        elif defaultAnnotation == 'otherROI':
            theRet = 4
        return theRet

    def __str__(self):

        objCount = 0
        for stack in self.stacks:
            objCount += len(stack.getPointAnnotations())

        '''
        theRet = {}
        theRet['info'] = ('map:' + self.name
            + ' map segments:' + str(self.numMapSegments)
            + ' stacks:' + str(self.numSessions)
            + ' total object:' + str(objCount))
        theRet['map'] = self
        '''
        retStr = ('map:' + self.name
            + ' map segments:' + str(self.numMapSegments)
            + ' stacks:' + str(self.numSessions)
            + ' total object:' + str(objCount))
        return retStr

    def getDataFrame(self):
        df = pd.DataFrame()
        df['Idx'] = range(self.numSessions)
        df['File'] = [self._getStackName(tp) for tp in range(self.numSessions)]
        return df

    def mapInfo(self):
        """
        Get information on the map

        Returns:
            | A dict of
            | mapName : Str
            | numSessions : Int
            | numChannels : Int
            | numMapSegments : Int
            |
            | The following are string list with numSessions elements
            | stackNames :
            | importedStackName :
            | numSlices :
            | date :
            | time :
            | dx : Voxel size in um
            | dy : Voxel size in um
            | dz : Voxel size in um
            | px : Number of Pixels
            | py : Number of Pixels
            | pz : Number of Pixels
            | ...
        """
        theRet = {}
        theRet['mapName'] = self.name
        theRet['numSessions'] = self.numSessions
        theRet['numChannels'] = self.numChannels
        theRet['defaultAnnotation'] = self.defaultAnnotation
        theRet['numAnnotations'] = 0
        # lists, one value per session
        theRet['stackNames'] = []
        theRet['importedStackName'] = []
        theRet['date'] = []
        theRet['time'] = []
        theRet['px'] = [] # pixels
        theRet['py'] = []
        theRet['numSlices'] = []
        theRet['dx'] = [] # voxels in um
        theRet['dy'] = []
        theRet['dz'] = []
        theRet['numROI'] = []
        for idx in range(self.numSessions):
            theRet['stackNames'].append(self.table.loc['hsStack'][idx])
            theRet['importedStackName'].append(self.table.loc['importedStackName'][idx])
            theRet['date'].append(self.table.loc['date'][idx])
            theRet['time'].append(self.table.loc['time'][idx])
            theRet['px'].append(self.table.loc['px'][idx])
            theRet['py'].append(self.table.loc['py'][idx])
            theRet['numSlices'].append(self.table.loc['pz'][idx]) # changing name

            theRet['dx'].append(self.table.loc['dx'][idx])
            theRet['dy'].append(self.table.loc['dy'][idx])
            theRet['dz'].append(self.table.loc['dz'][idx])

            thisNum = self.stacks[idx].countObj(roiType=self.defaultAnnotation)
            theRet['numROI'].append(thisNum)
            theRet['numAnnotations'] = theRet['numAnnotations'] + self.stacks[idx].numObj

            runIdx = 6

        if self.segMap is not None:
            theRet['numMapSegments'] = self.segRunMap.shape[0]
        else:
            theRet['numMapSegments'] = 0

        '''
        # these were not being used
        theRet['objMap'] = self.objMap[runIdx].astype('int') # from spine index to run index
        theRet['runMap'] = self.runMap.astype('int') # from run idx to spine idx
        theRet['segMap'] = None
        theRet['numMapSegments'] = 0
        if self.segMap is not None:
            theRet['segMap'] = self.segMap.astype('int')
            theRet['numMapSegments'] = self.segRunMap.shape[0]
        '''

        #print 'mapInfo() theRet:', theRet
        return theRet

    def getValue(self, name, sessionNumber):
        """
        Get a value from the map (not from a stack!).

        Args:
            name: Name of map value
            sessionNumber: Session number of the stack

        Returns:
            Str (this is a single value)

        Examples::

            m.getValue('pixelsz', 2) # get the number of z-slices (pixels) of stack 2.
            m.getValue('voxelx', 5) # get the x voxel size of stack 5 (in um/pixel).
            m.getValue('hsStack',3) # get the name of stack 3.
        """
        # .loc specifies row, .iloc specifies a column
        return self.table.loc[name].iloc[sessionNumber]

    def _getStackName(self, session : int) -> str:
        """Get the name of the stack at session.
        """
        ret = self.getValue('hsStack', session)
        if ret.endswith('_ch1') or ret.endswith('_ch2'):
            ret = ret[:-4]
        return ret

    def getMapDynamics(self, pd, thisMatrix=None):

        if thisMatrix is None:
            pd = self.getMapValues3(pd)
            thisMatrix = pd['stackidx']

        # print(thisMatrix)
        # _val = thisMatrix[0, 3]
        # print(_val, type(_val), _val>0, _val.astype(int))
        # sys.exit(1)

        nSpineRun = thisMatrix.shape[0]
        nSessions = thisMatrix.shape[1]

        pd['dynamics'] = np.empty([nSpineRun,nSessions])
        pd['dynamics'][:] = np.NAN

        # 1:add, 2:sub, 3:transient, 4:persisten
        kAdd = 1
        kSubtract = 2
        kTransient = 3
        kPersistent = 4

        for i in range(nSpineRun):
            for j in range(nSessions):
                if not thisMatrix[i,j]>=0:
                    continue
                if j == 0:
                    # first session
                    if thisMatrix[i,j+1]>=0:
                        pd['dynamics'][i,j] = kPersistent
                    else:
                        pd['dynamics'][i,j] = kSubtract
                elif j == nSessions - 1:
                    # last session
                    if thisMatrix[i,j-1]>=0:
                        pd['dynamics'][i,j] = kPersistent
                    else:
                        pd['dynamics'][i,j] = kAdd
                else:
                    # middle session (not first or last)
                    added = not thisMatrix[i,j-1] >= 0
                    subtracted = not thisMatrix[i,j+1] >= 0
                    if added and subtracted:
                        pd['dynamics'][i,j] = kTransient
                    elif added:
                        pd['dynamics'][i,j] = kAdd
                    elif subtracted:
                        pd['dynamics'][i,j] = kSubtract
                    else:
                        pd['dynamics'][i,j] = kPersistent

        # print(pd['dynamics'])
        # sys.exit(1)

        return pd

    def ingest(self, tp, channel=1):
        """
        Take a raw 3D .tif and populate raw/ingest/tp<tp> with single channel .tif files.

        Args:
            tp (int) : The timepoint to ingest
            channel (int) : The channel to ingest, valid channels are (1,2,3)

        Returns:
            None
        """

        print('mmMap.ingest() is ingesting tp:', tp, 'channel:', channel)

        outFileType = '.png'

        # '/Users/cudmore/Desktop/tmp/'
        savePath = self._folder # ends in '/'
        savePath += 'raw/'
        if not os.path.isdir(savePath):
            os.makedirs(savePath)
        savePath += 'ingested/'
        if not os.path.isdir(savePath):
            os.makedirs(savePath)
        savePath += 'tp' + str(tp) + '/'
        if not os.path.isdir(savePath):
            os.makedirs(savePath)

        maxSavePath = self._folder + 'raw/ingested/'

        print('   loading full 3d .tif')
        # load the full 3D .tif
        image = self.stacks[tp].loadStackImages(channel=channel)
        print('   image shape:', image.shape)
        [slices, m, n] = image.shape
        for slice in range(slices):
            outfile = self.name + '_tp' + str(tp) + '_ch' + str(channel) + '_s' + str(slice).zfill(4) + outFileType
            outfilepath = savePath + outfile

            if slice % 10 == 0:
                print('   saving slice:', slice, 'of', slices, outfilepath)

            # this saves .png as 8-bit, I am not sure if it is doing normalization?
            scipy.misc.imsave(outfilepath, image[slice,:,:])

        # make maximal intensity projection
        maxfile = 'MAX_' + self.name + '_tp' + str(tp) + '_ch' + str(channel) + outFileType
        maxfilepath = maxSavePath + maxfile
        print('   making and saving max project', maxfilepath)
        max_ = np.zeros((m, n), dtype='uint8')
        for slice in range(slices):
            max_ = np.maximum(max_, image[slice,:,:])
        # MAX_rr30a_tp0_ch2
        scipy.misc.imsave(maxfilepath, max_)

        print('done ingesting')

    def getMapValues3(self, pd):
        """Get values of a stack annotation across all stacks in the map.

        Args:
            pd (dict): A plot dictionary describing what to plot. Get default from mmUtil.newplotdict().

        Returns:

            | pd['x'], 2D ndarray of xstat values, rows are runs, cols are sessions, nan is where there is no stackdb annotation
            | pd['y'], same
            | pd['z'], same
            | pd['stackidx'], Each [i]j[] gives the stack centric index of annotation value at [i][j].
            | pd['mapsess'], Each [i][j] gives the map session of value at annotation [i][j].
            | pd['runrow'],

        """
        startTime = time.time()

        # make sure pd['roitype'] is a list
        if not isinstance(pd['roitype'], list):
            pd['roitype'] = [pd['roitype']]

        m = self.runMap.shape[0]
        n = self.runMap.shape[1]

        if pd['xstat']:
            pd['x'] = np.empty([m, n])
            pd['x'][:] = np.NAN
        if pd['ystat']:
            pd['y'] = np.empty([m, n])
            pd['y'][:] = np.NAN
        if pd['zstat']:
            pd['z'] = np.empty([m, n])
            pd['z'][:] = np.NAN

        # keep track of stack centric index we are plotting
        yIdx = np.empty([m, n])
        yIdx[:] = np.NAN

        # keep track of session index
        ySess = np.empty([m, n])
        ySess[:] = np.NAN

        # keep track of run map rows (we already know the session/column)
        yRunRow = np.empty([m, n])
        yRunRow[:] = np.NAN

        # always make a matrix of bad
        isBad = np.empty([m, n])
        isBad[:] = np.NAN

        # keep track of map segment id
        yMapSegment = []
        if self.segMap is not None:
            yMapSegment = np.empty([m, n])
            yMapSegment[:] = np.NAN

        # 20171225, cPnt is overkill but until I rewrite REST
        # to get list of stat (x,y,z,pDist, cPnt, cx, cy, cz) etc. etc.
        cPnt = np.empty([m, n])
        cPnt[:] = np.NAN

        runIdxDim = 6

        if pd['stacklist'] is not None and len(pd['stacklist'])>0:
            myRange = pd['stacklist']
        else:
            myRange = range(n)

        for j in myRange:

            #print('*** getMapValues3() j:', j, "pd['segmentid']:", pd['segmentid'])
            # orig_df = self.stacks[j].stackdb
            orig_df = self.stacks[j].getPointAnnotations().getDataFrame()

            # print(orig_df.columns)
            # sys.exit(1)

            currSegmentID = []
            if self.numMapSegments > 0:
                # 20220103
                oneSegment = pd['segmentid']
                if isinstance(oneSegment, list):
                    logger.warning('abb 20220103 in mmMap.getMapValue3() fix this cludge from list to int')
                    if len(oneSegment) > 0:
                        oneSegment = oneSegment[0]
                    else:
                        oneSegment = None
                if oneSegment is not None and oneSegment >=0 :
                    currSegmentID = self.segRunMap[oneSegment, j]  # this only works for one segment -- NOT A LIST
                    #print('   currSegmentID:', currSegmentID)
                    if currSegmentID >= 0:
                        currSegmentID = int(currSegmentID)
                        # print 'getMapValues3() j:', j, 'currSegmentID:', currSegmentID
                        currSegmentID = [currSegmentID]
                    else:
                        currSegmentID = []
                #print('   currSegmentID:', currSegmentID)
                if oneSegment is not None and oneSegment >= 0 and not currSegmentID:
                    # this session does not have segmentID that match
                    #print('   getMapValues3() skipping tp', j)
                    continue

            goodIdx = self.runMap[:, j]  # valid indices from runMap

            #print goodIdx

            runMap_idx = orig_df.index.isin(goodIdx)  # series of boolean (Seems to play nice with nparray)

            if pd['roitype']:
                roiType_idx = orig_df['roiType'].isin(pd['roitype'])
                runMap_idx = runMap_idx & roiType_idx
            if currSegmentID:
                segmentID_idx = orig_df['segmentID'].isin(currSegmentID)
                runMap_idx = runMap_idx & segmentID_idx

            # bad
            if not pd['plotbad']:
                #print('mmMap.getMapValues3() is stripping out isBad')
                notBad_idx = ~orig_df['isBad'].isin([1])
                runMap_idx = runMap_idx & notBad_idx

            # final_df = orig_df.loc[runMap_idx]
            # 20210922 was this
            #final_df = orig_df.ix[runMap_idx]
            #print('20210922 orig_df:')
            #print(orig_df)
            final_df = orig_df.loc[runMap_idx]
            #print(final_df)

            # 20230523
            _days = self.getValue('days', j)  # _days is a str
            # logger.info(f'runMap_idx: {runMap_idx}')
            final_df.loc[runMap_idx, 'days'] = _days

            finalIndexList = final_df.index.tolist()

            # we have a list of valid stack centric index in runMap_idx
            # reverse this back into run centric to set rows in runMap (xPlot, yPlot)
            # finalRows = self.objMap[runIdxDim,final_df.index,j]
            finalRows = self.objMap[runIdxDim, finalIndexList, j]
            finalRows = finalRows.astype(int)

            #print 'getMapValues3() final_df:', final_df

            # convert to values at end
            try:
                if pd['xstat'] and pd['xstat'] != 'session':
                    pd['x'][finalRows, j] = final_df[pd['xstat']].values
                if pd['ystat']:
                    pd['y'][finalRows, j] = final_df[pd['ystat']].values
                if pd['zstat']:
                    pd['z'][finalRows, j] = final_df[pd['zstat']].values
            except (KeyError) as e:
                logger.error(f'getMapValues3() KeyError - {e}')
            # except:
            #     print('getMapValues3() error in assignment')

            # keep track of stack centric spine idx
            yIdx[finalRows, j] = final_df.index.values
            ySess[finalRows, j] = j
            yRunRow[finalRows, j] = finalRows  # final_df.index

            # bad
            if pd['plotbad']:
                bad_idx = final_df['isBad'].isin([1])
                '''
                if j == 3:
                    print(j, 'finalRows.shape:', finalRows.shape, finalRows.dtype)
                    print(j, 'bad_idx.shape:', bad_idx.shape, bad_idx.dtype)
                    print(final_df[['Idx', 'isBad']])
                '''
                isBad[finalRows, j] = bad_idx

            #print 'a', final_df['parentID'].values.astype(int)
            #print 'b', self.segMap[0, final_df['parentID'].values.astype(int), j]
            if self.segMap is not None:
                yMapSegment[finalRows, j] = self.segMap[0, final_df['segmentID'].values.astype(int), j]

            cPnt[finalRows, j] = final_df['brightestIndex'].values

            if pd['xstat'] == 'session':
                #print 'swapping x for session'
                pd['x'][finalRows, j] = j #ySess[finalRows,j]

        # strip out all nan rows, can't do this until we have gone through all sessions
        # makes plotting way faster
        ySess = ySess[~np.isnan(yIdx).all(axis=1)]
        yRunRow = yRunRow[~np.isnan(yIdx).all(axis=1)]
        if pd['plotbad']:
            isBad = isBad[~np.isnan(yIdx).all(axis=1)]
        if self.segMap is not None:
            yMapSegment = yMapSegment[~np.isnan(yIdx).all(axis=1)] # added 20171220
        cPnt = cPnt[~np.isnan(yIdx).all(axis=1)] # added 20171225
        if pd['xstat']:
            pd['x'] = pd['x'][~np.isnan(yIdx).all(axis=1)]
        if pd['ystat']:
            pd['y'] = pd['y'][~np.isnan(yIdx).all(axis=1)]
        if pd['zstat']:
            pd['z'] = pd['z'][~np.isnan(yIdx).all(axis=1)]
        yIdx = yIdx[~np.isnan(yIdx).all(axis=1)] # do this last


        pd['stackidx'] = yIdx
        pd['mapsess'] = ySess
        pd['runrow'] = yRunRow
        pd['mapsegment'] = yMapSegment
        pd['cPnt'] = cPnt
        if pd['plotbad']:
            pd['isBad'] = isBad
        else:
            pd['isBad'] = None

        if pd['getMapDynamics']:
            # creates pd['dynamics']
            pd = self.getMapDynamics(pd, thisMatrix=pd['stackidx'])

        stopTime = time.time()
        logger.info(f'   took:{round(stopTime - startTime, 2)} seconds')

        return pd

    def getMapValues2(self, stat, roiType=['spineROI'], segmentID=[], plotBad=False, plotIntBad=False):
        """Get values of a stack annotation across all stacks in the map.

        Args:
            stat (str): The stack annotation to get (corresponds to a column in mmStack.stackdb)
            roiType (str): xxx
            segmentID (list): xxx
            plotBad (boolean): xxx

        Returns:
            2D numpy array of stat values. Each row is a run of objects connected across sessions,
            columns are sessions, each [i][j] is a stat value
        """

        #if roiType not in ROI_TYPES:
        #    errStr = 'error: mmMap.getMapValues2() stat "' + roiType + '" is not in ' + ','.join(ROI_TYPES)
        #    raise h(errStr)

        plotDict = newplotdict()
        plotDict['roitype'] = roiType
        plotDict['xstat'] = stat
        plotDict['segmentid'] = segmentID
        plotDict['plotbad'] = plotBad
        plotDict['plotIntBad'] = plotIntBad

        plotDict = self.getMapValues3(plotDict)

        return plotDict['x']

    def _buildRunMap(self, theMap, roiTypeID=None):
        """Internal function.
            Converts 3D objMap into a 2D run map.
            A run map must be float as it uses np.NaN

        Args:
            theMap: Either self.objMap or self.segMap

        Returns:
            A numpy ndarray run map
        """

        idx = 0
        next = 1
        #nexttp = 2
        prev = 3
        #prevtp = 4
        runIdx = 6 #if this is correct we can build really fast
        nodeType = 9 # integer encoding type, spineROI==0
        m = theMap.shape[1]
        n = theMap.shape[2]
        k = theMap.shape[0]

        # reset
        theMap[runIdx][:][:] = '-1'

        # 20171222
        # was this
        #numRows = np.count_nonzero(~np.isnan(theMap[idx,:,0]))
        #retRunMap = np.empty([numRows,n]) #, dtype=int)
        # new
        retRunMap = np.empty([1, n])  #, dtype=int) # start as one row in run map
        retRunMap[:] = 'nan'

        emptyRow = np.empty([1, n])
        emptyRow[:] = 'nan'

        # thisroitype = 'spineROI'

        currRow = 0
        for j in range(0,n): #sessions
            # not loaded yet
            #stackdb = self.stacks[j].stackdb
            if j == 0:
                firstSessionAdded = 0
            for i in range(0,m):
                #retRunMap[i,j] = 'nan'
                # 20171221, if i just break on ! roiType (e.g. spine) then we get a run map without nan rows?
                # we need to add an updated %runIdx as we do this, e.g. theMap[runIdx][i][j]= currRow
                # new
                #if theMap[idx,i,j]>=0 and stackdb[i][%roiType] == thisroitype:
                #    pass
                #else:
                #    break
                # was this
                # if theMap[idx,i,j]>=0:
                if theMap[idx,i,j]>=0 and (roiTypeID is None or theMap[nodeType][i][j] == roiTypeID):
                    pass
                else:
                    continue
                if j==0:
                    '''
                    # was this 20171222
                    currRow = i
                    #currRow = firstSessionAdded
                    # new one line 20171222
                    # retRunMap = np.vstack([retRunMap, emptyRow])
                    retRunMap[currRow, j] = i
                    # new
                    #theMap[runIdx,i,j] = currRow
                    '''

                    if firstSessionAdded == 0:
                        currRow = 0
                        firstSessionAdded += 1
                    else:
                        retRunMap = np.vstack([retRunMap, emptyRow])
                        currRow += 1
                    retRunMap[currRow, j] = i
                    # new
                    theMap[runIdx,i,j] = currRow
                elif not (theMap[prev,i,j]>=0):
                    currRow += 1
                    retRunMap = np.vstack([retRunMap, emptyRow])
                    retRunMap[currRow, j] = i
                    # new
                    theMap[runIdx,i,j] = currRow
                else:
                    continue
                #retRunMap[currRow,j] = i
                nextNode = theMap[next,i, j]
                for k in range(j+1,n):
                    if nextNode >= 0:
                        retRunMap[currRow,k] = nextNode
                        # new, double check this
                        theMap[runIdx,int(nextNode),k] = currRow
                    else:
                        break
                    nextNode = theMap[next,int(nextNode),k]
        return retRunMap

    def _getStackSegmentID(self, mapSegmentNumber, sessIdx):
        """Given a map centric segment index (row in segRunMap),
            return the stack centric segmentID for session sessIdx

        Args:
            mapSegmentNumber (int): Map centric segment index, row in segRunMap
            sessIdx (int): Session number

        Returns: int or nan: Stack centric segmentID or None if no corresponding segment in that session.
        """
        stackSegment = np.nan
        if self.segRunMap is not None:
            stackSegment = self.segRunMap[mapSegmentNumber][sessIdx] # can be nan
        if math.isnan(stackSegment):
            return None
        else:
            return stackSegment

    ####################################################
    ## ingest
    ####################################################
    def ingest(self):
        print('mmMap.ingest()', self)
        for stack in self.stacks:
            #print(stack)
            stack.ingest()

Attributes¤

defaultAnnotation property ¤
numChannels property ¤

Number of image channels in each stack (must be the same for all stacks).

numMapSegments property ¤

The number of line segments in the map. Corresponding segments are connected together with the segMap.

numSessions property ¤

Number of sessions (timepoints) in the map (time-series).

stacks property ¤

List of :class:pymapmanager.mmStack in the map.

Functions¤

__init__(filePath=None, urlmap=None) ¤
Source code in pymapmanager/mmMap.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
def __init__(self, filePath=None, urlmap=None):
    startTime = time.time()

    self.filePath = ''
    # Full file path to .txt file for the map.

    self._folder = ''
    # Path to enclosing folder, ends in '/'.

    self.name = ''
    # Name of the map. For a map loaded with file a5n.txt, name is a5b. Same as enclosing folder name.
    # If urlmap then this is the name of the map to fetch from a :class:`pymapmanager.mmio` server.

    self.table = None
    # Pandas dataframe loaded from .txt file filePath or 'header' if using :class:`pymapmanager.mmio`.
    # Get values from this dataframe using getValue(name,sessionNumber)

    # removed 20170107, replaced with xxx
    # self.defaultRoiType = 'spineROI'
    #self.defaultRoiTypeID = 0

    self.server = None
    # Pointer to :class:`pymapmanager.mmio` server connection.
    # Only used to load from urlmap.

    self.objMap = None
    # 2D array where each row is a run of annotations.
    # objMap[i][j] gives us a mmStack centric index into mmStack.stackdb.

    self.segMap = None
    # 2D array where each row is a run of segments.
    # segMap[i][j] gives us mmStack centric index into mmStack._line

    self.segRunMap = None # 20180107, why was this not defaulted?

    # if we get a filePath, make sure it exists and decide if it is a folder or a file
    # in the end we will always load from a .txt file
    if filePath is not None:
        if filePath.endswith(os.sep):
            filePath = filePath[0:-1]
        if os.path.exists(filePath):
            if os.path.isdir(filePath):
                tmpPath, tmpName = os.path.split(filePath)
                filePath = os.path.join(filePath, tmpName + '.txt')
                # check if file exists
                if not os.path.isfile(filePath):
                    raise IOError(ENOENT, 'mmMap got a bad map folder:', filePath)
            else:
                pass
        else:
            # error
            raise IOError(ENOENT, 'mmMap got a bad map path:', filePath)

    ###############################################################################
    # map nv
    doFile = True
    if filePath is not None:
        if not os.path.isfile(filePath):
            raise IOError(ENOENT, 'mmMap did not find filePath:', filePath)
        self.filePath = filePath #  Path to file used to open map."""
        self._folder = os.path.dirname(filePath) + '/'
        self.name = os.path.basename(filePath).strip('.txt')
        self.table = pd.read_table(filePath, index_col=0)
    elif urlmap is not None:
        doFile = False
        # try loading from url
        self.name = urlmap
        self.server = mmio()
        tmp = self.server.getfile('header', self.name)
        self.table = pd.read_table(io.StringIO(tmp.decode('utf-8')), index_col=0)

    ###############################################################################
    # objMap (3d)
    if doFile:
        objMapFile = self._folder + self.name + '_objMap.txt'
        if not os.path.isfile(objMapFile):
            raise IOError(ENOENT, 'mmMap did not find objMapFile:', objMapFile)
        # with open(objMapFile, 'rU') as f:
        with open(objMapFile, 'r') as f:
            header = f.readline().rstrip()
        self.objMap = np.loadtxt(objMapFile, skiprows=1)
    else:
        tmp = self.server.getfile('objmap', self.name).decode("utf-8")
        header = tmp.split('\n')[0]
        self.objMap = np.loadtxt(tmp.split('\n'), skiprows=1)

    if header.endswith(';'):
        header = header[:-1]
    header = header.split(';')
    d = dict(s.split('=') for s in header)
    numRow = int(d['rows'])
    numCol = int(d['cols'])
    numBlock = int(d['blocks'])

    self.objMap.resize(numBlock,numRow,numCol)
    self.runMap = self._buildRunMap(self.objMap, roiTypeID=self.defaultAnnotationID)

    ###############################################################################
    # segMap (3d)
    header = None
    if doFile:
        segMapFile = self._folder + self.name + '_segMap.txt'
        if os.path.isfile(segMapFile):
            # with open(segMapFile, 'rU') as f:
            with open(segMapFile, 'r') as f:
                header = f.readline().rstrip()
            self.segMap = np.loadtxt(segMapFile, skiprows=1)
        else:
            #raise IOError(ENOENT, 'mmMap did not find segMapFile:', segMapFile)
            print('did not find segment map file, should be ok')
    else:
        tmp = self.server.getfile('segmap', self.name).decode("utf-8")
        #header = tmp.split('\r')[0] # works when server is running on OSX
        header = tmp.split('\n')[0]
        self.segMap = np.loadtxt(tmp.split('\n'), skiprows=1)

    if header is not None:
        if header.endswith(';'):
            header = header[:-1]
        header = header.split(';')
        d = dict(s.split('=') for s in header)
        numRow = int(d['rows'])
        numCol = int(d['cols'])
        numBlock = int(d['blocks'])

        self.segMap.resize(numBlock,numRow,numCol)
        self.segRunMap = self._buildRunMap(self.segMap, roiTypeID = None)

    ###############################################################################
    #load each stack db
    # this assumes self.objMap has already been loaded
    self._stacks = [] #  A list of mmStack
    for _session in range(0, self.numSessions):
        stackPath = self.getStackPath(_session)
        stack = pymapmanager.stack(stackPath,
                                   loadImageData=False,
                                   mmMap=self,
                                   mmMapSession=_session)
        # if doFile:
        #     stack = mmStack(name=self._getStackName(i), numChannels=self.numChannels, \
        #                     map=self, mapSession=i)
        # else:
        #     stack = mmStack(name=self._getStackName(i), numChannels=self.numChannels, \
        #                     map=self, mapSession=i, urlmap=self.name)
        self.stacks.append(stack)

    stopTime = time.time()
    print('map', self.name, 'loaded in', round(stopTime-startTime,2), 'seconds.')

    # 202402 need to add some columns to stack db
    logger.warning('REMOVE THIS INGEST !!!!!!!!!')
    from pymapmanager.interface2.mapWidgets._mapIngest import addDistance
    addDistance(self)
getMapValues2(stat, roiType=['spineROI'], segmentID=[], plotBad=False, plotIntBad=False) ¤

Get values of a stack annotation across all stacks in the map.

Args: stat (str): The stack annotation to get (corresponds to a column in mmStack.stackdb) roiType (str): xxx segmentID (list): xxx plotBad (boolean): xxx

Returns: 2D numpy array of stat values. Each row is a run of objects connected across sessions, columns are sessions, each [i][j] is a stat value

Source code in pymapmanager/mmMap.py
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
def getMapValues2(self, stat, roiType=['spineROI'], segmentID=[], plotBad=False, plotIntBad=False):
    """Get values of a stack annotation across all stacks in the map.

    Args:
        stat (str): The stack annotation to get (corresponds to a column in mmStack.stackdb)
        roiType (str): xxx
        segmentID (list): xxx
        plotBad (boolean): xxx

    Returns:
        2D numpy array of stat values. Each row is a run of objects connected across sessions,
        columns are sessions, each [i][j] is a stat value
    """

    #if roiType not in ROI_TYPES:
    #    errStr = 'error: mmMap.getMapValues2() stat "' + roiType + '" is not in ' + ','.join(ROI_TYPES)
    #    raise h(errStr)

    plotDict = newplotdict()
    plotDict['roitype'] = roiType
    plotDict['xstat'] = stat
    plotDict['segmentid'] = segmentID
    plotDict['plotbad'] = plotBad
    plotDict['plotIntBad'] = plotIntBad

    plotDict = self.getMapValues3(plotDict)

    return plotDict['x']
getMapValues3(pd) ¤

Get values of a stack annotation across all stacks in the map.

Args: pd (dict): A plot dictionary describing what to plot. Get default from mmUtil.newplotdict().

Returns:

| pd['x'], 2D ndarray of xstat values, rows are runs, cols are sessions, nan is where there is no stackdb annotation
| pd['y'], same
| pd['z'], same
| pd['stackidx'], Each [i]j[] gives the stack centric index of annotation value at [i][j].
| pd['mapsess'], Each [i][j] gives the map session of value at annotation [i][j].
| pd['runrow'],
Source code in pymapmanager/mmMap.py
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
def getMapValues3(self, pd):
    """Get values of a stack annotation across all stacks in the map.

    Args:
        pd (dict): A plot dictionary describing what to plot. Get default from mmUtil.newplotdict().

    Returns:

        | pd['x'], 2D ndarray of xstat values, rows are runs, cols are sessions, nan is where there is no stackdb annotation
        | pd['y'], same
        | pd['z'], same
        | pd['stackidx'], Each [i]j[] gives the stack centric index of annotation value at [i][j].
        | pd['mapsess'], Each [i][j] gives the map session of value at annotation [i][j].
        | pd['runrow'],

    """
    startTime = time.time()

    # make sure pd['roitype'] is a list
    if not isinstance(pd['roitype'], list):
        pd['roitype'] = [pd['roitype']]

    m = self.runMap.shape[0]
    n = self.runMap.shape[1]

    if pd['xstat']:
        pd['x'] = np.empty([m, n])
        pd['x'][:] = np.NAN
    if pd['ystat']:
        pd['y'] = np.empty([m, n])
        pd['y'][:] = np.NAN
    if pd['zstat']:
        pd['z'] = np.empty([m, n])
        pd['z'][:] = np.NAN

    # keep track of stack centric index we are plotting
    yIdx = np.empty([m, n])
    yIdx[:] = np.NAN

    # keep track of session index
    ySess = np.empty([m, n])
    ySess[:] = np.NAN

    # keep track of run map rows (we already know the session/column)
    yRunRow = np.empty([m, n])
    yRunRow[:] = np.NAN

    # always make a matrix of bad
    isBad = np.empty([m, n])
    isBad[:] = np.NAN

    # keep track of map segment id
    yMapSegment = []
    if self.segMap is not None:
        yMapSegment = np.empty([m, n])
        yMapSegment[:] = np.NAN

    # 20171225, cPnt is overkill but until I rewrite REST
    # to get list of stat (x,y,z,pDist, cPnt, cx, cy, cz) etc. etc.
    cPnt = np.empty([m, n])
    cPnt[:] = np.NAN

    runIdxDim = 6

    if pd['stacklist'] is not None and len(pd['stacklist'])>0:
        myRange = pd['stacklist']
    else:
        myRange = range(n)

    for j in myRange:

        #print('*** getMapValues3() j:', j, "pd['segmentid']:", pd['segmentid'])
        # orig_df = self.stacks[j].stackdb
        orig_df = self.stacks[j].getPointAnnotations().getDataFrame()

        # print(orig_df.columns)
        # sys.exit(1)

        currSegmentID = []
        if self.numMapSegments > 0:
            # 20220103
            oneSegment = pd['segmentid']
            if isinstance(oneSegment, list):
                logger.warning('abb 20220103 in mmMap.getMapValue3() fix this cludge from list to int')
                if len(oneSegment) > 0:
                    oneSegment = oneSegment[0]
                else:
                    oneSegment = None
            if oneSegment is not None and oneSegment >=0 :
                currSegmentID = self.segRunMap[oneSegment, j]  # this only works for one segment -- NOT A LIST
                #print('   currSegmentID:', currSegmentID)
                if currSegmentID >= 0:
                    currSegmentID = int(currSegmentID)
                    # print 'getMapValues3() j:', j, 'currSegmentID:', currSegmentID
                    currSegmentID = [currSegmentID]
                else:
                    currSegmentID = []
            #print('   currSegmentID:', currSegmentID)
            if oneSegment is not None and oneSegment >= 0 and not currSegmentID:
                # this session does not have segmentID that match
                #print('   getMapValues3() skipping tp', j)
                continue

        goodIdx = self.runMap[:, j]  # valid indices from runMap

        #print goodIdx

        runMap_idx = orig_df.index.isin(goodIdx)  # series of boolean (Seems to play nice with nparray)

        if pd['roitype']:
            roiType_idx = orig_df['roiType'].isin(pd['roitype'])
            runMap_idx = runMap_idx & roiType_idx
        if currSegmentID:
            segmentID_idx = orig_df['segmentID'].isin(currSegmentID)
            runMap_idx = runMap_idx & segmentID_idx

        # bad
        if not pd['plotbad']:
            #print('mmMap.getMapValues3() is stripping out isBad')
            notBad_idx = ~orig_df['isBad'].isin([1])
            runMap_idx = runMap_idx & notBad_idx

        # final_df = orig_df.loc[runMap_idx]
        # 20210922 was this
        #final_df = orig_df.ix[runMap_idx]
        #print('20210922 orig_df:')
        #print(orig_df)
        final_df = orig_df.loc[runMap_idx]
        #print(final_df)

        # 20230523
        _days = self.getValue('days', j)  # _days is a str
        # logger.info(f'runMap_idx: {runMap_idx}')
        final_df.loc[runMap_idx, 'days'] = _days

        finalIndexList = final_df.index.tolist()

        # we have a list of valid stack centric index in runMap_idx
        # reverse this back into run centric to set rows in runMap (xPlot, yPlot)
        # finalRows = self.objMap[runIdxDim,final_df.index,j]
        finalRows = self.objMap[runIdxDim, finalIndexList, j]
        finalRows = finalRows.astype(int)

        #print 'getMapValues3() final_df:', final_df

        # convert to values at end
        try:
            if pd['xstat'] and pd['xstat'] != 'session':
                pd['x'][finalRows, j] = final_df[pd['xstat']].values
            if pd['ystat']:
                pd['y'][finalRows, j] = final_df[pd['ystat']].values
            if pd['zstat']:
                pd['z'][finalRows, j] = final_df[pd['zstat']].values
        except (KeyError) as e:
            logger.error(f'getMapValues3() KeyError - {e}')
        # except:
        #     print('getMapValues3() error in assignment')

        # keep track of stack centric spine idx
        yIdx[finalRows, j] = final_df.index.values
        ySess[finalRows, j] = j
        yRunRow[finalRows, j] = finalRows  # final_df.index

        # bad
        if pd['plotbad']:
            bad_idx = final_df['isBad'].isin([1])
            '''
            if j == 3:
                print(j, 'finalRows.shape:', finalRows.shape, finalRows.dtype)
                print(j, 'bad_idx.shape:', bad_idx.shape, bad_idx.dtype)
                print(final_df[['Idx', 'isBad']])
            '''
            isBad[finalRows, j] = bad_idx

        #print 'a', final_df['parentID'].values.astype(int)
        #print 'b', self.segMap[0, final_df['parentID'].values.astype(int), j]
        if self.segMap is not None:
            yMapSegment[finalRows, j] = self.segMap[0, final_df['segmentID'].values.astype(int), j]

        cPnt[finalRows, j] = final_df['brightestIndex'].values

        if pd['xstat'] == 'session':
            #print 'swapping x for session'
            pd['x'][finalRows, j] = j #ySess[finalRows,j]

    # strip out all nan rows, can't do this until we have gone through all sessions
    # makes plotting way faster
    ySess = ySess[~np.isnan(yIdx).all(axis=1)]
    yRunRow = yRunRow[~np.isnan(yIdx).all(axis=1)]
    if pd['plotbad']:
        isBad = isBad[~np.isnan(yIdx).all(axis=1)]
    if self.segMap is not None:
        yMapSegment = yMapSegment[~np.isnan(yIdx).all(axis=1)] # added 20171220
    cPnt = cPnt[~np.isnan(yIdx).all(axis=1)] # added 20171225
    if pd['xstat']:
        pd['x'] = pd['x'][~np.isnan(yIdx).all(axis=1)]
    if pd['ystat']:
        pd['y'] = pd['y'][~np.isnan(yIdx).all(axis=1)]
    if pd['zstat']:
        pd['z'] = pd['z'][~np.isnan(yIdx).all(axis=1)]
    yIdx = yIdx[~np.isnan(yIdx).all(axis=1)] # do this last


    pd['stackidx'] = yIdx
    pd['mapsess'] = ySess
    pd['runrow'] = yRunRow
    pd['mapsegment'] = yMapSegment
    pd['cPnt'] = cPnt
    if pd['plotbad']:
        pd['isBad'] = isBad
    else:
        pd['isBad'] = None

    if pd['getMapDynamics']:
        # creates pd['dynamics']
        pd = self.getMapDynamics(pd, thisMatrix=pd['stackidx'])

    stopTime = time.time()
    logger.info(f'   took:{round(stopTime - startTime, 2)} seconds')

    return pd
getStackTimepoint(thisStack) ¤

Given a stack, find the timepoint.

Source code in pymapmanager/mmMap.py
134
135
136
137
138
139
140
def getStackTimepoint(self, thisStack : pymapmanager.stack) -> int:
    """Given a stack, find the timepoint.
    """ 
    for idx, stack in enumerate(self.stacks):
        if stack == thisStack:
            return idx
    return None
getValue(name, sessionNumber) ¤

Get a value from the map (not from a stack!).

Args: name: Name of map value sessionNumber: Session number of the stack

Returns: Str (this is a single value)

Examples::

m.getValue('pixelsz', 2) # get the number of z-slices (pixels) of stack 2.
m.getValue('voxelx', 5) # get the x voxel size of stack 5 (in um/pixel).
m.getValue('hsStack',3) # get the name of stack 3.
Source code in pymapmanager/mmMap.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def getValue(self, name, sessionNumber):
    """
    Get a value from the map (not from a stack!).

    Args:
        name: Name of map value
        sessionNumber: Session number of the stack

    Returns:
        Str (this is a single value)

    Examples::

        m.getValue('pixelsz', 2) # get the number of z-slices (pixels) of stack 2.
        m.getValue('voxelx', 5) # get the x voxel size of stack 5 (in um/pixel).
        m.getValue('hsStack',3) # get the name of stack 3.
    """
    # .loc specifies row, .iloc specifies a column
    return self.table.loc[name].iloc[sessionNumber]
mapInfo() ¤

Get information on the map

Returns: | A dict of | mapName : Str | numSessions : Int | numChannels : Int | numMapSegments : Int | | The following are string list with numSessions elements | stackNames : | importedStackName : | numSlices : | date : | time : | dx : Voxel size in um | dy : Voxel size in um | dz : Voxel size in um | px : Number of Pixels | py : Number of Pixels | pz : Number of Pixels | ...

Source code in pymapmanager/mmMap.py
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
def mapInfo(self):
    """
    Get information on the map

    Returns:
        | A dict of
        | mapName : Str
        | numSessions : Int
        | numChannels : Int
        | numMapSegments : Int
        |
        | The following are string list with numSessions elements
        | stackNames :
        | importedStackName :
        | numSlices :
        | date :
        | time :
        | dx : Voxel size in um
        | dy : Voxel size in um
        | dz : Voxel size in um
        | px : Number of Pixels
        | py : Number of Pixels
        | pz : Number of Pixels
        | ...
    """
    theRet = {}
    theRet['mapName'] = self.name
    theRet['numSessions'] = self.numSessions
    theRet['numChannels'] = self.numChannels
    theRet['defaultAnnotation'] = self.defaultAnnotation
    theRet['numAnnotations'] = 0
    # lists, one value per session
    theRet['stackNames'] = []
    theRet['importedStackName'] = []
    theRet['date'] = []
    theRet['time'] = []
    theRet['px'] = [] # pixels
    theRet['py'] = []
    theRet['numSlices'] = []
    theRet['dx'] = [] # voxels in um
    theRet['dy'] = []
    theRet['dz'] = []
    theRet['numROI'] = []
    for idx in range(self.numSessions):
        theRet['stackNames'].append(self.table.loc['hsStack'][idx])
        theRet['importedStackName'].append(self.table.loc['importedStackName'][idx])
        theRet['date'].append(self.table.loc['date'][idx])
        theRet['time'].append(self.table.loc['time'][idx])
        theRet['px'].append(self.table.loc['px'][idx])
        theRet['py'].append(self.table.loc['py'][idx])
        theRet['numSlices'].append(self.table.loc['pz'][idx]) # changing name

        theRet['dx'].append(self.table.loc['dx'][idx])
        theRet['dy'].append(self.table.loc['dy'][idx])
        theRet['dz'].append(self.table.loc['dz'][idx])

        thisNum = self.stacks[idx].countObj(roiType=self.defaultAnnotation)
        theRet['numROI'].append(thisNum)
        theRet['numAnnotations'] = theRet['numAnnotations'] + self.stacks[idx].numObj

        runIdx = 6

    if self.segMap is not None:
        theRet['numMapSegments'] = self.segRunMap.shape[0]
    else:
        theRet['numMapSegments'] = 0

    '''
    # these were not being used
    theRet['objMap'] = self.objMap[runIdx].astype('int') # from spine index to run index
    theRet['runMap'] = self.runMap.astype('int') # from run idx to spine idx
    theRet['segMap'] = None
    theRet['numMapSegments'] = 0
    if self.segMap is not None:
        theRet['segMap'] = self.segMap.astype('int')
        theRet['numMapSegments'] = self.segRunMap.shape[0]
    '''

    #print 'mapInfo() theRet:', theRet
    return theRet

Functions¤

newplotdict() ¤

Get a new default plot dictionary.

The plot dictionary is used to tell plot functions what to plot (e.g. ['xtat'] and ['ystat']).

All plot function return the same plot dictionary with keys filled in with values that were plotted (e.g. ['x'] and ['y']).

Example::

import pymapmanager as pmm

path = 'PyMapManager/examples/exampleMaps/rr30a/rr30a.txt'
map = pmm.mmMap(path)
plotdict = pmm.mmUtil.newplotdict()
plotdict['xstat'] = 'days'
plotdict['ystat'] = 'pDist' # position of spine on its parent segment
plotdict = map.getMapValues3(plotdict)

# display with matplotlib
plotdict['x']
plotdict['y']
Source code in pymapmanager/mmMap.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def newplotdict():
    """
    Get a new default plot dictionary.

    The plot dictionary is used to tell plot functions what to plot (e.g. ['xtat'] and ['ystat']).

    All plot function return the same plot dictionary with keys filled in with values that were plotted
    (e.g. ['x'] and ['y']).

    Example::

        import pymapmanager as pmm

        path = 'PyMapManager/examples/exampleMaps/rr30a/rr30a.txt'
        map = pmm.mmMap(path)
        plotdict = pmm.mmUtil.newplotdict()
        plotdict['xstat'] = 'days'
        plotdict['ystat'] = 'pDist' # position of spine on its parent segment
        plotdict = map.getMapValues3(plotdict)

        # display with matplotlib
        plotdict['x']
        plotdict['y']

    """
    return PLOT_DICT.copy()
All material is Copyright 2011-2024 Robert H. Cudmore