Exemplo n.º 1
0
def runNeuroMAnalysis(path):
    fullState = files.loadState(usePathOrPick(path))
    # NOTE: need to load one image, so set up volume size
    _IMG_CACHE.handleNewUIState(fullState.uiStates[0])
    print("Loaded %d trees" % len(fullState.trees))
    result = neuroMAnalysisForNeurons(fullState)
    print(result)
Exemplo n.º 2
0
def runFiloTipCluster(path):
    fullState = files.loadState(usePathOrPick(path))
    # Process each tree in order:
    for treeIdx, tree in enumerate(fullState.trees):
        branchIDList = util.sortedBranchIDList([tree])

        # Find the types of each branch:
        filoTypes, _, _, _, _, _ = addedSubtractedTransitioned([tree])

        # Keep only interstitial filo...
        interstitialFiloIDs = []
        for branchID, filoType in zip(branchIDList, filoTypes[0]):
            if filoType == FiloType.INTERSTITIAL:
                interstitialFiloIDs.append(branchID)
        print("%d Interstitial Filos detected" % (len(interstitialFiloIDs)))

        # and map to the points at their tip:
        tipPoints = []
        for branch in tree.branches:
            if branch.id in interstitialFiloIDs:
                if len(branch.points) > 0:
                    tipPoints.append(branch.points[-1])
        fig = plt.figure()
        fig.suptitle("Interstitial Filo Tip clustering for [%d]" %
                     (treeIdx + 1))
        fig.subplots_adjust(left=0.02,
                            bottom=0.07,
                            right=0.98,
                            top=0.9,
                            wspace=0.05,
                            hspace=0.2)

        # 3D plot showing where the filo tips are on the branches.
        ax3D = fig.add_subplot(121, projection='3d')
        ax3D.set_title("3D positions")
        for branch in tree.branches:
            if branch.parentPoint is not None:
                points = [branch.parentPoint] + branch.points
                ax3D.plot(*tree.worldCoordPoints(points),
                          c=(0.5, 0.5, 0.5, 0.1))
        ax3D.scatter(*tree.worldCoordPoints(tipPoints))

        # 2D plot comparing spatial distance to tree distance
        sDs, tDs = [], []
        ax2D = fig.add_subplot(122)
        ax2D.set_title("Spatial distance vs Tree Distance")
        ax2D.set_xlabel("Spatial Distance (uM)")
        ax2D.set_ylabel("Tree Distance (uM)")
        for i, p1 in enumerate(tipPoints):
            for p2 in tipPoints[i + 1:]:
                spatialDist, treeDist = tree.spatialAndTreeDist(p1, p2)
                sDs.append(spatialDist)
                tDs.append(treeDist)
        if len(sDs) > 0 and len(tDs) > 0:
            ax2D.scatter(sDs, tDs)
            ax2D.plot([0, np.max(sDs)], [0, np.max(sDs)],
                      '--',
                      c=(0.5, 0.5, 0.5, 0.7))
        plt.show()
Exemplo n.º 3
0
def doCleanups(path):
    origPath = usePathOrPick(path)
    fullState = files.loadState(origPath)
    cleanupEmptyBranches(fullState)
    # TODO - add more cleanups here
    cleanPath = os.path.join(os.path.dirname(origPath),
                             "clean." + os.path.basename(origPath))
    files.saveState(fullState, cleanPath)
    print("State saved to %s" % cleanPath)
Exemplo n.º 4
0
def testImportNoChange(path='data/localFirst.dyn.gz'):
    print("Testing no motility changes after nodes copied...")
    fullState = files.loadState(path)
    assert len(fullState.trees) == 1

    treeA = fullState.trees[0]

    # NOTE: old trees sometimes have empty branches:
    emptyBranches = [b for b in treeA.branches if len(b.points) == 0]
    for emptyBranch in emptyBranches:
        treeA.removeBranch(emptyBranch)

    treeB = Tree()
    treeB.clearAndCopyFrom(treeA, fullState)
    treeB._parentState = treeA._parentState
    # Copy branch and point IDs:
    for i in range(len(treeA.branches)):
        treeB.branches[i].id = treeA.branches[i].id
        for j in range(len(treeA.branches[i].points)):
            treeB.branches[i].points[j].id = treeA.branches[i].points[j].id
    trees = [treeA, treeB]

    print("\nResults:\n---------")

    # TDBL the same for identical trees
    allTDBL = [
        TDBL(tree,
             excludeAxon=True,
             excludeBasal=False,
             includeFilo=False,
             filoDist=5) for tree in trees
    ]
    # print (allTDBL)
    assert allTDBL[0] == allTDBL[1]
    print("🙌 TDBL match!")

    filoTypes, added, subtracted, transitioned, masterChanged, masterNodes = \
        addedSubtractedTransitioned(trees, excludeAxon=True, excludeBasal=False, terminalDist=5, filoDist=5)

    assert not np.any(added)
    assert not np.any(subtracted)
    assert not np.any(transitioned)
    print("🙌 Nothing added, subtracted or transitioned!")

    motilities, filoLengths = motility(trees,
                                       excludeAxon=True,
                                       excludeBasal=False,
                                       terminalDist=5,
                                       filoDist=5)
    mot = motilities['raw'][0]
    assert np.all(np.logical_or(mot == 0, np.isnan(mot)))
    assert np.all(
        np.logical_or(filoLengths[0] == filoLengths[1],
                      np.isnan(filoLengths[0])))
    assert np.array_equal(filoTypes[0], filoTypes[1])
    print("🙌 Filotypes, filo lengths match!")
Exemplo n.º 5
0
 def openFromFile(self, filePath=""):
     print("File: '%s'" % filePath)
     if filePath == "":
         filePath, _ = QtWidgets.QFileDialog.getOpenFileName(
             self, "Open dynamo save file", "", "Dynamo files (*.dyn.gz)")
     if filePath != "":
         self.stackList.show()
         self.fullState = loadState(filePath)
         self.history = History(self.fullState)
         self.fullActions = FullStateActions(self.fullState, self.history)
         self.autoSaver = AutoSaver(self.fullState)
         BranchToColorMap().initFromFullState(self.fullState)
         self.initialMenu.hide()
         self.makeNewWindows()
Exemplo n.º 6
0
def testParents():
    fullState = files.loadState(
        "pydynamo_brain/pydynamo_brain/test/files/example2.dyn.gz")
    fullID = id(fullState)
    for uiState in fullState.uiStates:
        assert id(uiState.parent()) == fullID

    h = History(fullState)
    h.pushState()
    h.undo()

    for uiState in fullState.uiStates:
        assert id(uiState.parent()) == fullID
    print("Full State history passed! 🙌")
Exemplo n.º 7
0
def allTrees(stateOrPath: Union[FullState,
                                str], funcs: List[Callable[..., pd.DataFrame]],
             **kwargs: Any) -> pd.DataFrame:
    # Load state first if provided as a string.
    fullState = None
    if isinstance(stateOrPath, FullState):
        fullState = stateOrPath
    else:
        assert isinstance(stateOrPath, str)
        fullState = files.loadState(stateOrPath)
    assert fullState is not None

    # Merge all results into one dataframe.
    result = pd.DataFrame(index=list(range(len(fullState.trees))))
    for func in funcs:
        result = result.join(func(fullState, **kwargs))
    return result
Exemplo n.º 8
0
def allPuncta(stateOrPath: Union[FullState, str],
              funcs: List[Callable[..., pd.DataFrame]],
              **kwargs: Any) -> pd.DataFrame:
    # Load state first if provided as a string.
    fullState = None
    if isinstance(stateOrPath, FullState):
        fullState = stateOrPath
    else:
        assert isinstance(stateOrPath, str)
        fullState = files.loadState(stateOrPath)
    assert fullState is not None

    # Merge all results into one dataframe.
    sortedPunctaIDs = util.sortedPunctaIDList(fullState.puncta)
    result = pd.DataFrame(index=sortedPunctaIDs)
    for func in funcs:
        result = result.join(func(fullState, sortedPunctaIDs, **kwargs))
    return result
Exemplo n.º 9
0
def calculateResults(path='data/movie5local.mat'):
    results = {}
    if path.endswith('.mat'):
        # Keep orphans around, to match against old matlab analysis
        fullState = files.importFromMatlab(path, removeOrphanBranches=False)
    else:
        assert path.endswith('.dyn.gz')
        fullState = files.loadState(path)
    trees = fullState.trees

    TERM_DIST = 5
    FILO_DIST = 5

    allTDBL = [
        TDBL(tree,
             excludeAxon=True,
             excludeBasal=False,
             includeFilo=False,
             filoDist=FILO_DIST) for tree in trees
    ]
    results['tdbl'] = np.array([allTDBL])

    filoTypes, added, subtracted, transitioned, masterChanged, masterNodes = \
        addedSubtractedTransitioned(trees, excludeAxon=True, excludeBasal=False, terminalDist=TERM_DIST, filoDist=FILO_DIST)
    results['filotypes'] = filoTypes
    results['added'] = added
    results['subtracted'] = subtracted
    results['transitioned'] = transitioned
    results['masterChanged'] = masterChanged
    results['masterNodes'] = masterNodes

    motilities, filoLengths = motility(trees,
                                       excludeAxon=True,
                                       excludeBasal=False,
                                       terminalDist=TERM_DIST,
                                       filoDist=FILO_DIST)
    results['filolengths'] = filoLengths

    return fullState, results
Exemplo n.º 10
0
def run(path='pydynamo_brain/pydynamo_brain/test/files/example2.dyn.gz'):
    tree = files.loadState(path).trees[0]
    pointX, pointY = calculatePositions(tree)

    # TODO: Verify X and Y positions
    return True