Skip to content

Commit

Permalink
Merge branch 'johnson-dev' into cudmore-dev
Browse files Browse the repository at this point in the history
  • Loading branch information
cudmore committed Jul 21, 2024
2 parents 861fdc2 + eb9edb4 commit e430f00
Show file tree
Hide file tree
Showing 10 changed files with 358 additions and 126 deletions.
34 changes: 28 additions & 6 deletions pymapmanager/annotations/baseAnnotationsCore.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
import pandas as pd
import shapely

import mapmanagercore
from mapmanagercore import MapAnnotations
# from mapmanagercore import MapAnnotations, MultiImageLoader
# from mapmanagercore.annotations.single_time_point.base import SingleTimePointFrame
# from mapmanagercore import single_time_point
from mapmanagercore.layers.line import clipLines
from mapmanagercore.lazy_geo_pandas import LazyGeoFrame

Expand Down Expand Up @@ -89,8 +93,12 @@ def getSegmentPlot(self, segmentID,
_stopSlice = zSlice + zPlusMinus

df = self.getDataFrame()
# logger.info(f"df: {df}")
df['rowIndex'] = list(np.arange(len(df)))
df = df[(df['z']>=_startSlice) & (df['z']<=_stopSlice)]

#abj: 7/17/24
if not df.empty:
df = df[(df['z']>=_startSlice) & (df['z']<=_stopSlice)]

return df

Expand Down Expand Up @@ -165,6 +173,10 @@ def moveSpine(self, spineID :int, x, y, z):
# _moved = self._fullMap.moveSpine((spineID, self.sessionID), x=x, y=y, z=z)
_moved = self._fullMap.moveSpine(spineID, x=x, y=y, z=z)

#abj: 7/5
#update background ROI
self._fullMap.snapBackgroundOffset(spineID)

# rebuild df from mutated full map
self._buildDataFrame()

Expand Down Expand Up @@ -252,17 +264,22 @@ def _buildDataFrame(self):
"""

# _startSec = time.time()

# logger.info(f"self._fullMap.points {self._fullMap.points}")
# logger.info(f"type self._fullMap.points {type(self._fullMap.points)}")
try:
allSpinesDf = self._fullMap.points[:]
except (KeyError) as e:
logger.warning(e)
return

# add (x, y) if it does not exists
xyCoord = allSpinesDf['point'].get_coordinates()
allSpinesDf['x'] = xyCoord['x']
allSpinesDf['y'] = xyCoord['y']
#abj: check if points are empty:
if len(allSpinesDf) > 0:
logger.info(f"allSpinesDf {type(allSpinesDf)}") # <class 'geopandas.geodataframe.GeoDataFrame'>
# logger.info(f"allSpinesDf['point'] {type(allSpinesDf['point'])}")
# add (x, y) if it does not exists
xyCoord = allSpinesDf['point'].get_coordinates()
allSpinesDf['x'] = xyCoord['x']
allSpinesDf['y'] = xyCoord['y']

allSpinesDf['roiType'] = 'spineROI'
allSpinesDf.insert(0,'index', allSpinesDf.index) # index is first column
Expand Down Expand Up @@ -295,6 +312,11 @@ def getSpineLines(self):
1 382.0 250.0 NaN
"""
# anchorDf = self._sessionMap['anchors'].get_coordinates(include_z=True)

# test= self._fullMap.points['anchorLine']
# logger.info(f"getSpineLines test {test}")
# logger.info(f"getSpineLines test type {type(test)}")

anchorDf = self._fullMap.points['anchorLine'].get_coordinates(include_z=True)

# for undo delete, we need to re-assing row lables to match points self._df
Expand Down
16 changes: 15 additions & 1 deletion pymapmanager/interface2/mainMenus.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,20 @@ def _buildMenus(self, mainMenu, mainWindow):

fileMenu.addSeparator()

# abj
saveFileAction = QtWidgets.QAction("Save", self.getApp())
saveFileAction.setCheckable(False) # setChecked is True by default?
saveFileAction.setShortcut("Ctrl+S")
saveFileAction.triggered.connect(self.getApp().saveFile)
fileMenu.addAction(saveFileAction)

saveAsFileAction = QtWidgets.QAction("Save As", self.getApp())
saveAsFileAction.setCheckable(False) # setChecked is True by default?
saveAsFileAction.triggered.connect(self.getApp().saveAsFile)
fileMenu.addAction(saveAsFileAction)

fileMenu.addSeparator()

# open recent (submenu) will show two lists, one for files and then one for folders
self.openRecentMenu = QtWidgets.QMenu("Open Recent ...")
self.openRecentMenu.aboutToShow.connect(self._refreshOpenRecent)
Expand Down Expand Up @@ -130,7 +144,7 @@ def _buildMenus(self, mainMenu, mainWindow):
self._helpMenuAction = _action

return self._helpMenuAction

def _refreshPluginsMenu(self):
logger.info('re-create plugin menu with available pligins')

Expand Down
36 changes: 35 additions & 1 deletion pymapmanager/interface2/openFirstWindow.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class OpenFirstWindow(MainWindow):
def __init__(self, pyMapManagerApp : PyMapManagerApp, parent=None):
super().__init__(parent)

# self._app = pyMapManagerApp
self._app = pyMapManagerApp

self.recentStackList = self.getApp().getConfigDict().getRecentStacks()
self.recentMapList = self.getApp().getConfigDict().getRecentMaps()
Expand Down Expand Up @@ -160,6 +160,13 @@ def _buildUI(self):
aButton.clicked.connect(partial(self._on_open_button_click, name))
hBoxLayout.addWidget(aButton, alignment=QtCore.Qt.AlignLeft)

name = 'Drag and Drop'
aButton = DragAndDropWidget(name, self._app)
aButton.setFixedSize(QtCore.QSize(200, 60))
aButton.setToolTip('Drag and Drop Tif File.')
# aButton.clicked.connect(partial(self._on_open_button_click, name))
hBoxLayout.addWidget(aButton, alignment=QtCore.Qt.AlignLeft)

# recent files and tables
recent_vBoxLayout = QtWidgets.QVBoxLayout()

Expand All @@ -185,6 +192,33 @@ def _buildUI(self):

_mainVLayout.addLayout(recent_vBoxLayout)

# QtWidgets.QPushButton
# QtWidgets.QMainWindow
class DragAndDropWidget(QtWidgets.QPushButton):
def __init__(self, name, app: PyMapManagerApp):
super().__init__(name)
self.setWindowTitle("Drag and Drop")
self.resize(720, 480)
self.setAcceptDrops(True)

self._app = app

def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()

def dropEvent(self, event):
files = [u.toLocalFile() for u in event.mimeData().urls()]
for tifFile in files:
# print(f)
logger.info(f"loading file {tifFile}")
self._app.loadTifFile(tifFile)
# Create new image loader iwth path
# emit f = path to file


def test():
import sys
from sanpy.interface import SanPyApp
Expand Down
89 changes: 89 additions & 0 deletions pymapmanager/interface2/pyMapManagerApp2.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,43 @@ def openTimeSeries(self):
logger.info('')
pass

def saveFile(self):
""" Save new changes to current file
"""
# zarrPath = self.stackWidget.getStack().getPath()
# <pymapmanager.interface2.stackWidgets.stackWidget2.stackWidget2 object at 0x00000194F144C790>
# temp = self._stackWidgetDict['\\Users\\johns\\Documents\\GitHub\\MapManagerCore\\data\\rr30a_s0u.mmap']
# logger.info(f'Saving file at path: {temp}')

logger.info(f'Saving file at path: { self._stackWidgetDict.keys()}')
for key in self._stackWidgetDict.keys():
# looping through every path in stackWidgetDict
# key = path of current stack
stackWidget = self._stackWidgetDict[key]
stackWidget.save(key)

def saveAsFile(self):
""" Save change to a new file
2 Scenarios:
1.) mmap file has not been created yet and we need to save a new one
2.) There is already a mmap file and user wants to create a new one
- in this scenario, after creating a new one, save would still save on the old one,
until user loads in that new file
"""
logger.info(f'Saving as file { self._stackWidgetDict.keys()}')

# scenario 1) Should be called when something is dragged and dropped, new file is loaded in
# this is handled in loadTifFile
# scenario 2)
if len(self._stackWidgetDict) > 0:
for key in self._stackWidgetDict.keys():
# looping through every path in stackWidgetDict
# key = path of current stack
stackWidget = self._stackWidgetDict[key]
stackWidget.fileSaveAs()
# stackWidget.saveAs(key)

def _undo_action(self):
self.getFrontWindow().emitUndoEvent()

Expand Down Expand Up @@ -357,6 +394,58 @@ def loadMapWidget(self, path):

return self._mapWidgetDict[path]

def loadTifFile(self, path : str):
"""Load a stack from tif from a path.
Only happens on first load/ drag and drop
Create stackwidget/ mmap from tif file
Parameters
----------
path : str
Full path to tif file
"""
from mapmanagercore import MapAnnotations, MultiImageLoader
from mapmanagercore.lazy_geo_pandas import LazyGeoFrame
from mapmanagercore.schemas import Segment, Spine

loader = MultiImageLoader()
# path = "C:\\Users\\johns\\Documents\\GitHub\\PyMapManager-Data\\one-timepoint\\rr30a_s0_ch1.tif"

try: # Check if path is a tif file
# TODO: detect channel, move channel to parameter
loader.read(path, channel=0)
logger.info("loading tif file!")
except Exception as e: # else return error message
logger.info(f"Exeception when reading tif file: {e}")
return
import pandas as pd
import geopandas
lineSegments = geopandas.GeoDataFrame()
points = geopandas.GeoDataFrame()


# Might no be necessary, example.ipynb works with empty geodataframes
# self._segments = LazyGeoFrame(
# Segment, data=lineSegments, store=self)
# self._points = LazyGeoFrame(Spine, data=points, store=self)

map = MapAnnotations(loader.build(),
lineSegments=lineSegments,
points=points)

# Save new mmap file in same directory as tif file
import os
pathParse = os.path.splitext(path)[0] # without extension
newMapPath = pathParse + ".mmap"
logger.info("Save new Map from tif file")
map.save(newMapPath)

self.loadStackWidget(newMapPath)
# map.points[:]
# need to save zarr file first. so that we can create a stack from it within stackwidget
# need to create stackwidget from new map
#only save when user clicks save as

def loadStackWidget(self, path : str):
"""Load a stack from a path.
Expand Down
18 changes: 15 additions & 3 deletions pymapmanager/interface2/runInterfaceJohnson.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,11 @@ def run():
# path = '../PyMapManager-Data/core-map/one-timepoint/oneTimepoint.mmap'
# path ='\\Users\\johns\\Documents\\GitHub\\MapManagerCore\\sandbox\\data\\rr30a_s0.mmap'
# path = 'C:\\Users\\johns\\Documents\\GitHub\\MapManagerCore\\data\\rr30a_s0u.mmap'
path = '\\Users\\johns\\Documents\\GitHub\\MapManagerCore\\data\\rr30a_s0u.mmap'

# path = '\\Users\\johns\\Documents\\GitHub\\MapManagerCore\\data\\rr30a_s0u.mmap'
path = '/Users/johns/Documents/GitHub/MapManagerCore/data/rr30a_s0u.mmap'
# path = '/Users/johns/Documents/GitHub/PyMapManager-Data/one-timepoint/rr30a_s0_ch1.mmap'
# import mapmanagercore
# path = mapmanagercore.getSingleTimepointMap()
sw2 = app.loadStackWidget(path)

df = sw2.getStack().getPointAnnotations().getDataFrame()
Expand All @@ -40,5 +43,14 @@ def run():

sys.exit(app.exec_())

def run2():
app = PyMapManagerApp()
# path = '/Users/johns/Documents/GitHub/PyMapManager-Data/one-timepoint/rr30a_s0_ch1.tif'
path = '/Users/johns/Documents/GitHub/PyMapManager-Data/one-timepoint/rr30a_s0_ch1.mmap'
# sw2 = app.loadTifFile(path)
sw2 = app.loadStackWidget(path)
sys.exit(app.exec_())

if __name__ == '__main__':
run()
run()
# run2()
Loading

0 comments on commit e430f00

Please sign in to comment.