diff --git a/.cache/v/cache/lastfailed b/.cache/v/cache/lastfailed old mode 100644 new mode 100755 diff --git a/.directory b/.directory old mode 100644 new mode 100755 diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 index 27ad398..3a7bd0c --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # Don't push data Benchmarking/ TestDataset/ +packages/ # Don't push older versions oldversions/ @@ -71,7 +72,7 @@ PyFRAP.wiki/ # Don't push .zip files *zip - +*.bak diff --git a/2to3_folder.py b/2to3_folder.py new file mode 100755 index 0000000..f905fd9 --- /dev/null +++ b/2to3_folder.py @@ -0,0 +1,15 @@ +import os +import glob +import sys + +files=glob.glob(sys.argv[1]+'*.py') + +for i,f in enumerate(files): + + print("%i/%i: Fixing %s"%(i,len(files),f)) + + cmd="2to3 -w %s"%f + os.system(cmd) + + + diff --git a/ChangeLog.txt b/ChangeLog.txt old mode 100644 new mode 100755 diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 diff --git a/MANIFEST.in b/MANIFEST.in old mode 100644 new mode 100755 diff --git a/PyFRAP.wiki_backup b/PyFRAP.wiki_backup new file mode 160000 index 0000000..0163cc5 --- /dev/null +++ b/PyFRAP.wiki_backup @@ -0,0 +1 @@ +Subproject commit 0163cc51783763b479c92cac3e75804ddd8f48e0 diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/_config.yml b/_config.yml old mode 100644 new mode 100755 diff --git a/build_app.py b/build_app.py new file mode 100755 index 0000000..c4a44eb --- /dev/null +++ b/build_app.py @@ -0,0 +1,22 @@ +import os +import sys +import platform + +print("This system is running", platform.system(), platform.release(), platform.architecture()[0]) +arch1=platform.architecture()[0] +arch2=platform.machine() + +if platform.system() in ["Darwin"]: + name="pyfrap_"+"OSX_"+platform.mac_ver()[0]+"_"+arch1 + os.system("pyinstaller -F -y -n "+ name +" -i logo/pyfdap_icon.icns --windowed pyfdap_app.py") +elif platform.system() in ["Linux"]: + name="pyfrap_"+"Linux_"+platform.release()+"_"+arch1 + #os.system("pyinstaller -F -y -n "+ name +" -i logo/pyfdap_icon.ico --windowed pyfdap_app.py") + os.system("pyinstaller -F -y -n "+ name +" --windowed "+sys.argv[1]) +elif platform.system() in ["Windows"]: + name="pyfdap_"+"Win_"+platform.release()+"_"+arch1 + if arch1=="64bit": + os.system("pyinstaller -F -y -i logo/pyfdap_icon.ico -n" + name +" pyfdap_app.py") + else: + os.system("pyinstaller -F -y -i logo/pyfdap_icon.ico -n" + name +" pyfdap_app_win32build.py") + diff --git a/docs/Makefile b/docs/Makefile old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_ROI/plotSimConcProfile.png b/docs/imgs/pyfrp_ROI/plotSimConcProfile.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_fit/fit.png b/docs/imgs/pyfrp_fit/fit.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/ball.eps b/docs/imgs/pyfrp_geometry/ball.eps old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/ball.png b/docs/imgs/pyfrp_geometry/ball.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/boundaryLayerField_geometry.png b/docs/imgs/pyfrp_geometry/boundaryLayerField_geometry.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/boundaryLayerField_mesh.png b/docs/imgs/pyfrp_geometry/boundaryLayerField_mesh.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/cone.eps b/docs/imgs/pyfrp_geometry/cone.eps old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/cone.png b/docs/imgs/pyfrp_geometry/cone.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/cylinder.eps b/docs/imgs/pyfrp_geometry/cylinder.eps old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/cylinder.png b/docs/imgs/pyfrp_geometry/cylinder.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/cylinderquad.eps b/docs/imgs/pyfrp_geometry/cylinderquad.eps old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/cylinderquad.png b/docs/imgs/pyfrp_geometry/cylinderquad.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/dome.eps b/docs/imgs/pyfrp_geometry/dome.eps old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/dome.png b/docs/imgs/pyfrp_geometry/dome.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/domequad.eps b/docs/imgs/pyfrp_geometry/domequad.eps old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_geometry/domequad.png b/docs/imgs/pyfrp_geometry/domequad.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/addBallByParameters.png b/docs/imgs/pyfrp_gmsh_geometry/addBallByParameters.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/addCircleByParameters.png b/docs/imgs/pyfrp_gmsh_geometry/addCircleByParameters.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/addCuboidByParameters.png b/docs/imgs/pyfrp_gmsh_geometry/addCuboidByParameters.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/addCylinderByParameters.png b/docs/imgs/pyfrp_gmsh_geometry/addCylinderByParameters.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/addPolygonByParameters.png b/docs/imgs/pyfrp_gmsh_geometry/addPolygonByParameters.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/addPrismByParameters.png b/docs/imgs/pyfrp_gmsh_geometry/addPrismByParameters.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/addRectangleByParameters.png b/docs/imgs/pyfrp_gmsh_geometry/addRectangleByParameters.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/addSquareByParameters.png b/docs/imgs/pyfrp_gmsh_geometry/addSquareByParameters.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/approxBySpline1.png b/docs/imgs/pyfrp_gmsh_geometry/approxBySpline1.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/approxBySpline2.png b/docs/imgs/pyfrp_gmsh_geometry/approxBySpline2.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/arc.png b/docs/imgs/pyfrp_gmsh_geometry/arc.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/arc.svg b/docs/imgs/pyfrp_gmsh_geometry/arc.svg old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/boundaryLayerField_geometry.png b/docs/imgs/pyfrp_gmsh_geometry/boundaryLayerField_geometry.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/boundaryLayerField_mesh.png b/docs/imgs/pyfrp_gmsh_geometry/boundaryLayerField_mesh.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/thresholdField.png b/docs/imgs/pyfrp_gmsh_geometry/thresholdField.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gmsh_geometry/thresholdField.svg b/docs/imgs/pyfrp_gmsh_geometry/thresholdField.svg old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gui_vtk/vtkSimVisualizer.png b/docs/imgs/pyfrp_gui_vtk/vtkSimVisualizer.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_gui_vtk/vtkSimVisualizerCutter.png b/docs/imgs/pyfrp_gui_vtk/vtkSimVisualizerCutter.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_idx_module/neighbours3D.png b/docs/imgs/pyfrp_idx_module/neighbours3D.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_img_module/genFakeIC.png b/docs/imgs/pyfrp_img_module/genFakeIC.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_img_module/genFakeSigmoidIC.png b/docs/imgs/pyfrp_img_module/genFakeSigmoidIC.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_img_module/plotRadialHist.png b/docs/imgs/pyfrp_img_module/plotRadialHist.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_img_module/plotRadialProfile.png b/docs/imgs/pyfrp_img_module/plotRadialProfile.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_mesh/density_plot.png b/docs/imgs/pyfrp_mesh/density_plot.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_mesh/plotCellCenters.png b/docs/imgs/pyfrp_mesh/plotCellCenters.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_plot_module/makeSubplot.png b/docs/imgs/pyfrp_plot_module/makeSubplot.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_sim_module/sigmoidFct.png b/docs/imgs/pyfrp_sim_module/sigmoidFct.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_simulation/ICcompare.png b/docs/imgs/pyfrp_simulation/ICcompare.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_simulation/ICstack.png b/docs/imgs/pyfrp_simulation/ICstack.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_simulation/showIC.png b/docs/imgs/pyfrp_simulation/showIC.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_simulation/showICimg.png b/docs/imgs/pyfrp_simulation/showICimg.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_simulation/showInterpolatedIC.png b/docs/imgs/pyfrp_simulation/showInterpolatedIC.png old mode 100644 new mode 100755 diff --git a/docs/imgs/pyfrp_simulation/showInterpolatedICimg.png b/docs/imgs/pyfrp_simulation/showInterpolatedICimg.png old mode 100644 new mode 100755 diff --git a/docs/make.bat b/docs/make.bat old mode 100644 new mode 100755 diff --git a/docs/source/conf.py b/docs/source/conf.py old mode 100644 new mode 100755 index 1cbfc5f..abdad2e --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -57,13 +57,13 @@ 'scipy','scipy.optimize','scipy.interpolate','scipy.ndimage','scipy.ndimage.interpolation', #Matplotlib (and all submodules) 'matplotlib', 'matplotlib.pyplot','matplotlib.axes','mpl_toolkits','mpl_toolkits.mplot3d','matplotlib.collections', - 'matplotlib.patches','matplotlib.tri','matplotlib.backends','matplotlib.backends.backend_qt4agg', - 'matplotlib.bakends.backend_qt4agg.FigureCanvasQTAgg','matplotlib.backends.backend_qt4agg.FigureCanvas', + 'matplotlib.patches','matplotlib.tri','matplotlib.backends','matplotlib.backends.backend_qt5agg', + 'matplotlib.bakends.backend_qt5agg.FigureCanvasQTAgg','matplotlib.backends.backend_qt5agg.FigureCanvas', 'matplotlib.figure','mpl_toolkits.mplot3d.art3d', #Skimage 'skimage','skimage.io','skimage.morphology','scipy.signal','skimage.measure','skimage.filters', #PyQT - 'PyQt4','PyQt4.QtGui','PyQt4.QtCore', + 'PyQt5','PyQt5.QtGui','PyQt5.QtCore', #MeshIO 'meshio', #VTK diff --git a/docs/source/index.rst b/docs/source/index.rst old mode 100644 new mode 100755 diff --git a/docs/source/modules.rst b/docs/source/modules.rst old mode 100644 new mode 100755 diff --git a/docs/source/pyfrp.gui.rst b/docs/source/pyfrp.gui.rst old mode 100644 new mode 100755 diff --git a/docs/source/pyfrp.modules.rst b/docs/source/pyfrp.modules.rst old mode 100644 new mode 100755 diff --git a/docs/source/pyfrp.rst b/docs/source/pyfrp.rst old mode 100644 new mode 100755 diff --git a/docs/source/pyfrp.subclasses.rst b/docs/source/pyfrp.subclasses.rst old mode 100644 new mode 100755 diff --git a/docs/source/setup.rst b/docs/source/setup.rst old mode 100644 new mode 100755 diff --git a/examples/geometryAndMeshing/attractorMesh.py b/examples/geometryAndMeshing/attractorMesh.py old mode 100644 new mode 100755 diff --git a/examples/geometryAndMeshing/bleachedBL.py b/examples/geometryAndMeshing/bleachedBL.py old mode 100644 new mode 100755 diff --git a/examples/geometryAndMeshing/createCircularGeometry.py b/examples/geometryAndMeshing/createCircularGeometry.py old mode 100644 new mode 100755 diff --git a/examples/geometryAndMeshing/createCylinderGeometry.py b/examples/geometryAndMeshing/createCylinderGeometry.py old mode 100644 new mode 100755 diff --git a/examples/geometryAndMeshing/mergedROIMesh.py b/examples/geometryAndMeshing/mergedROIMesh.py old mode 100644 new mode 100755 diff --git a/examples/geometryAndMeshing/sliceBL.py b/examples/geometryAndMeshing/sliceBL.py old mode 100644 new mode 100755 diff --git a/examples/geometryAndMeshing/test.eps b/examples/geometryAndMeshing/test.eps old mode 100644 new mode 100755 diff --git a/examples/scripting/demo.geo b/examples/scripting/demo.geo old mode 100644 new mode 100755 diff --git a/examples/scripting/simpleAnalysis.py b/examples/scripting/simpleAnalysis.py old mode 100644 new mode 100755 index 71ec56f..dc96105 --- a/examples/scripting/simpleAnalysis.py +++ b/examples/scripting/simpleAnalysis.py @@ -104,11 +104,11 @@ stopTime=time.time() # Print time it took -print "Analysis done in ", stopTime-starTime , " seconds." +print("Analysis done in ", stopTime-starTime , " seconds.") try: emb.save(sys.argv[2]) except IndexError: - print "Did not save embryo, no output given." + print("Did not save embryo, no output given.") -raw_input() +input() diff --git a/examples/visualization/visualizeMesh.py b/examples/visualization/visualizeMesh.py old mode 100644 new mode 100755 diff --git a/examples/visualization/visualizeSimulation.py b/examples/visualization/visualizeSimulation.py old mode 100644 new mode 100755 diff --git a/install_linux.sh b/install_linux.sh index 0ddb1af..b72bc96 100755 --- a/install_linux.sh +++ b/install_linux.sh @@ -4,26 +4,26 @@ sudo apt-get install -y git sudo apt-get install default-jdk sudo apt-get install default-jre -sudo apt-get install -y python-numpy -sudo apt-get install -y python-scipy -sudo apt-get install -y python-matplotlib -sudo apt-get install -y python-qt4 -sudo apt-get install -y python-skimage -sudo apt-get install -y python-vtk +sudo apt-get install -y python3-numpy +sudo apt-get install -y python3-scipy +sudo apt-get install -y python3-matplotlib +sudo apt-get install -y python3-pyqt5 +sudo apt-get install -y python3-skimage +sudo apt-get install -y python3-vtk # Install everything that is in pip -sudo pip install fipy -sudo pip install solidpython -sudo pip install numpy-stl -sudo pip install wget -sudo pip install python-bioformats +sudo pip3 install fipy +sudo pip3 install solidpython +sudo pip3 install numpy-stl +sudo pip3 install wget +sudo pip3 install python-bioformats # Install openscad sudo apt-get install openscad # Clone PyFRAP and install -cd PyFRAP-master -sudo python setup.py install +# cd PyFRAP-master +# sudo python setup.py install diff --git a/install_linux_new.sh b/install_linux_new.sh old mode 100644 new mode 100755 diff --git a/install_win.bat b/install_win.bat old mode 100644 new mode 100755 diff --git a/notebooks/.ipynb_checkpoints/Untitled-checkpoint.ipynb b/notebooks/.ipynb_checkpoints/Untitled-checkpoint.ipynb new file mode 100755 index 0000000..2fd6442 --- /dev/null +++ b/notebooks/.ipynb_checkpoints/Untitled-checkpoint.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/notebooks/.ipynb_checkpoints/analyse_embryo-checkpoint.ipynb b/notebooks/.ipynb_checkpoints/analyse_embryo-checkpoint.ipynb new file mode 100755 index 0000000..85395de --- /dev/null +++ b/notebooks/.ipynb_checkpoints/analyse_embryo-checkpoint.ipynb @@ -0,0 +1,66 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\u001b[33mWARNING (): \u001b[39mCannot import bioformats\n" + ] + }, + { + "ename": "ModuleNotFoundError", + "evalue": "No module named 'vtk'", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m~/anaconda3/lib/python3.7/site-packages/pyfrp/__init__.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 19\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 20\u001b[0m \u001b[0;31m#Basic PyFRAP modules\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 21\u001b[0;31m \u001b[0;32mfrom\u001b[0m \u001b[0;34m.\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mmodules\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 22\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[0;31m#PyFRAP classes\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m~/anaconda3/lib/python3.7/site-packages/pyfrp/modules/__init__.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 20\u001b[0m \u001b[0;31m#Basic PyFRAP modules\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 21\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;34m.\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp_term_module\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 22\u001b[0;31m \u001b[0;32mfrom\u001b[0m \u001b[0;34m.\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp_IO_module\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 23\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;34m.\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp_misc_module\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 24\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;34m.\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp_plot_module\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m~/anaconda3/lib/python3.7/site-packages/pyfrp/modules/pyfrp_IO_module.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 43\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 44\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mpyfrp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmodules\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp_misc_module\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 45\u001b[0;31m \u001b[0;32mfrom\u001b[0m \u001b[0mpyfrp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmodules\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp_gmsh_IO_module\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 46\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mpyfrp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmodules\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpyfrp_term_module\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 47\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m~/anaconda3/lib/python3.7/site-packages/pyfrp/modules/pyfrp_gmsh_IO_module.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 47\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 48\u001b[0m \u001b[0;31m#PyFRAP Modules\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 49\u001b[0;31m \u001b[0;32mfrom\u001b[0m \u001b[0;34m.\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp_gmsh_geometry\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 50\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;34m.\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp_misc_module\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 51\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;34m.\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp_gmsh_module\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m~/anaconda3/lib/python3.7/site-packages/pyfrp/modules/pyfrp_gmsh_geometry.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 64\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;34m.\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp_geometry_module\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 65\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;34m.\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp_IO_module\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 66\u001b[0;31m \u001b[0;32mfrom\u001b[0m \u001b[0;34m.\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpyfrp_vtk_module\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 67\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 68\u001b[0m \u001b[0;31m#Matplotlib\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m~/anaconda3/lib/python3.7/site-packages/pyfrp/modules/pyfrp_vtk_module.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 41\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 42\u001b[0m \u001b[0;31m#Plotting\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 43\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mvtk\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 44\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mmatplotlib\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 45\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'vtk'" + ] + } + ], + "source": [ + "import pyfrp" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.4" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/notebooks/Untitled.ipynb b/notebooks/Untitled.ipynb new file mode 100755 index 0000000..2fd6442 --- /dev/null +++ b/notebooks/Untitled.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/notebooks/analyse_embryo.ipynb b/notebooks/analyse_embryo.ipynb new file mode 100755 index 0000000..a7f547a --- /dev/null +++ b/notebooks/analyse_embryo.ipynb @@ -0,0 +1,58 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import sys\n", + "\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "import pyfrp" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "in_dir='../TestDataset/embryo/sqtGFP_20170609_01/recover/'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "nation" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/pyfdap_Linux_5.0.0-29-generic_64bit.spec b/pyfdap_Linux_5.0.0-29-generic_64bit.spec new file mode 100755 index 0000000..230ffa1 --- /dev/null +++ b/pyfdap_Linux_5.0.0-29-generic_64bit.spec @@ -0,0 +1,33 @@ +# -*- mode: python ; coding: utf-8 -*- + +block_cipher = None + + +a = Analysis(['pyfrp/PyFRAP.py'], + pathex=['/home/alexander/Dropbox/Alex/Documents/Research/PyFRAP'], + binaries=[], + datas=[], + hiddenimports=[], + hookspath=[], + runtime_hooks=[], + excludes=[], + win_no_prefer_redirects=False, + win_private_assemblies=False, + cipher=block_cipher, + noarchive=False) +pyz = PYZ(a.pure, a.zipped_data, + cipher=block_cipher) +exe = EXE(pyz, + a.scripts, + a.binaries, + a.zipfiles, + a.datas, + [], + name='pyfdap_Linux_5.0.0-29-generic_64bit', + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=True, + upx_exclude=[], + runtime_tmpdir=None, + console=False ) diff --git a/pyfrap.yaml b/pyfrap.yaml new file mode 100755 index 0000000..01458e3 --- /dev/null +++ b/pyfrap.yaml @@ -0,0 +1,351 @@ +name: pyfrap +channels: + - conda-forge + - defaults +dependencies: + - _ipyw_jlab_nb_ext_conf=0.1.0=py37_0 + - _libgcc_mutex=0.1=main + - alabaster=0.7.12=py37_0 + - anaconda=2019.10=py37_0 + - anaconda-client=1.7.2=py37_0 + - anaconda-navigator=1.9.7=py37_0 + - anaconda-project=0.8.3=py_0 + - anndata=0.7.1=py37_0 + - asn1crypto=1.0.1=py37_0 + - astroid=2.3.1=py37_0 + - astropy=3.2.2=py37h7b6447c_0 + - atomicwrites=1.3.0=py37_1 + - attrs=19.2.0=py_0 + - babel=2.7.0=py_0 + - backcall=0.1.0=py37_0 + - backports=1.0=py_2 + - backports.functools_lru_cache=1.5=py_2 + - backports.os=0.1.1=py37_0 + - backports.shutil_get_terminal_size=1.0.0=py37_2 + - backports.tempfile=1.0=py_1 + - backports.weakref=1.0.post1=py_1 + - basemap=1.2.1=py37hd1be537_2 + - beautifulsoup4=4.8.0=py37_0 + - bitarray=1.0.1=py37h7b6447c_0 + - bkcharts=0.2=py37_0 + - blas=1.0=mkl + - bleach=3.1.0=py37_0 + - blosc=1.16.3=hd408876_0 + - boto=2.49.0=py37_0 + - bottleneck=1.2.1=py37h035aef0_1 + - bzip2=1.0.8=h7b6447c_0 + - ca-certificates=2019.8.28=0 + - cairo=1.14.12=h8948797_3 + - certifi=2019.9.11=py37_0 + - cffi=1.12.3=py37h2e261b9_0 + - chardet=3.0.4=py37_1003 + - click=7.0=py37_0 + - cloudpickle=1.2.2=py_0 + - clyent=1.2.2=py37_1 + - colorama=0.4.1=py37_0 + - conda=4.8.2=py37_0 + - conda-build=3.18.9=py37_3 + - conda-env=2.6.0=1 + - conda-package-handling=1.6.0=py37h7b6447c_0 + - conda-verify=3.4.2=py_1 + - contextlib2=0.6.0=py_0 + - cryptography=2.7=py37h1ba5d50_0 + - curl=7.65.3=hbc83047_0 + - cycler=0.10.0=py37_0 + - cython=0.29.13=py37he6710b0_0 + - cytoolz=0.10.0=py37h7b6447c_0 + - dask=2.5.2=py_0 + - dask-core=2.5.2=py_0 + - dbus=1.13.6=h746ee38_0 + - decorator=4.4.0=py37_1 + - defusedxml=0.6.0=py_0 + - distributed=2.5.2=py_0 + - docutils=0.15.2=py37_0 + - entrypoints=0.3=py37_0 + - et_xmlfile=1.0.1=py37_0 + - expat=2.2.6=he6710b0_0 + - fastcache=1.1.0=py37h7b6447c_0 + - filelock=3.0.12=py_0 + - flask=1.1.1=py_0 + - fontconfig=2.13.0=h9420a91_0 + - freetype=2.9.1=h8a8886c_1 + - fribidi=1.0.5=h7b6447c_0 + - fsspec=0.5.2=py_0 + - future=0.17.1=py37_0 + - geos=3.8.0=he1b5a44_0 + - get_terminal_size=1.0.0=haa9412d_0 + - gevent=1.4.0=py37h7b6447c_0 + - glib=2.56.2=hd408876_0 + - glob2=0.7=py_0 + - gmp=6.1.2=h6c8ec71_1 + - gmpy2=2.0.8=py37h10f8cd9_2 + - graphite2=1.3.13=h23475e2_0 + - greenlet=0.4.15=py37h7b6447c_0 + - gst-plugins-base=1.14.0=hbbd80ab_1 + - gstreamer=1.14.0=hb453b48_1 + - h5py=2.9.0=py37h7918eee_0 + - harfbuzz=1.8.8=hffaf4a1_0 + - hdf5=1.10.4=hb1b8bf9_0 + - heapdict=1.0.1=py_0 + - html5lib=1.0.1=py37_0 + - icu=58.2=h9c2bf20_1 + - idna=2.8=py37_0 + - imageio=2.6.0=py37_0 + - imagesize=1.1.0=py37_0 + - importlib_metadata=0.23=py37_0 + - intel-openmp=2019.4=243 + - ipykernel=5.1.2=py37h39e3cac_0 + - ipython=7.8.0=py37h39e3cac_0 + - ipython_genutils=0.2.0=py37_0 + - ipywidgets=7.5.1=py_0 + - isort=4.3.21=py37_0 + - itsdangerous=1.1.0=py37_0 + - jbig=2.1=hdba287a_0 + - jdcal=1.4.1=py_0 + - jedi=0.15.1=py37_0 + - jeepney=0.4.1=py_0 + - jinja2=2.10.3=py_0 + - joblib=0.13.2=py37_0 + - jpeg=9b=h024ee3a_2 + - json5=0.8.5=py_0 + - jsonschema=3.0.2=py37_0 + - jupyter=1.0.0=py37_7 + - jupyter_client=5.3.3=py37_1 + - jupyter_console=6.0.0=py37_0 + - jupyter_core=4.5.0=py_0 + - jupyterlab=1.1.4=pyhf63ae98_0 + - jupyterlab_server=1.0.6=py_0 + - keyring=18.0.0=py37_0 + - kiwisolver=1.1.0=py37he6710b0_0 + - krb5=1.16.1=h173b8e3_7 + - lazy-object-proxy=1.4.2=py37h7b6447c_0 + - libarchive=3.3.3=h5d8350f_5 + - libcurl=7.65.3=h20c2e04_0 + - libedit=3.1.20181209=hc058e9b_0 + - libffi=3.2.1=hd88cf55_4 + - libgcc-ng=9.1.0=hdf63c60_0 + - libgfortran-ng=7.3.0=hdf63c60_0 + - liblief=0.9.0=h7725739_2 + - libpng=1.6.37=hbc83047_0 + - libsodium=1.0.16=h1bed415_0 + - libssh2=1.8.2=h1ba5d50_0 + - libstdcxx-ng=9.1.0=hdf63c60_0 + - libtiff=4.0.10=h2733197_2 + - libtool=2.4.6=h7b6447c_5 + - libuuid=1.0.3=h1bed415_2 + - libxcb=1.13=h1bed415_1 + - libxml2=2.9.9=hea5a465_1 + - libxslt=1.1.33=h7d1a2b0_0 + - llvmlite=0.29.0=py37hd408876_0 + - locket=0.2.0=py37_1 + - lxml=4.4.1=py37hefd8a0e_0 + - lz4-c=1.8.1.2=h14c3975_0 + - lzo=2.10=h49e0be7_2 + - markupsafe=1.1.1=py37h7b6447c_0 + - matplotlib=3.1.1=py37h5429711_0 + - matplotlib-base=3.1.2=py37hef1b27d_1 + - mccabe=0.6.1=py37_1 + - mistune=0.8.4=py37h7b6447c_0 + - mkl=2019.4=243 + - mkl-service=2.3.0=py37he904b0f_0 + - mkl_fft=1.0.14=py37ha843d7b_0 + - mkl_random=1.1.0=py37hd6b4f25_0 + - mock=3.0.5=py37_0 + - more-itertools=7.2.0=py37_0 + - mpc=1.1.0=h10f8cd9_1 + - mpfr=4.0.1=hdf1c602_3 + - mpmath=1.1.0=py37_0 + - msgpack-python=0.6.1=py37hfd86e86_1 + - multipledispatch=0.6.0=py37_0 + - natsort=7.0.1=py_0 + - navigator-updater=0.2.1=py37_0 + - nbconvert=5.6.0=py37_1 + - nbformat=4.4.0=py37_0 + - ncurses=6.1=he6710b0_1 + - networkx=2.3=py_0 + - nltk=3.4.5=py37_0 + - nose=1.3.7=py37_2 + - notebook=6.0.1=py37_0 + - numba=0.45.1=py37h962f231_0 + - numexpr=2.7.0=py37h9e4a6bb_0 + - numpy=1.17.2=py37haad9e8e_0 + - numpy-base=1.17.2=py37hde5b4d6_0 + - numpydoc=0.9.1=py_0 + - olefile=0.46=py37_0 + - openpyxl=3.0.0=py_0 + - openssl=1.1.1d=h7b6447c_2 + - packaging=19.2=py_0 + - pandas=0.25.1=py37he6710b0_0 + - pandoc=2.2.3.2=0 + - pandocfilters=1.4.2=py37_1 + - pango=1.42.4=h049681c_0 + - parso=0.5.1=py_0 + - partd=1.0.0=py_0 + - patchelf=0.9=he6710b0_3 + - path.py=12.0.1=py_0 + - pathlib2=2.3.5=py37_0 + - patsy=0.5.1=py37_0 + - pcre=8.43=he6710b0_0 + - pep8=1.7.1=py37_0 + - pexpect=4.7.0=py37_0 + - pickleshare=0.7.5=py37_0 + - pillow=6.2.0=py37h34e0f95_0 + - pip=19.2.3=py37_0 + - pixman=0.38.0=h7b6447c_0 + - pkginfo=1.5.0.1=py37_0 + - pluggy=0.13.0=py37_0 + - ply=3.11=py37_0 + - proj4=5.2.0=he1b5a44_1006 + - prometheus_client=0.7.1=py_0 + - prompt_toolkit=2.0.10=py_0 + - psutil=5.6.3=py37h7b6447c_0 + - ptyprocess=0.6.0=py37_0 + - py=1.8.0=py37_0 + - py-lief=0.9.0=py37h7725739_2 + - pycodestyle=2.5.0=py37_0 + - pycosat=0.6.3=py37h14c3975_0 + - pycparser=2.19=py37_0 + - pycrypto=2.6.1=py37h14c3975_9 + - pycurl=7.43.0.3=py37h1ba5d50_0 + - pyflakes=2.1.1=py37_0 + - pygments=2.4.2=py_0 + - pylint=2.4.2=py37_0 + - pyodbc=4.0.27=py37he6710b0_0 + - pyopenssl=19.0.0=py37_0 + - pyparsing=2.4.2=py_0 + - pyproj=1.9.6=py37h516909a_1002 + - pyqt=5.9.2=py37h05f1152_2 + - pyrsistent=0.15.4=py37h7b6447c_0 + - pyshp=2.1.0=py_0 + - pysocks=1.7.1=py37_0 + - pytables=3.5.2=py37h71ec239_1 + - pytest=5.2.1=py37_0 + - pytest-arraydiff=0.3=py37h39e3cac_0 + - pytest-astropy=0.5.0=py37_0 + - pytest-doctestplus=0.4.0=py_0 + - pytest-openfiles=0.4.0=py_0 + - pytest-remotedata=0.3.2=py37_0 + - python=3.7.4=h265db76_1 + - python-dateutil=2.8.0=py37_0 + - python-libarchive-c=2.8=py37_13 + - pytz=2019.3=py_0 + - pywavelets=1.0.3=py37hdd07704_1 + - pyyaml=5.1.2=py37h7b6447c_0 + - pyzmq=18.1.0=py37he6710b0_0 + - qt=5.9.7=h5867ecd_1 + - qtawesome=0.6.0=py_0 + - qtconsole=4.5.5=py_0 + - qtpy=1.9.0=py_0 + - readline=7.0=h7b6447c_5 + - requests=2.22.0=py37_0 + - ripgrep=0.10.0=hc07d326_0 + - rope=0.14.0=py_0 + - ruamel_yaml=0.15.46=py37h14c3975_0 + - scikit-image=0.15.0=py37he6710b0_0 + - scikit-learn=0.21.3=py37hd81dba3_0 + - scipy=1.3.1=py37h7c811a0_0 + - seaborn=0.9.0=py37_0 + - secretstorage=3.1.1=py37_0 + - send2trash=1.5.0=py37_0 + - setuptools=41.4.0=py37_0 + - simplegeneric=0.8.1=py37_2 + - singledispatch=3.4.0.3=py37_0 + - sip=4.19.8=py37hf484d3e_0 + - six=1.12.0=py37_0 + - snappy=1.1.7=hbae5bb6_3 + - snowballstemmer=2.0.0=py_0 + - sortedcollections=1.1.2=py37_0 + - sortedcontainers=2.1.0=py37_0 + - soupsieve=1.9.3=py37_0 + - sphinx=2.2.0=py_0 + - sphinxcontrib=1.0=py37_1 + - sphinxcontrib-applehelp=1.0.1=py_0 + - sphinxcontrib-devhelp=1.0.1=py_0 + - sphinxcontrib-htmlhelp=1.0.2=py_0 + - sphinxcontrib-jsmath=1.0.1=py_0 + - sphinxcontrib-qthelp=1.0.2=py_0 + - sphinxcontrib-serializinghtml=1.1.3=py_0 + - sphinxcontrib-websupport=1.1.2=py_0 + - spyder=3.3.6=py37_0 + - spyder-kernels=0.5.2=py37_0 + - sqlalchemy=1.3.9=py37h7b6447c_0 + - sqlite=3.30.0=h7b6447c_0 + - statsmodels=0.10.1=py37hdd07704_0 + - sympy=1.4=py37_0 + - tbb=2019.4=hfd86e86_0 + - tblib=1.4.0=py_0 + - terminado=0.8.2=py37_0 + - testpath=0.4.2=py37_0 + - tk=8.6.8=hbc83047_0 + - toolz=0.10.0=py_0 + - tornado=6.0.3=py37h7b6447c_0 + - tqdm=4.36.1=py_0 + - traitlets=4.3.3=py37_0 + - unicodecsv=0.14.1=py37_0 + - unixodbc=2.3.7=h14c3975_0 + - urllib3=1.24.2=py37_0 + - wcwidth=0.1.7=py37_0 + - webencodings=0.5.1=py37_1 + - werkzeug=0.16.0=py_0 + - wheel=0.33.6=py37_0 + - widgetsnbextension=3.5.1=py37_0 + - wrapt=1.11.2=py37h7b6447c_0 + - wurlitzer=1.0.3=py37_0 + - xlrd=1.2.0=py37_0 + - xlsxwriter=1.2.1=py_0 + - xlwt=1.3.0=py37_0 + - xz=5.2.4=h14c3975_4 + - yaml=0.1.7=had09818_2 + - zeromq=4.3.1=he6710b0_3 + - zict=1.0.0=py_0 + - zipp=0.6.0=py_0 + - zlib=1.2.11=h7b6447c_3 + - zstd=1.3.7=h0b5b093_0 + - pip: + - async-generator==1.10 + - bokeh==1.4.0 + - bqplot==0.12.3 + - cachetools==4.0.0 + - colorcet==2.0.2 + - complexheatmap==0.1 + - datetime==4.3 + - geojson==2.5.0 + - google-api-core==1.16.0 + - google-api-python-client==1.8.0 + - google-auth==1.11.3 + - google-auth-httplib2==0.0.3 + - googleapis-common-protos==1.51.0 + - holoviews==1.12.7 + - httplib2==0.17.0 + - hvplot==0.5.2 + - ipympl==0.5.0 + - jupyter-contrib-core==0.3.3 + - jupyter-contrib-nbextensions==0.5.1 + - jupyter-highlight-selected-word==0.2.0 + - jupyter-latex-envs==1.4.6 + - jupyter-nbextensions-configurator==0.4.1 + - jupyter-server==0.1.1 + - jupyterlab-pygments==0.1.0 + - markdown==3.2.1 + - mplleaflet==0.0.5 + - oauth2client==4.1.3 + - osmpythontools==0.2.6 + - panel==0.8.0 + - param==1.9.3 + - protobuf==3.11.3 + - pyasn1==0.4.8 + - pyasn1-modules==0.2.8 + - pyct==0.4.6 + - pydrive==1.3.1 + - pyviz-comms==0.7.3 + - rsa==4.0 + - traittypes==0.2.1 + - ujson==1.35 + - umap-learn==0.3.10 + - uritemplate==3.0.1 + - voila==0.1.20 + - voila-gridstack==0.0.8 + - xarray==0.15.0 + - zope-interface==4.7.1 +prefix: /home/alexander/anaconda3 + diff --git a/pyfrap_clean.yaml b/pyfrap_clean.yaml new file mode 100755 index 0000000..bdca05e --- /dev/null +++ b/pyfrap_clean.yaml @@ -0,0 +1,349 @@ +channels: + - conda-forge + - defaults +dependencies: + - _ipyw_jlab_nb_ext_conf=0.1.0=py37_0 + - _libgcc_mutex=0.1=main + - alabaster=0.7.12=py37_0 + - anaconda=2019.10=py37_0 + - anaconda-client=1.7.2=py37_0 + - anaconda-navigator=1.9.7=py37_0 + - anaconda-project=0.8.3=py_0 + - anndata=0.7.1=py37_0 + - asn1crypto=1.0.1=py37_0 + - astroid=2.3.1=py37_0 + - astropy=3.2.2=py37h7b6447c_0 + - atomicwrites=1.3.0=py37_1 + - attrs=19.2.0=py_0 + - babel=2.7.0=py_0 + - backcall=0.1.0=py37_0 + - backports=1.0=py_2 + - backports.functools_lru_cache=1.5=py_2 + - backports.os=0.1.1=py37_0 + - backports.shutil_get_terminal_size=1.0.0=py37_2 + - backports.tempfile=1.0=py_1 + - backports.weakref=1.0.post1=py_1 + - basemap=1.2.1=py37hd1be537_2 + - beautifulsoup4=4.8.0=py37_0 + - bitarray=1.0.1=py37h7b6447c_0 + - bkcharts=0.2=py37_0 + - blas=1.0=mkl + - bleach=3.1.0=py37_0 + - blosc=1.16.3=hd408876_0 + - boto=2.49.0=py37_0 + - bottleneck=1.2.1=py37h035aef0_1 + - bzip2=1.0.8=h7b6447c_0 + - ca-certificates=2019.8.28=0 + - cairo=1.14.12=h8948797_3 + - certifi=2019.9.11=py37_0 + - cffi=1.12.3=py37h2e261b9_0 + - chardet=3.0.4=py37_1003 + - click=7.0=py37_0 + - cloudpickle=1.2.2=py_0 + - clyent=1.2.2=py37_1 + - colorama=0.4.1=py37_0 + - conda=4.8.2=py37_0 + - conda-build=3.18.9=py37_3 + - conda-env=2.6.0=1 + - conda-package-handling=1.6.0=py37h7b6447c_0 + - conda-verify=3.4.2=py_1 + - contextlib2=0.6.0=py_0 + - cryptography=2.7=py37h1ba5d50_0 + - curl=7.65.3=hbc83047_0 + - cycler=0.10.0=py37_0 + - cython=0.29.13=py37he6710b0_0 + - cytoolz=0.10.0=py37h7b6447c_0 + - dask=2.5.2=py_0 + - dask-core=2.5.2=py_0 + - dbus=1.13.6=h746ee38_0 + - decorator=4.4.0=py37_1 + - defusedxml=0.6.0=py_0 + - distributed=2.5.2=py_0 + - docutils=0.15.2=py37_0 + - entrypoints=0.3=py37_0 + - et_xmlfile=1.0.1=py37_0 + - expat=2.2.6=he6710b0_0 + - fastcache=1.1.0=py37h7b6447c_0 + - filelock=3.0.12=py_0 + - flask=1.1.1=py_0 + - fontconfig=2.13.0=h9420a91_0 + - freetype=2.9.1=h8a8886c_1 + - fribidi=1.0.5=h7b6447c_0 + - fsspec=0.5.2=py_0 + - future=0.17.1=py37_0 + - geos=3.8.0=he1b5a44_0 + - get_terminal_size=1.0.0=haa9412d_0 + - gevent=1.4.0=py37h7b6447c_0 + - glib=2.56.2=hd408876_0 + - glob2=0.7=py_0 + - gmp=6.1.2=h6c8ec71_1 + - gmpy2=2.0.8=py37h10f8cd9_2 + - graphite2=1.3.13=h23475e2_0 + - greenlet=0.4.15=py37h7b6447c_0 + - gst-plugins-base=1.14.0=hbbd80ab_1 + - gstreamer=1.14.0=hb453b48_1 + - h5py=2.9.0=py37h7918eee_0 + - harfbuzz=1.8.8=hffaf4a1_0 + - hdf5=1.10.4=hb1b8bf9_0 + - heapdict=1.0.1=py_0 + - html5lib=1.0.1=py37_0 + - icu=58.2=h9c2bf20_1 + - idna=2.8=py37_0 + - imageio=2.6.0=py37_0 + - imagesize=1.1.0=py37_0 + - importlib_metadata=0.23=py37_0 + - intel-openmp=2019.4=243 + - ipykernel=5.1.2=py37h39e3cac_0 + - ipython=7.8.0=py37h39e3cac_0 + - ipython_genutils=0.2.0=py37_0 + - ipywidgets=7.5.1=py_0 + - isort=4.3.21=py37_0 + - itsdangerous=1.1.0=py37_0 + - jbig=2.1=hdba287a_0 + - jdcal=1.4.1=py_0 + - jedi=0.15.1=py37_0 + - jeepney=0.4.1=py_0 + - jinja2=2.10.3=py_0 + - joblib=0.13.2=py37_0 + - jpeg=9b=h024ee3a_2 + - json5=0.8.5=py_0 + - jsonschema=3.0.2=py37_0 + - jupyter=1.0.0=py37_7 + - jupyter_client=5.3.3=py37_1 + - jupyter_console=6.0.0=py37_0 + - jupyter_core=4.5.0=py_0 + - jupyterlab=1.1.4=pyhf63ae98_0 + - jupyterlab_server=1.0.6=py_0 + - keyring=18.0.0=py37_0 + - kiwisolver=1.1.0=py37he6710b0_0 + - krb5=1.16.1=h173b8e3_7 + - lazy-object-proxy=1.4.2=py37h7b6447c_0 + - libarchive=3.3.3=h5d8350f_5 + - libcurl=7.65.3=h20c2e04_0 + - libedit=3.1.20181209=hc058e9b_0 + - libffi=3.2.1=hd88cf55_4 + - libgcc-ng=9.1.0=hdf63c60_0 + - libgfortran-ng=7.3.0=hdf63c60_0 + - liblief=0.9.0=h7725739_2 + - libpng=1.6.37=hbc83047_0 + - libsodium=1.0.16=h1bed415_0 + - libssh2=1.8.2=h1ba5d50_0 + - libstdcxx-ng=9.1.0=hdf63c60_0 + - libtiff=4.0.10=h2733197_2 + - libtool=2.4.6=h7b6447c_5 + - libuuid=1.0.3=h1bed415_2 + - libxcb=1.13=h1bed415_1 + - libxml2=2.9.9=hea5a465_1 + - libxslt=1.1.33=h7d1a2b0_0 + - llvmlite=0.29.0=py37hd408876_0 + - locket=0.2.0=py37_1 + - lxml=4.4.1=py37hefd8a0e_0 + - lz4-c=1.8.1.2=h14c3975_0 + - lzo=2.10=h49e0be7_2 + - markupsafe=1.1.1=py37h7b6447c_0 + - matplotlib=3.1.1=py37h5429711_0 + - matplotlib-base=3.1.2=py37hef1b27d_1 + - mccabe=0.6.1=py37_1 + - mistune=0.8.4=py37h7b6447c_0 + - mkl=2019.4=243 + - mkl-service=2.3.0=py37he904b0f_0 + - mkl_fft=1.0.14=py37ha843d7b_0 + - mkl_random=1.1.0=py37hd6b4f25_0 + - mock=3.0.5=py37_0 + - more-itertools=7.2.0=py37_0 + - mpc=1.1.0=h10f8cd9_1 + - mpfr=4.0.1=hdf1c602_3 + - mpmath=1.1.0=py37_0 + - msgpack-python=0.6.1=py37hfd86e86_1 + - multipledispatch=0.6.0=py37_0 + - natsort=7.0.1=py_0 + - navigator-updater=0.2.1=py37_0 + - nbconvert=5.6.0=py37_1 + - nbformat=4.4.0=py37_0 + - ncurses=6.1=he6710b0_1 + - networkx=2.3=py_0 + - nltk=3.4.5=py37_0 + - nose=1.3.7=py37_2 + - notebook=6.0.1=py37_0 + - numba=0.45.1=py37h962f231_0 + - numexpr=2.7.0=py37h9e4a6bb_0 + - numpy=1.17.2=py37haad9e8e_0 + - numpy-base=1.17.2=py37hde5b4d6_0 + - numpydoc=0.9.1=py_0 + - olefile=0.46=py37_0 + - openpyxl=3.0.0=py_0 + - openssl=1.1.1d=h7b6447c_2 + - packaging=19.2=py_0 + - pandas=0.25.1=py37he6710b0_0 + - pandoc=2.2.3.2=0 + - pandocfilters=1.4.2=py37_1 + - pango=1.42.4=h049681c_0 + - parso=0.5.1=py_0 + - partd=1.0.0=py_0 + - patchelf=0.9=he6710b0_3 + - path.py=12.0.1=py_0 + - pathlib2=2.3.5=py37_0 + - patsy=0.5.1=py37_0 + - pcre=8.43=he6710b0_0 + - pep8=1.7.1=py37_0 + - pexpect=4.7.0=py37_0 + - pickleshare=0.7.5=py37_0 + - pillow=6.2.0=py37h34e0f95_0 + - pip=19.2.3=py37_0 + - pixman=0.38.0=h7b6447c_0 + - pkginfo=1.5.0.1=py37_0 + - pluggy=0.13.0=py37_0 + - ply=3.11=py37_0 + - proj4=5.2.0=he1b5a44_1006 + - prometheus_client=0.7.1=py_0 + - prompt_toolkit=2.0.10=py_0 + - psutil=5.6.3=py37h7b6447c_0 + - ptyprocess=0.6.0=py37_0 + - py=1.8.0=py37_0 + - py-lief=0.9.0=py37h7725739_2 + - pycodestyle=2.5.0=py37_0 + - pycosat=0.6.3=py37h14c3975_0 + - pycparser=2.19=py37_0 + - pycrypto=2.6.1=py37h14c3975_9 + - pycurl=7.43.0.3=py37h1ba5d50_0 + - pyflakes=2.1.1=py37_0 + - pygments=2.4.2=py_0 + - pylint=2.4.2=py37_0 + - pyodbc=4.0.27=py37he6710b0_0 + - pyopenssl=19.0.0=py37_0 + - pyparsing=2.4.2=py_0 + - pyproj=1.9.6=py37h516909a_1002 + - pyqt=5.9.2=py37h05f1152_2 + - pyrsistent=0.15.4=py37h7b6447c_0 + - pyshp=2.1.0=py_0 + - pysocks=1.7.1=py37_0 + - pytables=3.5.2=py37h71ec239_1 + - pytest=5.2.1=py37_0 + - pytest-arraydiff=0.3=py37h39e3cac_0 + - pytest-astropy=0.5.0=py37_0 + - pytest-doctestplus=0.4.0=py_0 + - pytest-openfiles=0.4.0=py_0 + - pytest-remotedata=0.3.2=py37_0 + - python=3.7.4=h265db76_1 + - python-dateutil=2.8.0=py37_0 + - python-libarchive-c=2.8=py37_13 + - pytz=2019.3=py_0 + - pywavelets=1.0.3=py37hdd07704_1 + - pyyaml=5.1.2=py37h7b6447c_0 + - pyzmq=18.1.0=py37he6710b0_0 + - qt=5.9.7=h5867ecd_1 + - qtawesome=0.6.0=py_0 + - qtconsole=4.5.5=py_0 + - qtpy=1.9.0=py_0 + - readline=7.0=h7b6447c_5 + - requests=2.22.0=py37_0 + - ripgrep=0.10.0=hc07d326_0 + - rope=0.14.0=py_0 + - ruamel_yaml=0.15.46=py37h14c3975_0 + - scikit-image=0.15.0=py37he6710b0_0 + - scikit-learn=0.21.3=py37hd81dba3_0 + - scipy=1.3.1=py37h7c811a0_0 + - seaborn=0.9.0=py37_0 + - secretstorage=3.1.1=py37_0 + - send2trash=1.5.0=py37_0 + - setuptools=41.4.0=py37_0 + - simplegeneric=0.8.1=py37_2 + - singledispatch=3.4.0.3=py37_0 + - sip=4.19.8=py37hf484d3e_0 + - six=1.12.0=py37_0 + - snappy=1.1.7=hbae5bb6_3 + - snowballstemmer=2.0.0=py_0 + - sortedcollections=1.1.2=py37_0 + - sortedcontainers=2.1.0=py37_0 + - soupsieve=1.9.3=py37_0 + - sphinx=2.2.0=py_0 + - sphinxcontrib=1.0=py37_1 + - sphinxcontrib-applehelp=1.0.1=py_0 + - sphinxcontrib-devhelp=1.0.1=py_0 + - sphinxcontrib-htmlhelp=1.0.2=py_0 + - sphinxcontrib-jsmath=1.0.1=py_0 + - sphinxcontrib-qthelp=1.0.2=py_0 + - sphinxcontrib-serializinghtml=1.1.3=py_0 + - sphinxcontrib-websupport=1.1.2=py_0 + - spyder=3.3.6=py37_0 + - spyder-kernels=0.5.2=py37_0 + - sqlalchemy=1.3.9=py37h7b6447c_0 + - sqlite=3.30.0=h7b6447c_0 + - statsmodels=0.10.1=py37hdd07704_0 + - sympy=1.4=py37_0 + - tbb=2019.4=hfd86e86_0 + - tblib=1.4.0=py_0 + - terminado=0.8.2=py37_0 + - testpath=0.4.2=py37_0 + - tk=8.6.8=hbc83047_0 + - toolz=0.10.0=py_0 + - tornado=6.0.3=py37h7b6447c_0 + - tqdm=4.36.1=py_0 + - traitlets=4.3.3=py37_0 + - unicodecsv=0.14.1=py37_0 + - unixodbc=2.3.7=h14c3975_0 + - urllib3=1.24.2=py37_0 + - wcwidth=0.1.7=py37_0 + - webencodings=0.5.1=py37_1 + - werkzeug=0.16.0=py_0 + - wheel=0.33.6=py37_0 + - widgetsnbextension=3.5.1=py37_0 + - wrapt=1.11.2=py37h7b6447c_0 + - wurlitzer=1.0.3=py37_0 + - xlrd=1.2.0=py37_0 + - xlsxwriter=1.2.1=py_0 + - xlwt=1.3.0=py37_0 + - xz=5.2.4=h14c3975_4 + - yaml=0.1.7=had09818_2 + - zeromq=4.3.1=he6710b0_3 + - zict=1.0.0=py_0 + - zipp=0.6.0=py_0 + - zlib=1.2.11=h7b6447c_3 + - zstd=1.3.7=h0b5b093_0 + - pip: + - async-generator==1.10 + - bokeh==1.4.0 + - bqplot==0.12.3 + - cachetools==4.0.0 + - colorcet==2.0.2 + - datetime==4.3 + - geojson==2.5.0 + - google-api-core==1.16.0 + - google-api-python-client==1.8.0 + - google-auth==1.11.3 + - google-auth-httplib2==0.0.3 + - googleapis-common-protos==1.51.0 + - holoviews==1.12.7 + - httplib2==0.17.0 + - hvplot==0.5.2 + - ipympl==0.5.0 + - jupyter-contrib-core==0.3.3 + - jupyter-contrib-nbextensions==0.5.1 + - jupyter-highlight-selected-word==0.2.0 + - jupyter-latex-envs==1.4.6 + - jupyter-nbextensions-configurator==0.4.1 + - jupyter-server==0.1.1 + - jupyterlab-pygments==0.1.0 + - markdown==3.2.1 + - mplleaflet==0.0.5 + - oauth2client==4.1.3 + - osmpythontools==0.2.6 + - panel==0.8.0 + - param==1.9.3 + - protobuf==3.11.3 + - pyasn1==0.4.8 + - pyasn1-modules==0.2.8 + - pyct==0.4.6 + - pydrive==1.3.1 + - pyviz-comms==0.7.3 + - rsa==4.0 + - traittypes==0.2.1 + - ujson==1.35 + - umap-learn==0.3.10 + - uritemplate==3.0.1 + - voila==0.1.20 + - voila-gridstack==0.0.8 + - xarray==0.15.0 + - zope-interface==4.7.1 +prefix: /home/alexander/anaconda3 + diff --git a/pyfrp/PyFRAP.py b/pyfrp/PyFRAP.py old mode 100644 new mode 100755 index 6e78a58..8c22a47 --- a/pyfrp/PyFRAP.py +++ b/pyfrp/PyFRAP.py @@ -6,7 +6,8 @@ if __name__ == '__main__': #if len(sys.argv)==1: + pyfrp.main() #else: #pyfrp_cmdline(sys.argv) - \ No newline at end of file + diff --git a/pyfrp/PyFRAP_cmdline.py b/pyfrp/PyFRAP_cmdline.py old mode 100644 new mode 100755 index 328866d..9d62cab --- a/pyfrp/PyFRAP_cmdline.py +++ b/pyfrp/PyFRAP_cmdline.py @@ -38,7 +38,7 @@ args = parser.parse_args() -print args +print(args) # Choose what kind of data is given and what to do with it. #inputTypes=[] diff --git a/pyfrp/__init__.py b/pyfrp/__init__.py old mode 100644 new mode 100755 index b850d69..a7443ec --- a/pyfrp/__init__.py +++ b/pyfrp/__init__.py @@ -15,7 +15,7 @@ if platform.system() in ["Darwin"]: import matplotlib - matplotlib.use('qt4agg') + matplotlib.use('qt5agg') #Basic PyFRAP modules from . import modules diff --git a/pyfrp/configurations/macros/czi2tif.ijm b/pyfrp/configurations/macros/czi2tif.ijm old mode 100644 new mode 100755 diff --git a/pyfrp/configurations/macros/lsm2tif.ijm b/pyfrp/configurations/macros/lsm2tif.ijm old mode 100644 new mode 100755 diff --git a/pyfrp/configurations/paths b/pyfrp/configurations/paths old mode 100644 new mode 100755 diff --git a/pyfrp/configurations/paths.cluster b/pyfrp/configurations/paths.cluster old mode 100644 new mode 100755 diff --git a/pyfrp/configurations/paths.default b/pyfrp/configurations/paths.default old mode 100644 new mode 100755 diff --git a/pyfrp/gui/__init__.py b/pyfrp/gui/__init__.py old mode 100644 new mode 100755 index 42bcc52..febe7db --- a/pyfrp/gui/__init__.py +++ b/pyfrp/gui/__init__.py @@ -12,15 +12,15 @@ # (We have to do this to make sure that pyplot import works in non-framework # installations) # This might cause warnings if pyplot is already imported. - + if platform.system() in ["Darwin"]: - import matplotlib - matplotlib.use('qt4agg') + import matplotlib + + matplotlib.use("qt5agg") -#PyFRAP main GUI +# PyFRAP main GUI from . import pyfrp_gui_builder from . import pyfrp_gui_vtk from . import pyfrp_app -#from . import pyfrp_term - +# from . import pyfrp_term diff --git a/pyfrp/gui/pyfrp_app.py b/pyfrp/gui/pyfrp_app.py old mode 100644 new mode 100755 index 77697f4..4c6a6b6 --- a/pyfrp/gui/pyfrp_app.py +++ b/pyfrp/gui/pyfrp_app.py @@ -1,39 +1,39 @@ -#===================================================================================================================================== -#Copyright -#===================================================================================================================================== +# ===================================================================================================================================== +# Copyright +# ===================================================================================================================================== -#Copyright (C) 2014 Alexander Blaessle, Patrick Mueller and the Friedrich Miescher Laboratory of the Max Planck Society -#This software is distributed under the terms of the GNU General Public License. +# Copyright (C) 2014 Alexander Blaessle, Patrick Mueller and the Friedrich Miescher Laboratory of the Max Planck Society +# This software is distributed under the terms of the GNU General Public License. -#This file is part of PyFRAP. +# This file is part of PyFRAP. -#PyFRAP is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License as published by -#the Free Software Foundation, either version 3 of the License, or -#(at your option) any later version. +# PyFRAP is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -#GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. -#You should have received a copy of the GNU General Public License -#along with this program. If not, see . +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . #! /usr/bin/python -#===================================================================================================================================== -#Description -#===================================================================================================================================== +# ===================================================================================================================================== +# Description +# ===================================================================================================================================== -#PyFRAP is a free Python based software to analyze FRAP measurements. This file contains the main GUI helping to access the different -#modules and classes: +# PyFRAP is a free Python based software to analyze FRAP measurements. This file contains the main GUI helping to access the different +# modules and classes: -#===================================================================================================================================== -#Importing Packages and Modules -#===================================================================================================================================== +# ===================================================================================================================================== +# Importing Packages and Modules +# ===================================================================================================================================== -#Standard packages +# Standard packages import sys import os, os.path import time @@ -41,11 +41,11 @@ import functools import code -#Numpy/Scipy +# Numpy/Scipy import numpy as np -#PyFRAP Modules -from pyfrp_term import * +# PyFRAP Modules +from .pyfrp_term import * from pyfrp.modules.pyfrp_term_module import * from pyfrp.modules import pyfrp_misc_module from pyfrp.modules import pyfrp_IO_module @@ -53,7 +53,7 @@ from pyfrp.modules import pyfrp_stats_module -#PyFRAP GUIs +# PyFRAP GUIs from pyfrp.gui import pyfrp_gui_molecule_dialogs from pyfrp.gui import pyfrp_gui_embryo_dialogs from pyfrp.gui import pyfrp_gui_ROI_manager @@ -68,14 +68,14 @@ from pyfrp.gui import pyfrp_gui_basics from pyfrp.gui import pyfrp_gui_settings_dialogs -#PyFRAP Classes +# PyFRAP Classes from pyfrp.subclasses import pyfrp_conf from pyfrp.subclasses import pyfrp_molecule -#QT -from PyQt4 import QtGui, QtCore +# QT +from PyQt5 import QtGui, QtCore, QtWidgets -#Matplotlib +# Matplotlib import matplotlib.pyplot as plt import matplotlib from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas @@ -86,2663 +86,3018 @@ """ try: - from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar + from matplotlib.backends.backend_qt4agg import ( + NavigationToolbar2QTAgg as NavigationToolbar, + ) except ImportError: - try: - from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar - except ImportError: - printWarning("Cannot import NavigationToolbar.") - + try: + from matplotlib.backends.backend_qt4agg import ( + NavigationToolbar2QT as NavigationToolbar, + ) + except ImportError: + printWarning("Cannot import NavigationToolbar.") + from matplotlib.figure import Figure from mpl_toolkits.mplot3d import Axes3D -#VTK -from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor +# VTK +from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor # bioformats -import javabridge -import bioformats -#===================================================================================================================================== -#Main Simulation window -#===================================================================================================================================== +# Try reimport +try: + import javabridge + import bioformats -class pyfrp(QtGui.QMainWindow): - - #Initializes main GUI window - def __init__(self, parent=None,redirect=False): - QtGui.QWidget.__init__(self, parent) - - #------------------------------------------- - #Version - #------------------------------------------- - - from pyfrp import __version__ as version +except: + print("Cannot import bioformats") + + +# ===================================================================================================================================== +# Main Simulation window +# ===================================================================================================================================== + + +class pyfrp(QtWidgets.QMainWindow): + + # Initializes main GUI window + def __init__(self, parent=None, redirect=False, overwrite_conf=False): + QtWidgets.QWidget.__init__(self, parent) + + # ------------------------------------------- + # Version + # ------------------------------------------- + + from pyfrp import __version__ as version + + # ------------------------------------------- + # Initializing window + # ------------------------------------------- + + self.setWindowTitle("PyFRAP") + self.setMinimumSize(400, 300) + self.resize(1500, 1000) + self.dpi = 100 + self.version = version + self.website = "http://www.fml.tuebingen.mpg.de/de/mueller-group/software.html" + self.pyfrpDir = pyfrp_misc_module.getConfDir().replace("configurations/", "") + + # ------------------------------------------- + # Statusbar + # ------------------------------------------- + + self.statusBar().showMessage("Idle") + + # ------------------------------------------- + # Some variables + # ------------------------------------------- + + # Keep track of plotting tabs + self.tabAxes = [] + self.tabFigs = [] + + # Keep track of all molecules currently open + self.molecules = [] + + # Keep track of which objects are currently used + self.currMolecule = None + self.currNode = None + self.currMoleculeNode = None + self.currObj = None + + # Keep track of which folder was recently used + self.lastopen = os.getcwd() + + # ------------------------------------------- + # Menubar + # ------------------------------------------- + + self.menubar = self.menuBar() + + # Init Menubars + self.initMainMenubar() + self.initMenubars() + + # Setting + # ------------------------------------------- + # Embryo list + # ------------------------------------------- + + self.objectBar = QtWidgets.QTreeWidget() + self.objectBar.setHeaderLabels(["Object", "Analyzed", "Simulated", "Fitted"]) + self.objectBar.setColumnWidth(0, 200) + self.objectBar.setColumnWidth(1, 75) + self.objectBar.setColumnWidth(2, 75) + self.objectBar.itemClicked.connect(self.updatePropBar) + + # ------------------------------------------- + # Property bar + # ------------------------------------------- + + self.propBar = QtWidgets.QListWidget() + # self.propBar.itemDoubleClicked.connect(self.edit_prop) + + # ------------------------------------------- + # Console + # ------------------------------------------- + + self.console = PyInterp(self, redirect=redirect) + self.console.initInterpreter(locals()) + + # ------------------------------------------- + # Splitter + # ------------------------------------------- + + # Creating splitters + self.horizontalSplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal) + self.verticalSplitter = QtWidgets.QSplitter(QtCore.Qt.Vertical) + + # ------------------------------------------- + # Frames + # ------------------------------------------- + + # Creating frames for widgets + self.objectBarFrame = QtWidgets.QFrame() + self.objectBarFrame = self.createEmptyFrame(self.objectBarFrame) + + self.propBarFrame = QtWidgets.QFrame() + self.propBarFrame = self.createEmptyFrame(self.propBarFrame) + + self.terminalFrame = QtWidgets.QFrame() + self.terminalFrame = self.createEmptyFrame(self.terminalFrame) + + # ------------------------------------------- + # Plotting tabs + # ------------------------------------------- + + self.plotTabs = QtWidgets.QTabWidget() + self.plotTabs.setTabsClosable(False) + self.plotTabs.currentChanged.connect(self.currentTabChanged) + self.plotTabs.tabCloseRequested.connect(self.currentTabClosed) + + # ------------------------------------------- + # Final Layout + # ------------------------------------------- + + ##Adding widgets to splitters + self.horizontalSplitter.addWidget(self.objectBar) + self.horizontalSplitter.addWidget(self.plotTabs) + self.horizontalSplitter.addWidget(self.propBar) + self.verticalSplitter.addWidget(self.horizontalSplitter) + self.verticalSplitter.addWidget(self.console) + + # Setting default sizes of splitters + self.verticalSplitter.setSizes([750, 250]) + self.horizontalSplitter.setSizes([350, 900, 250]) + + # Connecting splitter movement to figure size adjustment + self.horizontalSplitter.splitterMoved.connect(self.adjustCanvas) + self.verticalSplitter.splitterMoved.connect(self.adjustCanvas) + + # Create first plot tab + self.createDummpyTab() + + # Load config file + self.initConfiguration(overwrite=overwrite_conf) + + self.setCentralWidget(self.verticalSplitter) + QtWidgets.QApplication.setStyle(QtWidgets.QStyleFactory.create("Cleanlooks")) + + self.show() + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # List of Methods + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecInit: Initialization Methods + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def initMainMenubar(self): + + """Initiates main menubar.""" + + self.mbFile = self.menubar.addMenu("&File") + self.mbEdit = self.menubar.addMenu("&Edit") + self.mbEmbryo = self.menubar.addMenu("&Embryo") + self.mbAnalysis = self.menubar.addMenu("&Data Analysis") + self.mbSimulation = self.menubar.addMenu("&Simulation") + self.mbPinning = self.menubar.addMenu("&Pinning") + self.mbFitting = self.menubar.addMenu("&Fitting") + self.mbStatistics = self.menubar.addMenu("&Statistics") + self.mbSettings = self.menubar.addMenu("&Settings") + + return + + def initMenubars(self): + + """Initiates all menubars.""" + + self.initFileMenubar() + self.initEditMenubar() + self.initEmbryoMenubar() + self.initAnalysisMenubar() + self.initPinningMenubar() + self.initSimulationMenubar() + self.initFittingMenubar() + self.initStatsMenubar() + # self.initPlottingMenubar() + self.initSettingsMenubar() + + def initFileMenubar(self): + + """Creates entries of file menubar and connects actions with gui methods. + """ + + newMoleculeButton = QtWidgets.QAction("New Molecule", self) + newMoleculeButton.triggered.connect(self.newMolecule) + + loadMoleculeButton = QtWidgets.QAction("Open Molecule", self) + loadMoleculeButton.triggered.connect(self.loadMolecule) + + saveMoleculeButton = QtWidgets.QAction("Save Molecule", self) + saveMoleculeButton.triggered.connect(self.saveMolecule) + + exitButton = QtWidgets.QAction("Exit", self) + exitButton.setShortcut("Ctrl+Q") + exitButton.triggered.connect(self.close) + + self.mbFile.addAction(newMoleculeButton) + self.mbFile.addAction(loadMoleculeButton) + self.recentMB = self.mbFile.addMenu("&Open recent") + self.mbFile.addAction(saveMoleculeButton) + + self.mbFile.addAction(exitButton) + + return + + def initEditMenubar(self): + + """Creates entries of edit menubar and connects actions with gui methods. + """ + + editMoleculeButton = QtWidgets.QAction("Edit Molecule", self) + editMoleculeButton.triggered.connect(self.editMolecule) + + removeMoleculeButton = QtWidgets.QAction("Remove Molecule", self) + removeMoleculeButton.triggered.connect(self.removeMolecule) + + openWizardButton = QtWidgets.QAction("PyFRAP Wizard", self) + openWizardButton.triggered.connect(self.openWizard) + + self.mbEdit.addAction(editMoleculeButton) + self.mbEdit.addAction(removeMoleculeButton) + self.mbEdit.addAction(openWizardButton) + + def initEmbryoMenubar(self): + + """Creates entries of embryo menubar and connects actions with gui methods. + """ + + newEmbryoButton = QtWidgets.QAction("New Embryo", self) + newEmbryoButton.triggered.connect(self.newEmbryo) + + removeEmbryoButton = QtWidgets.QAction("Remove Embryo", self) + removeEmbryoButton.triggered.connect(self.removeEmbryo) + + editEmbryoButton = QtWidgets.QAction("Edit Embryo", self) + editEmbryoButton.triggered.connect(self.editEmbryo) + + loadEmbryoButton = QtWidgets.QAction("Load Embryo", self) + loadEmbryoButton.triggered.connect(self.loadEmbryo) + + selectGeometryButton = QtWidgets.QAction("Select Geometry", self) + selectGeometryButton.triggered.connect(self.selectGeometry) + + editGeometryButton = QtWidgets.QAction("Edit Geometry", self) + editGeometryButton.triggered.connect(self.editGeometry) + + editGeoFileButton = QtWidgets.QAction("Edit GeoFile", self) + editGeoFileButton.triggered.connect(self.editGeoFile) + + drawGeometryButton = QtWidgets.QAction("Plot Geometry", self) + drawGeometryButton.triggered.connect(self.drawGeometry) + + roiManagerButton = QtWidgets.QAction("ROI Manager", self) + roiManagerButton.triggered.connect(self.openROIManager) + + defaultROIButton = QtWidgets.QAction("Create Default ROIs", self) + defaultROIButton.triggered.connect(self.createDefaultROIs) + + defaultROIWizardButton = QtWidgets.QAction("Default ROIs Wizard", self) + defaultROIWizardButton.triggered.connect(self.defaultROIsWizard) + + indexROIButton = QtWidgets.QAction("Update ROIs indices", self) + indexROIButton.triggered.connect(self.updateROIIdxs) + + self.mbEmbryo.addAction(newEmbryoButton) + self.mbEmbryo.addAction(editEmbryoButton) + self.mbEmbryo.addAction(loadEmbryoButton) + self.mbEmbryo.addAction(removeEmbryoButton) + + self.geometryMB = self.mbEmbryo.addMenu("&Geometry") + self.geometryMB.addAction(selectGeometryButton) + self.geometryMB.addAction(editGeometryButton) + self.geometryMB.addAction(editGeoFileButton) + self.geometryMB.addAction(drawGeometryButton) + + self.roiMB = self.mbEmbryo.addMenu("&ROIs") + self.roiMB.addAction(roiManagerButton) + self.roiMB.addAction(defaultROIButton) + self.roiMB.addAction(defaultROIWizardButton) + + self.roiMB.addAction(indexROIButton) + + return + + def initAnalysisMenubar(self): + + """Creates entries of analysis menubar and connects actions with gui methods. + """ + + editAnalysisButton = QtWidgets.QAction("Analysis Settings", self) + editAnalysisButton.triggered.connect(self.editAnalysis) + + analyzeEmbryoButton = QtWidgets.QAction("Analyze Embryo", self) + analyzeEmbryoButton.triggered.connect(self.analyzeEmbryo) + + plotEmbryoAnalysisButton = QtWidgets.QAction( + "Plot Analysis Result of Embryo", self + ) + plotEmbryoAnalysisButton.triggered.connect(self.plotAllDataTSOfEmbryo) + + self.mbAnalysis.addAction(editAnalysisButton) + self.runAnalysisMB = self.mbAnalysis.addMenu("&Run Analysis") + self.runAnalysisMB.addAction(analyzeEmbryoButton) + + self.plotAnalysisMB = self.mbAnalysis.addMenu("&Plotting") + self.plotAnalysisMB.addAction(plotEmbryoAnalysisButton) + + return + + def initSimulationMenubar(self): + + """Creates entries of simulation menubar and connects actions with gui methods. + """ + + editSimulationButton = QtWidgets.QAction("Simulation Settings", self) + editSimulationButton.triggered.connect(self.editSimulation) + + simulateEmbryoButton = QtWidgets.QAction("Simulate Embryo", self) + simulateEmbryoButton.triggered.connect(self.simulateEmbryo) + + editMeshButton = QtWidgets.QAction("Mesh Settings", self) + editMeshButton.triggered.connect(self.editMesh) + + genMeshButton = QtWidgets.QAction("Generate Mesh", self) + genMeshButton.triggered.connect(self.generateMesh) + + refineMeshButton = QtWidgets.QAction("Refine Mesh", self) + refineMeshButton.triggered.connect(self.refineMesh) + + addBoundaryLayerMeshAroundROIButton = QtWidgets.QAction( + "Add boundary layer around ROI", self + ) + addBoundaryLayerMeshAroundROIButton.triggered.connect( + self.addBoundaryLayerMeshAroundROI + ) + + forceMeshButton = QtWidgets.QAction("Force Mesh Density", self) + forceMeshButton.triggered.connect(self.forceMeshDensity) + + forceROIMeshButton = QtWidgets.QAction("Refine Mesh in ROI", self) + forceROIMeshButton.triggered.connect(self.forceROIMeshDensity) + + printMeshButton = QtWidgets.QAction("Mesh Stats", self) + printMeshButton.triggered.connect(self.printMeshStats) + + plotMeshButton = QtWidgets.QAction("Plot Mesh", self) + plotMeshButton.triggered.connect(self.plotMesh) + + plotMeshDensityButton = QtWidgets.QAction("Plot Mesh Density", self) + plotMeshDensityButton.triggered.connect(self.plotMeshDensity) + + plotSimButton = QtWidgets.QAction("Plot Simulation", self) + plotSimButton.triggered.connect(self.plotAllSimTSOfEmbryo) + + plotSimAndDataButton = QtWidgets.QAction("Plot Simulaten & Data", self) + plotSimAndDataButton.triggered.connect(self.plotAllSimAndDataTSOfEmbryo) + + self.mbSimulation.addAction(editSimulationButton) + self.runSimulationMB = self.mbSimulation.addMenu("&Run Simulation") + self.runSimulationMB.addAction(simulateEmbryoButton) + + self.meshSimulationMB = self.mbSimulation.addMenu("&Mesh") + self.meshSimulationMB.addAction(editMeshButton) + self.meshSimulationMB.addAction(genMeshButton) + self.meshSimulationMB.addAction(refineMeshButton) + self.meshSimulationMB.addAction(forceMeshButton) + self.meshSimulationMB.addAction(forceROIMeshButton) + self.meshSimulationMB.addAction(addBoundaryLayerMeshAroundROIButton) + self.meshSimulationMB.addAction(printMeshButton) + self.meshSimulationMB.addAction(plotMeshButton) + self.meshSimulationMB.addAction(plotMeshDensityButton) + + self.plotSimulationMB = self.mbSimulation.addMenu("&Plotting") + self.plotSimulationMB.addAction(plotSimButton) + self.plotSimulationMB.addAction(plotSimAndDataButton) + + def initPinningMenubar(self): + + """Creates entries of pinning menubar and connects actions with gui methods. + """ + + defaultPinButton = QtWidgets.QAction("Default Pinning", self) + defaultPinButton.triggered.connect(self.defaultPinEmbryo) + + idealPinButton = QtWidgets.QAction("Ideal Pinning", self) + idealPinButton.triggered.connect(self.idealPinEmbryo) + + self.mbPinning.addAction(defaultPinButton) + self.mbPinning.addAction(idealPinButton) + + def initFittingMenubar(self): + + """Creates entries of fitting menubar and connects actions with gui methods. + """ + + newFitButton = QtWidgets.QAction("New fit", self) + newFitButton.triggered.connect(self.newFit) + + removeFitButton = QtWidgets.QAction("Remove fit", self) + removeFitButton.triggered.connect(self.removeFit) + + editFitButton = QtWidgets.QAction("Edit fit", self) + editFitButton.triggered.connect(self.editFit) + + # editmultfit = QtWidgets.QAction('Edit multiple fits', self) + # editmultfit.triggered.connect(self.edit_mult_fit) + + # copyfit = QtWidgets.QAction('Copy fit', self) + # copyfit.triggered.connect(self.copy_fit) + + # copyfitforall = QtWidgets.QAction('Copy fit into all embryos', self) + # copyfitforall.triggered.connect(self.copy_fit_to_all) + + performFitButton = QtWidgets.QAction("Perform fit", self) + performFitButton.triggered.connect(self.performFit) + + # fitall = QtWidgets.QAction('Perform all fits in molecule', self) + # fitall.triggered.connect(self.perform_fits_molecule) + + plotFitButton = QtWidgets.QAction("Plot fit", self) + plotFitButton.triggered.connect(self.plotFit) + + # plottrackfit = QtWidgets.QAction('Plot fitting progress', self) + # plottrackfit.triggered.connect(self.plot_track_fit) + + printFitButton = QtWidgets.QAction("Print fit results", self) + printFitButton.triggered.connect(self.printFitResults) + + self.mbFitting.addAction(newFitButton) + self.mbFitting.addAction(editFitButton) + self.mbFitting.addAction(removeFitButton) + self.mbFitting.addAction(performFitButton) + self.mbFitting.addAction(printFitButton) + + self.plotFittingMB = self.mbFitting.addMenu("&Plotting") + self.plotFittingMB.addAction(plotFitButton) + + return + + def initStatsMenubar(self): + + """Creates entries of statistics menubar and connects actions with gui methods. + """ + + selectFitsButton = QtWidgets.QAction("Select Fits", self) + selectFitsButton.triggered.connect(self.selectFits) + + selectCrucialParametersButton = QtWidgets.QAction( + "Select CrucialParameters", self + ) + selectCrucialParametersButton.triggered.connect(self.selectCrucialParameters) + + summarizeMoleculeButton = QtWidgets.QAction("Summarize Molecule", self) + summarizeMoleculeButton.triggered.connect(self.summarizeMolecule) + + tTest = QtWidgets.QAction("Perform standard t-test", self) + tTest.triggered.connect(self.performtTest) + + tTestWelch = QtWidgets.QAction("Perform Welchs t-test", self) + tTestWelch.triggered.connect(self.performtTestWelch) + + wilcoxonTest = QtWidgets.QAction("Perform Wilcoxon test", self) + wilcoxonTest.triggered.connect(self.performWilcoxon) + + mannWhitneyUTest = QtWidgets.QAction("Perform Mann-Whitney-U test", self) + mannWhitneyUTest.triggered.connect(self.performMannWhitneyUTest) + + shapiroTest = QtWidgets.QAction("Perform Shaprio test", self) + shapiroTest.triggered.connect(self.performShapiroTest) + + AIC = QtWidgets.QAction("Perform Akaike Information Criterion", self) + AIC.triggered.connect(self.performAIC) + + self.mbStatistics.addAction(selectFitsButton) + self.mbStatistics.addAction(selectCrucialParametersButton) + self.mbStatistics.addAction(summarizeMoleculeButton) + + self.statisticsTestMB = self.mbStatistics.addMenu("&Tests") + self.statisticsTestMB.addAction(tTest) + self.statisticsTestMB.addAction(tTestWelch) + self.statisticsTestMB.addAction(wilcoxonTest) + self.statisticsTestMB.addAction(mannWhitneyUTest) + self.statisticsTestMB.addAction(shapiroTest) + + self.statisticsComparisonMB = self.mbStatistics.addMenu("&Model comparison") + self.statisticsComparisonMB.addAction(AIC) + + # def initPlottingMenubar(self): + + # """Creates entries of statistics menubar and connects actions with gui methods. + # """ + + # newMPLTabButton = QtWidgets.QAction('New Matplotlib tab', self) + # newMPLTabButton.triggered.connect(self.createPlotTab) + + # newVTKTabButton = QtWidgets.QAction('New Matplotlib tab', self) + # newVTKTabButton.triggered.connect(self.createVtkTab) + + # self.newTabMB=self.mbPlotting.addMenu('&New Tab') + # self.newTabMB.addAction(newMPLTabButton) + # self.newTabMB.addAction(newVTKTabButton) + + # showImgIndButton = QtWidgets.QAction('Show image indices', self) + # showImgIndButton.triggered.connect(self.showROIImgIdx) + + # showMeshIndButton = QtWidgets.QAction('Show mesh indices', self) + # showImgIndButton.triggered.connect(self.showROIMeshIdx) + + # showExtIndButton = QtWidgets.QAction('Show extended indices', self) + # showExtIndButton.triggered.connect(self.showROIExtIdx) + + # showROIIndButton = QtWidgets.QAction('Show all indices', self) + # showROIIndButton.triggered.connect(self.showROIIdx) + + # showROIBoundButton = QtWidgets.QAction('Show ROI boundaries', self) + # showROIBoundButton.triggered.connect(self.showROIBoundaries) + + # showROIBoundButton = QtWidgets.QAction('Show all ROI boundaries', self) + # showROIBoundButton.triggered.connect(self.showAllROIBoundaries) + + # self.embryoPlotMB=self.mbPlotting.addMenu('&Embryo') + # self.ROIPlotMB=self.embryoPlotMB.addMenu('&ROI') + + # self.geomPlotMB=self.embryoPlotMB.addMenu('&Geometry') + # self.analysisPlotMB=self.embryoPlotMB.addMenu('&Analysis') + # self.simulationPlotMB=self.embryoPlotMB.addMenu('&Simulation') + # self.fittingPlotMB=self.embryoPlotMB.addMenu('&Fitting') + # self.statisticsPlotMB=self.embryoPlotMB.addMenu('&Statistics') + + def initSettingsMenubar(self): + + """Creates entries of settings menubar and connects actions with gui methods. + """ + + setPathFileButton = QtWidgets.QAction("Set Path File", self) + setPathFileButton.triggered.connect(self.setPathFile) + + setGmshButton = QtWidgets.QAction("Set Gmsh Path", self) + setGmshButton.triggered.connect(self.setGmshPath) + + setFijiButton = QtWidgets.QAction("Set Fiji Path", self) + setFijiButton.triggered.connect(self.setFijiPath) + + setOpenscadButton = QtWidgets.QAction("Set Openscad Path", self) + setOpenscadButton.triggered.connect(self.setOpenscadPath) + + printPathsButton = QtWidgets.QAction("Print Paths", self) + printPathsButton.triggered.connect(self.printPaths) + + printPathFileButton = QtWidgets.QAction("Print Path File Location", self) + printPathFileButton.triggered.connect(self.printPathFile) + + checkPathsButton = QtWidgets.QAction("Check paths in path file", self) + checkPathsButton.triggered.connect(self.checkPaths) + + self.mbSettings.addAction(setPathFileButton) + self.mbSettings.addAction(setGmshButton) + self.mbSettings.addAction(setFijiButton) + self.mbSettings.addAction(setOpenscadButton) + self.mbSettings.addAction(printPathsButton) + self.mbSettings.addAction(printPathFileButton) + self.mbSettings.addAction(checkPathsButton) + + def closeEvent(self, event): + + """Closes GUI and saves configuration. - #------------------------------------------- - #Initializing window - #------------------------------------------- + Args: + event (QtCore.closeEvent): Close event triggered by close signal. - self.setWindowTitle('PyFRAP') - self.setMinimumSize(400,300) - self.resize(1500,1000) - self.dpi = 100 - self.version=version - self.website="http://www.fml.tuebingen.mpg.de/de/mueller-group/software.html" - self.pyfrpDir=pyfrp_misc_module.getConfDir().replace("configurations/","") + """ + + reply = QtWidgets.QMessageBox.question( + self, + "Message", + "Are you sure you want to quit?", + QtWidgets.QMessageBox.Yes, + QtWidgets.QMessageBox.No, + ) + + if reply == QtWidgets.QMessageBox.Yes: + fn = pyfrp_misc_module.getConfDir() + "lastConfiguration.conf" + self.config.consoleHistory = self.console.history + self.config.backupPathFile() + self.config.save(fn=fn) + try: + javabridge.kill_vm() + except: + printWarning("Wasn't able to kill javabridge") + + event.accept() + else: + event.ignore() + + return + + # def show_about(self): + + # ret=pyfrp_subwin.about_dialog(self).exec_() + + def createEmptyFrame(self, frame): + + """Creates frame around widget. - #------------------------------------------- - #Statusbar - #------------------------------------------- + Args: + frame (QtWidgets.QWidget): Widget to be framed - self.statusBar().showMessage("Idle") + Returns: + QtWidgets.QWidget: Framed Widget - #------------------------------------------- - #Some variables - #------------------------------------------- + """ + + frame.setFrameStyle(QtWidgets.QFrame.StyledPanel) + frame.setBackgroundRole(QtGui.QPalette.Light) + frame.setAutoFillBackground(True) + frame.setLineWidth(1) + frame.setFrameShadow(frame.Sunken) + + return frame + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecConfig: Configuration handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def initConfiguration(self, overwrite=False): + + """Initialize Configuration from file. - #Keep track of plotting tabs - self.tabAxes=[] - self.tabFigs=[] + Does this by: - #Keep track of all molecules currently open - self.molecules=[] + * Loading config file. + * Updating history + * Calling :py:func:`updateConfig`. - #Keep track of which objects are currently used - self.currMolecule=None - self.currNode=None - self.currMoleculeNode=None - self.currObj=None + """ + + fn = pyfrp_misc_module.getConfDir() + "lastConfiguration.conf" + + if os.path.isfile(fn) and not overwrite: + self.config = pyfrp_IO_module.loadFromPickle(fn) + else: + self.config = pyfrp_conf.configuration() + + self.console.history = list(self.config.consoleHistory) + + self.updateConfig() + + return self.config + + def updateConfig(self): + + """Update configuration of GUI to match with config. - #Keep track of which folder was recently used - self.lastopen=os.getcwd() - - #------------------------------------------- - #Menubar - #------------------------------------------- - - self.menubar = self.menuBar() - - #Init Menubars - self.initMainMenubar() - self.initMenubars() - - #Setting - #------------------------------------------- - #Embryo list - #------------------------------------------- - - self.objectBar=QtGui.QTreeWidget() - self.objectBar.setHeaderLabels(["Object","Analyzed","Simulated","Fitted"]) - self.objectBar.setColumnWidth(0,200) - self.objectBar.setColumnWidth(1,75) - self.objectBar.setColumnWidth(2,75) - self.objectBar.itemClicked.connect(self.updatePropBar) - - #------------------------------------------- - #Property bar - #------------------------------------------- - - self.propBar=QtGui.QListWidget() - #self.propBar.itemDoubleClicked.connect(self.edit_prop) - - #------------------------------------------- - #Console - #------------------------------------------- + That is: - self.console = PyInterp(self,redirect=redirect) - self.console.initInterpreter(locals()) - - #------------------------------------------- - #Splitter - #------------------------------------------- - - #Creating splitters - self.horizontalSplitter = QtGui.QSplitter(QtCore.Qt.Horizontal) - self.verticalSplitter = QtGui.QSplitter(QtCore.Qt.Vertical) + * hide/show parts of GUI. + * Update recently opened files menubar. + * Update Path file. + + """ + + self.console.setHidden(self.config.termHidden) + self.propBar.setHidden(self.config.propHidden) + self.plotTabs.setHidden(self.config.plotHidden) + + self.verticalSplitter.refresh() + self.horizontalSplitter.refresh() + # self.adjustCanvas() + + self.updateRecentMBs() + + self.config.copyPathFileToDefaultLocation() + + return self.config + + def appendRecent(self, fn): + + """Makes filename the most recently opened file, adds it to config.recentFiles and updates menubar. - #------------------------------------------- - #Frames - #------------------------------------------- + Args: + fn (str): Some filename. + """ + + self.config.addRecentFile(fn) + self.recentMB.clear() + self.updateRecentMBs() + + return self.recentMB + + def updateRecentMBs(self): + + """Updates recently opened menubar. - #Creating frames for widgets - self.objectBarFrame = QtGui.QFrame() - self.objectBarFrame = self.createEmptyFrame(self.objectBarFrame) + Loops through current loaded configuration ``config.recentFiles`` and appends the 5 newest entries to + ``self.recentActions``. - self.propBarFrame = QtGui.QFrame() - self.propBarFrame = self.createEmptyFrame(self.propBarFrame) + """ + + self.recentActions = [] + + for i in range(len(self.config.recentFiles)): + if i > 5: + self.config.recentFiles.pop(i) + else: + self.recentActions.append( + QtWidgets.QAction(self.config.recentFiles[i], self) + ) + item = self.recentActions[i] + item.triggered.connect( + functools.partial( + self.openMolecule, + pyfrp_misc_module.fixPath(self.config.recentFiles[i]), + ) + ) + + self.recentMB.addAction(item) + + return self.recentMB + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # secObjectBar: Object Bar handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def highlightCurrentObjectNode(self): + + """Highlists the currently used Node of the objectBar. + """ + + self.objectBar.setCurrentItem(self.currNode) + return self.objectBar + + def checkSelectedNode(self, typ="any"): + + """Checks if the current selected node is of certain type and returns respective error popups - self.terminalFrame = QtGui.QFrame() - self.terminalFrame = self.createEmptyFrame(self.terminalFrame) + Keyword Args: + typ (str): Desired Node type. Use ``"any"`` if type doesn't matter. - #------------------------------------------- - #Plotting tabs - #------------------------------------------- + Returns: + bool: True if proper node is selected - self.plotTabs = QtGui.QTabWidget() - self.plotTabs.setTabsClosable(False) - self.plotTabs.currentChanged.connect(self.currentTabChanged) - self.plotTabs.tabCloseRequested.connect(self.currentTabClosed) - - #------------------------------------------- - #Final Layout - #------------------------------------------- - - ##Adding widgets to splitters - self.horizontalSplitter.addWidget(self.objectBar) - self.horizontalSplitter.addWidget(self.plotTabs) - self.horizontalSplitter.addWidget(self.propBar) - self.verticalSplitter.addWidget(self.horizontalSplitter) - self.verticalSplitter.addWidget(self.console) - - #Setting default sizes of splitters - self.verticalSplitter.setSizes([750,250]) - self.horizontalSplitter.setSizes([350,900,250]) - - #Connecting splitter movement to figure size adjustment - self.horizontalSplitter.splitterMoved.connect(self.adjustCanvas) - self.verticalSplitter.splitterMoved.connect(self.adjustCanvas) - - #Create first plot tab - self.createDummpyTab() - - #Load config file - self.initConfiguration() - - self.setCentralWidget(self.verticalSplitter) - QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Cleanlooks')) - - self.show() - - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #List of Methods - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecInit: Initialization Methods - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - def initMainMenubar(self): - - """Initiates main menubar.""" - - self.mbFile = self.menubar.addMenu('&File') - self.mbEdit = self.menubar.addMenu('&Edit') - self.mbEmbryo = self.menubar.addMenu('&Embryo') - self.mbAnalysis = self.menubar.addMenu('&Data Analysis') - self.mbSimulation = self.menubar.addMenu('&Simulation') - self.mbPinning = self.menubar.addMenu('&Pinning') - self.mbFitting = self.menubar.addMenu('&Fitting') - self.mbStatistics = self.menubar.addMenu('&Statistics') - self.mbSettings = self.menubar.addMenu('&Settings') - - return - - def initMenubars(self): - - """Initiates all menubars.""" - - self.initFileMenubar() - self.initEditMenubar() - self.initEmbryoMenubar() - self.initAnalysisMenubar() - self.initPinningMenubar() - self.initSimulationMenubar() - self.initFittingMenubar() - self.initStatsMenubar() - #self.initPlottingMenubar() - self.initSettingsMenubar() - - def initFileMenubar(self): - - """Creates entries of file menubar and connects actions with gui methods. """ + + if self.objectBar.currentItem() == None: + QtWidgets.QMessageBox.critical( + None, + "Error", + "Nothing selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return False + if typ == "any": + return True + if typ == self.currNodeType: + return True + + return False + + def embryo2ObjectBar(self, embryo, parentNode): + + """Adds Embryo to ObjectBar. - newMoleculeButton = QtGui.QAction('New Molecule', self) - self.connect(newMoleculeButton, QtCore.SIGNAL('triggered()'), self.newMolecule) - - loadMoleculeButton = QtGui.QAction('Open Molecule', self) - self.connect(loadMoleculeButton, QtCore.SIGNAL('triggered()'), self.loadMolecule) - - saveMoleculeButton = QtGui.QAction('Save Molecule', self) - self.connect(saveMoleculeButton, QtCore.SIGNAL('triggered()'), self.saveMolecule) - - exitButton = QtGui.QAction('Exit', self) - exitButton.setShortcut('Ctrl+Q') - self.connect(exitButton, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()')) - - self.mbFile.addAction(newMoleculeButton) - self.mbFile.addAction(loadMoleculeButton) - self.recentMB=self.mbFile.addMenu('&Open recent') - self.mbFile.addAction(saveMoleculeButton) - - self.mbFile.addAction(exitButton) - - return - def initEditMenubar(self): - """Creates entries of edit menubar and connects actions with gui methods. """ + + # Embryo Status + analyzed = str(int(embryo.isAnalyzed())) + simulated = str(int(embryo.isSimulated())) + fitted = str(int(embryo.isFitted())) + + # Create new node + newEmbryoNode = QtWidgets.QTreeWidgetItem( + parentNode, [embryo.name, analyzed, simulated, fitted] + ) + + # Geometry node + newGeometryNode = QtWidgets.QTreeWidgetItem( + newEmbryoNode, ["Geometry", "", "", ""] + ) + + # ROIs node + newROIsNode = QtWidgets.QTreeWidgetItem(newEmbryoNode, ["ROIs", "", "", ""]) + + # Add ROIs + for roi in embryo.ROIs: + newROINode = QtWidgets.QTreeWidgetItem( + newROIsNode, + [ + roi.name, + str(int(roi.isAnalyzed())), + str(int(roi.isSimulated())), + str(int(roi.isFitted())), + ], + ) + + # Analysis node + newAnalysisNode = QtWidgets.QTreeWidgetItem( + newEmbryoNode, ["Analysis", analyzed, "", ""] + ) + + # Simulation node + newSimulationNode = QtWidgets.QTreeWidgetItem( + newEmbryoNode, ["Simulation", "", simulated, ""] + ) + + # if embryo.simulation!=None: + newMeshNode = QtWidgets.QTreeWidgetItem(newSimulationNode, ["Mesh", "", "", ""]) + + # Fits node + newFitsNode = QtWidgets.QTreeWidgetItem(newEmbryoNode, ["Fits", "", "", ""]) + + # Add Fits + for fit in embryo.fits: + newFitNode = QtWidgets.QTreeWidgetItem( + newFitsNode, [fit.name, "", "", str(int(fit.isFitted()))] + ) + + # Expand Fits node + self.objectBar.expandItem(newFitsNode) + + return newEmbryoNode + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Update ObjectBar Properties of embryo Node + + def updateEmbryoNodeProps(self, embryoNode): + currEmbryoNode = self.getCurrentEmbryoNode() + currEmbryo = self.getCurrentEmbryo() + + currEmbryoNode.setText(1, str(int(currEmbryo.isAnalyzed()))) + currEmbryoNode.setText(2, str(int(currEmbryo.isSimulated()))) + currEmbryoNode.setText(3, str(int(currEmbryo.isFitted()))) + + return + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Update ObjectBar Properties of embryo Node + + def updateEmbryoNodeChildren(self): + self.updateFitsNodeChildren() + self.updateROIsNodeChildren() + return + + def getChildByName(self, node, name): + for i in range(node.childCount()): + try: + curr_name = str(node.child(i).data(0, 0).toString()) + except AttributeError: + curr_name = str(node.child(i).data(0, 0)) + + if name == str(curr_name): + return node.child(i) + return None + + def removeAllNodeChildren(self, node): + nChild = node.childCount() + for i in range(nChild): + node.takeChild(0) + + return node + + def updateFitsNodeChildren(self): + + currEmbryo = self.getCurrentEmbryo() + currEmbryoNode = self.getCurrentEmbryoNode() + if currEmbryoNode != None: + fitsNode = self.getChildByName(currEmbryoNode, "Fits") + self.removeAllNodeChildren(fitsNode) + for fit in currEmbryo.fits: + newFitNode = QtWidgets.QTreeWidgetItem( + fitsNode, [fit.name, "", "", str(int(fit.isFitted()))] + ) + self.getCurrentObjNode() + return newFitNode + + def updateROIsNodeChildren(self): + + currEmbryo = self.getCurrentEmbryo() + currEmbryoNode = self.getCurrentEmbryoNode() + if currEmbryoNode != None: + roisNode = self.getChildByName(currEmbryoNode, "ROIs") + self.removeAllNodeChildren(roisNode) + for roi in currEmbryo.ROIs: + newROINode = QtWidgets.QTreeWidgetItem( + roisNode, + [ + roi.name, + str(int(roi.isAnalyzed())), + str(int(roi.isSimulated())), + str(int(roi.isFitted())), + ], + ) + self.getCurrentObjNode() + + def getCurrentObjNode(self): + + """Returns Current Object Node from objectBar + """ + + self.currNode = self.objectBar.currentItem() + + #print(self.currNode.data(0, 0),type(self.currNode.data(0, 0))) + + nodeStr=self.getNodeStr(self.currNode) + + if self.currNode.parent() == None: + self.currNodeType = "molecule" + else: + if self.currNode.parent().parent() == None: + self.currNodeType = "embryo" + elif nodeStr == "Fits": + self.currNodeType = "fits" + elif self.getNodeStr(self.currNode.parent()) == "Fits": + self.currNodeType = "fit" + elif nodeStr == "Simulation": + self.currNodeType = "simulation" + elif nodeStr == "Analysis": + self.currNodeType = "analysis" + elif nodeStr == "Mesh": + self.currNodeType = "mesh" + elif nodeStr == "Geometry": + self.currNodeType = "geometry" + elif nodeStr == "ROIs": + self.currNodeType = "rois" + elif self.getNodeStr(self.currNode.parent()) == "ROIs": + self.currNodeType = "roi" + + return self.currNode, self.currNodeType + + def getNodeStr(self,node): + try: + nodeStr=node.data(0, 0).toString() + except AttributeError: + nodeStr=node.data(0, 0) + + return nodeStr + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Returns Current Object selected in objectBar + + def getCurrentObj(self): + + # Find out current node and which type it is + self.getCurrentObjNode() + + # Find current molecule node + self.getCurrentMoleculeNode() + + # Find corresponding molecule object + self.getCurrentMolecule() + + # Get node string + nodeStr=self.getNodeStr(self.currNode) + + if self.currNodeType == "molecule": + self.currObj = self.currMolecule + else: + currEmbryo = self.getCurrentEmbryo() + + if self.currNodeType == "embryo": + self.currObj = currEmbryo + elif self.currNodeType == "analysis": + self.currObj = currEmbryo.analysis + elif self.currNodeType == "geometry": + self.currObj = currEmbryo.geometry + elif self.currNodeType == "simulation": + self.currObj = currEmbryo.simulation + elif self.currNodeType == "mesh": + self.currObj = currEmbryo.simulation.mesh + elif self.currNodeType == "fit": + self.currObj = currEmbryo.getFitByName( + nodeStr + ) + elif self.currNodeType == "roi": + self.currObj = currEmbryo.getROIByName( + nodeStr + ) + else: + self.currObj = None + + return self.currObj + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Returns Current Molecule Node + + def getCurrentMoleculeNode(self): + if self.currNodeType == "molecule": + self.currMoleculeNode = self.currNode + elif self.currNodeType == "embryo": + self.currMoleculeNode = self.currNode.parent() + elif self.currNodeType in [ + "analysis", + "simulation", + "fits", + "geometry", + "rois", + ]: + self.currMoleculeNode = self.currNode.parent().parent() + elif self.currNodeType in ["mesh", "roi", "fit"]: + self.currMoleculeNode = self.currNode.parent().parent().parent() + + ###NOTE: Try later if this is the smarter way + # ind=self.objectBar.indexOfTopLevelItem(self.currNode) + # self.currMoleculeNode=self.objectBar.topLevelItem(ind) + + return self.currMoleculeNode + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Returns Current Embryo Node + + def getCurrentEmbryoNode(self): + if self.currNodeType == "molecule": + currEmbryoNode = None + elif self.currNodeType == "embryo": + currEmbryoNode = self.currNode + elif self.currNodeType in [ + "analysis", + "simulation", + "fits", + "geometry", + "rois", + ]: + currEmbryoNode = self.currNode.parent() + elif self.currNodeType in ["mesh", "roi", "fit"]: + currEmbryoNode = self.currNode.parent().parent() + + return currEmbryoNode + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Returns Current Molecule + + def getCurrentMolecule(self): + molNames = pyfrp_misc_module.objAttrToList(self.molecules, "name") + try: + self.currMolecule = self.molecules[ + molNames.index(self.currMoleculeNode.data(0, 0).toString()) + ] + except AttributeError: + self.currMolecule = self.molecules[ + molNames.index(self.currMoleculeNode.data(0, 0)) + ] + return self.currMolecule + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Returns Current Embryo + + def getCurrentEmbryo(self): + currEmbryoNode = self.getCurrentEmbryoNode() + if currEmbryoNode == None: + return None + + embryoNames = pyfrp_misc_module.objAttrToList(self.currMolecule.embryos, "name") + try: + currEmbryo = self.currMolecule.embryos[ + embryoNames.index(currEmbryoNode.data(0, 0).toString()) + ] + except AttributeError: + currEmbryo = self.currMolecule.embryos[ + embryoNames.index(currEmbryoNode.data(0, 0)) + ] + + return currEmbryo + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecPropertyBar: Porperty Bar handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def showObjPropsInBar(self, obj, maxArraySize=3): + + """Shows property bar. - editMoleculeButton = QtGui.QAction('Edit Molecule', self) - self.connect(editMoleculeButton, QtCore.SIGNAL('triggered()'), self.editMolecule) - - removeMoleculeButton = QtGui.QAction('Remove Molecule', self) - self.connect(removeMoleculeButton, QtCore.SIGNAL('triggered()'), self.removeMolecule) - - openWizardButton = QtGui.QAction('PyFRAP Wizard', self) - self.connect(openWizardButton, QtCore.SIGNAL('triggered()'), self.openWizard) + Args: + obj (object): Object selected in objectBar. + + Keyword Args: + maxArraySize (int): Maximal length of array to still be displayed. + + """ + + if obj == None: + return self.propBar + + for item in vars(obj): + + ###NOTE: Creates deprecation warning on Windows + + # First check if numpy array or list + if isinstance(vars(obj)[str(item)], (np.ndarray, list)): + + # Check if array is not too long + if ( + len(np.shape(vars(obj)[str(item)])) > 0 + and np.shape(vars(obj)[str(item)])[0] < maxArraySize + ): + pass + else: + continue + + # All other variables, check if type is OK + if ( + isinstance(vars(obj)[str(item)], (int, float, str)) + or vars(obj)[str(item)] == None + ): + pass + else: + continue + + self.propBar.addItem(item + "=" + str(vars(obj)[str(item)])) + + return self.propBar + + def updatePropBar(self): + + """Updates Property bar.""" + + # Clearing property list + self.propBar.clear() + + # Get Current Object + self.getCurrentObj() + + # Show properties + self.showObjPropsInBar(self.currObj) + + # Sort prop_list + self.propBar.sortItems() + + return self.propBar + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecMolecule: Molecule handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Creates new molecule object and asks for name, then automatically adds it to objectBar + + def newMolecule(self): + + # Generate name + moleculeNames = pyfrp_misc_module.objAttrToList(self.molecules, "name") + newName = pyfrp_misc_module.enumeratedName( + "newMolecule", moleculeNames, sep="_" + ) + + # Create new molecule object + mol = pyfrp_molecule.molecule(newName) + pyfrp_gui_molecule_dialogs.moleculeDialog(mol, self).exec_() + + # Make current molecule + self.currMolecule = mol + + # Add new molecule to list of embryos + self.molecules.append(mol) + + # Add to objectBar + self.currNode = QtWidgets.QTreeWidgetItem( + self.objectBar, [self.currMolecule.name] + ) + + # Memorize molecule node + self.currMoleculeNode = self.currNode + + # Highligth new node + self.highlightCurrentObjectNode() + + # Show molecule properties + self.updatePropBar() + + # Check if names are alright + self.checkObjNames() + + return self.currMolecule + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Edit Molecule + + def editMolecule(self): + + self.getCurrentMolecule() + ret = pyfrp_gui_molecule_dialogs.moleculeDialog(self.currMolecule, self).exec_() + + self.currMoleculeNode.setText(0, self.currMolecule.name) + + self.updatePropBar() + + return self.currMolecule + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Removes Molecule from PyFRAP + + def removeMolecule(self): + + # Check if molecule or subnode selected + if not self.checkSelectedNode(): + return + + # Remove from list of molecules used + self.molecules.remove(self.currMolecule) + + # Remove from objectBar + ind = self.objectBar.indexOfTopLevelItem(self.currMoleculeNode) + self.objectBar.takeTopLevelItem(ind) + + # Update current Node + self.currNode = self.objectBar.currentItem() + + # Update PropBar + if self.currNode != None: + self.updatePropBar() + else: + self.propBar.clear() + + return self.molecules + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Saves molecule object into pickle file + + def saveMolecule(self): + + # Check if molecule or subnode selected + if not self.checkSelectedNode(): + return + + # Filename dialog + fn = QtWidgets.QFileDialog.getSaveFileName( + self, + "Save file", + self.lastopen + "/" + self.currMolecule.name + ".mol", + "*.mol", + ) + fn = str(fn) + + # Check if folder exists + if not os.path.exists(os.path.dirname(fn)): + return + + # Remember folder + self.lastopen = os.path.dirname(str(fn)) + + # Ask if extract save + # reply = QtWidgets.QMessageBox.question(self, 'Message',"Do you want to save (Will only keep essential results and delete everything else)?", QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) + + # No slim save + # if reply == QtWidgets.QMessageBox.No: + self.currMolecule.save(fn=fn) + # else: + + ##Temporarily save molecule + # if self.config.backup2File: + # fn_backup=self.lastopen+"/"+self.currMolecule.name+"_backup.mol" + # self.currMolecule.save(fn=fn_backup) + # tempMolecule=self.currMolecule + + ##Temporarily make a copy of molecule into memory + # if self.config.backup2Memory: + # tempMolecule=cpy.deepcopy(self.currMolecule) + + ####NOTE: Need to specify what needs to be deleted for slim save + ##Make a function in embryo object for this + ##Delete big stuff + ##for temp_emb in temp_mol.embryos: + + ###Deleting all image data to reduce file size + ##temp_emb.masks_embryo=[] + + # if self.config.backup2File: + # self.currMolecule=pyfrp_IO_module.loadFromPickle(fn_backup) + # os.remove(fn_backup) + # if self.config.backup2Memory: + # self.currMolecule=cpy.deepcopy(tempMolecule) + # tempMolecule=None + + self.appendRecent(fn) + + return fn + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Load molecule + + def loadMolecule(self): + + fnLoad = QtWidgets.QFileDialog.getOpenFileName( + self, "Open file", self.lastopen, "*.mol" + ) + if fnLoad == "": + return + + self.currMolecule = self.openMolecule(fnLoad) + + return self.currMolecule + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Open molecule + + def openMolecule(self, fnLoad): + + # Memorize last path and append to recently opened + self.lastopen = os.path.dirname(str(fnLoad)) + self.appendRecent(fnLoad) + + # Load molecule object + self.currMolecule = pyfrp_IO_module.loadFromPickle(fnLoad) + + # Update Version + self.currMolecule.updateVersion() + + # Add molecule to list of molecules + self.molecules.append(self.currMolecule) + + # Adding molecule to sidebar + self.currNode = QtWidgets.QTreeWidgetItem( + self.objectBar, [self.currMolecule.name, "", "", ""] + ) + self.currMoleculeNode = self.currNode + + for embryo in self.currMolecule.embryos: + self.embryo2ObjectBar(embryo, self.currMoleculeNode) + + self.objectBar.expandItem(self.currNode) + + self.checkObjNames() + + return self.currMolecule + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # Embryo handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def newEmbryo(self): + + """Creates new embryo object and adds it to molecule. - self.mbEdit.addAction(editMoleculeButton) - self.mbEdit.addAction(removeMoleculeButton) - self.mbEdit.addAction(openWizardButton) + Will first run :py:func:`selectEmbryoGenMode` to choose way of embryo generation. + Will create embryo instance via :py:func:`LSM2EmbryoWizard` if selected, ohterwise + will create default embryo. - def initEmbryoMenubar(self): + Returns: + pyfrp.subclasses.pyfrp_embryo: New embryo object. - """Creates entries of embryo menubar and connects actions with gui methods. """ + + # Check if molecule or subnode selected + if not self.checkSelectedNode(): + return + + ret = self.selectEmbryoGenMode() + if ret == -1: + return 0 + elif ret == 0: + + # Generate name + embryoNames = pyfrp_misc_module.objAttrToList( + self.currMolecule.embryos, "name" + ) + newName = pyfrp_misc_module.enumeratedName( + "newEmbryo", embryoNames, sep="_" + ) + + # Create new embryo + newEmbryo = self.currMolecule.newEmbryo(newName) + + # Append to object bar + newNode = self.embryo2ObjectBar(newEmbryo, self.currMoleculeNode) + self.objectBar.setCurrentItem(newNode) + self.getCurrentObj() + + # Call embryo editor + ret = self.editEmbryo() + if ret == 0: + return 0 + + # Geometry Editor + ret = self.selectGeometry() + if ret == 0: + return 0 + + ret = self.editGeometry() + if ret == 0: + return 0 + + return 1 + + def loadEmbryo(self): + + """Loads saved embryo object and adds it to currently selected molecule file. - newEmbryoButton = QtGui.QAction('New Embryo', self) - self.connect(newEmbryoButton, QtCore.SIGNAL('triggered()'), self.newEmbryo) - - removeEmbryoButton = QtGui.QAction('Remove Embryo', self) - self.connect(removeEmbryoButton, QtCore.SIGNAL('triggered()'), self.removeEmbryo) - - editEmbryoButton = QtGui.QAction('Edit Embryo', self) - self.connect(editEmbryoButton, QtCore.SIGNAL('triggered()'), self.editEmbryo) + Returns: + pyfrp.subclasses.pyfrp_embryo: Loaded embryo object. - loadEmbryoButton = QtGui.QAction('Load Embryo', self) - self.connect(loadEmbryoButton, QtCore.SIGNAL('triggered()'), self.loadEmbryo) + """ + + # Check if molecule or subnode selected + if not self.checkSelectedNode(): + return + + # Get filename + fnLoad = QtWidgets.QFileDialog.getOpenFileName( + self, "Open file", self.lastopen, "*.emb" + ) + + # Load and add to molecule + newEmbryo = pyfrp_misc_module.loadFromPickle(fnLoad) + self.currMolecule.addEmbryo(newEmbryo) + + # Append to object bar + newNode = self.embryo2ObjectBar(newEmbryo, self.currMoleculeNode) + self.objectBar.setCurrentItem(newNode) + self.getCurrentObj() + + return newEmbryo + + def editEmbryo(self): + + """Opens main embryo editing dialog. - selectGeometryButton = QtGui.QAction('Select Geometry', self) - self.connect(selectGeometryButton, QtCore.SIGNAL('triggered()'), self.selectGeometry) + Returns: + pyfrp.subclasses.pyfrp_embryo: Edited embryo object. - editGeometryButton = QtGui.QAction('Edit Geometry', self) - self.connect(editGeometryButton, QtCore.SIGNAL('triggered()'), self.editGeometry) + """ + + currEmbryoNode = self.getCurrentEmbryoNode() + currEmbryo = self.getCurrentEmbryo() + + if ( + self.checkSelectedNode(typ="molecule") + or self.objectBar.currentItem() == None + ): + return 0 + + ret = pyfrp_gui_embryo_dialogs.embryoDialog(currEmbryo, self).exec_() + + if ret == 0: + return 0 + + currEmbryoNode.setText(0, currEmbryo.name) + + self.updatePropBar() + + return 1 + + def removeEmbryo(self): + + """Removes selected embryo object both from molecule object as well as + main GUI. - editGeoFileButton = QtGui.QAction('Edit GeoFile', self) - self.connect(editGeoFileButton, QtCore.SIGNAL('triggered()'), self.editGeoFile) + Returns: + list: Updated pyfrp.subclasses.pyfrp_molecule.embryos list - drawGeometryButton = QtGui.QAction('Plot Geometry', self) - self.connect(drawGeometryButton, QtCore.SIGNAL('triggered()'), self.drawGeometry) + """ + + currEmbryoNode = self.getCurrentEmbryoNode() + currEmbryo = self.getCurrentEmbryo() + + if ( + self.checkSelectedNode(typ="molecule") + or self.objectBar.currentItem() == None + ): + return + + # Remove from list of embryo objects + self.currMolecule.embryos.remove(currEmbryo) + + # Remove from sidebar + ind = self.currMoleculeNode.indexOfChild(currEmbryoNode) + self.currMoleculeNode.takeChild(ind) + + self.objectBar.setCurrentItem(self.currMoleculeNode) + + self.updatePropBar() + + return self.currMolecule.embryos + + def checkObjNames(self): + + """Checks if molecules or embryos have the same name. - roiManagerButton = QtGui.QAction('ROI Manager', self) - self.connect(roiManagerButton, QtCore.SIGNAL('triggered()'), self.openROIManager) + Returns: + bool: True if there is a molecule/embryo with the same name. + """ + + b = False + + b = self.checkMolNames() + + for mol in self.molecules: + b = self.checkEmbryoNames(mol=mol) + + return b + + def checkMolNames(self): + + """Checks if molecules have the same name. - defaultROIButton = QtGui.QAction('Create Default ROIs', self) - self.connect(defaultROIButton, QtCore.SIGNAL('triggered()'), self.createDefaultROIs) + Returns: + bool: True if there is a molecule the same name. + """ + + b = False + + molNames = pyfrp_misc_module.objAttrToList(self.molecules, "name") + for name in molNames: + if molNames.count(name) > 1: + b = True + printWarning( + "Molecule with name " + + name + + " exists twice. This can lead to problems" + ) + + return b + + def checkEmbryoNames(self, mol=None): + + """#Checks if embryos have the same name. - defaultROIWizardButton = QtGui.QAction('Default ROIs Wizard', self) - self.connect(defaultROIWizardButton, QtCore.SIGNAL('triggered()'), self.defaultROIsWizard) + Returns: + bool: True if there is a embryo the same name. + """ + + mol = pyfrp_misc_module.assignIfVal(mol, self.currMolecule, None) + + b = False + + embryoNames = pyfrp_misc_module.objAttrToList(self.currMolecule.embryos, "name") + for name in embryoNames: + if embryoNames.count(name) > 1: + b = True + printWarning( + "Embryo with name " + + name + + " exists twice in molecule " + + mol.name + + ". This can lead to problems" + ) + + return b + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecWizards: Wizards + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def LSM2EmbryoWizard(self): + + """Opens :py:class:`pyfrp.gui.pyfrp_gui_embryo_dialogs.lsmWizard` which lets + one to extract and sort microscope files and then creates new + :py:class:`pyfrp.subclasses.pyfrp_embryo.embryo` including new data. - indexROIButton = QtGui.QAction('Update ROIs indices', self) - self.connect(indexROIButton, QtCore.SIGNAL('triggered()'), self.updateROIIdxs) + .. note:: Uses Fiji. Fiji path needs to be set properly for success. - self.mbEmbryo.addAction(newEmbryoButton) - self.mbEmbryo.addAction(editEmbryoButton) - self.mbEmbryo.addAction(loadEmbryoButton) - self.mbEmbryo.addAction(removeEmbryoButton) + """ + + lsmWizard = pyfrp_gui_embryo_dialogs.lsmWizard(self) + if lsmWizard.exec_(): + embryo = lsmWizard.getEmbryo() + if embryo == None: + return + + self.currMolecule.addEmbryo(embryo) + + newNode = self.embryo2ObjectBar(embryo, self.currMoleculeNode) + self.objectBar.setCurrentItem(newNode) + self.getCurrentObj() + + def openWizard(self): + + """Wizard for PyFRAP analysis. - self.geometryMB=self.mbEmbryo.addMenu('&Geometry') - self.geometryMB.addAction(selectGeometryButton) - self.geometryMB.addAction(editGeometryButton) - self.geometryMB.addAction(editGeoFileButton) - self.geometryMB.addAction(drawGeometryButton) + Leads user through following steps: - self.roiMB=self.mbEmbryo.addMenu('&ROIs') - self.roiMB.addAction(roiManagerButton) - self.roiMB.addAction(defaultROIButton) - self.roiMB.addAction(defaultROIWizardButton) - - self.roiMB.addAction(indexROIButton) - - return - - def initAnalysisMenubar(self): - - """Creates entries of analysis menubar and connects actions with gui methods. + * Embryo creation :py:func:`newEmbryo`. + * ROI creation :py:func:`createDefaultROIs`. + * ROI handling :py:func:`openROIManager`. + * Mesh generation :py:func:`generateMesh`. + * Data analysis :py:func:`analyzeEmbryo`. + * FRAP simulation :py:func:`simulateEmbryo`. + * Fit creation :py:func:`newFit`. + * Fit plotting :py:func:`plotFit`. + """ + + ret = self.newEmbryo() + if ret == 0: + return 0 + + ret = self.ROIWizardSelector() + if ret == 0: + return 0 + + ret = self.editGeometry() + if ret == 0: + return 0 + + self.getCurrentEmbryo().newSimulation() + ret = self.generateMesh() + if ret == 0: + return 0 + + self.updateROIIdxs() + ret = self.analyzeEmbryo() + if ret == 0: + return 0 + + ret = self.simulateEmbryo() + if ret == 0: + return 0 + + ret = self.newFit() + if ret == 0: + return 0 + + self.plotFit() + + return 1 + + def selectEmbryoGenMode(self): + + """Opens :py:class:`pyfrp.gui.pyfrp_gui_embryo_dialogs.wizardSelector` + and lets user select embryo generation mode. - editAnalysisButton = QtGui.QAction('Analysis Settings', self) - self.connect(editAnalysisButton, QtCore.SIGNAL('triggered()'), self.editAnalysis) - - analyzeEmbryoButton = QtGui.QAction('Analyze Embryo', self) - self.connect(analyzeEmbryoButton, QtCore.SIGNAL('triggered()'), self.analyzeEmbryo) - - plotEmbryoAnalysisButton = QtGui.QAction('Plot Analysis Result of Embryo', self) - self.connect(plotEmbryoAnalysisButton, QtCore.SIGNAL('triggered()'), self.plotAllDataTSOfEmbryo) - - self.mbAnalysis.addAction(editAnalysisButton) - self.runAnalysisMB=self.mbAnalysis.addMenu('&Run Analysis') - self.runAnalysisMB.addAction(analyzeEmbryoButton) - - - self.plotAnalysisMB=self.mbAnalysis.addMenu('&Plotting') - self.plotAnalysisMB.addAction(plotEmbryoAnalysisButton) - - return - - def initSimulationMenubar(self): + Returns: + int: 1 if user chose from microscope, 0 if not, -1 else. - """Creates entries of simulation menubar and connects actions with gui methods. """ + + selectWizard = pyfrp_gui_embryo_dialogs.wizardSelector(self) + if selectWizard.exec_(): + useLSM = selectWizard.getUseLSM() + if useLSM == None: + return -1 + + if useLSM: + ret = self.LSM2EmbryoWizard() + if ret == 0: + return -1 + + return 1 + return 0 + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecEmbryo: Embryo Menubar Methods + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def openROIManager(self): + + """Open ROI Manager for current embryo. - editSimulationButton = QtGui.QAction('Simulation Settings', self) - self.connect(editSimulationButton, QtCore.SIGNAL('triggered()'), self.editSimulation) - - simulateEmbryoButton = QtGui.QAction('Simulate Embryo', self) - self.connect(simulateEmbryoButton, QtCore.SIGNAL('triggered()'), self.simulateEmbryo) + Returns: + int: Dialog Code (0 when cancelled, 1 when accepted.) + """ + + currEmbryo = self.getCurrentEmbryo() + if currEmbryo != None: + ret = pyfrp_gui_ROI_manager.ROImanager(currEmbryo, self).exec_() + + if ret == 0: + return ret + elif ret == 1: + self.updateROIsNodeChildren() + return ret + return 0 + + def createDefaultROIs(self): + + """Create default ROIs for current embryo. - editMeshButton = QtGui.QAction('Mesh Settings', self) - self.connect(editMeshButton, QtCore.SIGNAL('triggered()'), self.editMesh) + Returns: + int: Dialog Code (0 when cancelled, 1 when accepted.) + """ + + currEmbryo = self.getCurrentEmbryo() + if currEmbryo != None: + ret = pyfrp_gui_ROI_manager.defaultROIsDialog(currEmbryo, self).exec_() + if ret == 0: + return ret + elif ret == 1: + self.updateROIsNodeChildren() + return ret + return 0 + + def ROIWizardSelector(self): + + """Lets the user select between the createDefaultROIs, defaultROIsWizard or ROImanager. - genMeshButton = QtGui.QAction('Generate Mesh', self) - self.connect(genMeshButton, QtCore.SIGNAL('triggered()'), self.generateMesh) + Opens :py:class:`pyfrp.gui.pyfrp_gui_ROI_manager.wizardSelector` + and lets user select ROI generation mode. - refineMeshButton = QtGui.QAction('Refine Mesh', self) - self.connect(refineMeshButton, QtCore.SIGNAL('triggered()'), self.refineMesh) + Launches the right wizard afterwards. - addBoundaryLayerMeshAroundROIButton = QtGui.QAction('Add boundary layer around ROI', self) - self.connect(addBoundaryLayerMeshAroundROIButton, QtCore.SIGNAL('triggered()'), self.addBoundaryLayerMeshAroundROI) + Returns: + int: 0 when default, 1 for wizard and 2 for manager - forceMeshButton = QtGui.QAction('Force Mesh Density', self) - self.connect(forceMeshButton, QtCore.SIGNAL('triggered()'), self.forceMeshDensity) + """ + + selectWizard = pyfrp_gui_ROI_manager.wizardSelector(self) + if selectWizard.exec_(): + mode = selectWizard.getMode() + + print("mode is", mode) + + if mode == None: + return 0 + + if mode == 0: + ret = self.createDefaultROIs() + elif mode == 1: + ret = self.defaultROIsWizard() + elif mode == 2: + ret = self.openROIManager() + + return ret + + return 0 + + def defaultROIsWizard(self): + + """Small Wizard that helps creating a set of default ROIs for current embryo. - forceROIMeshButton = QtGui.QAction('Refine Mesh in ROI', self) - self.connect(forceROIMeshButton, QtCore.SIGNAL('triggered()'), self.forceROIMeshDensity) + Returns: + int: Dialog Code (0 when cancelled, 1 when accepted.) + """ + + currEmbryo = self.getCurrentEmbryo() + if currEmbryo == None: + return 0 + + # Select Slice ROI + sliceSelector = pyfrp_gui_ROI_manager.ROISelector( + currEmbryo, + "radialSlice", + self, + msg="Select Slice ROI", + sliceHeight=currEmbryo.sliceHeightPx, + sliceWidth=currEmbryo.sliceWidthPx, + color="g", + name="Slice", + ) + if sliceSelector.exec_(): + sliceROI = sliceSelector.getROI() + + # Select Bleached ROI + squSelector = pyfrp_gui_ROI_manager.ROISelector( + currEmbryo, + "squareSlice", + self, + msg="Select Bleached ROI", + sliceHeight=currEmbryo.sliceHeightPx, + sliceWidth=currEmbryo.sliceWidthPx, + color="b", + name="Bleached Square", + ) + if squSelector.exec_(): + bleachedROI = squSelector.getROI() + + # Select Rim ROI + if hasattr(sliceROI, "radius"): + radius = sliceROI.radius * 0.66 + center = sliceROI.center + rimSelector = pyfrp_gui_ROI_manager.ROISelector( + currEmbryo, + "radialSlice", + self, + msg="Select Rim ROI", + radius=radius, + center=center, + sliceHeight=currEmbryo.sliceHeightPx, + sliceWidth=currEmbryo.sliceWidthPx, + color="y", + name="Slice rim", + ) + else: + radius = 133.0 + rimSelector = pyfrp_gui_ROI_manager.ROISelector( + currEmbryo, + "radialSlice", + self, + msg="Select Rim ROI", + radius=radius, + sliceHeight=currEmbryo.sliceHeightPx, + sliceWidth=currEmbryo.sliceWidthPx, + color="y", + name="Slice rim", + ) + + if rimSelector.exec_(): + rimROI = rimSelector.getROI() + + # Build default ROIs + radius = 300.0 + center = [256.0, 256.0] + if hasattr(sliceROI, "radius"): + radius = sliceROI.radius + center = sliceROI.center + else: + if currEmbryo.geometry != None: + if hasattr(currEmbryo.geometry, "imagingRadius"): + radius = currEmbryo.geometry.imagingRadius + else: + if hasattr(currEmbryo.geometry, "radius"): + radius = currEmbryo.geometry.radius + + currEmbryo.genDefaultROIs( + center, + radius, + rimFactor=0.66, + masterROI=sliceROI, + bleachedROI=bleachedROI, + rimROI=rimROI, + clean=True, + ) + + self.updateROIsNodeChildren() + + return 1 + + def updateROIIdxs(self): + + """Updates all ROI Idxs.""" + + currEmbryo = self.getCurrentEmbryo() + + if currEmbryo != None: + + # Genereate wait popup + self.progressDialog = pyfrp_gui_ROI_manager.indexProgressDialog(None) + + # Make backup copy of embryo + self.originalObj = currEmbryo + self.backupObj = cpy.deepcopy(currEmbryo) + + self.statusBar().showMessage("Indexing ROIs of embryo " + currEmbryo.name) + + # Generate worker and generate Qthread + self.task = pyfrp_gui_basics.pyfrpThread() + self.worker = pyfrp_gui_basics.pyfrpWorker( + currEmbryo.computeROIIdxs, signal=self.task.progressSignal + ) + + # Start + self.initTask() + else: + return 0 + + return 1 + + def selectGeometry(self): + + """Open Geometry Editor for current embryo.""" + + currEmbryo = self.getCurrentEmbryo() + + if currEmbryo != None: + ret = pyfrp_gui_geometry_dialogs.geometrySelectDialog( + currEmbryo, self + ).exec_() + else: + return 0 + + return ret + + def editGeometry(self): + + """Open Geometry Editor for current embryo.""" + + currEmbryo = self.getCurrentEmbryo() + + if currEmbryo != None: + if "zebrafishDomeStage" in currEmbryo.geometry.typ: + ret = pyfrp_gui_geometry_dialogs.zebrafishDomeStageDialog( + currEmbryo.geometry, self + ).exec_() + elif "cylinder" in currEmbryo.geometry.typ: + ret = pyfrp_gui_geometry_dialogs.cylinderDialog( + currEmbryo.geometry, self + ).exec_() + elif "xenopusBall" in currEmbryo.geometry.typ: + ret = pyfrp_gui_geometry_dialogs.xenopusBallDialog( + currEmbryo.geometry, self + ).exec_() + elif "cone" in currEmbryo.geometry.typ: + ret = pyfrp_gui_geometry_dialogs.coneDialog( + currEmbryo.geometry, self + ).exec_() + else: + ret = pyfrp_gui_geometry_dialogs.geometryDialog( + currEmbryo.geometry, self + ).exec_() + + return ret + + return 0 + + def editGeoFile(self): + + """Open Geometry Editor for current embryo.""" + + currEmbryo = self.getCurrentEmbryo() + if currEmbryo != None: + ret = pyfrp_gui_gmsh_editor.gmshFileEditor( + currEmbryo.geometry, self + ).exec_() + + return ret + + def drawGeometry(self, ann=False): + + """Draw Geometry in plot tab.""" + + currEmbryo = self.getCurrentEmbryo() + if currEmbryo != None: + self.createPlotTab("xyz", plotName="Geometry", proj=["3d"]) + currEmbryo.geometry.plotGeometry(ax=self.ax, ann=ann) + self.adjustCanvas() + return + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecAnalysis: Analysis handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def editAnalysis(self): + + """Edit Analysis Settings.""" + + currEmbryo = self.getCurrentEmbryo() + if currEmbryo != None: + if currEmbryo.analysis == None: + currEmbryo.newAnalysis() + + ret = pyfrp_gui_analysis_dialogs.analysisDialog( + currEmbryo.analysis, self + ).exec_() + else: + return 0 + + return ret + + def analyzeEmbryo(self): + + """Analyze embryo task/progressbar.""" + + # Grab embryo + currEmbryo = self.getCurrentEmbryo() + if currEmbryo == None: + return 0 + + # Launching Dialog + ret = self.editAnalysis() + if ret == 0: + return 0 + + # Genereate wait popup + self.progressDialog = pyfrp_gui_analysis_dialogs.analysisProgressDialog(None) + + # Make backup copy of embryo + self.originalObj = currEmbryo + self.backupObj = cpy.deepcopy(currEmbryo) + + self.statusBar().showMessage("Analyzing Dataset " + currEmbryo.name) + + # Generate Qthread and pass analysis there + self.task = pyfrp_gui_basics.pyfrpThread() + self.worker = pyfrp_gui_basics.pyfrpWorker( + currEmbryo.analysis.run, signal=self.task.progressSignal + ) + + # Init and start + self.initTask() + + return 1 + + def plotAllDataTSOfEmbryo(self): + + """Plots data analysis results of all ROIs of embryo.""" + + currEmbryo = self.getCurrentEmbryo() + + if currEmbryo == None: + return + + self.createPlotTab( + "intensityTS", plotName=currEmbryo.name + " data", size=[1, 1] + ) + currEmbryo.plotAllData(ax=self.ax) + + self.adjustCanvas() + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecSimulation: Simulation handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def editSimulation(self): + + """Edit Simulation Settings.""" + + currEmbryo = self.getCurrentEmbryo() + if currEmbryo != None: + if currEmbryo.simulation == None: + currEmbryo.newSimulation() + + ret = pyfrp_gui_simulation_dialogs.simulationSettingsDialog( + currEmbryo.simulation, self + ).exec_() + + else: + return 0 + + return ret + + def simulateEmbryo(self): + + """Simulate embryo task/progressbar.""" + + # Grab embryo + currEmbryo = self.getCurrentEmbryo() + if currEmbryo == None: + return 0 + + # Launching Dialog + ret = self.editSimulation() + if ret == 0: + return 0 + + # Genereate wait popup + self.progressDialog = pyfrp_gui_simulation_dialogs.simulationProgressDialog( + None + ) + + # Make backup copy of embryo + self.originalObj = currEmbryo + self.backupObj = cpy.deepcopy(currEmbryo) + + self.statusBar().showMessage("Simulating Dataset " + currEmbryo.name) + + # Generate Qthread and pass analysis there + self.task = pyfrp_gui_basics.pyfrpThread() + self.worker = pyfrp_gui_basics.pyfrpWorker( + currEmbryo.simulation.run, signal=self.task.progressSignal + ) + + # Init and start + self.initTask() + + return 1 + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecMesh: Mesh handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def editMesh(self): + + """Edit Mesh Settings. - printMeshButton = QtGui.QAction('Mesh Stats', self) - self.connect(printMeshButton, QtCore.SIGNAL('triggered()'), self.printMeshStats) + Launches :py:class:`pyfrp.gui.pyfrp_gui_mesh_dialogs.meshSettingsDialog` and lets user define standard mesh properties. - plotMeshButton = QtGui.QAction('Plot Mesh', self) - self.connect(plotMeshButton, QtCore.SIGNAL('triggered()'), self.plotMesh) + """ + currEmbryo = self.getCurrentEmbryo() + if currEmbryo != None: + if currEmbryo.simulation == None: + currEmbryo.newSimulation() + ret = pyfrp_gui_mesh_dialogs.meshSettingsDialog( + currEmbryo.simulation.mesh, self + ).exec_() + return ret + + else: + return 0 + + def generateMesh(self): + + """Generate Mesh. - plotMeshDensityButton = QtGui.QAction('Plot Mesh Density', self) - self.connect(plotMeshDensityButton, QtCore.SIGNAL('triggered()'), self.plotMeshDensity) + Does this via submitting mesh generation to a seperate `QThread`. Meanwhile displays + :py:class:`pyfrp.gui.pyfrp_gui_mesh_dialogs.genMeshProgressDialog`. - plotSimButton = QtGui.QAction('Plot Simulation', self) - self.connect(plotSimButton, QtCore.SIGNAL('triggered()'), self.plotAllSimTSOfEmbryo) + Prints out mesh statistics at the end. - plotSimAndDataButton = QtGui.QAction('Plot Simulaten & Data', self) - self.connect(plotSimAndDataButton, QtCore.SIGNAL('triggered()'), self.plotAllSimAndDataTSOfEmbryo) + """ + + # Grab embryo + currEmbryo = self.getCurrentEmbryo() + if currEmbryo == None: + return 0 + + # Launching Dialog + ret = self.editMesh() + if ret == 0: + return 0 + + # Genereate wait popup + # self.progressDialog=pyfrp_gui_mesh_dialogs.genMeshProgressDialog(None) + + ##Make backup copy of embryo + # self.originalObj=currEmbryo + # self.backupObj=cpy.deepcopy(currEmbryo) + + # self.statusBar().showMessage("Generating Mesh " + currEmbryo.name) + + ##Generate Qthread and pass analysis there + # self.task=pyfrp_gui_basics.pyfrpThread() + # self.worker=pyfrp_gui_basics.pyfrpWorker(currEmbryo.simulation.mesh.genMesh) + printNote("Generating Mesh... This can take a few seconds...") + currEmbryo.simulation.mesh.genMesh() + + # Print out mesh stats + self.printMeshStats() + + # Init and start + # self.initTask() + + return 1 + + def refineMesh(self): + + """Refine Mesh by tetrahedron splitting. + Submits py:func:`pyfrp.subclasses.pyfrp_mesh.mesh.refine` to a seperate QThread. + Meanwhile displays :py:class:`pyfrp.gui.pyfrp_gui_mesh_dialogs.refineMeshProgressDialog`. - self.mbSimulation.addAction(editSimulationButton) - self.runSimulationMB=self.mbSimulation.addMenu('&Run Simulation') - self.runSimulationMB.addAction(simulateEmbryoButton) + """ + + # Grab embryo + currEmbryo = self.getCurrentEmbryo() + if currEmbryo == None: + return 0 + + # Genereate wait popup + self.progressDialog = pyfrp_gui_mesh_dialogs.refineMeshProgressDialog(None) + + # Make backup copy of embryo + self.originalObj = currEmbryo + self.backupObj = cpy.deepcopy(currEmbryo) + + self.statusBar().showMessage("Refining Mesh " + currEmbryo.name) + + # Generate Qthread and pass analysis there + self.task = pyfrp_gui_basics.pyfrpThread() + self.worker = pyfrp_gui_basics.pyfrpWorker(currEmbryo.simulation.mesh.refine) + + # Init and start + self.initTask() + + return 1 + + def forceMeshDensity(self): + + """Force Mesh to have given density globally. - self.meshSimulationMB=self.mbSimulation.addMenu('&Mesh') - self.meshSimulationMB.addAction(editMeshButton) - self.meshSimulationMB.addAction(genMeshButton) - self.meshSimulationMB.addAction(refineMeshButton) - self.meshSimulationMB.addAction(forceMeshButton) - self.meshSimulationMB.addAction(forceROIMeshButton) - self.meshSimulationMB.addAction(addBoundaryLayerMeshAroundROIButton) - self.meshSimulationMB.addAction(printMeshButton) - self.meshSimulationMB.addAction(plotMeshButton) - self.meshSimulationMB.addAction(plotMeshDensityButton) + Submits py:func:`pyfrp.subclasses.pyfrp_mesh.mesh.refine` to a seperate QThread. + Meanwhile displays :py:class:`pyfrp.gui.pyfrp_gui_mesh_dialogs.refineMeshProgressDialog`. + """ + + # Grab embryo + currEmbryo = self.getCurrentEmbryo() + if currEmbryo == None: + return 0 + + # Get options + forceMeshDialog = pyfrp_gui_mesh_dialogs.forceMeshSettingsDialog( + currEmbryo.simulation.mesh, self + ) + if forceMeshDialog.exec_(): + roiUsed, density, stepPercentage, debug, findIdxs, method, maxCells = ( + forceMeshDialog.getVals() + ) + + # Genereate wait popup + self.progressDialog = pyfrp_gui_mesh_dialogs.forceMeshProgressDialog(None) + + # Make backup copy of embryo + self.originalObj = currEmbryo + self.backupObj = cpy.deepcopy(currEmbryo) + + self.statusBar().showMessage( + "Computing new mesh with required density " + currEmbryo.name + ) + + # Generate Qthread and pass analysis there + self.task = pyfrp_gui_basics.pyfrpThread() + self.worker = pyfrp_gui_basics.pyfrpWorker( + currEmbryo.simulation.mesh.forceMinMeshDensityInROI, + roiUsed, + density, + stepPercentage, + debug=debug, + findIdxs=findIdxs, + method=method, + maxCells=maxCells, + ) + + # Init and start + self.initTask() + + return 1 + + def forceROIMeshDensity(self): + + """Force Mesh to have given density in ROI. + See also :py:class:`pyfrp.gui.pyfrp_gui_mesh_dialogs.refineROIMeshSettingsDialog`. - self.plotSimulationMB=self.mbSimulation.addMenu('&Plotting') - self.plotSimulationMB.addAction(plotSimButton) - self.plotSimulationMB.addAction(plotSimAndDataButton) + """ - def initPinningMenubar(self): - - """Creates entries of pinning menubar and connects actions with gui methods. + # Grab embryo + currEmbryo = self.getCurrentEmbryo() + if currEmbryo == None: + return 0 + + # Get options + ret = pyfrp_gui_mesh_dialogs.refineROIMeshSettingsDialog( + currEmbryo.simulation.mesh, self + ).exec_() + + return ret + + def printMeshStats(self): + + """Prints out mesh statistics.""" + + # Grab embryo + currEmbryo = self.getCurrentEmbryo() + if currEmbryo == None: + return 0 + + currEmbryo.simulation.mesh.printStats() + + def plotMesh(self): + + """Plots mesh of selected embryo. """ + + # Grab embryo + currEmbryo = self.getCurrentEmbryo() + if currEmbryo == None: + QtWidgets.QMessageBox.critical( + None, + "Error", + "No embryo selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return + + # try: + self.renderer = currEmbryo.simulation.mesh.plotMesh(renderWindow=1) + # except AttributeError: + # QtWidgets.QMessageBox.critical(None, "Error","Embryo has no simulation or mesh yet.",QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default) + + self.createVtkTab() + + self.vtkCanvas.GetRenderWindow().AddRenderer(self.renderer) + self.vtkCanvas.GetRenderWindow().GetInteractor().Initialize() + + def plotMeshDensity(self): + + """Plots mesh density in x/y/z direction.""" + + currEmbryo = self.getCurrentEmbryo() + if currEmbryo == None: + return + + self.createPlotTab( + "meshDensity", plotName=currEmbryo.name + " mesh density", size=[2, 2] + ) + + currEmbryo.simulation.mesh.plotDensity(axes=self.axes) + + def addBoundaryLayerMeshAroundROI(self): + + """Adds boundary layer around ROI. - defaultPinButton = QtGui.QAction('Default Pinning', self) - self.connect(defaultPinButton, QtCore.SIGNAL('triggered()'), self.defaultPinEmbryo) - - idealPinButton = QtGui.QAction('Ideal Pinning', self) - self.connect(idealPinButton, QtCore.SIGNAL('triggered()'), self.idealPinEmbryo) - - self.mbPinning.addAction(defaultPinButton) - self.mbPinning.addAction(idealPinButton) - - def initFittingMenubar(self): - - """Creates entries of fitting menubar and connects actions with gui methods. """ + + currEmbryo = self.getCurrentEmbryo() + if currEmbryo == None: + return + + dialog = pyfrp_gui_mesh_dialogs.boundaryLayerAroundROISettingsDialog( + currEmbryo, self + ) + if dialog.exec_(): + fnOut, roiUsed, segments, simplify, iterations, triangIterations, fixSurfaces, debug, volSizePx, thickness, volSizeLayer, cleanUp, approxBySpline, angleThresh, faces, onlyAbs = ( + dialog.getVals() + ) + + # Genereate wait popup + self.progressDialog = pyfrp_gui_mesh_dialogs.boundaryLayerProgressDialog(None) + + # Make backup copy of embryo + self.originalObj = currEmbryo + self.backupObj = cpy.deepcopy(currEmbryo) + + self.statusBar().showMessage( + "Computing new mesh with required density " + currEmbryo.name + ) + + # Generate Qthread and pass analysis there + self.task = pyfrp_gui_basics.pyfrpThread() + + # For now don't submit to QThread and see how it works out. + self.worker = pyfrp_gui_basics.pyfrpWorker( + currEmbryo.simulation.mesh.addBoundaryLayerAroundROI, + roiUsed, + fnOut=fnOut, + segments=segments, + simplify=simplify, + iterations=iterations, + triangIterations=triangIterations, + fixSurfaces=fixSurfaces, + debug=debug, + volSizePx=volSizePx, + volSizeLayer=volSizeLayer, + thickness=thickness, + cleanUp=cleanUp, + approxBySpline=approxBySpline, + angleThresh=angleThresh, + faces=faces, + onlyAbs=onlyAbs, + ) + + # Init and start + self.initTask() + + def plotAllSimTSOfEmbryo(self): + + """Plots simulation results of all ROIs of embryo.""" + + currEmbryo = self.getCurrentEmbryo() + + if currEmbryo == None: + return + + self.createPlotTab( + "intensityTS", plotName=currEmbryo.name + " data", size=[1, 1] + ) + currEmbryo.plotAllSim(ax=self.ax) + + self.adjustCanvas() + + def plotAllSimAndDataTSOfEmbryo(self): + + """Plots simulation results of all ROIs of embryo.""" + + currEmbryo = self.getCurrentEmbryo() + + if currEmbryo == None: + return + + self.createPlotTab( + "intensityTS", plotName=currEmbryo.name + " data", size=[1, 1] + ) + currEmbryo.plotAllData(ax=self.ax) + currEmbryo.plotAllSim(ax=self.ax) + + self.adjustCanvas() + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecPinning: Pinning handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def defaultPinEmbryo(self): + + """Default Pinning. - newFitButton = QtGui.QAction('New fit', self) - self.connect(newFitButton, QtCore.SIGNAL('triggered()'), self.newFit) - - removeFitButton = QtGui.QAction('Remove fit', self) - self.connect(removeFitButton, QtCore.SIGNAL('triggered()'), self.removeFit) + Lets the user selected his/her pinning options themself by launching + :py:class:`pyfrp.gui.pyfrp_gui_pinning_dialogs.defaultPinningDialog`. - editFitButton = QtGui.QAction('Edit fit', self) - self.connect(editFitButton, QtCore.SIGNAL('triggered()'), self.editFit) - #editmultfit = QtGui.QAction('Edit multiple fits', self) - #self.connect(editmultfit, QtCore.SIGNAL('triggered()'), self.edit_mult_fit) + """ + + currEmbryo = self.getCurrentEmbryo() + + if currEmbryo == None: + QtWidgets.QMessageBox.critical( + None, + "Error", + "No embryo selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + # Launch dialog + ret = pyfrp_gui_pinning_dialogs.defaultPinningDialog(currEmbryo, self).exec_() + + return ret + + def idealPinEmbryo(self): + + """Ideal Pinning. - #copyfit = QtGui.QAction('Copy fit', self) - #self.connect(copyfit, QtCore.SIGNAL('triggered()'), self.copy_fit) + Lets the user select some options for ideal pinning via + :py:class:`pyfrp.gui.pyfrp_gui_pinning_dialogs.idealPinningDialog`. - #copyfitforall = QtGui.QAction('Copy fit into all embryos', self) - #self.connect(copyfitforall, QtCore.SIGNAL('triggered()'), self.copy_fit_to_all) - - performFitButton = QtGui.QAction('Perform fit', self) - self.connect(performFitButton, QtCore.SIGNAL('triggered()'), self.performFit) - - - #fitall = QtGui.QAction('Perform all fits in molecule', self) - #self.connect(fitall, QtCore.SIGNAL('triggered()'), self.perform_fits_molecule) - - plotFitButton = QtGui.QAction('Plot fit', self) - self.connect(plotFitButton, QtCore.SIGNAL('triggered()'), self.plotFit) - - #plottrackfit = QtGui.QAction('Plot fitting progress', self) - #self.connect(plottrackfit, QtCore.SIGNAL('triggered()'), self.plot_track_fit) - - printFitButton = QtGui.QAction('Print fit results', self) - self.connect(printFitButton, QtCore.SIGNAL('triggered()'), self.printFitResults) - - - self.mbFitting.addAction(newFitButton) - self.mbFitting.addAction(editFitButton) - self.mbFitting.addAction(removeFitButton) - self.mbFitting.addAction(performFitButton) - self.mbFitting.addAction(printFitButton) - - self.plotFittingMB=self.mbFitting.addMenu('&Plotting') - self.plotFittingMB.addAction(plotFitButton) - - return - - def initStatsMenubar(self): - - """Creates entries of statistics menubar and connects actions with gui methods. - """ - - selectFitsButton = QtGui.QAction('Select Fits', self) - self.connect(selectFitsButton, QtCore.SIGNAL('triggered()'), self.selectFits) - - selectCrucialParametersButton = QtGui.QAction('Select CrucialParameters', self) - self.connect(selectCrucialParametersButton, QtCore.SIGNAL('triggered()'), self.selectCrucialParameters) - - summarizeMoleculeButton = QtGui.QAction('Summarize Molecule', self) - self.connect(summarizeMoleculeButton, QtCore.SIGNAL('triggered()'), self.summarizeMolecule) - - tTest = QtGui.QAction('Perform standard t-test', self) - self.connect(tTest, QtCore.SIGNAL('triggered()'), self.performtTest) - - tTestWelch = QtGui.QAction('Perform Welchs t-test', self) - self.connect(tTestWelch, QtCore.SIGNAL('triggered()'), self.performtTestWelch) - - wilcoxonTest = QtGui.QAction('Perform Wilcoxon test', self) - self.connect(wilcoxonTest, QtCore.SIGNAL('triggered()'), self.performWilcoxon) - - mannWhitneyUTest = QtGui.QAction('Perform Mann-Whitney-U test', self) - self.connect(mannWhitneyUTest, QtCore.SIGNAL('triggered()'), self.performMannWhitneyUTest) - - shapiroTest = QtGui.QAction('Perform Shaprio test', self) - self.connect(shapiroTest, QtCore.SIGNAL('triggered()'), self.performShapiroTest) - - AIC = QtGui.QAction('Perform Akaike Information Criterion', self) - self.connect(AIC, QtCore.SIGNAL('triggered()'), self.performAIC) - - - self.mbStatistics.addAction(selectFitsButton) - self.mbStatistics.addAction(selectCrucialParametersButton) - self.mbStatistics.addAction(summarizeMoleculeButton) - - self.statisticsTestMB=self.mbStatistics.addMenu('&Tests') - self.statisticsTestMB.addAction(tTest) - self.statisticsTestMB.addAction(tTestWelch) - self.statisticsTestMB.addAction(wilcoxonTest) - self.statisticsTestMB.addAction(mannWhitneyUTest) - self.statisticsTestMB.addAction(shapiroTest) - - self.statisticsComparisonMB=self.mbStatistics.addMenu('&Model comparison') - self.statisticsComparisonMB.addAction(AIC) - - - - #def initPlottingMenubar(self): - - #"""Creates entries of statistics menubar and connects actions with gui methods. - #""" - - #newMPLTabButton = QtGui.QAction('New Matplotlib tab', self) - #self.connect(newMPLTabButton, QtCore.SIGNAL('triggered()'), self.createPlotTab) - - #newVTKTabButton = QtGui.QAction('New Matplotlib tab', self) - #self.connect(newVTKTabButton, QtCore.SIGNAL('triggered()'), self.createVtkTab) - - #self.newTabMB=self.mbPlotting.addMenu('&New Tab') - #self.newTabMB.addAction(newMPLTabButton) - #self.newTabMB.addAction(newVTKTabButton) - - #showImgIndButton = QtGui.QAction('Show image indices', self) - #self.connect(showImgIndButton, QtCore.SIGNAL('triggered()'), self.showROIImgIdx) - - #showMeshIndButton = QtGui.QAction('Show mesh indices', self) - #self.connect(showImgIndButton, QtCore.SIGNAL('triggered()'), self.showROIMeshIdx) - - #showExtIndButton = QtGui.QAction('Show extended indices', self) - #self.connect(showExtIndButton, QtCore.SIGNAL('triggered()'), self.showROIExtIdx) - - #showROIIndButton = QtGui.QAction('Show all indices', self) - #self.connect(showROIIndButton, QtCore.SIGNAL('triggered()'), self.showROIIdx) - - #showROIBoundButton = QtGui.QAction('Show ROI boundaries', self) - #self.connect(showROIBoundButton, QtCore.SIGNAL('triggered()'), self.showROIBoundaries) - - #showROIBoundButton = QtGui.QAction('Show all ROI boundaries', self) - #self.connect(showROIBoundButton, QtCore.SIGNAL('triggered()'), self.showAllROIBoundaries) - - #self.embryoPlotMB=self.mbPlotting.addMenu('&Embryo') - #self.ROIPlotMB=self.embryoPlotMB.addMenu('&ROI') - - - - - - #self.geomPlotMB=self.embryoPlotMB.addMenu('&Geometry') - #self.analysisPlotMB=self.embryoPlotMB.addMenu('&Analysis') - #self.simulationPlotMB=self.embryoPlotMB.addMenu('&Simulation') - #self.fittingPlotMB=self.embryoPlotMB.addMenu('&Fitting') - #self.statisticsPlotMB=self.embryoPlotMB.addMenu('&Statistics') - - def initSettingsMenubar(self): - - """Creates entries of settings menubar and connects actions with gui methods. - """ - - setPathFileButton = QtGui.QAction('Set Path File', self) - self.connect(setPathFileButton, QtCore.SIGNAL('triggered()'), self.setPathFile) - - setGmshButton = QtGui.QAction('Set Gmsh Path', self) - self.connect(setGmshButton, QtCore.SIGNAL('triggered()'), self.setGmshPath) - - setFijiButton = QtGui.QAction('Set Fiji Path', self) - self.connect(setFijiButton, QtCore.SIGNAL('triggered()'), self.setFijiPath) - - setOpenscadButton = QtGui.QAction('Set Openscad Path', self) - self.connect(setOpenscadButton, QtCore.SIGNAL('triggered()'), self.setOpenscadPath) - - printPathsButton = QtGui.QAction('Print Paths', self) - self.connect(printPathsButton, QtCore.SIGNAL('triggered()'), self.printPaths) - - printPathFileButton = QtGui.QAction('Print Path File Location', self) - self.connect(printPathFileButton, QtCore.SIGNAL('triggered()'), self.printPathFile) - - checkPathsButton = QtGui.QAction('Check paths in path file', self) - self.connect(checkPathsButton, QtCore.SIGNAL('triggered()'), self.checkPaths) - - self.mbSettings.addAction(setPathFileButton) - self.mbSettings.addAction(setGmshButton) - self.mbSettings.addAction(setFijiButton) - self.mbSettings.addAction(setOpenscadButton) - self.mbSettings.addAction(printPathsButton) - self.mbSettings.addAction(printPathFileButton) - self.mbSettings.addAction(checkPathsButton) - - def closeEvent(self, event): - - """Closes GUI and saves configuration. - - Args: - event (QtCore.closeEvent): Close event triggered by close signal. - - """ - - reply = QtGui.QMessageBox.question(self, 'Message',"Are you sure you want to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) - - if reply == QtGui.QMessageBox.Yes: - fn=pyfrp_misc_module.getConfDir()+"lastConfiguration.conf" - self.config.consoleHistory=self.console.history - self.config.backupPathFile() - self.config.save(fn=fn) - - javabridge.kill_vm() - - event.accept() - else: - event.ignore() - - return - - #def show_about(self): - - #ret=pyfrp_subwin.about_dialog(self).exec_() - - - def createEmptyFrame(self,frame): - - """Creates frame around widget. - - Args: - frame (QtGui.QWidget): Widget to be framed - - Returns: - QtGui.QWidget: Framed Widget - - """ - - frame.setFrameStyle(QtGui.QFrame.StyledPanel) - frame.setBackgroundRole(QtGui.QPalette.Light) - frame.setAutoFillBackground(True) - frame.setLineWidth(1) - frame.setFrameShadow(frame.Sunken) - - return frame - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecConfig: Configuration handling - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - def initConfiguration(self): - - """Initialize Configuration from file. - - Does this by: - - * Loading config file. - * Updating history - * Calling :py:func:`updateConfig`. - - """ - - fn=pyfrp_misc_module.getConfDir()+"lastConfiguration.conf" - - if os.path.isfile(fn): - self.config=pyfrp_IO_module.loadFromPickle(fn) - else: - self.config=pyfrp_conf.configuration() - - self.console.history=list(self.config.consoleHistory) - - self.updateConfig() - - return self.config - - def updateConfig(self): - - """Update configuration of GUI to match with config. - - That is: - - * hide/show parts of GUI. - * Update recently opened files menubar. - * Update Path file. - - """ - - self.console.setHidden(self.config.termHidden) - self.propBar.setHidden(self.config.propHidden) - self.plotTabs.setHidden(self.config.plotHidden) - - self.verticalSplitter.refresh() - self.horizontalSplitter.refresh() - #self.adjustCanvas() - - self.updateRecentMBs() - - self.config.copyPathFileToDefaultLocation() - - return self.config - - def appendRecent(self,fn): - - """Makes filename the most recently opened file, adds it to config.recentFiles and updates menubar. - - Args: - fn (str): Some filename. - """ - - self.config.addRecentFile(fn) - self.recentMB.clear() - self.updateRecentMBs() - - return self.recentMB - - def updateRecentMBs(self): - - """Updates recently opened menubar. - - Loops through current loaded configuration ``config.recentFiles`` and appends the 5 newest entries to - ``self.recentActions``. """ - - self.recentActions=[] - - for i in range(len(self.config.recentFiles)): - if i>5: - self.config.recentFiles.pop(i) - else: - self.recentActions.append(QtGui.QAction(self.config.recentFiles[i], self)) - item=self.recentActions[i] - item.triggered.connect(functools.partial(self.openMolecule,pyfrp_misc_module.fixPath(self.config.recentFiles[i]))) - - self.recentMB.addAction(item) - - return self.recentMB - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #secObjectBar: Object Bar handling - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - def highlightCurrentObjectNode(self): - - """Highlists the currently used Node of the objectBar. - """ - - self.objectBar.setCurrentItem(self.currNode) - return self.objectBar - - def checkSelectedNode(self,typ="any"): - - """Checks if the current selected node is of certain type and returns respective error popups + currEmbryo = self.getCurrentEmbryo() + + if currEmbryo == None: + QtWidgets.QMessageBox.critical( + None, + "Error", + "No embryo selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + # Launch dialog + ret = pyfrp_gui_pinning_dialogs.idealPinningDialog(currEmbryo, self).exec_() + + return ret + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecFit: Fit handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def newFit(self): + + """Creates new fit.""" + + currEmbryo = self.getCurrentEmbryo() + + if currEmbryo == None: + QtWidgets.QMessageBox.critical( + None, + "Error", + "No embryo selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + # Generate name + fitNames = pyfrp_misc_module.objAttrToList(currEmbryo.fits, "name") + newName = pyfrp_misc_module.enumeratedName("newFit", fitNames, sep="_") + + # Generate new fit + newFit = currEmbryo.newFit(newName) + + # Launch editor + ret = pyfrp_gui_fit_dialogs.fitSettingsDialog(newFit, self).exec_() + + if ret == 0: + return 0 + + # Update Object Bar + newNode = self.updateFitsNodeChildren() + self.objectBar.setCurrentItem(newNode) + + # Perform the new fit + self.performFit() + + return 1 + + def editFit(self): + + """Opens edit fit dialog.""" + + self.getCurrentObj() + + if self.currNodeType != "fit": + QtWidgets.QMessageBox.critical( + None, + "Error", + "No fit selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + # Launch editor + ret = pyfrp_gui_fit_dialogs.fitSettingsDialog(self.currObj, self).exec_() + + if ret == 0: + return 0 + + # Update Object Bar + self.updateFitsNodeChildren() + + return 1 + + def removeFit(self): + + """Removes fit.""" + + self.getCurrentObj() + + if self.currNodeType != "fit": + QtWidgets.QMessageBox.critical( + None, + "Error", + "No fit selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + currEmbryo = self.getCurrentEmbryo() + + currEmbryo.deleteFit(currEmbryo.fits.index(self.currObj)) + + # Update Object Bar + self.updateFitsNodeChildren() + + return 1 + + def performFit(self): + + """Runs fitting progess for selected fit.""" + + self.getCurrentObj() + + if self.currNodeType != "fit": + QtWidgets.QMessageBox.critical( + None, + "Error", + "No fit selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + # Check if pinned + if self.currObj.fitPinned: + if not self.currObj.checkPinned(): + self.idealPinEmbryo() + + # Genereate wait popup + self.progressDialog = pyfrp_gui_fit_dialogs.fittingProgressDialog(None) + + # Make backup copy of embryo + self.originalObj = self.currObj + self.backupObj = cpy.deepcopy(self.currObj) + + self.statusBar().showMessage("Performing fit " + self.currObj.name) + + # Generate Qthread and pass analysis there + self.task = pyfrp_gui_basics.pyfrpThread() + self.worker = pyfrp_gui_basics.pyfrpWorker(self.currObj.run) + + # Init and start + self.initTask() + + return 1 + + def printFitResults(self): + + """Print fit results.""" + + self.getCurrentObj() + + if self.currNodeType != "fit": + QtWidgets.QMessageBox.critical( + None, + "Error", + "No fit selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + self.currObj.printResults() + + return 1 + + def plotFit(self): + + """Plots currently selected fit.""" + + self.getCurrentObj() + + if self.currNodeType != "fit": + QtWidgets.QMessageBox.critical( + None, + "Error", + "No fit selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + if self.currObj.isFitted(): + + self.createPlotTab( + "intensityTS", plotName=self.currObj.name + " ", size=[1, 1] + ) + self.currObj.plotFit(ax=self.ax) + + self.adjustCanvas() + + return 1 + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecStatistics: Statistics handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def selectFits(self): + + """Opens fit selector for selected molecule.""" + + self.getCurrentObj() + + if self.currMoleculeNode == None: + QtWidgets.QMessageBox.critical( + None, + "Error", + "No molecule selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + if len(self.currMolecule.embryos) == 0: + QtWidgets.QMessageBox.critical( + None, + "Error", + "Molecule does not have any embryos to average.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + # Open Fit selector dialog + ret = pyfrp_gui_statistics_dialogs.fitSelector( + self.currMolecule, True, self + ).exec_() + + return ret + + def selectCrucialParameters(self): + + """Opens crucial parameter selector.""" + + self.getCurrentObj() + + if self.currMoleculeNode == None: + QtWidgets.QMessageBox.critical( + None, + "Error", + "No molecule selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + if len(self.currMolecule.embryos) == 0: + QtWidgets.QMessageBox.critical( + None, + "Error", + "Molecule does not have any embryos to average.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + # Open Fit selector dialog + ret = pyfrp_gui_statistics_dialogs.crucialParameterSelector( + self.currMolecule, self + ).exec_() + + return ret + + def summarizeMolecule(self): + + """Summarizes currently selected molecule.""" + + self.getCurrentObj() + + if self.currMoleculeNode == None: + QtWidgets.QMessageBox.critical( + None, + "Error", + "No molecule selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return 0 + + # if len(self.currMolecule.selFits)==0: + ret = self.selectFits() + if ret == 0: + return 0 + + ret = self.selectCrucialParameters() + if ret == 0: + return 0 + + self.currMolecule.sumUpResults() + + return 1 + + def selMolecules(self, n=2, nmin=2): + + """Opens listSelectorDialog and lets user select n molecules. Keyword Args: - typ (str): Desired Node type. Use ``"any"`` if type doesn't matter. + n (int): Number of molecules that should be selected + Returns: - bool: True if proper node is selected - - """ - - if self.objectBar.currentItem()==None: - QtGui.QMessageBox.critical(None, "Error","Nothing selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return False - if typ=="any": - return True - if typ==self.currNodeType: - return True - - return False - - def embryo2ObjectBar(self,embryo,parentNode): - - """Adds Embryo to ObjectBar. - - + list: List of molecules. """ - - #Embryo Status - analyzed=str(int(embryo.isAnalyzed())) - simulated=str(int(embryo.isSimulated())) - fitted=str(int(embryo.isFitted())) - - #Create new node - newEmbryoNode=QtGui.QTreeWidgetItem(parentNode,[embryo.name,analyzed,simulated,fitted]) - - #Geometry node - newGeometryNode=QtGui.QTreeWidgetItem(newEmbryoNode,['Geometry','','','']) - - #ROIs node - newROIsNode=QtGui.QTreeWidgetItem(newEmbryoNode,['ROIs','','','']) - - #Add ROIs - for roi in embryo.ROIs: - newROINode=QtGui.QTreeWidgetItem(newROIsNode,[roi.name,str(int(roi.isAnalyzed())),str(int(roi.isSimulated())),str(int(roi.isFitted()))]) - - #Analysis node - newAnalysisNode=QtGui.QTreeWidgetItem(newEmbryoNode,['Analysis',analyzed,'','']) - - #Simulation node - newSimulationNode=QtGui.QTreeWidgetItem(newEmbryoNode,['Simulation','',simulated,'']) - - #if embryo.simulation!=None: - newMeshNode=QtGui.QTreeWidgetItem(newSimulationNode,['Mesh','','','']) - - #Fits node - newFitsNode=QtGui.QTreeWidgetItem(newEmbryoNode,['Fits','','','']) - - #Add Fits - for fit in embryo.fits: - newFitNode=QtGui.QTreeWidgetItem(newFitsNode,[fit.name,'','',str(int(fit.isFitted()))]) - - #Expand Fits node - self.objectBar.expandItem(newFitsNode) - - return newEmbryoNode - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #Update ObjectBar Properties of embryo Node - def updateEmbryoNodeProps(self,embryoNode): - currEmbryoNode = self.getCurrentEmbryoNode() - currEmbryo = self.getCurrentEmbryo() - - currEmbryoNode.setText(1,str(int(currEmbryo.isAnalyzed()))) - currEmbryoNode.setText(2,str(int(currEmbryo.isSimulated()))) - currEmbryoNode.setText(3,str(int(currEmbryo.isFitted()))) - - return - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #Update ObjectBar Properties of embryo Node + names = [] + for mol in self.molecules: + names.append(mol.name) - def updateEmbryoNodeChildren(self): - self.updateFitsNodeChildren() - self.updateROIsNodeChildren() - return - - def getChildByName(self,node,name): - for i in range(node.childCount()): - if name==str(node.child(i).data(0,0).toString()): - return node.child(i) - return None - - def removeAllNodeChildren(self,node): - nChild=node.childCount() - for i in range(nChild): - node.takeChild(0) - - return node + selDialog = pyfrp_gui_basics.listSelectorDialog( + self, names, leftTitle="Available", rightTitle="Selected", itemsRight=[] + ) - def updateFitsNodeChildren(self): - - currEmbryo=self.getCurrentEmbryo() - currEmbryoNode=self.getCurrentEmbryoNode() - if currEmbryoNode!=None: - fitsNode=self.getChildByName(currEmbryoNode,'Fits') - self.removeAllNodeChildren(fitsNode) - for fit in currEmbryo.fits: - newFitNode=QtGui.QTreeWidgetItem(fitsNode,[fit.name,'','',str(int(fit.isFitted()))]) - self.getCurrentObjNode() - return newFitNode - - - def updateROIsNodeChildren(self): - - currEmbryo=self.getCurrentEmbryo() - currEmbryoNode=self.getCurrentEmbryoNode() - if currEmbryoNode!=None: - roisNode=self.getChildByName(currEmbryoNode,'ROIs') - self.removeAllNodeChildren(roisNode) - for roi in currEmbryo.ROIs: - newROINode=QtGui.QTreeWidgetItem(roisNode,[roi.name,str(int(roi.isAnalyzed())),str(int(roi.isSimulated())),str(int(roi.isFitted()))]) - self.getCurrentObjNode() - - - def getCurrentObjNode(self): - - """Returns Current Object Node from objectBar - """ - - self.currNode=self.objectBar.currentItem() - - if self.currNode.parent()==None: - self.currNodeType='molecule' - else: - if self.currNode.parent().parent()==None: - self.currNodeType='embryo' - elif self.currNode.data(0,0).toString()=="Fits": - self.currNodeType='fits' - elif self.currNode.parent().data(0,0).toString()=="Fits": - self.currNodeType='fit' - elif self.currNode.data(0,0).toString()=="Simulation": - self.currNodeType='simulation' - elif self.currNode.data(0,0).toString()=="Analysis": - self.currNodeType='analysis' - elif self.currNode.data(0,0).toString()=="Mesh": - self.currNodeType='mesh' - elif self.currNode.data(0,0).toString()=="Geometry": - self.currNodeType='geometry' - elif self.currNode.data(0,0).toString()=="ROIs": - self.currNodeType='rois' - elif self.currNode.parent().data(0,0).toString()=="ROIs": - self.currNodeType='roi' - - return self.currNode, self.currNodeType - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #Returns Current Object selected in objectBar + selectedMols = [] - def getCurrentObj(self): - - #Find out current node and which type it is - self.getCurrentObjNode() - - #Find current molecule node - self.getCurrentMoleculeNode() - - #Find corresponding molecule object - self.getCurrentMolecule() - - if self.currNodeType=="molecule": - self.currObj=self.currMolecule - else: - currEmbryo=self.getCurrentEmbryo() - - if self.currNodeType=="embryo": - self.currObj=currEmbryo - elif self.currNodeType=="analysis": - self.currObj=currEmbryo.analysis - elif self.currNodeType=="geometry": - self.currObj=currEmbryo.geometry - elif self.currNodeType=="simulation": - self.currObj=currEmbryo.simulation - elif self.currNodeType=="mesh": - self.currObj=currEmbryo.simulation.mesh - elif self.currNodeType=="fit": - self.currObj=currEmbryo.getFitByName(self.currNode.data(0,0).toString()) - elif self.currNodeType=="roi": - self.currObj=currEmbryo.getROIByName(self.currNode.data(0,0).toString()) - else: - self.currObj=None - - return self.currObj - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #Returns Current Molecule Node - - def getCurrentMoleculeNode(self): - if self.currNodeType=='molecule': - self.currMoleculeNode=self.currNode - elif self.currNodeType=='embryo': - self.currMoleculeNode=self.currNode.parent() - elif self.currNodeType in ["analysis","simulation","fits","geometry","rois"]: - self.currMoleculeNode=self.currNode.parent().parent() - elif self.currNodeType in ["mesh","roi","fit"]: - self.currMoleculeNode=self.currNode.parent().parent().parent() - - - ###NOTE: Try later if this is the smarter way - #ind=self.objectBar.indexOfTopLevelItem(self.currNode) - #self.currMoleculeNode=self.objectBar.topLevelItem(ind) - - return self.currMoleculeNode - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #Returns Current Embryo Node - - def getCurrentEmbryoNode(self): - if self.currNodeType=='molecule': - currEmbryoNode=None - elif self.currNodeType=='embryo': - currEmbryoNode=self.currNode - elif self.currNodeType in ["analysis","simulation","fits","geometry","rois"]: - currEmbryoNode=self.currNode.parent() - elif self.currNodeType in ["mesh","roi","fit"]: - currEmbryoNode=self.currNode.parent().parent() - - return currEmbryoNode - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #Returns Current Molecule - - def getCurrentMolecule(self): - molNames=pyfrp_misc_module.objAttrToList(self.molecules,"name") - self.currMolecule=self.molecules[molNames.index(self.currMoleculeNode.data(0,0).toString())] - return self.currMolecule - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #Returns Current Embryo - - def getCurrentEmbryo(self): - currEmbryoNode=self.getCurrentEmbryoNode() - if currEmbryoNode==None: - return None - - embryoNames=pyfrp_misc_module.objAttrToList(self.currMolecule.embryos,"name") - currEmbryo=self.currMolecule.embryos[embryoNames.index(currEmbryoNode.data(0,0).toString())] - return currEmbryo - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecPropertyBar: Porperty Bar handling - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - def showObjPropsInBar(self,obj,maxArraySize=3): - - """Shows property bar. - - Args: - obj (object): Object selected in objectBar. - - Keyword Args: - maxArraySize (int): Maximal length of array to still be displayed. - - """ - - if obj==None: - return self.propBar - - for item in vars(obj): - - ###NOTE: Creates deprecation warning on Windows - - # First check if numpy array or list - if isinstance(vars(obj)[str(item)],(np.ndarray,list)): - - # Check if array is not too long - if len(np.shape(vars(obj)[str(item)]))>0 and np.shape(vars(obj)[str(item)])[0] n: + printWarning( + "More than " + + str(n) + + " molecules selected. Will only use the first and second molecule." + ) + selectedMols = selectedMols[0:n] - def checkObjNames(self): - - """Checks if molecules or embryos have the same name. - - Returns: - bool: True if there is a molecule/embryo with the same name. - """ - - b=False - - b=self.checkMolNames() - - for mol in self.molecules: - b=self.checkEmbryoNames(mol=mol) - - return b - - def checkMolNames(self): - - """Checks if molecules have the same name. - - Returns: - bool: True if there is a molecule the same name. - """ - - b=False - - molNames=pyfrp_misc_module.objAttrToList(self.molecules,"name") - for name in molNames: - if molNames.count(name)>1: - b=True - printWarning("Molecule with name " + name + " exists twice. This can lead to problems") - - return b - - def checkEmbryoNames(self,mol=None): - - """#Checks if embryos have the same name. - - Returns: - bool: True if there is a embryo the same name. - """ - - mol = pyfrp_misc_module.assignIfVal(mol,self.currMolecule,None) - - b=False - - embryoNames=pyfrp_misc_module.objAttrToList(self.currMolecule.embryos,"name") - for name in embryoNames: - if embryoNames.count(name)>1: - b=True - printWarning("Embryo with name " + name + " exists twice in molecule " + mol.name +". This can lead to problems") - - return b - - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecWizards: Wizards - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - def LSM2EmbryoWizard(self): - - """Opens :py:class:`pyfrp.gui.pyfrp_gui_embryo_dialogs.lsmWizard` which lets - one to extract and sort microscope files and then creates new - :py:class:`pyfrp.subclasses.pyfrp_embryo.embryo` including new data. - - .. note:: Uses Fiji. Fiji path needs to be set properly for success. - - """ - - lsmWizard = pyfrp_gui_embryo_dialogs.lsmWizard(self) - if lsmWizard.exec_(): - embryo = lsmWizard.getEmbryo() - if embryo==None: - return - - self.currMolecule.addEmbryo(embryo) - - newNode=self.embryo2ObjectBar(embryo,self.currMoleculeNode) - self.objectBar.setCurrentItem(newNode) - self.getCurrentObj() - - def openWizard(self): - - """Wizard for PyFRAP analysis. - - Leads user through following steps: - - * Embryo creation :py:func:`newEmbryo`. - * ROI creation :py:func:`createDefaultROIs`. - * ROI handling :py:func:`openROIManager`. - * Mesh generation :py:func:`generateMesh`. - * Data analysis :py:func:`analyzeEmbryo`. - * FRAP simulation :py:func:`simulateEmbryo`. - * Fit creation :py:func:`newFit`. - * Fit plotting :py:func:`plotFit`. - - """ - - ret=self.newEmbryo() - if ret==0: - return 0 - - ret=self.ROIWizardSelector() - if ret==0: - return 0 - - ret=self.editGeometry() - if ret==0: - return 0 - - - self.getCurrentEmbryo().newSimulation() - ret=self.generateMesh() - if ret==0: - return 0 - - self.updateROIIdxs() - ret=self.analyzeEmbryo() - if ret==0: - return 0 - - ret=self.simulateEmbryo() - if ret==0: - return 0 - - ret=self.newFit() - if ret==0: - return 0 - - self.plotFit() - - return 1 - - def selectEmbryoGenMode(self): - - """Opens :py:class:`pyfrp.gui.pyfrp_gui_embryo_dialogs.wizardSelector` - and lets user select embryo generation mode. - - Returns: - int: 1 if user chose from microscope, 0 if not, -1 else. - - """ - - selectWizard = pyfrp_gui_embryo_dialogs.wizardSelector(self) - if selectWizard.exec_(): - useLSM = selectWizard.getUseLSM() - if useLSM==None: - return -1 - - if useLSM: - ret=self.LSM2EmbryoWizard() - if ret==0: - return -1 - - return 1 - return 0 - - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecEmbryo: Embryo Menubar Methods - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - def openROIManager(self): - - """Open ROI Manager for current embryo. - - Returns: - int: Dialog Code (0 when cancelled, 1 when accepted.) - """ - - currEmbryo=self.getCurrentEmbryo() - if currEmbryo!=None: - ret=pyfrp_gui_ROI_manager.ROImanager(currEmbryo,self).exec_() - - if ret==0: - return ret - elif ret==1: - self.updateROIsNodeChildren() - return ret - return 0 - - def createDefaultROIs(self): - - """Create default ROIs for current embryo. - - Returns: - int: Dialog Code (0 when cancelled, 1 when accepted.) - """ - - currEmbryo=self.getCurrentEmbryo() - if currEmbryo!=None: - ret=pyfrp_gui_ROI_manager.defaultROIsDialog(currEmbryo,self).exec_() - if ret==0: - return ret - elif ret==1: - self.updateROIsNodeChildren() - return ret - return 0 - - def ROIWizardSelector(self): - - """Lets the user select between the createDefaultROIs, defaultROIsWizard or ROImanager. - - Opens :py:class:`pyfrp.gui.pyfrp_gui_ROI_manager.wizardSelector` - and lets user select ROI generation mode. - - Launches the right wizard afterwards. - - Returns: - int: 0 when default, 1 for wizard and 2 for manager - - """ - - selectWizard = pyfrp_gui_ROI_manager.wizardSelector(self) - if selectWizard.exec_(): - mode = selectWizard.getMode() - - print "mode is", mode - - if mode==None: - return 0 - - if mode==0: - ret=self.createDefaultROIs() - elif mode==1: - ret=self.defaultROIsWizard() - elif mode==2: - ret=self.openROIManager() - - return ret - - return 0 - - def defaultROIsWizard(self): - - """Small Wizard that helps creating a set of default ROIs for current embryo. - - Returns: - int: Dialog Code (0 when cancelled, 1 when accepted.) - """ - - currEmbryo=self.getCurrentEmbryo() - if currEmbryo==None: - return 0 - - #Select Slice ROI - sliceSelector = pyfrp_gui_ROI_manager.ROISelector(currEmbryo,'radialSlice',self,msg='Select Slice ROI',sliceHeight=currEmbryo.sliceHeightPx,sliceWidth=currEmbryo.sliceWidthPx,color='g',name='Slice') - if sliceSelector.exec_(): - sliceROI=sliceSelector.getROI() - - #Select Bleached ROI - squSelector = pyfrp_gui_ROI_manager.ROISelector(currEmbryo,'squareSlice',self,msg='Select Bleached ROI',sliceHeight=currEmbryo.sliceHeightPx,sliceWidth=currEmbryo.sliceWidthPx,color='b',name='Bleached Square') - if squSelector.exec_(): - bleachedROI=squSelector.getROI() - - #Select Rim ROI - if hasattr(sliceROI,'radius'): - radius=sliceROI.radius*0.66 - center=sliceROI.center - rimSelector = pyfrp_gui_ROI_manager.ROISelector(currEmbryo,'radialSlice',self,msg='Select Rim ROI',radius=radius,center=center,sliceHeight=currEmbryo.sliceHeightPx,sliceWidth=currEmbryo.sliceWidthPx,color='y',name='Slice rim') - else: - radius=133. - rimSelector = pyfrp_gui_ROI_manager.ROISelector(currEmbryo,'radialSlice',self,msg='Select Rim ROI',radius=radius,sliceHeight=currEmbryo.sliceHeightPx,sliceWidth=currEmbryo.sliceWidthPx,color='y',name='Slice rim') - - if rimSelector.exec_(): - rimROI=rimSelector.getROI() - - #Build default ROIs - radius=300. - center=[256.,256.] - if hasattr(sliceROI,'radius'): - radius=sliceROI.radius - center=sliceROI.center - else: - if currEmbryo.geometry!=None: - if hasattr(currEmbryo.geometry,'imagingRadius'): - radius=currEmbryo.geometry.imagingRadius - else: - if hasattr(currEmbryo.geometry,'radius'): - radius=currEmbryo.geometry.radius - - currEmbryo.genDefaultROIs(center,radius,rimFactor=0.66,masterROI=sliceROI,bleachedROI=bleachedROI,rimROI=rimROI,clean=True) - - self.updateROIsNodeChildren() - - return 1 - - def updateROIIdxs(self): - - """Updates all ROI Idxs.""" - - currEmbryo=self.getCurrentEmbryo() - - if currEmbryo!=None: - - #Genereate wait popup - self.progressDialog=pyfrp_gui_ROI_manager.indexProgressDialog(None) - - #Make backup copy of embryo - self.originalObj=currEmbryo - self.backupObj=cpy.deepcopy(currEmbryo) - - self.statusBar().showMessage("Indexing ROIs of embryo " + currEmbryo.name) - - #Generate worker and generate Qthread - self.task=pyfrp_gui_basics.pyfrpThread() - self.worker=pyfrp_gui_basics.pyfrpWorker(currEmbryo.computeROIIdxs,signal=self.task.progressSignal) - - #Start - self.initTask() - else: - return 0 - - - return 1 - - def selectGeometry(self): - - """Open Geometry Editor for current embryo.""" - - currEmbryo=self.getCurrentEmbryo() - - if currEmbryo!=None: - ret=pyfrp_gui_geometry_dialogs.geometrySelectDialog(currEmbryo,self).exec_() - else: - return 0 - - return ret - - def editGeometry(self): - - """Open Geometry Editor for current embryo.""" - - currEmbryo=self.getCurrentEmbryo() - - if currEmbryo!=None: - if "zebrafishDomeStage" in currEmbryo.geometry.typ: - ret=pyfrp_gui_geometry_dialogs.zebrafishDomeStageDialog(currEmbryo.geometry,self).exec_() - elif "cylinder" in currEmbryo.geometry.typ: - ret=pyfrp_gui_geometry_dialogs.cylinderDialog(currEmbryo.geometry,self).exec_() - elif "xenopusBall" in currEmbryo.geometry.typ: - ret=pyfrp_gui_geometry_dialogs.xenopusBallDialog(currEmbryo.geometry,self).exec_() - elif "cone" in currEmbryo.geometry.typ: - ret=pyfrp_gui_geometry_dialogs.coneDialog(currEmbryo.geometry,self).exec_() - else: - ret=pyfrp_gui_geometry_dialogs.geometryDialog(currEmbryo.geometry,self).exec_() - - return ret - - return 0 - - def editGeoFile(self): - - """Open Geometry Editor for current embryo.""" - - currEmbryo=self.getCurrentEmbryo() - if currEmbryo!=None: - ret=pyfrp_gui_gmsh_editor.gmshFileEditor(currEmbryo.geometry,self).exec_() - - return ret - - def drawGeometry(self,ann=False): - - """Draw Geometry in plot tab.""" - - - currEmbryo=self.getCurrentEmbryo() - if currEmbryo!=None: - self.createPlotTab('xyz',plotName='Geometry',proj=['3d']) - currEmbryo.geometry.plotGeometry(ax=self.ax,ann=ann) - self.adjustCanvas() - return - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecAnalysis: Analysis handling - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - def editAnalysis(self): - - """Edit Analysis Settings.""" - - currEmbryo=self.getCurrentEmbryo() - if currEmbryo!=None: - if currEmbryo.analysis==None: - currEmbryo.newAnalysis() - - ret=pyfrp_gui_analysis_dialogs.analysisDialog(currEmbryo.analysis,self).exec_() - else: - return 0 - - return ret - - def analyzeEmbryo(self): - - """Analyze embryo task/progressbar.""" - - #Grab embryo - currEmbryo=self.getCurrentEmbryo() - if currEmbryo==None: - return 0 - - #Launching Dialog - ret=self.editAnalysis() - if ret==0: - return 0 - - #Genereate wait popup - self.progressDialog=pyfrp_gui_analysis_dialogs.analysisProgressDialog(None) - - #Make backup copy of embryo - self.originalObj=currEmbryo - self.backupObj=cpy.deepcopy(currEmbryo) - - self.statusBar().showMessage("Analyzing Dataset " + currEmbryo.name) - - #Generate Qthread and pass analysis there - self.task=pyfrp_gui_basics.pyfrpThread() - self.worker=pyfrp_gui_basics.pyfrpWorker(currEmbryo.analysis.run,signal=self.task.progressSignal) - - #Init and start - self.initTask() - - return 1 - - def plotAllDataTSOfEmbryo(self): - - """Plots data analysis results of all ROIs of embryo.""" - - currEmbryo=self.getCurrentEmbryo() - - if currEmbryo==None: - return - - self.createPlotTab("intensityTS",plotName=currEmbryo.name+" data",size=[1,1]) - currEmbryo.plotAllData(ax=self.ax) - - self.adjustCanvas() - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecSimulation: Simulation handling - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - def editSimulation(self): - - """Edit Simulation Settings.""" - - currEmbryo=self.getCurrentEmbryo() - if currEmbryo!=None: - if currEmbryo.simulation==None: - currEmbryo.newSimulation() - - ret=pyfrp_gui_simulation_dialogs.simulationSettingsDialog(currEmbryo.simulation,self).exec_() - - else: - return 0 - - return ret - - def simulateEmbryo(self): - - """Simulate embryo task/progressbar.""" - - #Grab embryo - currEmbryo=self.getCurrentEmbryo() - if currEmbryo==None: - return 0 - - #Launching Dialog - ret=self.editSimulation() - if ret==0: - return 0 - - #Genereate wait popup - self.progressDialog=pyfrp_gui_simulation_dialogs.simulationProgressDialog(None) - - #Make backup copy of embryo - self.originalObj=currEmbryo - self.backupObj=cpy.deepcopy(currEmbryo) - - self.statusBar().showMessage("Simulating Dataset " + currEmbryo.name) - - #Generate Qthread and pass analysis there - self.task=pyfrp_gui_basics.pyfrpThread() - self.worker=pyfrp_gui_basics.pyfrpWorker(currEmbryo.simulation.run,signal=self.task.progressSignal) - - #Init and start - self.initTask() - - return 1 - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecMesh: Mesh handling - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - def editMesh(self): - - """Edit Mesh Settings. - - Launches :py:class:`pyfrp.gui.pyfrp_gui_mesh_dialogs.meshSettingsDialog` and lets user define standard mesh properties. - - """ - currEmbryo=self.getCurrentEmbryo() - if currEmbryo!=None: - if currEmbryo.simulation==None: - currEmbryo.newSimulation() - ret=pyfrp_gui_mesh_dialogs.meshSettingsDialog(currEmbryo.simulation.mesh,self).exec_() - return ret - - else: - return 0 - - def generateMesh(self): - - """Generate Mesh. - - Does this via submitting mesh generation to a seperate `QThread`. Meanwhile displays - :py:class:`pyfrp.gui.pyfrp_gui_mesh_dialogs.genMeshProgressDialog`. - - Prints out mesh statistics at the end. - - """ - - #Grab embryo - currEmbryo=self.getCurrentEmbryo() - if currEmbryo==None: - return 0 - - #Launching Dialog - ret=self.editMesh() - if ret==0: - return 0 - - #Genereate wait popup - #self.progressDialog=pyfrp_gui_mesh_dialogs.genMeshProgressDialog(None) - - ##Make backup copy of embryo - #self.originalObj=currEmbryo - #self.backupObj=cpy.deepcopy(currEmbryo) - - #self.statusBar().showMessage("Generating Mesh " + currEmbryo.name) - - ##Generate Qthread and pass analysis there - #self.task=pyfrp_gui_basics.pyfrpThread() - #self.worker=pyfrp_gui_basics.pyfrpWorker(currEmbryo.simulation.mesh.genMesh) - printNote("Generating Mesh... This can take a few seconds...") - currEmbryo.simulation.mesh.genMesh() - + if len(selected) < nmin: + printError("Less than " + str(nmin) + " molecules selected.") + return [] - #Print out mesh stats - self.printMeshStats() - - #Init and start - #self.initTask() - - return 1 - - def refineMesh(self): - - """Refine Mesh by tetrahedron splitting. - - Submits py:func:`pyfrp.subclasses.pyfrp_mesh.mesh.refine` to a seperate QThread. - Meanwhile displays :py:class:`pyfrp.gui.pyfrp_gui_mesh_dialogs.refineMeshProgressDialog`. - - """ - - #Grab embryo - currEmbryo=self.getCurrentEmbryo() - if currEmbryo==None: - return 0 - - #Genereate wait popup - self.progressDialog=pyfrp_gui_mesh_dialogs.refineMeshProgressDialog(None) - - #Make backup copy of embryo - self.originalObj=currEmbryo - self.backupObj=cpy.deepcopy(currEmbryo) - - self.statusBar().showMessage("Refining Mesh " + currEmbryo.name) - - #Generate Qthread and pass analysis there - self.task=pyfrp_gui_basics.pyfrpThread() - self.worker=pyfrp_gui_basics.pyfrpWorker(currEmbryo.simulation.mesh.refine) - - #Init and start - self.initTask() - - return 1 - - - def forceMeshDensity(self): - - """Force Mesh to have given density globally. - - Submits py:func:`pyfrp.subclasses.pyfrp_mesh.mesh.refine` to a seperate QThread. - Meanwhile displays :py:class:`pyfrp.gui.pyfrp_gui_mesh_dialogs.refineMeshProgressDialog`. - - """ - - #Grab embryo - currEmbryo=self.getCurrentEmbryo() - if currEmbryo==None: - return 0 - - #Get options - forceMeshDialog=pyfrp_gui_mesh_dialogs.forceMeshSettingsDialog(currEmbryo.simulation.mesh,self) - if forceMeshDialog.exec_(): - roiUsed,density,stepPercentage,debug,findIdxs,method,maxCells=forceMeshDialog.getVals() - - #Genereate wait popup - self.progressDialog=pyfrp_gui_mesh_dialogs.forceMeshProgressDialog(None) - - #Make backup copy of embryo - self.originalObj=currEmbryo - self.backupObj=cpy.deepcopy(currEmbryo) - - self.statusBar().showMessage("Computing new mesh with required density " + currEmbryo.name) - - #Generate Qthread and pass analysis there - self.task=pyfrp_gui_basics.pyfrpThread() - self.worker=pyfrp_gui_basics.pyfrpWorker(currEmbryo.simulation.mesh.forceMinMeshDensityInROI,roiUsed,density,stepPercentage,debug=debug,findIdxs=findIdxs,method=method,maxCells=maxCells) - - #Init and start - self.initTask() - - return 1 - - def forceROIMeshDensity(self): - - """Force Mesh to have given density in ROI. - - See also :py:class:`pyfrp.gui.pyfrp_gui_mesh_dialogs.refineROIMeshSettingsDialog`. - - """ - - #Grab embryo - currEmbryo=self.getCurrentEmbryo() - if currEmbryo==None: - return 0 - - #Get options - ret=pyfrp_gui_mesh_dialogs.refineROIMeshSettingsDialog(currEmbryo.simulation.mesh,self).exec_() - - return ret - - def printMeshStats(self): - - """Prints out mesh statistics.""" - - #Grab embryo - currEmbryo=self.getCurrentEmbryo() - if currEmbryo==None: - return 0 - - currEmbryo.simulation.mesh.printStats() - - - def plotMesh(self): - - """Plots mesh of selected embryo. - """ - - #Grab embryo - currEmbryo=self.getCurrentEmbryo() - if currEmbryo==None: - QtGui.QMessageBox.critical(None, "Error","No embryo selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return - - #try: - self.renderer = currEmbryo.simulation.mesh.plotMesh(renderWindow=1) - #except AttributeError: - #QtGui.QMessageBox.critical(None, "Error","Embryo has no simulation or mesh yet.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - - self.createVtkTab() - - self.vtkCanvas.GetRenderWindow().AddRenderer(self.renderer) - self.vtkCanvas.GetRenderWindow().GetInteractor().Initialize() - - - def plotMeshDensity(self): - - """Plots mesh density in x/y/z direction.""" - - currEmbryo=self.getCurrentEmbryo() - if currEmbryo==None: - return - - self.createPlotTab("meshDensity",plotName=currEmbryo.name+" mesh density",size=[2,2]) - - currEmbryo.simulation.mesh.plotDensity(axes=self.axes) - - def addBoundaryLayerMeshAroundROI(self): - - """Adds boundary layer around ROI. - - """ - - currEmbryo=self.getCurrentEmbryo() - if currEmbryo==None: - return - - dialog = pyfrp_gui_mesh_dialogs.boundaryLayerAroundROISettingsDialog(currEmbryo,self) - if dialog.exec_(): - fnOut,roiUsed,segments,simplify,iterations,triangIterations,fixSurfaces,debug,volSizePx,thickness,volSizeLayer,cleanUp,approxBySpline,angleThresh,faces,onlyAbs = dialog.getVals() - - - #Genereate wait popup - self.progressDialog=pyfrp_gui_mesh_dialogs.boundaryLayerProgressDialog(None) - - #Make backup copy of embryo - self.originalObj=currEmbryo - self.backupObj=cpy.deepcopy(currEmbryo) - - self.statusBar().showMessage("Computing new mesh with required density " + currEmbryo.name) - - #Generate Qthread and pass analysis there - self.task=pyfrp_gui_basics.pyfrpThread() - - # For now don't submit to QThread and see how it works out. - self.worker=pyfrp_gui_basics.pyfrpWorker(currEmbryo.simulation.mesh.addBoundaryLayerAroundROI,roiUsed,fnOut=fnOut,segments=segments,simplify=simplify,iterations=iterations,triangIterations=triangIterations, - fixSurfaces=fixSurfaces,debug=debug,volSizePx=volSizePx,volSizeLayer=volSizeLayer,thickness=thickness,cleanUp=cleanUp, - approxBySpline=approxBySpline,angleThresh=angleThresh,faces=faces,onlyAbs=onlyAbs) - - #Init and start - self.initTask() - - def plotAllSimTSOfEmbryo(self): - - """Plots simulation results of all ROIs of embryo.""" - - currEmbryo=self.getCurrentEmbryo() - - if currEmbryo==None: - return - - self.createPlotTab("intensityTS",plotName=currEmbryo.name+" data",size=[1,1]) - currEmbryo.plotAllSim(ax=self.ax) - - self.adjustCanvas() - - def plotAllSimAndDataTSOfEmbryo(self): - - """Plots simulation results of all ROIs of embryo.""" - - currEmbryo=self.getCurrentEmbryo() - - if currEmbryo==None: - return - - self.createPlotTab("intensityTS",plotName=currEmbryo.name+" data",size=[1,1]) - currEmbryo.plotAllData(ax=self.ax) - currEmbryo.plotAllSim(ax=self.ax) - - self.adjustCanvas() - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecPinning: Pinning handling - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - def defaultPinEmbryo(self): - - """Default Pinning. - - Lets the user selected his/her pinning options themself by launching - :py:class:`pyfrp.gui.pyfrp_gui_pinning_dialogs.defaultPinningDialog`. - - - """ - - currEmbryo=self.getCurrentEmbryo() - - if currEmbryo==None: - QtGui.QMessageBox.critical(None, "Error","No embryo selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - #Launch dialog - ret=pyfrp_gui_pinning_dialogs.defaultPinningDialog(currEmbryo,self).exec_() - - return ret - - def idealPinEmbryo(self): - - """Ideal Pinning. - - Lets the user select some options for ideal pinning via - :py:class:`pyfrp.gui.pyfrp_gui_pinning_dialogs.idealPinningDialog`. - - - """ - - currEmbryo=self.getCurrentEmbryo() - - if currEmbryo==None: - QtGui.QMessageBox.critical(None, "Error","No embryo selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - #Launch dialog - ret=pyfrp_gui_pinning_dialogs.idealPinningDialog(currEmbryo,self).exec_() - - return ret - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecFit: Fit handling - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - def newFit(self): - - """Creates new fit.""" - - currEmbryo=self.getCurrentEmbryo() - - if currEmbryo==None: - QtGui.QMessageBox.critical(None, "Error","No embryo selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - #Generate name - fitNames=pyfrp_misc_module.objAttrToList(currEmbryo.fits,"name") - newName=pyfrp_misc_module.enumeratedName("newFit",fitNames,sep="_") - - #Generate new fit - newFit=currEmbryo.newFit(newName) - - #Launch editor - ret=pyfrp_gui_fit_dialogs.fitSettingsDialog(newFit,self).exec_() - - if ret==0: - return 0 - - #Update Object Bar - newNode=self.updateFitsNodeChildren() - self.objectBar.setCurrentItem(newNode) - - #Perform the new fit - self.performFit() - - return 1 - - def editFit(self): - - """Opens edit fit dialog.""" - - self.getCurrentObj() - - if self.currNodeType!='fit': - QtGui.QMessageBox.critical(None, "Error","No fit selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - #Launch editor - ret=pyfrp_gui_fit_dialogs.fitSettingsDialog(self.currObj,self).exec_() - - if ret==0: - return 0 - - #Update Object Bar - self.updateFitsNodeChildren() - - return 1 - - def removeFit(self): - - """Removes fit.""" - - self.getCurrentObj() - - if self.currNodeType!='fit': - QtGui.QMessageBox.critical(None, "Error","No fit selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - currEmbryo=self.getCurrentEmbryo() - - currEmbryo.deleteFit(currEmbryo.fits.index(self.currObj)) - - #Update Object Bar - self.updateFitsNodeChildren() - - return 1 - - def performFit(self): - - """Runs fitting progess for selected fit.""" - - self.getCurrentObj() - - if self.currNodeType!='fit': - QtGui.QMessageBox.critical(None, "Error","No fit selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - #Check if pinned - if self.currObj.fitPinned: - if not self.currObj.checkPinned(): - self.idealPinEmbryo() - - #Genereate wait popup - self.progressDialog=pyfrp_gui_fit_dialogs.fittingProgressDialog(None) - - #Make backup copy of embryo - self.originalObj=self.currObj - self.backupObj=cpy.deepcopy(self.currObj) - - self.statusBar().showMessage("Performing fit " + self.currObj.name) - - #Generate Qthread and pass analysis there - self.task=pyfrp_gui_basics.pyfrpThread() - self.worker=pyfrp_gui_basics.pyfrpWorker(self.currObj.run) - - #Init and start - self.initTask() - - return 1 - - def printFitResults(self): - - """Print fit results.""" - - self.getCurrentObj() - - if self.currNodeType!='fit': - QtGui.QMessageBox.critical(None, "Error","No fit selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - self.currObj.printResults() - - return 1 - - - def plotFit(self): - - """Plots currently selected fit.""" - - self.getCurrentObj() - - if self.currNodeType!='fit': - QtGui.QMessageBox.critical(None, "Error","No fit selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - if self.currObj.isFitted(): - - self.createPlotTab("intensityTS",plotName=self.currObj.name+" ",size=[1,1]) - self.currObj.plotFit(ax=self.ax) - - self.adjustCanvas() - - return 1 - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecStatistics: Statistics handling - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - def selectFits(self): - - """Opens fit selector for selected molecule.""" - - self.getCurrentObj() - - if self.currMoleculeNode==None: - QtGui.QMessageBox.critical(None, "Error","No molecule selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - if len(self.currMolecule.embryos)==0: - QtGui.QMessageBox.critical(None, "Error","Molecule does not have any embryos to average.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - #Open Fit selector dialog - ret=pyfrp_gui_statistics_dialogs.fitSelector(self.currMolecule,True,self).exec_() - - return ret - - def selectCrucialParameters(self): - - """Opens crucial parameter selector.""" - - self.getCurrentObj() - - if self.currMoleculeNode==None: - QtGui.QMessageBox.critical(None, "Error","No molecule selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - if len(self.currMolecule.embryos)==0: - QtGui.QMessageBox.critical(None, "Error","Molecule does not have any embryos to average.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - #Open Fit selector dialog - ret=pyfrp_gui_statistics_dialogs.crucialParameterSelector(self.currMolecule,self).exec_() - - return ret - - def summarizeMolecule(self): - - """Summarizes currently selected molecule.""" - - self.getCurrentObj() - - if self.currMoleculeNode==None: - QtGui.QMessageBox.critical(None, "Error","No molecule selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return 0 - - #if len(self.currMolecule.selFits)==0: - ret=self.selectFits() - if ret==0: - return 0 - - ret=self.selectCrucialParameters() - if ret==0: - return 0 - - - self.currMolecule.sumUpResults() - - return 1 - - def selMolecules(self,n=2,nmin=2): - - """Opens listSelectorDialog and lets user select n molecules. - - Keyword Args: - n (int): Number of molecules that should be selected - - - Returns: - list: List of molecules. - - """ - - names=[] - for mol in self.molecules: - names.append(mol.name) - - selDialog=pyfrp_gui_basics.listSelectorDialog(self,names,leftTitle="Available",rightTitle="Selected",itemsRight=[]) - - selectedMols=[] - - if selDialog.exec_(): - selected = selDialog.getSelection() - - for mol in self.molecules: - if mol.name in selected: - selectedMols.append(mol) - - if len(selected)>n: - printWarning("More than "+str(n)+ " molecules selected. Will only use the first and second molecule.") - selectedMols=selectedMols[0:n] - - if len(selected)0: - - self.ax=self.tabAxes[value] - self.fig=self.tabFigs[value] - - if self.currTab!=None: - self.verticalSplitter.refresh() - self.horizontalSplitter.refresh() - self.currTab.setHidden(True) - self.currTab.setVisible(True) - - self.adjustCanvas() - - def currentTabClosed(self,value): - - """Callback if the current tab is closed. + + self.currTab = self.plotTabs.widget(value) + if len(self.tabAxes) > 0: + + self.ax = self.tabAxes[value] + self.fig = self.tabFigs[value] + + if self.currTab != None: + self.verticalSplitter.refresh() + self.horizontalSplitter.refresh() + self.currTab.setHidden(True) + self.currTab.setVisible(True) + + self.adjustCanvas() + + def currentTabClosed(self, value): + + """Callback if the current tab is closed. Removes widgets from bookkeeping lists and creates new dummy tab if there is no tab left. """ - - self.currTab=self.plotTabs.widget(value) - if len(self.tabAxes)>0: - self.tabAxes.pop(value) - self.tabFigs.pop(value) - - self.plotTabs.removeTab(value) - - if self.plotTabs.count()==0: - self.createDummpyTab() - - def createDummpyTab(self): - - """Creates dummy tab and adds it to plot tabs.""" - - - self.currTab=QtGui.QWidget() - self.firstTab=self.plotTabs.addTab(self.currTab,"PlotTab") - self.plotTabs.setTabsClosable(False) - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecVTK: vtk handling - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - def createVtkTab(self,plotName="",addRenderer=False): - - """Creates VTK tab for plotting. + + self.currTab = self.plotTabs.widget(value) + if len(self.tabAxes) > 0: + self.tabAxes.pop(value) + self.tabFigs.pop(value) + + self.plotTabs.removeTab(value) + + if self.plotTabs.count() == 0: + self.createDummpyTab() + + def createDummpyTab(self): + + """Creates dummy tab and adds it to plot tabs.""" + + self.currTab = QtWidgets.QWidget() + self.firstTab = self.plotTabs.addTab(self.currTab, "PlotTab") + self.plotTabs.setTabsClosable(False) + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecVTK: vtk handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def createVtkTab(self, plotName="", addRenderer=False): + + """Creates VTK tab for plotting. Creates new tab and adds it to plotTabs. @@ -2809,52 +3163,57 @@ def createVtkTab(self,plotName="",addRenderer=False): vtk.QVTKRenderWindowInteractor """ - - #Grab embryo (might need to change this if whole molecule plots) - currEmbryo=self.getCurrentEmbryo() - if currEmbryo==None: - QtGui.QMessageBox.critical(None, "Error","No embryo selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return - #Create tab name - tabname=currEmbryo.name+"/"+plotName+"#1" - - #Increment tab counter in name - for i in range(self.plotTabs.count()): - if self.plotTabs.tabText(i)==tabname: - nme,nmbr=tabname.split("#") - nmbr=str(int(nmbr)+1) - tabname=nme+"#"+nmbr - - # New empty widget - self.currTab=QtGui.QWidget() - - # Create canvas - self.createVtkCanvas(addRenderer=addRenderer) - - # Add to bookkeeping lists - self.tabAxes.append(self.vtkCanvas) - self.tabFigs.append(None) - - # Add tab - self.plotTabs.addTab(self.currTab,tabname) - - #Check for dummy plot tab - if self.plotTabs.tabText(0)=="PlotTab": - self.plotTabs.removeTab(self.plotTabs.currentIndex()) - self.plotTabs.setTabsClosable(True) - - # Set as current tab - self.plotTabs.setCurrentWidget(self.currTab) - - # Adjust size - self.adjustCanvas() - - return self.vtkCanvas - - def createVtkCanvas(self,addRenderer=False): - - """Create vtk canvas. + # Grab embryo (might need to change this if whole molecule plots) + currEmbryo = self.getCurrentEmbryo() + if currEmbryo == None: + QtWidgets.QMessageBox.critical( + None, + "Error", + "No embryo selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return + + # Create tab name + tabname = currEmbryo.name + "/" + plotName + "#1" + + # Increment tab counter in name + for i in range(self.plotTabs.count()): + if self.plotTabs.tabText(i) == tabname: + nme, nmbr = tabname.split("#") + nmbr = str(int(nmbr) + 1) + tabname = nme + "#" + nmbr + + # New empty widget + self.currTab = QtWidgets.QWidget() + + # Create canvas + self.createVtkCanvas(addRenderer=addRenderer) + + # Add to bookkeeping lists + self.tabAxes.append(self.vtkCanvas) + self.tabFigs.append(None) + + # Add tab + self.plotTabs.addTab(self.currTab, tabname) + + # Check for dummy plot tab + if self.plotTabs.tabText(0) == "PlotTab": + self.plotTabs.removeTab(self.plotTabs.currentIndex()) + self.plotTabs.setTabsClosable(True) + + # Set as current tab + self.plotTabs.setCurrentWidget(self.currTab) + + # Adjust size + self.adjustCanvas() + + return self.vtkCanvas + + def createVtkCanvas(self, addRenderer=False): + + """Create vtk canvas. Keyword Args: addRenderer (bool): Adds renderer. @@ -2863,182 +3222,198 @@ def createVtkCanvas(self,addRenderer=False): vtk.QVTKRenderWindowInteractor """ - - self.vtkCanvas = QVTKRenderWindowInteractor(self.currTab) - self.vtkCanvas.UpdateSize(int(self.currTab.width()),int(self.currTab.height())) - - self.vboxVTKCanvas = QtGui.QVBoxLayout() - self.vboxVTKCanvas.addWidget(self.vtkCanvas,stretch=1) - - self.currTab.setLayout(self.vboxVTKCanvas) - - if addRenderer: - self.renderer=vtk.vtkRenderer() - self.vtkCanvas.GetRenderWindow().AddRenderer(self.renderer) - - return self.vtkCanvas - - def adjustCanvas(self): - - """Adjust canvas if slider/splitter changes to currently maximum size. + + self.vtkCanvas = QVTKRenderWindowInteractor(self.currTab) + self.vtkCanvas.UpdateSize(int(self.currTab.width()), int(self.currTab.height())) + + self.vboxVTKCanvas = QtWidgets.QVBoxLayout() + self.vboxVTKCanvas.addWidget(self.vtkCanvas, stretch=1) + + self.currTab.setLayout(self.vboxVTKCanvas) + + if addRenderer: + self.renderer = vtk.vtkRenderer() + self.vtkCanvas.GetRenderWindow().AddRenderer(self.renderer) + + return self.vtkCanvas + + def adjustCanvas(self): + + """Adjust canvas if slider/splitter changes to currently maximum size. """ - - if hasattr(self,'currTab'): - h=int(self.horizontalSplitter.sizes()[1]) - v=int(self.verticalSplitter.sizes()[0]) - self.currTab.resize(h,v) - else: - return - - if not hasattr(self,'fig'): - return - - if self.fig!=None: - - h=float(self.horizontalSplitter.sizes()[1])/float(self.dpi) - v=float(self.verticalSplitter.sizes()[0])/float(self.dpi) - - if hasattr(self.currTab,'currSlider'): - - hSlider=float(self.currTab.currSlider.size().width())/float(self.dpi) - vSlider=float(self.currTab.currSlider.size().height())/float(self.dpi) - - v=v-5*vSlider - - self.fig.set_size_inches(h,v,forward=False) - - self.canvas.draw() - return - - elif self.fig==None: - - h=int(self.horizontalSplitter.sizes()[1]) - v=int(self.verticalSplitter.sizes()[0]) - - self.vtkCanvas.UpdateSize(h,v) - return - - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - #SecSettings: Settings handling - #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - - def setPath(self,identifier="",path=""): - - """Opens path setting dialog and afterwards sets path in path file. + + if hasattr(self, "currTab"): + h = int(self.horizontalSplitter.sizes()[1]) + v = int(self.verticalSplitter.sizes()[0]) + self.currTab.resize(h, v) + else: + return + + if not hasattr(self, "fig"): + return + + if self.fig != None: + + h = float(self.horizontalSplitter.sizes()[1]) / float(self.dpi) + v = float(self.verticalSplitter.sizes()[0]) / float(self.dpi) + + if hasattr(self.currTab, "currSlider"): + + hSlider = float(self.currTab.currSlider.size().width()) / float( + self.dpi + ) + vSlider = float(self.currTab.currSlider.size().height()) / float( + self.dpi + ) + + v = v - 5 * vSlider + + self.fig.set_size_inches(h, v, forward=False) + + self.canvas.draw() + return + + elif self.fig == None: + + h = int(self.horizontalSplitter.sizes()[1]) + v = int(self.verticalSplitter.sizes()[0]) + + self.vtkCanvas.UpdateSize(h, v) + return + + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + # SecSettings: Settings handling + # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def setPath(self, identifier="", path=""): + + """Opens path setting dialog and afterwards sets path in path file. Keyword Args: identifier (str): Identifier displayed at dialog startup. path (str): Path displayed at dialog startup. """ - - pathDialog = pyfrp_gui_settings_dialogs.pathDialog(identifier,path,self) - if pathDialog.exec_(): - identifier,path = pathDialog.getPath() - - pyfrp_misc_module.setPath(identifier,path) - - return 1 - - def setGmshPath(self): - - """Opens path setting dialog and lets user set path to gmsh binary. + + pathDialog = pyfrp_gui_settings_dialogs.pathDialog(identifier, path, self) + if pathDialog.exec_(): + identifier, path = pathDialog.getPath() + + pyfrp_misc_module.setPath(identifier, path) + + return 1 + + def setGmshPath(self): + + """Opens path setting dialog and lets user set path to gmsh binary. """ - - path=pyfrp_misc_module.getPath('gmshBin') - self.setPath(identifier='gmshBin',path=path) - - return 1 - - def setFijiPath(self): - - """Opens path setting dialog and lets user set path to gmsh binary. + + path = pyfrp_misc_module.getPath("gmshBin") + self.setPath(identifier="gmshBin", path=path) + + return 1 + + def setFijiPath(self): + + """Opens path setting dialog and lets user set path to gmsh binary. """ - - path=pyfrp_misc_module.getPath('fijiBin') - self.setPath(identifier='fijiBin',path=path) - - return 1 - - def setOpenscadPath(self): - - """Opens path setting dialog and lets user set path to gmsh binary. + + path = pyfrp_misc_module.getPath("fijiBin") + self.setPath(identifier="fijiBin", path=path) + + return 1 + + def setOpenscadPath(self): + + """Opens path setting dialog and lets user set path to gmsh binary. """ - - path=pyfrp_misc_module.getPath('openscadBin') - self.setPath(identifier='openscadBin',path=path) - - return 1 - - def printPathFile(self): - - """Prints out path file.""" - - print pyfrp_misc_module.getPathFile() - - return 1 - - def printPaths(self): - - """Prints out all content of path file.""" - - pyfrp_misc_module.printPaths() - - return 1 - - def checkPaths(self): - - """Checks if all paths in path file exist.""" - - pyfrp_misc_module.checkPaths() - - return 1 - - def setPathFile(self): - - """Allows setting the path file.""" - - fn = str(QtGui.QFileDialog.getOpenFileName(self, 'Choose path file',pyfrp_misc_module.getConfDir(),)) - if fn=='': - return 0 - - self.config.setPathFile(fn) - - return 1 - - -#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -#Main function calling PyFRAP main GUI -#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - + path = pyfrp_misc_module.getPath("openscadBin") + self.setPath(identifier="openscadBin", path=path) + + return 1 + + def printPathFile(self): + + """Prints out path file.""" + + print(pyfrp_misc_module.getPathFile()) + + return 1 + + def printPaths(self): + + """Prints out all content of path file.""" + + pyfrp_misc_module.printPaths() + + return 1 + + def checkPaths(self): + + """Checks if all paths in path file exist.""" + + pyfrp_misc_module.checkPaths() + + return 1 + + def setPathFile(self): + + """Allows setting the path file.""" + + fn = str( + QtWidgets.QFileDialog.getOpenFileName( + self, "Choose path file", pyfrp_misc_module.getConfDir() + ) + ) + if fn == "": + return 0 + + self.config.setPathFile(fn) + + return 1 + + +# --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +# Main function calling PyFRAP main GUI +# --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + def main(): - - #Creating application - #font=QtGui.QFont() - app = QtGui.QApplication(sys.argv) - font=app.font() - font.setPointSize(12) - app.setFont(font) - - #Check if stout/sterr should be redirected - try: - print sys.argv[1] - redirect=bool(int(sys.argv[1])) - print redirect - except: - redirect=True - - # Start javabridge - javabridge.start_vm(class_path=bioformats.JARS) - - mainWin = pyfrp(redirect=redirect) - mainWin.show() - - sys.exit(app.exec_()) - -if __name__ == '__main__': - main() + + # Creating application + # font=QtGui.QFont() + app = QtWidgets.QApplication(sys.argv) + font = app.font() + font.setPointSize(12) + app.setFont(font) + + # Check if stout/sterr should be redirected + try: + print("redirect = %s" % sys.argv[1]) + redirect = bool(int(sys.argv[1])) + # print(redirect) + except IndexError: + redirect = True + + try: + print("overwrite_conf = %s" % sys.argv[2]) + overwrite_conf = bool(int(sys.argv[2])) + # print(redirect) + except IndexError: + overwrite_conf = False + + # Start javabridge + try: + javabridge.start_vm(class_path=bioformats.JARS) + except: + printWarning("Not able to start javabridge") + + mainWin = pyfrp(redirect=redirect, overwrite_conf=overwrite_conf) + mainWin.show() + + sys.exit(app.exec_()) +if __name__ == "__main__": + main() diff --git a/pyfrp/gui/pyfrp_gui_ROI_manager.py b/pyfrp/gui/pyfrp_gui_ROI_manager.py old mode 100644 new mode 100755 index 4f79261..6163859 --- a/pyfrp/gui/pyfrp_gui_ROI_manager.py +++ b/pyfrp/gui/pyfrp_gui_ROI_manager.py @@ -43,10 +43,10 @@ #=========================================================================================================================================================================== #QT -from PyQt4 import QtGui, QtCore +from PyQt5 import QtGui, QtCore, QtWidgets #PyFRAP GUI classes -import pyfrp_gui_basics +from . import pyfrp_gui_basics #PyFRAP modules from pyfrp.modules.pyfrp_term_module import * @@ -65,7 +65,7 @@ #Main ROI Manager #=================================================================================================================================== -class ROImanager(QtGui.QDialog): +class ROImanager(QtWidgets.QDialog): def __init__(self,embryo,parent): super(ROImanager,self).__init__(parent) @@ -79,7 +79,7 @@ def __init__(self,embryo,parent): #TreeWidget #------------------------------------------------------------------------------------------------------------------- - self.ROIList=QtGui.QTreeWidget() + self.ROIList=QtWidgets.QTreeWidget() self.ROIList.setHeaderLabels(["Name","Typ"]) self.ROIList.setColumnWidth(0,200) self.ROIList.itemClicked.connect(self.roiSelected) @@ -88,32 +88,32 @@ def __init__(self,embryo,parent): #Buttons #------------------------------------------------------------------------------------------------------------------- - self.btnDone=QtGui.QPushButton('Done') - self.btnDone.connect(self.btnDone, QtCore.SIGNAL('clicked()'), self.donePressed) + self.btnDone=QtWidgets.QPushButton('Done') + self.btnDone.clicked.connect(self.donePressed) - self.btnNewROI=QtGui.QPushButton('New') - self.btnNewROI.connect(self.btnNewROI, QtCore.SIGNAL('clicked()'), self.newROI) + self.btnNewROI=QtWidgets.QPushButton('New') + self.btnNewROI.clicked.connect(self.newROI) - self.btnRemoveROI=QtGui.QPushButton('Remove') - self.btnRemoveROI.connect(self.btnRemoveROI, QtCore.SIGNAL('clicked()'), self.removeROI) + self.btnRemoveROI=QtWidgets.QPushButton('Remove') + self.btnRemoveROI.clicked.connect(self.removeROI) - self.btnEditROI=QtGui.QPushButton('Edit') - self.btnEditROI.connect(self.btnEditROI, QtCore.SIGNAL('clicked()'), self.editROI) + self.btnEditROI=QtWidgets.QPushButton('Edit') + self.btnEditROI.clicked.connect(self.editROI) - self.btnComputeIdxs=QtGui.QPushButton('Compute Idxs') - self.btnComputeIdxs.connect(self.btnComputeIdxs, QtCore.SIGNAL('clicked()'), self.computeIdxs) + self.btnComputeIdxs=QtWidgets.QPushButton('Compute Idxs') + self.btnComputeIdxs.clicked.connect(self.computeIdxs) - self.btnComputeAllIdxs=QtGui.QPushButton('Compute Idxs') - self.btnComputeAllIdxs.connect(self.btnComputeAllIdxs, QtCore.SIGNAL('clicked()'), self.computeAllIdxs) + self.btnComputeAllIdxs=QtWidgets.QPushButton('Compute Idxs') + self.btnComputeAllIdxs.clicked.connect(self.computeAllIdxs) - self.btnShowIdxs=QtGui.QPushButton('Show Idxs') - #self.btnShowIdxs.connect(self.btnShowIdxs, QtCore.SIGNAL('clicked()'), self.showIdxs) + self.btnShowIdxs=QtWidgets.QPushButton('Show Idxs') + self.btnShowIdxs.clicked.connect(self.showIdxs) #------------------------------------------------------------------------------------------------------------------- #Combo Box #------------------------------------------------------------------------------------------------------------------- - self.comboType = QtGui.QComboBox(self) + self.comboType = QtWidgets.QComboBox(self) self.comboType.addItem("radial") self.comboType.addItem("slice") self.comboType.addItem("radialSlice") @@ -129,7 +129,7 @@ def __init__(self,embryo,parent): #Layout #------------------------------------------------------------------------------------------------------------------- - self.grid = QtGui.QGridLayout() + self.grid = QtWidgets.QGridLayout() self.grid.addWidget(self.btnNewROI,1,1) self.grid.addWidget(self.btnEditROI,2,1) @@ -141,11 +141,11 @@ def __init__(self,embryo,parent): self.grid.addWidget(self.comboType,2,2) - self.hbox = QtGui.QHBoxLayout() + self.hbox = QtWidgets.QHBoxLayout() self.hbox.addLayout(self.grid) self.hbox.addWidget(self.ROIList) - self.vbox = QtGui.QVBoxLayout() + self.vbox = QtWidgets.QVBoxLayout() self.vbox.addLayout(self.hbox) self.vbox.addWidget(self.btnDone) @@ -164,7 +164,7 @@ def updateROIList(self): self.ROIList.clear() for r in self.embryo.ROIs: - QtGui.QTreeWidgetItem(self.ROIList,[r.name,r.getType()]) + QtWidgets.QTreeWidgetItem(self.ROIList,[r.name,r.getType()]) return self.ROIList def newROI(self): @@ -276,15 +276,15 @@ def __init__(self,ROI,parent): self.ROI=ROI #Labels - self.lblName = QtGui.QLabel("Name:", self) - self.lblZmin = QtGui.QLabel("zmin:", self) - self.lblZmax = QtGui.QLabel("zmax:", self) - self.lblColor = QtGui.QLabel("Color:", self) + self.lblName = QtWidgets.QLabel("Name:", self) + self.lblZmin = QtWidgets.QLabel("zmin:", self) + self.lblZmax = QtWidgets.QLabel("zmax:", self) + self.lblColor = QtWidgets.QLabel("Color:", self) #LineEdits - self.qleName = QtGui.QLineEdit(self.ROI.name) - self.qleZmin = QtGui.QLineEdit(str(self.ROI.zmin)) - self.qleZmax = QtGui.QLineEdit(str(self.ROI.zmax)) + self.qleName = QtWidgets.QLineEdit(self.ROI.name) + self.qleZmin = QtWidgets.QLineEdit(str(self.ROI.zmin)) + self.qleZmax = QtWidgets.QLineEdit(str(self.ROI.zmax)) self.doubleValid=QtGui.QDoubleValidator() @@ -296,14 +296,14 @@ def __init__(self,ROI,parent): self.qleZmax.editingFinished.connect(self.setZmax) #Checkboxes - self.cbUseForRim = QtGui.QCheckBox('Use for rim?', self) + self.cbUseForRim = QtWidgets.QCheckBox('Use for rim?', self) self.cbUseForRim.setCheckState(2*int(self.ROI.useForRim)) - self.connect(self.cbUseForRim, QtCore.SIGNAL('stateChanged(int)'), self.checkUseForRim) + self.cbUseForRim.stateChanged.connect(self.checkUseForRim) #Buttons self.initColorButton() - self.btnColor.connect(self.btnColor, QtCore.SIGNAL('clicked()'), self.setColor) + self.btnColor.clicked.connect(self.setColor) #Layout self.grid.addWidget(self.lblName,1,1) @@ -348,7 +348,7 @@ def checkUseForRim(self,val): return self.ROI.getUseForRim() def initColorButton(self): - self.btnColor=QtGui.QPushButton(' ') + self.btnColor=QtWidgets.QPushButton(' ') self.updateColorButton() return @@ -410,12 +410,12 @@ def __init__(self,ROI,parent): super(sliceROIDialog,self).__init__(ROI,parent) #Labels - self.lblHeight = QtGui.QLabel("Height:", self) - self.lblWidth = QtGui.QLabel("Width:", self) + self.lblHeight = QtWidgets.QLabel("Height:", self) + self.lblWidth = QtWidgets.QLabel("Width:", self) #LineEdits - self.qleHeight = QtGui.QLineEdit(str(self.ROI.height)) - self.qleWidth = QtGui.QLineEdit(str(self.ROI.width)) + self.qleHeight = QtWidgets.QLineEdit(str(self.ROI.height)) + self.qleWidth = QtWidgets.QLineEdit(str(self.ROI.width)) self.qleHeight.setValidator(self.doubleValid) self.qleWidth.setValidator(self.doubleValid) @@ -424,10 +424,10 @@ def __init__(self,ROI,parent): self.qleWidth.editingFinished.connect(self.setWidth) #Checkboxes - self.cbSliceBottom = QtGui.QCheckBox('SliceBottom?', self) + self.cbSliceBottom = QtWidgets.QCheckBox('SliceBottom?', self) self.cbSliceBottom.setCheckState(2*int(self.ROI.sliceBottom)) - self.connect(self.cbSliceBottom, QtCore.SIGNAL('stateChanged(int)'), self.checkSliceBottom) + self.cbSliceBottom.stateChanged.connect(self.checkSliceBottom) #Layout nRows=self.grid.rowCount() @@ -465,19 +465,19 @@ def __init__(self,ROI,parent): super(radialROIDialog,self).__init__(ROI,parent) #Labels - self.lblRadius = QtGui.QLabel("Radius:", self) - self.lblCenter = QtGui.QLabel("Center:", self) + self.lblRadius = QtWidgets.QLabel("Radius:", self) + self.lblCenter = QtWidgets.QLabel("Center:", self) #LineEdits - self.qleRadius = QtGui.QLineEdit(str(self.ROI.radius)) - self.qleCenterX = QtGui.QLineEdit(str(self.ROI.center[0])) - self.qleCenterY = QtGui.QLineEdit(str(self.ROI.center[1])) + self.qleRadius = QtWidgets.QLineEdit(str(self.ROI.radius)) + self.qleCenterX = QtWidgets.QLineEdit(str(self.ROI.center[0])) + self.qleCenterY = QtWidgets.QLineEdit(str(self.ROI.center[1])) self.qleRadius.setValidator(self.doubleValid) self.qleCenterX.setValidator(self.doubleValid) self.qleCenterY.setValidator(self.doubleValid) - self.centerGrid = QtGui.QGridLayout() + self.centerGrid = QtWidgets.QGridLayout() self.centerGrid.addWidget(self.qleCenterX) self.centerGrid.addWidget(self.qleCenterY) @@ -656,19 +656,19 @@ def __init__(self,ROI,parent): super(squareROIDialog,self).__init__(ROI,parent) #Labels - self.lblSidelength = QtGui.QLabel("Sidelength:", self) - self.lblOffset = QtGui.QLabel("Offset:", self) + self.lblSidelength = QtWidgets.QLabel("Sidelength:", self) + self.lblOffset = QtWidgets.QLabel("Offset:", self) #LineEdits - self.qleSidelength = QtGui.QLineEdit(str(self.ROI.sidelength)) - self.qleOffsetX = QtGui.QLineEdit(str(self.ROI.offset[0])) - self.qleOffsetY = QtGui.QLineEdit(str(self.ROI.offset[1])) + self.qleSidelength = QtWidgets.QLineEdit(str(self.ROI.sidelength)) + self.qleOffsetX = QtWidgets.QLineEdit(str(self.ROI.offset[0])) + self.qleOffsetY = QtWidgets.QLineEdit(str(self.ROI.offset[1])) self.qleSidelength.setValidator(self.doubleValid) self.qleOffsetX.setValidator(self.doubleValid) self.qleOffsetY.setValidator(self.doubleValid) - self.offsetGrid = QtGui.QGridLayout() + self.offsetGrid = QtWidgets.QGridLayout() self.offsetGrid.addWidget(self.qleOffsetX) self.offsetGrid.addWidget(self.qleOffsetY) @@ -828,22 +828,22 @@ def __init__(self,ROI,parent): super(rectangleROIDialog,self).__init__(ROI,parent) #Labels - self.lblSidelengthX = QtGui.QLabel("SidelengthX:", self) - self.lblSidelengthY = QtGui.QLabel("SidelengthY:", self) - self.lblOffset = QtGui.QLabel("Offset:", self) + self.lblSidelengthX = QtWidgets.QLabel("SidelengthX:", self) + self.lblSidelengthY = QtWidgets.QLabel("SidelengthY:", self) + self.lblOffset = QtWidgets.QLabel("Offset:", self) #LineEdits - self.qleSidelengthX = QtGui.QLineEdit(str(self.ROI.sidelengthX)) - self.qleSidelengthY = QtGui.QLineEdit(str(self.ROI.sidelengthY)) - self.qleOffsetX = QtGui.QLineEdit(str(self.ROI.offset[0])) - self.qleOffsetY = QtGui.QLineEdit(str(self.ROI.offset[1])) + self.qleSidelengthX = QtWidgets.QLineEdit(str(self.ROI.sidelengthX)) + self.qleSidelengthY = QtWidgets.QLineEdit(str(self.ROI.sidelengthY)) + self.qleOffsetX = QtWidgets.QLineEdit(str(self.ROI.offset[0])) + self.qleOffsetY = QtWidgets.QLineEdit(str(self.ROI.offset[1])) self.qleSidelengthX.setValidator(self.doubleValid) self.qleSidelengthY.setValidator(self.doubleValid) self.qleOffsetX.setValidator(self.doubleValid) self.qleOffsetY.setValidator(self.doubleValid) - self.offsetGrid = QtGui.QGridLayout() + self.offsetGrid = QtWidgets.QGridLayout() self.offsetGrid.addWidget(self.qleOffsetX) self.offsetGrid.addWidget(self.qleOffsetY) @@ -1044,16 +1044,16 @@ def __init__(self,ROI,parent): self.currInd=None #Labels - self.lblCorners = QtGui.QLabel("Corners:", self) + self.lblCorners = QtWidgets.QLabel("Corners:", self) #TreeWidget - self.cornerList=QtGui.QTreeWidget() + self.cornerList=QtWidgets.QTreeWidget() self.cornerList.setHeaderLabels(["x","y"]) self.cornerList.itemClicked.connect(self.cornerSelected) #Buttons - self.btnRemoveCorner=QtGui.QPushButton('Remove') - self.btnRemoveCorner.connect(self.btnRemoveCorner, QtCore.SIGNAL('clicked()'), self.removeCornerPressed) + self.btnRemoveCorner=QtWidgets.QPushButton('Remove') + self.btnRemoveCorner.clicked.connect(self.removeCornerPressed) #Layout nRows=self.grid.rowCount() @@ -1072,7 +1072,7 @@ def __init__(self,ROI,parent): def updateCornerList(self): self.cornerList.clear() for corner in self.ROI.corners: - QtGui.QTreeWidgetItem(self.cornerList,[str(corner[0]),str(corner[1])]) + QtWidgets.QTreeWidgetItem(self.cornerList,[str(corner[0]),str(corner[1])]) return self.cornerList def cornerSelected(self): @@ -1210,7 +1210,7 @@ def moveLeft(self): if len(self.artists)>0 and self.highlighted!=None: self.ROI.moveCorner(self.currInd,self.currCorner[0]-1,self.currCorner[1]) - print self.ROI.getCorners() + print(self.ROI.getCorners()) self.updateCornerList() self.drawPolygon() @@ -1258,33 +1258,33 @@ def __init__(self,ROI,parent): super(customROIDialog,self).__init__(ROI,parent) #Labels - self.lblAvailable = QtGui.QLabel("Available ROIs:", self) - self.lblIncluded = QtGui.QLabel("Included ROIs:", self) + self.lblAvailable = QtWidgets.QLabel("Available ROIs:", self) + self.lblIncluded = QtWidgets.QLabel("Included ROIs:", self) #TreeWidget - self.includedList=QtGui.QTreeWidget() + self.includedList=QtWidgets.QTreeWidget() self.includedList.setHeaderLabels(["name","operation"]) self.includedList.itemClicked.connect(self.includedSelected) - self.availableList=QtGui.QTreeWidget() + self.availableList=QtWidgets.QTreeWidget() self.availableList.setHeaderLabels(["name"]) self.availableList.itemClicked.connect(self.availableSelected) #Buttons - self.btnRemoveROI=QtGui.QPushButton('Remove') - self.btnRemoveROI.connect(self.btnRemoveROI, QtCore.SIGNAL('clicked()'), self.removeROI) + self.btnRemoveROI=QtWidgets.QPushButton('Remove') + self.btnRemoveROI.clicked.connect(self.removeROI) - self.btnAddROI=QtGui.QPushButton('Add') - self.btnAddROI.connect(self.btnAddROI, QtCore.SIGNAL('clicked()'), self.addROI) + self.btnAddROI=QtWidgets.QPushButton('Add') + self.btnAddROI.clicked.connect(self.addROI) - self.btnSubsctractROI=QtGui.QPushButton('Substract') - self.btnSubsctractROI.connect(self.btnSubsctractROI, QtCore.SIGNAL('clicked()'), self.substractROI) + self.btnSubsctractROI=QtWidgets.QPushButton('Substract') + self.btnSubsctractROI.clicked.connect(self.substractROI) - self.btnMoveUp=QtGui.QPushButton('Move Up') - self.btnMoveUp.connect(self.btnMoveUp, QtCore.SIGNAL('clicked()'), self.moveROIUp) + self.btnMoveUp=QtWidgets.QPushButton('Move Up') + self.btnMoveUp.clicked.connect(self.moveROIUp) - self.btnMoveDown=QtGui.QPushButton('Move Down') - self.btnMoveDown.connect(self.btnMoveDown, QtCore.SIGNAL('clicked()'), self.moveROIDown) + self.btnMoveDown=QtWidgets.QPushButton('Move Down') + self.btnMoveDown.clicked.connect(self.moveROIDown) #Layout nRows=self.grid.rowCount() @@ -1311,7 +1311,7 @@ def updateAvailableList(self): self.availableList.clear() for roi in self.ROI.embryo.ROIs: if roi not in self.ROI.ROIsIncluded and roi!=self: - item=QtGui.QTreeWidgetItem(self.availableList,[roi.name]) + item=QtWidgets.QTreeWidgetItem(self.availableList,[roi.name]) item.setBackgroundColor(0,self.getQColor(roi.color)) a=self.getQColor(roi.color) @@ -1329,7 +1329,7 @@ def updateIncludedList(self): op=' ' printWarning('Unknown procedure ' + str(roi.procedures[i])) - item=QtGui.QTreeWidgetItem(self.includedList,[roi.name,op]) + item=QtWidgets.QTreeWidgetItem(self.includedList,[roi.name,op]) item.setBackgroundColor(0,self.getQColor(roi.color)) item.setBackgroundColor(1,self.getQColor(roi.color)) @@ -1430,11 +1430,11 @@ def __init__(self,embryo,parent): self.radius=300 #Labels - self.lblRadius = QtGui.QLabel("Radius of ROIs:", self) - self.lblCenter = QtGui.QLabel("Center of ROIs:", self) + self.lblRadius = QtWidgets.QLabel("Radius of ROIs:", self) + self.lblCenter = QtWidgets.QLabel("Center of ROIs:", self) #LineEdits - self.qleRadius = QtGui.QLineEdit(str(self.radius)) + self.qleRadius = QtWidgets.QLineEdit(str(self.radius)) self.initCenterQle() @@ -1453,7 +1453,7 @@ def __init__(self,embryo,parent): self.grid.addWidget(self.lblRadius,nRows+1,1) self.grid.addWidget(self.lblCenter,nRows+2,1) - self.centerGrid = QtGui.QGridLayout() + self.centerGrid = QtWidgets.QGridLayout() self.centerGrid.addWidget(self.qleCenterX) self.centerGrid.addWidget(self.qleCenterY) @@ -1477,8 +1477,8 @@ def initCenterQle(self): self.center=[256,256] else: self.center=list(self.embryo.geometry.center) - self.qleCenterX = QtGui.QLineEdit(str(self.center[0])) - self.qleCenterY = QtGui.QLineEdit(str(self.center[1])) + self.qleCenterX = QtWidgets.QLineEdit(str(self.center[0])) + self.qleCenterY = QtWidgets.QLineEdit(str(self.center[1])) def setCenter(self): self.center=[float(self.qleCenterX.text()),float(self.qleCenterY.text())] @@ -1650,7 +1650,7 @@ def donePressed(self): #Default ROI Dialog #=================================================================================================================================== -class ROISelector(QtGui.QDialog): +class ROISelector(QtWidgets.QDialog): """Simple dialog allowing to select between different ROI types. @@ -1665,17 +1665,17 @@ def __init__(self,embryo,initType,parent,**kwargs): self.ROI=None #Labels - self.lblMsg=QtGui.QLabel(self.msg, self) + self.lblMsg=QtWidgets.QLabel(self.msg, self) #Buttons - self.btnDefault=QtGui.QPushButton('Use Default') - self.btnDefault.connect(self.btnDefault, QtCore.SIGNAL('clicked()'), self.defaultPressed) + self.btnDefault=QtWidgets.QPushButton('Use Default') + self.btnDefault.clicked.connect(self.defaultPressed) - self.btnDone=QtGui.QPushButton('Create ROI') - self.btnDone.connect(self.btnDone, QtCore.SIGNAL('clicked()'), self.donePressed) + self.btnDone=QtWidgets.QPushButton('Create ROI') + self.btnDone.clicked.connect(self.donePressed) #Combo box - self.comboType = QtGui.QComboBox(self) + self.comboType = QtWidgets.QComboBox(self) self.comboType.addItem("radial") self.comboType.addItem("slice") self.comboType.addItem("radialSlice") @@ -1690,7 +1690,7 @@ def __init__(self,embryo,initType,parent,**kwargs): self.initComboType(initType) #Layout - self.vbox = QtGui.QVBoxLayout() + self.vbox = QtWidgets.QVBoxLayout() self.vbox.addWidget(self.lblMsg) self.vbox.addWidget(self.comboType) self.vbox.addWidget(self.btnDefault) @@ -1723,13 +1723,13 @@ def parseInInput(self,kwargs,embryo): self.embryo=embryo #Grab ROI name - if "name" in kwargs.keys(): + if "name" in list(kwargs.keys()): self.name=str(kwargs["name"]) else: self.name="newROI" #Grab center - if "center" in kwargs.keys(): + if "center" in list(kwargs.keys()): self.center=kwargs["center"] else: if self.embryo.geometry!=None: @@ -1738,55 +1738,55 @@ def parseInInput(self,kwargs,embryo): self.center=[self.embryo.dataResPx/2.]*2 #Grab sidelength - if "sidelength" in kwargs.keys(): + if "sidelength" in list(kwargs.keys()): self.sidelength=kwargs["sidelength"] else: self.sidelength=100 #Grab offset - if "offset" in kwargs.keys(): + if "offset" in list(kwargs.keys()): self.offset=kwargs["offset"] else: self.offset=np.asarray(self.center)-self.sidelength/2. #Grab radius - if "radius" in kwargs.keys(): + if "radius" in list(kwargs.keys()): self.radius=kwargs["radius"] else: self.radius=200. #Grab color - if "color" in kwargs.keys(): + if "color" in list(kwargs.keys()): self.color=kwargs["color"] else: self.color='r' #Grab slice height - if "sliceHeight" in kwargs.keys(): + if "sliceHeight" in list(kwargs.keys()): self.sliceHeight=kwargs["sliceHeight"] else: self.sliceHeight=self.embryo.sliceHeightPx #Grab slice width - if "sliceWidth" in kwargs.keys(): + if "sliceWidth" in list(kwargs.keys()): self.sliceWidth=kwargs["sliceWidth"] else: self.sliceWidth=self.embryo.sliceWidthPx #Grab title - if "title" in kwargs.keys(): + if "title" in list(kwargs.keys()): self.title=kwargs["title"] else: self.title="ROI Selector" #Grab Message - if "msg" in kwargs.keys(): + if "msg" in list(kwargs.keys()): self.msg=kwargs["msg"] else: self.msg="Select ROI type" #Grab asMaster - if "asMaster" in kwargs.keys(): + if "asMaster" in list(kwargs.keys()): self.asMaster=kwargs["asMaster"] else: self.asMaster=False @@ -1894,7 +1894,7 @@ def runTask(self,debug=False): #Dialogs for wizard selection #=================================================================================================================================== -class wizardSelector(QtGui.QDialog): +class wizardSelector(QtWidgets.QDialog): """Dialog to select if either use default ROIs, Wizard, or ROI manager.""" @@ -1908,16 +1908,16 @@ def __init__(self,parent): self.mode=None #Buttons - self.btnUseDefault=QtGui.QPushButton('Create default ROIs') - self.btnUseDefault.connect(self.btnUseDefault, QtCore.SIGNAL('clicked()'), self.setUseDefault) + self.btnUseDefault=QtWidgets.QPushButton('Create default ROIs') + self.btnUseDefault.clicked.connect(self.setUseDefault) - self.btnUseWizard=QtGui.QPushButton('Use ROI Wizard') - self.btnUseWizard.connect(self.btnUseWizard, QtCore.SIGNAL('clicked()'), self.setUseWizard) + self.btnUseWizard=QtWidgets.QPushButton('Use ROI Wizard') + self.btnUseWizard.clicked.connect(self.setUseWizard) - self.btnUseManager=QtGui.QPushButton('Use ROI Manager') - self.btnUseManager.connect(self.btnUseManager, QtCore.SIGNAL('clicked()'), self.setUseManager) + self.btnUseManager=QtWidgets.QPushButton('Use ROI Manager') + self.btnUseManager.clicked.connect(self.setUseManager) - self.vbox = QtGui.QVBoxLayout() + self.vbox = QtWidgets.QVBoxLayout() self.vbox.addWidget(self.btnUseDefault) self.vbox.addWidget(self.btnUseWizard) self.vbox.addWidget(self.btnUseManager) @@ -1941,4 +1941,4 @@ def setUseManager(self): self.done(1) def getMode(self): - return self.mode \ No newline at end of file + return self.mode diff --git a/pyfrp/gui/pyfrp_gui_analysis_dialogs.py b/pyfrp/gui/pyfrp_gui_analysis_dialogs.py old mode 100644 new mode 100755 index 9c93b0e..5fa429e --- a/pyfrp/gui/pyfrp_gui_analysis_dialogs.py +++ b/pyfrp/gui/pyfrp_gui_analysis_dialogs.py @@ -32,10 +32,10 @@ #=========================================================================================================================================================================== #QT -from PyQt4 import QtGui, QtCore +from PyQt5 import QtGui, QtCore, QtWidgets #PyFRAP GUI classes -import pyfrp_gui_basics +from . import pyfrp_gui_basics #PyFRAP modules from pyfrp.modules.pyfrp_term_module import * @@ -63,32 +63,32 @@ def __init__(self,analysis,parent): self.nCharDisplayed=50 #Labels - self.lblFnPreimage = QtGui.QLabel("Pre-Image:", self) - self.lblFnFlatten = QtGui.QLabel("Flattening Folder:", self) - self.lblFnBkgd = QtGui.QLabel("Background Folder:", self) + self.lblFnPreimage = QtWidgets.QLabel("Pre-Image:", self) + self.lblFnFlatten = QtWidgets.QLabel("Flattening Folder:", self) + self.lblFnBkgd = QtWidgets.QLabel("Background Folder:", self) - self.lblMedianRadius = QtGui.QLabel("Median Radius:", self) - self.lblGaussianSigma = QtGui.QLabel("Gaussian Sigma:", self) + self.lblMedianRadius = QtWidgets.QLabel("Median Radius:", self) + self.lblGaussianSigma = QtWidgets.QLabel("Gaussian Sigma:", self) - self.lblFnPreimageValue = QtGui.QLabel("", self) - self.lblFnFlattenValue = QtGui.QLabel("", self) - self.lblFnBkgdValue = QtGui.QLabel("", self) + self.lblFnPreimageValue = QtWidgets.QLabel("", self) + self.lblFnFlattenValue = QtWidgets.QLabel("", self) + self.lblFnBkgdValue = QtWidgets.QLabel("", self) - self.lblNPre = QtGui.QLabel("Number of Images used: ", self) - self.lblNFlatten = QtGui.QLabel("Number of Images used: ", self) - self.lblNBkgd = QtGui.QLabel("Number of Images used: ", self) + self.lblNPre = QtWidgets.QLabel("Number of Images used: ", self) + self.lblNFlatten = QtWidgets.QLabel("Number of Images used: ", self) + self.lblNBkgd = QtWidgets.QLabel("Number of Images used: ", self) self.updateFlattenLbl() self.updatePreImageLbl() self.updateBkgdLbl() #LineEdits - self.qleMedianRadius = QtGui.QLineEdit(str(self.analysis.medianRadius)) - self.qleGaussianSigma = QtGui.QLineEdit(str(self.analysis.gaussianSigma)) + self.qleMedianRadius = QtWidgets.QLineEdit(str(self.analysis.medianRadius)) + self.qleGaussianSigma = QtWidgets.QLineEdit(str(self.analysis.gaussianSigma)) - self.qleNPre = QtGui.QLineEdit(str(self.analysis.nPre)) - self.qleNFlatten = QtGui.QLineEdit(str(self.analysis.nFlatten)) - self.qleNBkgd = QtGui.QLineEdit(str(self.analysis.nBkgd)) + self.qleNPre = QtWidgets.QLineEdit(str(self.analysis.nPre)) + self.qleNFlatten = QtWidgets.QLineEdit(str(self.analysis.nFlatten)) + self.qleNBkgd = QtWidgets.QLineEdit(str(self.analysis.nBkgd)) self.doubleValid=QtGui.QDoubleValidator() self.intValid=QtGui.QIntValidator() @@ -108,47 +108,47 @@ def __init__(self,analysis,parent): self.qleNFlatten.editingFinished.connect(self.setNFlatten) #Checkboxes - self.cbNorm = QtGui.QCheckBox('Norm by pre-image?', self) - self.cbMedian = QtGui.QCheckBox('Apply median filter?', self) - self.cbGaussian = QtGui.QCheckBox('Apply gaussian filter?', self) - self.cbFlatten = QtGui.QCheckBox('Apply flattening mask?', self) - self.cbBkgd = QtGui.QCheckBox('Substract Background mask?', self) + self.cbNorm = QtWidgets.QCheckBox('Norm by pre-image?', self) + self.cbMedian = QtWidgets.QCheckBox('Apply median filter?', self) + self.cbGaussian = QtWidgets.QCheckBox('Apply gaussian filter?', self) + self.cbFlatten = QtWidgets.QCheckBox('Apply flattening mask?', self) + self.cbBkgd = QtWidgets.QCheckBox('Substract Background mask?', self) - self.cbQuad = QtGui.QCheckBox('Flip to quadrant?', self) - self.cbFlip = QtGui.QCheckBox('Flip before process?', self) + self.cbQuad = QtWidgets.QCheckBox('Flip to quadrant?', self) + self.cbFlip = QtWidgets.QCheckBox('Flip before process?', self) self.updateCBs() - self.connect(self.cbMedian, QtCore.SIGNAL('stateChanged(int)'), self.checkMedian) - self.connect(self.cbGaussian, QtCore.SIGNAL('stateChanged(int)'), self.checkGaussian) - self.connect(self.cbFlatten, QtCore.SIGNAL('stateChanged(int)'), self.checkFlatten) - self.connect(self.cbNorm, QtCore.SIGNAL('stateChanged(int)'), self.checkNorm) - self.connect(self.cbQuad, QtCore.SIGNAL('stateChanged(int)'), self.checkQuad) - self.connect(self.cbFlip, QtCore.SIGNAL('stateChanged(int)'), self.checkFlip) - self.connect(self.cbBkgd, QtCore.SIGNAL('stateChanged(int)'), self.checkBkgd) + self.cbMedian.stateChanged.connect(self.checkMedian) + self.cbGaussian.stateChanged.connect(self.checkGaussian) + self.cbFlatten.stateChanged.connect(self.checkFlatten) + self.cbNorm.stateChanged.connect(self.checkNorm) + self.cbQuad.stateChanged.connect(self.checkQuad) + self.cbFlip.stateChanged.connect(self.checkFlip) + self.cbBkgd.stateChanged.connect(self.checkBkgd) #Buttons - self.btnFnPreImage=QtGui.QPushButton('Change') - self.btnFnFlatten=QtGui.QPushButton('Change') - self.btnFnBkgd=QtGui.QPushButton('Change') + self.btnFnPreImage=QtWidgets.QPushButton('Change') + self.btnFnFlatten=QtWidgets.QPushButton('Change') + self.btnFnBkgd=QtWidgets.QPushButton('Change') - self.btnFnPreImage.connect(self.btnFnPreImage, QtCore.SIGNAL('clicked()'), self.setFnPreImage) - self.btnFnFlatten.connect(self.btnFnFlatten, QtCore.SIGNAL('clicked()'), self.setFnFlatten) - self.btnFnBkgd.connect(self.btnFnBkgd, QtCore.SIGNAL('clicked()'), self.setFnBkgd) + self.btnFnPreImage.clicked.connect(self.setFnPreImage) + self.btnFnFlatten.clicked.connect(self.setFnFlatten) + self.btnFnBkgd.clicked.connect(self.setFnBkgd) #Layout - self.preImageGrid = QtGui.QGridLayout() + self.preImageGrid = QtWidgets.QGridLayout() self.preImageGrid.addWidget(self.lblFnPreimageValue,1,1) self.preImageGrid.addWidget(self.btnFnPreImage,1,2) self.preImageGrid.setColumnMinimumWidth(1,150) - self.flattenGrid = QtGui.QGridLayout() + self.flattenGrid = QtWidgets.QGridLayout() self.flattenGrid.addWidget(self.lblFnFlattenValue,1,1) self.flattenGrid.addWidget(self.btnFnFlatten,1,2) self.flattenGrid.setColumnMinimumWidth(1,150) - self.bkgdGrid = QtGui.QGridLayout() + self.bkgdGrid = QtWidgets.QGridLayout() self.bkgdGrid.addWidget(self.lblFnBkgdValue,1,1) self.bkgdGrid.addWidget(self.btnFnBkgd,1,2) self.bkgdGrid.setColumnMinimumWidth(1,150) @@ -197,7 +197,7 @@ def updateCBs(self): self.cbNorm.setCheckState(2*int(self.inProcess('norm'))) def inProcess(self,key): - return key in self.analysis.process.keys() + return key in list(self.analysis.process.keys()) def checkMedian(self,val): self.analysis.setMedian(bool(2*val)) @@ -222,7 +222,7 @@ def checkFlip(self,val): def setFnPreImage(self): - folder = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Preimage Directory", self.parent.lastopen,)) + folder = str(QtWidgets.QFileDialog.getExistingDirectory(self, "Select Preimage Directory", self.parent.lastopen,)) if folder=='': return @@ -235,7 +235,7 @@ def setFnPreImage(self): def setFnFlatten(self): - folder = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Flatten Directory", self.parent.lastopen,)) + folder = str(QtWidgets.QFileDialog.getExistingDirectory(self, "Select Flatten Directory", self.parent.lastopen,)) if folder=='': return @@ -247,7 +247,7 @@ def setFnFlatten(self): def setFnBkgd(self): - folder = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Background Directory", self.parent.lastopen,)) + folder = str(QtWidgets.QFileDialog.getExistingDirectory(self, "Select Background Directory", self.parent.lastopen,)) if folder=='': return @@ -313,4 +313,4 @@ def __init__(self, embryo=None, parent=None): def runTask(self,debug=False): self.embryo.analysis.run(signal=self.progressSignal,embCount=None,debug=debug) - \ No newline at end of file + diff --git a/pyfrp/gui/pyfrp_gui_basics.py b/pyfrp/gui/pyfrp_gui_basics.py old mode 100644 new mode 100755 index 0666818..5cdb239 --- a/pyfrp/gui/pyfrp_gui_basics.py +++ b/pyfrp/gui/pyfrp_gui_basics.py @@ -42,12 +42,12 @@ from pyfrp.modules.pyfrp_term_module import * #PyQT -from PyQt4 import QtGui, QtCore +from PyQt5 import QtGui, QtCore, QtWidgets #matplotlib import matplotlib.pyplot as plt import matplotlib -from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas +from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas """ Apparently the NavigationToolbar naming has changed in newer matplotlib versions, thus @@ -55,10 +55,10 @@ """ try: - from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar + from matplotlib.backends.backend_qt5agg import NavigationToolbar2QTAgg as NavigationToolbar except ImportError: try: - from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar + from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar except ImportError: printWarning("Cannot import NavigationToolbar.") @@ -68,7 +68,7 @@ #Basic Dialog with space for QLEs/Btns on left hand side and canvas on right hand side #=================================================================================================================================== -class basicCanvasDialog(QtGui.QDialog): +class basicCanvasDialog(QtWidgets.QDialog): def __init__(self,parent,xlim=[0,512],ylim=[0,512]): @@ -89,21 +89,21 @@ def __init__(self,parent,xlim=[0,512],ylim=[0,512]): #------------------------------------------------------------------------------------------------------------------- #Done button - self.btnDone=QtGui.QPushButton('Done') - self.btnDone.connect(self.btnDone, QtCore.SIGNAL('clicked()'), self.donePressed) + self.btnDone=QtWidgets.QPushButton('Done') + self.btnDone.clicked.connect(self.donePressed) #------------------------------------------------------------------------------------------------------------------- #Plot frame #------------------------------------------------------------------------------------------------------------------- - self.plotFrame = QtGui.QWidget() + self.plotFrame = QtWidgets.QWidget() self.plotFrame.setMaximumWidth(1) #------------------------------------------------------------------------------------------------------------------- #Layout #------------------------------------------------------------------------------------------------------------------- - self.grid = QtGui.QGridLayout() + self.grid = QtWidgets.QGridLayout() self.grid.setColumnMinimumWidth(2,200) #------------------------------------------------------------------------------------------------------------------- @@ -116,12 +116,12 @@ def __init__(self,parent,xlim=[0,512],ylim=[0,512]): #Final Layout #------------------------------------------------------------------------------------------------------------------- - self.vbox = QtGui.QVBoxLayout() + self.vbox = QtWidgets.QVBoxLayout() self.vbox.addWidget(self.canvas) self.vbox.addWidget(self.btnDone) #Add everything to Horizontal Box - self.hbox = QtGui.QHBoxLayout() + self.hbox = QtWidgets.QHBoxLayout() self.hbox.addLayout(self.grid) self.hbox.addLayout(self.vbox) @@ -205,7 +205,7 @@ def donePressed(self): #Basic Dialog for settings of any kind. #=================================================================================================================================== -class basicSettingsDialog(QtGui.QDialog): +class basicSettingsDialog(QtWidgets.QDialog): def __init__(self,parent): @@ -219,14 +219,14 @@ def __init__(self,parent): #------------------------------------------------------------------------------------------------------------------- #Done button - self.btnDone=QtGui.QPushButton('Done') - self.btnDone.connect(self.btnDone, QtCore.SIGNAL('clicked()'), self.donePressed) + self.btnDone=QtWidgets.QPushButton('Done') + self.btnDone.clicked.connect(self.donePressed) #------------------------------------------------------------------------------------------------------------------- #Layout #------------------------------------------------------------------------------------------------------------------- - self.grid = QtGui.QGridLayout() + self.grid = QtWidgets.QGridLayout() self.grid.setColumnMinimumWidth(2,20) #------------------------------------------------------------------------------------------------------------------- @@ -240,10 +240,10 @@ def __init__(self,parent): #Final Layout #------------------------------------------------------------------------------------------------------------------- - self.vbox = QtGui.QVBoxLayout() + self.vbox = QtWidgets.QVBoxLayout() self.vbox.addLayout(self.grid) - self.hbox = QtGui.QHBoxLayout() + self.hbox = QtWidgets.QHBoxLayout() self.hbox.addWidget(self.btnDone,stretch=0,alignment=QtCore.Qt.AlignRight) self.vbox.addLayout(self.hbox) @@ -259,7 +259,7 @@ def donePressed(self): #Basic Selector for a single item out of a list #=================================================================================================================================== -class basicSelectorDialog(QtGui.QDialog): +class basicSelectorDialog(QtWidgets.QDialog): def __init__(self,List,parent): @@ -269,20 +269,20 @@ def __init__(self,List,parent): self.List=List #Done button - self.btnDone=QtGui.QPushButton('Done') - self.btnDone.connect(self.btnDone, QtCore.SIGNAL('clicked()'), self.donePressed) + self.btnDone=QtWidgets.QPushButton('Done') + self.btnDone.clicked.connect(self.donePressed) #QTreeWidget - self.ListWidget=QtGui.QTreeWidget() + self.ListWidget=QtWidgets.QTreeWidget() self.ListWidget.setColumnWidth(0,100) self.ListWidget.itemClicked.connect(self.itemClicked) self.updateList() #Layout - self.vbox = QtGui.QVBoxLayout() + self.vbox = QtWidgets.QVBoxLayout() self.vbox.addWidget(self.ListWidget) - self.hbox = QtGui.QHBoxLayout() + self.hbox = QtWidgets.QHBoxLayout() self.hbox.addWidget(self.btnDone,stretch=0,alignment=QtCore.Qt.AlignRight) self.vbox.addLayout(self.hbox) @@ -295,7 +295,7 @@ def updateList(self): self.ListWidget.clear() for r in self.List: - QtGui.QTreeWidgetItem(self.ListWidget,[r]) + QtWidgets.QTreeWidgetItem(self.ListWidget,[r]) return def itemClicked(self): @@ -313,13 +313,13 @@ def donePressed(self): #Basic Selector for a list of items out of a list #=================================================================================================================================== -class listSelectorDialog(QtGui.QDialog): +class listSelectorDialog(QtWidgets.QDialog): def __init__(self,parent,List,leftTitle="",rightTitle="",itemsRight=[]): super(listSelectorDialog,self).__init__(parent) #print type(self), type(parent) - #QtGui.QDialog.__init__() + #QtWidgets.QDialog.__init__() self.itemsRight=itemsRight @@ -328,42 +328,42 @@ def __init__(self,parent,List,leftTitle="",rightTitle="",itemsRight=[]): self.List=List #Buttons - self.btnAdd=QtGui.QToolButton() - self.btnAdd.connect(self.btnAdd, QtCore.SIGNAL('clicked()'), self.addItem) + self.btnAdd=QtWidgets.QToolButton() + self.btnAdd.clicked.connect(self.addItem) self.btnAdd.setArrowType(QtCore.Qt.RightArrow) - self.btnRemove=QtGui.QToolButton() - self.btnRemove.connect(self.btnRemove, QtCore.SIGNAL('clicked()'), self.removeItem) + self.btnRemove=QtWidgets.QToolButton() + self.btnRemove.clicked.connect(self.removeItem) self.btnRemove.setArrowType(QtCore.Qt.LeftArrow) - self.btnDone=QtGui.QPushButton('Done') - self.btnDone.connect(self.btnDone, QtCore.SIGNAL('clicked()'), self.donePressed) + self.btnDone=QtWidgets.QPushButton('Done') + self.btnDone.clicked.connect(self.donePressed) #Left QtreeWidgetItem - self.leftList=QtGui.QTreeWidget() + self.leftList=QtWidgets.QTreeWidget() self.leftList.setHeaderLabels([leftTitle]) self.leftList.setColumnWidth(0,200) self.leftList.setColumnWidth(1,75) self.leftList.itemDoubleClicked.connect(self.addItem) #right QtreeWidgetItem - self.rightList=QtGui.QTreeWidget() + self.rightList=QtWidgets.QTreeWidget() self.rightList.setHeaderLabels([rightTitle]) self.rightList.setColumnWidth(0,200) self.rightList.setColumnWidth(1,75) self.rightList.itemDoubleClicked.connect(self.removeItem) #Layout - self.vbox = QtGui.QVBoxLayout() + self.vbox = QtWidgets.QVBoxLayout() self.vbox.addWidget(self.btnAdd) self.vbox.addWidget(self.btnRemove) - self.hbox = QtGui.QHBoxLayout() + self.hbox = QtWidgets.QHBoxLayout() self.hbox.addWidget(self.leftList) self.hbox.addLayout(self.vbox) self.hbox.addWidget(self.rightList) - self.vbox2 = QtGui.QVBoxLayout() + self.vbox2 = QtWidgets.QVBoxLayout() self.vbox2.addLayout(self.hbox) self.vbox2.addWidget(self.btnDone) @@ -391,12 +391,12 @@ def initLeftList(self): self.getListDifference() for item in self.itemsLeft: - QtGui.QTreeWidgetItem(self.leftList,[item]) + QtWidgets.QTreeWidgetItem(self.leftList,[item]) def initRightList(self): for item in self.itemsRight: - QtGui.QTreeWidgetItem(self.rightList,[item]) + QtWidgets.QTreeWidgetItem(self.rightList,[item]) def addItem(self): @@ -404,7 +404,7 @@ def addItem(self): self.currentItem=str(self.leftList.currentItem().data(0,0).toString()) #Insert new node in right list - newNode=QtGui.QTreeWidgetItem(self.rightList,[self.currentItem]) + newNode=QtWidgets.QTreeWidgetItem(self.rightList,[self.currentItem]) #Remove node in left list self.currLeftInd=self.leftList.indexFromItem(self.leftList.currentItem()).row() @@ -420,7 +420,7 @@ def removeItem(self): self.currentItem=str(self.rightList.currentItem().data(0,0).toString()) #Insert new node in left list - newNode=QtGui.QTreeWidgetItem(self.leftList,[self.currentItem]) + newNode=QtWidgets.QTreeWidgetItem(self.leftList,[self.currentItem]) #Remove node in right list self.currRightInd=self.rightList.indexFromItem(self.rightList.currentItem()).row() @@ -451,12 +451,12 @@ def __init__(self,parent,List,leftTitle="",rightTitle="",itemsRight=[]): #listSelectorDialog.__init__(parent,List,leftTitle=leftTitle,rightTitle=rightTitle,itemsRight=itemsRight) - self.btnUp=QtGui.QToolButton() - self.btnUp.connect(self.btnUp, QtCore.SIGNAL('clicked()'), self.upItem) + self.btnUp=QtWidgets.QToolButton() + self.btnUp.clicked.connect(self.upItem) self.btnUp.setArrowType(QtCore.Qt.UpArrow) - self.btnDown=QtGui.QToolButton() - self.btnDown.connect(self.btnDown, QtCore.SIGNAL('clicked()'), self.downItem) + self.btnDown=QtWidgets.QToolButton() + self.btnDown.clicked.connect(self.downItem) self.btnDown.setArrowType(QtCore.Qt.DownArrow) self.vbox.addWidget(self.btnUp) @@ -504,25 +504,25 @@ def downItem(self): #Basic Progress Dialog #=================================================================================================================================== -class progressDialog(QtGui.QDialog): +class progressDialog(QtWidgets.QDialog): def __init__(self,parent): super(progressDialog,self).__init__(parent) #Labels - self.lblName = QtGui.QLabel("Something in progress...", self) + self.lblName = QtWidgets.QLabel("Something in progress...", self) #Buttons - self.btnCancel=QtGui.QPushButton('Cancel') - self.btnCancel.connect(self.btnCancel, QtCore.SIGNAL('clicked()'), self.cancel) + self.btnCancel=QtWidgets.QPushButton('Cancel') + self.btnCancel.clicked.connect(self.cancel) #ProgressBar - self.progressbar = QtGui.QProgressBar() + self.progressbar = QtWidgets.QProgressBar() self.progressbar.setMinimum(1) self.progressbar.setMaximum(100) #Layout - self.vbox = QtGui.QVBoxLayout() + self.vbox = QtWidgets.QVBoxLayout() self.vbox.addWidget(self.lblName) self.vbox.addWidget(self.progressbar) self.vbox.addWidget(self.btnCancel) @@ -575,20 +575,20 @@ def __del__(self): #Basic Wait Dialog #=================================================================================================================================== -class waitDialog(QtGui.QDialog): +class waitDialog(QtWidgets.QDialog): def __init__(self,parent): super(waitDialog,self).__init__(parent) #Labels - self.lblName = QtGui.QLabel("Something in progress...", self) + self.lblName = QtWidgets.QLabel("Something in progress...", self) #Buttons - self.btnCancel=QtGui.QPushButton('Cancel') - self.btnCancel.connect(self.btnCancel, QtCore.SIGNAL('clicked()'), self.cancel) + self.btnCancel=QtWidgets.QPushButton('Cancel') + self.btnCancel.clicked.connect(self.cancel) #Layout - self.vbox = QtGui.QVBoxLayout() + self.vbox = QtWidgets.QVBoxLayout() self.vbox.addWidget(self.lblName) self.vbox.addWidget(self.btnCancel) @@ -600,4 +600,4 @@ def __init__(self,parent): def cancel(self): self.accepted.emit() - \ No newline at end of file + diff --git a/pyfrp/gui/pyfrp_gui_builder.py b/pyfrp/gui/pyfrp_gui_builder.py old mode 100644 new mode 100755 index c3fff7e..da14959 --- a/pyfrp/gui/pyfrp_gui_builder.py +++ b/pyfrp/gui/pyfrp_gui_builder.py @@ -39,7 +39,7 @@ from pyfrp.modules.pyfrp_term_module import * #PyQT -from PyQt4 import QtGui, QtCore +from PyQt5 import QtGui, QtCore, QtWidgets #=========================================================================================================================================================================== #Module function @@ -53,24 +53,24 @@ def genSettingQLE(parent,lblText,qleText,callback=None,validator=None): .. note:: ``QLineEdit`` is conncect with ``editingFinished`` slot. Args: - parent (QtGui.QWidget): Some parenting widget. + parent (QtWidgets.QWidget): Some parenting widget. lblText (str): Text displayed in label. qleText (str): Text displayed initially in qle. Keyword Args: callback (function): Some callback function. - validator (QtGui.QValidator): Some validator. + validator (QtWidgets.QValidator): Some validator. Returns: tuple: Tuple containing: - * lbl (QtGui.QLabel): Label. - * qle (QtGui.QLineEdit): Lineedit. + * lbl (QtWidgets.QLabel): Label. + * qle (QtWidgets.QLineEdit): Lineedit. """ - lbl = QtGui.QLabel(lblText, parent) - qle = QtGui.QLineEdit(str(qleText),parent=parent) + lbl = QtWidgets.QLabel(lblText, parent) + qle = QtWidgets.QLineEdit(str(qleText),parent=parent) if validator!=None: qle.setValidator(validator) @@ -88,7 +88,7 @@ def genSettingCB(parent,lblText,cbVal,callback=None): .. note:: ``QCheckBox`` is conncect with ``stateChanged`` slot. Args: - parent (QtGui.QWidget): Some parenting widget. + parent (QtWidgets.QWidget): Some parenting widget. lblText (str): Text displayed in label. cbVal (bool): Checked or not. @@ -98,17 +98,17 @@ def genSettingCB(parent,lblText,cbVal,callback=None): Returns: tuple: Tuple containing: - * lbl (QtGui.QLabel): Label. - * cb (QtGui.QCheckBox): Checkbox. + * lbl (QtWidgets.QLabel): Label. + * cb (QtWidgets.QCheckBox): Checkbox. """ - lbl = QtGui.QLabel(lblText, parent) - cb = QtGui.QCheckBox('', parent) + lbl = QtWidgets.QLabel(lblText, parent) + cb = QtWidgets.QCheckBox('', parent) cb.setCheckState(2*int(cbVal)) if callback!=None: - parent.connect(cb, QtCore.SIGNAL('stateChanged(int)'), callback) + cb.stateChanged.connect(callback) return lbl,cb @@ -120,7 +120,7 @@ def genSettingBtn(parent,lblText,btnText,callback=None): .. note:: ``QPushButton`` is conncect with ``clicked`` slot. Args: - parent (QtGui.QWidget): Some parenting widget. + parent (QtWidgets.QWidget): Some parenting widget. lblText (str): Text displayed in label. btnText (str): Text displayed on button. @@ -130,16 +130,16 @@ def genSettingBtn(parent,lblText,btnText,callback=None): Returns: tuple: Tuple containing: - * lbl (QtGui.QLabel): Label. - * btn (QtGui.QPushButton): Push button. + * lbl (QtWidgets.QLabel): Label. + * btn (QtWidgets.QPushButton): Push button. """ - lbl = QtGui.QLabel(lblText, parent) - btn=QtGui.QPushButton(btnText) + lbl = QtWidgets.QLabel(lblText, parent) + btn=QtWidgets.QPushButton(btnText) if callback!=None: - btn.connect(btn, QtCore.SIGNAL('clicked()'), callback) + btn.clicked.connect(callback) return lbl,btn @@ -151,7 +151,7 @@ def genSettingCombo(parent,lblText,comboList,callback=None,idx=0): .. note:: ``QPushButton`` is conncect with ``clicked`` slot. Args: - parent (QtGui.QWidget): Some parenting widget. + parent (QtWidgets.QWidget): Some parenting widget. lblText (str): Text displayed in label. comboList (list): List of strings that are added to QComboBox. @@ -162,13 +162,13 @@ def genSettingCombo(parent,lblText,comboList,callback=None,idx=0): Returns: tuple: Tuple containing: - * lbl (QtGui.QLabel): Label. - * combo (QtGui.QComboBox): Combobox. + * lbl (QtWidgets.QLabel): Label. + * combo (QtWidgets.QComboBox): Combobox. """ - lbl = QtGui.QLabel(lblText, parent) - combo=QtGui.QComboBox(parent) + lbl = QtWidgets.QLabel(lblText, parent) + combo=QtWidgets.QComboBox(parent) for x in comboList: combo.addItem(x) diff --git a/pyfrp/gui/pyfrp_gui_embryo_dialogs.py b/pyfrp/gui/pyfrp_gui_embryo_dialogs.py old mode 100644 new mode 100755 index 9e0eee1..719f5e4 --- a/pyfrp/gui/pyfrp_gui_embryo_dialogs.py +++ b/pyfrp/gui/pyfrp_gui_embryo_dialogs.py @@ -32,10 +32,10 @@ #=========================================================================================================================================================================== #QT -from PyQt4 import QtGui, QtCore +from PyQt5 import QtGui, QtCore, QtWidgets #PyFRAP GUI classes -import pyfrp_gui_basics +from . import pyfrp_gui_basics #PyFRAP modules from pyfrp.modules.pyfrp_term_module import * @@ -64,39 +64,39 @@ def __init__(self,embryo,parent): self.nCharDisplayed=50 #Labels - self.lblName = QtGui.QLabel("Name:", self) + self.lblName = QtWidgets.QLabel("Name:", self) - self.lblDataFT = QtGui.QLabel("Data Filetype:", self) - self.lblDataEnc = QtGui.QLabel("Data Encoding:", self) + self.lblDataFT = QtWidgets.QLabel("Data Filetype:", self) + self.lblDataEnc = QtWidgets.QLabel("Data Encoding:", self) - self.lblFnDataFolder = QtGui.QLabel("Data Folder:", self) + self.lblFnDataFolder = QtWidgets.QLabel("Data Folder:", self) - self.lblDataResPx = QtGui.QLabel("Resolution (px):", self) - self.lblDataResMu = QtGui.QLabel("Resulution (um):", self) + self.lblDataResPx = QtWidgets.QLabel("Resolution (px):", self) + self.lblDataResMu = QtWidgets.QLabel("Resulution (um):", self) - self.lblSliceDepth = QtGui.QLabel("Imaging Depth (um):", self) + self.lblSliceDepth = QtWidgets.QLabel("Imaging Depth (um):", self) - self.lblFrameInterval = QtGui.QLabel("Frame Interval (s):", self) - self.lblnFrames = QtGui.QLabel("number of frames:", self) - self.lbltStart = QtGui.QLabel("tStart (s):", self) - self.lbltEnd = QtGui.QLabel("tEnd (s):", self) + self.lblFrameInterval = QtWidgets.QLabel("Frame Interval (s):", self) + self.lblnFrames = QtWidgets.QLabel("number of frames:", self) + self.lbltStart = QtWidgets.QLabel("tStart (s):", self) + self.lbltEnd = QtWidgets.QLabel("tEnd (s):", self) - self.lblFnDataFolderValue = QtGui.QLabel("", self) + self.lblFnDataFolderValue = QtWidgets.QLabel("", self) self.updateDataFolderLbl() #LineEdits - self.qleName = QtGui.QLineEdit(self.embryo.name) - self.qleDataResPx = QtGui.QLineEdit(str(self.embryo.dataResPx)) - self.qleDataResMu = QtGui.QLineEdit(str(self.embryo.dataResMu)) + self.qleName = QtWidgets.QLineEdit(self.embryo.name) + self.qleDataResPx = QtWidgets.QLineEdit(str(self.embryo.dataResPx)) + self.qleDataResMu = QtWidgets.QLineEdit(str(self.embryo.dataResMu)) - self.qleSliceDepth = QtGui.QLineEdit(str(self.embryo.sliceDepthMu)) + self.qleSliceDepth = QtWidgets.QLineEdit(str(self.embryo.sliceDepthMu)) - self.qleFrameInterval = QtGui.QLineEdit(str(self.embryo.frameInterval)) - self.qlenFrames = QtGui.QLineEdit(str(self.embryo.nFrames)) - self.qletStart = QtGui.QLineEdit(str(self.embryo.tStart)) - self.qletEnd = QtGui.QLineEdit(str(self.embryo.tEnd)) + self.qleFrameInterval = QtWidgets.QLineEdit(str(self.embryo.frameInterval)) + self.qlenFrames = QtWidgets.QLineEdit(str(self.embryo.nFrames)) + self.qletStart = QtWidgets.QLineEdit(str(self.embryo.tStart)) + self.qletEnd = QtWidgets.QLineEdit(str(self.embryo.tEnd)) self.doubleValid=QtGui.QDoubleValidator() @@ -119,11 +119,11 @@ def __init__(self,embryo,parent): self.qlenFrames.setReadOnly(True) #Combo - self.comboDataFt = QtGui.QComboBox(self) + self.comboDataFt = QtWidgets.QComboBox(self) self.comboDataFt.addItem("tif") self.comboDataFt.setCurrentIndex(self.comboDataFt.findText(self.embryo.getDataFT())) - self.comboDataEnc = QtGui.QComboBox(self) + self.comboDataEnc = QtWidgets.QComboBox(self) self.comboDataEnc.addItem("uint8") self.comboDataEnc.addItem("uint16") self.comboDataEnc.setCurrentIndex(self.comboDataEnc.findText(self.embryo.getDataEnc())) @@ -132,12 +132,12 @@ def __init__(self,embryo,parent): self.comboDataEnc.activated[str].connect(self.setDataEnc) #Buttons - self.btnFnDatafolder=QtGui.QPushButton('Change') + self.btnFnDatafolder=QtWidgets.QPushButton('Change') - self.btnFnDatafolder.connect(self.btnFnDatafolder, QtCore.SIGNAL('clicked()'), self.setFnDatafolder) + self.btnFnDatafolder.clicked.connect(self.setFnDatafolder) #Layout - self.dataFolderGrid = QtGui.QGridLayout() + self.dataFolderGrid = QtWidgets.QGridLayout() self.dataFolderGrid.addWidget(self.lblFnDataFolderValue,1,1) self.dataFolderGrid.addWidget(self.btnFnDatafolder,1,2) @@ -179,7 +179,7 @@ def __init__(self,embryo,parent): def setFnDatafolder(self): - folder = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Data Directory", self.parent.lastopen,)) + folder = str(QtWidgets.QFileDialog.getExistingDirectory(self, "Select Data Directory", self.parent.lastopen,)) if folder=='': return @@ -198,7 +198,7 @@ def setFnDatafolder(self): def setFnPreImage(self): - fn = str(QtGui.QFileDialog.getOpenFileName(self, 'Open file', self.parent.lastopen,)) + fn = str(QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', self.parent.lastopen,)) if fn=='': return @@ -308,36 +308,36 @@ def __init__(self,parent): self.cleanUp=True #Labels - self.lblName = QtGui.QLabel("Name:", self) + self.lblName = QtWidgets.QLabel("Name:", self) - self.lblDataFT = QtGui.QLabel("Data Filetype:", self) + self.lblDataFT = QtWidgets.QLabel("Data Filetype:", self) - self.lblFnDataFolder = QtGui.QLabel("Data Folder:", self) + self.lblFnDataFolder = QtWidgets.QLabel("Data Folder:", self) - self.lblFnDestFolder = QtGui.QLabel("Destination Folder:", self) + self.lblFnDestFolder = QtWidgets.QLabel("Destination Folder:", self) - self.lblNChannel = QtGui.QLabel("nChannel:", self) - self.lblCreate = QtGui.QLabel("Create Embryo:", self) + self.lblNChannel = QtWidgets.QLabel("nChannel:", self) + self.lblCreate = QtWidgets.QLabel("Create Embryo:", self) - self.lblFnDataFolderValue = QtGui.QLabel("", self) - self.lblFnDestFolderValue = QtGui.QLabel("", self) + self.lblFnDataFolderValue = QtWidgets.QLabel("", self) + self.lblFnDestFolderValue = QtWidgets.QLabel("", self) - self.lblRecoverIdent= QtGui.QLabel("Recover Identifiers", self) - self.lblPreIdent= QtGui.QLabel("Pre Identifiers", self) - self.lblBleachIdent= QtGui.QLabel("Bleach Identifiers", self) + self.lblRecoverIdent= QtWidgets.QLabel("Recover Identifiers", self) + self.lblPreIdent= QtWidgets.QLabel("Pre Identifiers", self) + self.lblBleachIdent= QtWidgets.QLabel("Bleach Identifiers", self) - self.lblColorPrefix = QtGui.QLabel("Color Prefix", self) - self.lblCleanUp = QtGui.QLabel("Clean Up Afterwards?", self) + self.lblColorPrefix = QtWidgets.QLabel("Color Prefix", self) + self.lblCleanUp = QtWidgets.QLabel("Clean Up Afterwards?", self) self.updateDataFolderLbl() #LineEdits - self.qleName = QtGui.QLineEdit("") - self.qleRecoverIdent = QtGui.QLineEdit(str(self.recoverIdent)) - self.qlePreIdent = QtGui.QLineEdit(str(self.preIdent)) - self.qleBleachIdent = QtGui.QLineEdit(str(self.bleachIdent)) + self.qleName = QtWidgets.QLineEdit("") + self.qleRecoverIdent = QtWidgets.QLineEdit(str(self.recoverIdent)) + self.qlePreIdent = QtWidgets.QLineEdit(str(self.preIdent)) + self.qleBleachIdent = QtWidgets.QLineEdit(str(self.bleachIdent)) - self.qleColorPrefix = QtGui.QLineEdit(self.colorPrefix) + self.qleColorPrefix = QtWidgets.QLineEdit(self.colorPrefix) self.qleName.editingFinished.connect(self.setName) self.qleRecoverIdent.editingFinished.connect(self.setRecoverIdent) @@ -348,11 +348,11 @@ def __init__(self,parent): #Combo - self.comboDataFt = QtGui.QComboBox(self) + self.comboDataFt = QtWidgets.QComboBox(self) self.comboDataFt.addItem("lsm") self.comboDataFt.addItem("czi") - self.comboNChannel = QtGui.QComboBox(self) + self.comboNChannel = QtWidgets.QComboBox(self) self.comboNChannel.addItem("1") self.comboNChannel.addItem("2") self.comboNChannel.addItem("3") @@ -364,30 +364,30 @@ def __init__(self,parent): self.comboNChannel.activated[str].connect(self.setNChannel) #Checkboxes - self.cbCreate = QtGui.QCheckBox('', self) - self.connect(self.cbCreate, QtCore.SIGNAL('stateChanged(int)'), self.checkCreate) + self.cbCreate = QtWidgets.QCheckBox('', self) + self.cbCreate.stateChanged.connect(self.checkCreate) self.cbCreate.setCheckState(2) - self.cbCleanUp = QtGui.QCheckBox('', self) - self.connect(self.cbCleanUp, QtCore.SIGNAL('stateChanged(int)'), self.checkCleanUp) + self.cbCleanUp = QtWidgets.QCheckBox('', self) + self.cbCleanUp.stateChanged.connect(self.checkCleanUp) self.cbCleanUp.setCheckState(2) #Buttons - self.btnFnDatafolder=QtGui.QPushButton('Change') - self.btnFnDatafolder.connect(self.btnFnDatafolder, QtCore.SIGNAL('clicked()'), self.setFnDatafolder) + self.btnFnDatafolder=QtWidgets.QPushButton('Change') + self.btnFnDatafolder.clicked.connect(self.setFnDatafolder) - self.btnFnDestfolder=QtGui.QPushButton('Change') - self.btnFnDestfolder.connect(self.btnFnDestfolder, QtCore.SIGNAL('clicked()'), self.setFnDestfolder) + self.btnFnDestfolder=QtWidgets.QPushButton('Change') + self.btnFnDestfolder.clicked.connect(self.setFnDestfolder) - self.btnBuild=QtGui.QPushButton('Build Embryo') - self.btnBuild.connect(self.btnBuild, QtCore.SIGNAL('clicked()'), self.buildEmbryo) + self.btnBuild=QtWidgets.QPushButton('Build Embryo') + self.btnBuild.clicked.connect(self.buildEmbryo) #Layout - self.dataFolderGrid = QtGui.QGridLayout() + self.dataFolderGrid = QtWidgets.QGridLayout() self.dataFolderGrid.addWidget(self.lblFnDataFolderValue,1,1) self.dataFolderGrid.addWidget(self.btnFnDatafolder,1,2) - self.destFolderGrid = QtGui.QGridLayout() + self.destFolderGrid = QtWidgets.QGridLayout() self.destFolderGrid.addWidget(self.lblFnDestFolderValue,1,1) self.destFolderGrid.addWidget(self.btnFnDestfolder,1,2) @@ -475,7 +475,7 @@ def buildEmbryo(self): def setFnDatafolder(self): - folder = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Data Directory", self.parent.lastopen,)) + folder = str(QtWidgets.QFileDialog.getExistingDirectory(self, "Select Data Directory", self.parent.lastopen,)) if folder=='': return @@ -501,7 +501,7 @@ def updateDataFolderLbl(self): def setFnDestfolder(self): - folder = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Dest Directory", self.parent.lastopen,)) + folder = str(QtWidgets.QFileDialog.getExistingDirectory(self, "Select Dest Directory", self.parent.lastopen,)) if folder=='': return @@ -533,7 +533,7 @@ def setNChannel(self,text): def getEmbryo(self): return self.embryo -class wizardSelector(QtGui.QDialog): +class wizardSelector(QtWidgets.QDialog): """Dialog to select if either use lsmWizard or not.""" @@ -547,13 +547,13 @@ def __init__(self,parent): self.useLSM=None #Buttons - self.btnUseLSM=QtGui.QPushButton('Create Embryo from Microscope Data') - self.btnUseLSM.connect(self.btnUseLSM, QtCore.SIGNAL('clicked()'), self.setUseLSM) + self.btnUseLSM=QtWidgets.QPushButton('Create Embryo from Microscope Data') + self.btnUseLSM.clicked.connect(self.setUseLSM) - self.btnUseSorted=QtGui.QPushButton('Create Embryo from already prepared Data') - self.btnUseSorted.connect(self.btnUseSorted, QtCore.SIGNAL('clicked()'), self.setUseSorted) + self.btnUseSorted=QtWidgets.QPushButton('Create Embryo from already prepared Data') + self.btnUseSorted.clicked.connect(self.setUseSorted) - self.vbox = QtGui.QVBoxLayout() + self.vbox = QtWidgets.QVBoxLayout() self.vbox.addWidget(self.btnUseLSM) self.vbox.addWidget(self.btnUseSorted) @@ -577,4 +577,4 @@ def getUseLSM(self): - \ No newline at end of file + diff --git a/pyfrp/gui/pyfrp_gui_fit_dialogs.py b/pyfrp/gui/pyfrp_gui_fit_dialogs.py old mode 100644 new mode 100755 index e5c86ba..c1504c4 --- a/pyfrp/gui/pyfrp_gui_fit_dialogs.py +++ b/pyfrp/gui/pyfrp_gui_fit_dialogs.py @@ -32,10 +32,10 @@ #=========================================================================================================================================================================== #QT -from PyQt4 import QtGui, QtCore +from PyQt5 import QtGui, QtCore, QtWidgets #PyFRAP GUI classes -import pyfrp_gui_basics +from . import pyfrp_gui_basics #PyFRAP modules from pyfrp.modules.pyfrp_term_module import * @@ -62,71 +62,71 @@ def __init__(self,fit,parent): self.fit = fit #Labels - self.lblName = QtGui.QLabel("Name:", self) + self.lblName = QtWidgets.QLabel("Name:", self) - self.lblOptMeth = QtGui.QLabel("Optimization Method:", self) - self.lblMaxFun = QtGui.QLabel("Max. Function Calls:", self) - self.lblOptTol = QtGui.QLabel("Precision goal:", self) + self.lblOptMeth = QtWidgets.QLabel("Optimization Method:", self) + self.lblMaxFun = QtWidgets.QLabel("Max. Function Calls:", self) + self.lblOptTol = QtWidgets.QLabel("Precision goal:", self) - self.lblX0D = QtGui.QLabel("x0(D):", self) - self.lblX0Prod = QtGui.QLabel("x0(production):", self) - self.lblX0Degr = QtGui.QLabel("x0(degration):", self) + self.lblX0D = QtWidgets.QLabel("x0(D):", self) + self.lblX0Prod = QtWidgets.QLabel("x0(production):", self) + self.lblX0Degr = QtWidgets.QLabel("x0(degration):", self) - self.lblBoundsD = QtGui.QLabel("<= D <=", self) - self.lblBoundsProd = QtGui.QLabel("<= production <=", self) - self.lblBoundsDegr = QtGui.QLabel("<= degration <=", self) + self.lblBoundsD = QtWidgets.QLabel("<= D <=", self) + self.lblBoundsProd = QtWidgets.QLabel("<= production <=", self) + self.lblBoundsDegr = QtWidgets.QLabel("<= degration <=", self) - self.lblKinetic = QtGui.QLabel("Kinetic Timescale:", self) - self.lblSaveTrack = QtGui.QLabel("Save Track:", self) + self.lblKinetic = QtWidgets.QLabel("Kinetic Timescale:", self) + self.lblSaveTrack = QtWidgets.QLabel("Save Track:", self) - self.lblEquOn = QtGui.QLabel("Equalization:", self) - self.lblFitPinned = QtGui.QLabel("Fit Pinned:", self) + self.lblEquOn = QtWidgets.QLabel("Equalization:", self) + self.lblFitPinned = QtWidgets.QLabel("Fit Pinned:", self) - self.lblFitProd = QtGui.QLabel("Fit Production:", self) - self.lblFitDegr = QtGui.QLabel("Fit Degradation:", self) + self.lblFitProd = QtWidgets.QLabel("Fit Production:", self) + self.lblFitDegr = QtWidgets.QLabel("Fit Degradation:", self) - self.lblFitCutOffT = QtGui.QLabel("Fit Cut-Off:", self) - self.lblCutOffT = QtGui.QLabel("t(Cut-Off):", self) + self.lblFitCutOffT = QtWidgets.QLabel("Fit Cut-Off:", self) + self.lblCutOffT = QtWidgets.QLabel("t(Cut-Off):", self) boldfont = QtGui.QFont() boldfont.setBold(True) - self.lblHeadBounds = QtGui.QLabel("Bounds:", self) + self.lblHeadBounds = QtWidgets.QLabel("Bounds:", self) self.lblHeadBounds.setFont(boldfont) - self.lblHeadX0 = QtGui.QLabel("Initial Guess:", self) + self.lblHeadX0 = QtWidgets.QLabel("Initial Guess:", self) self.lblHeadX0.setFont(boldfont) - self.lblHeadGeneral = QtGui.QLabel("General:", self) + self.lblHeadGeneral = QtWidgets.QLabel("General:", self) self.lblHeadGeneral.setFont(boldfont) - self.lblHeadROI = QtGui.QLabel("ROIs Fitted:", self) + self.lblHeadROI = QtWidgets.QLabel("ROIs Fitted:", self) self.lblHeadROI.setFont(boldfont) - self.lblHeadOptions = QtGui.QLabel("Fit Options:", self) + self.lblHeadOptions = QtWidgets.QLabel("Fit Options:", self) self.lblHeadOptions.setFont(boldfont) #LineEdits - self.qleName = QtGui.QLineEdit(self.fit.name) + self.qleName = QtWidgets.QLineEdit(self.fit.name) - self.qleMaxFun = QtGui.QLineEdit(str(self.fit.maxfun)) - self.qleOptTol = QtGui.QLineEdit(str(self.fit.optTol)) + self.qleMaxFun = QtWidgets.QLineEdit(str(self.fit.maxfun)) + self.qleOptTol = QtWidgets.QLineEdit(str(self.fit.optTol)) - self.qleX0D = QtGui.QLineEdit(str(self.fit.x0[0])) - self.qleX0Prod = QtGui.QLineEdit(str(self.fit.x0[1])) - self.qleX0Degr = QtGui.QLineEdit(str(self.fit.x0[2])) + self.qleX0D = QtWidgets.QLineEdit(str(self.fit.x0[0])) + self.qleX0Prod = QtWidgets.QLineEdit(str(self.fit.x0[1])) + self.qleX0Degr = QtWidgets.QLineEdit(str(self.fit.x0[2])) - self.qleLBD = QtGui.QLineEdit(str(self.fit.LBD)) - self.qleLBProd = QtGui.QLineEdit(str(self.fit.LBProd)) - self.qleLBDegr = QtGui.QLineEdit(str(self.fit.LBDegr)) + self.qleLBD = QtWidgets.QLineEdit(str(self.fit.LBD)) + self.qleLBProd = QtWidgets.QLineEdit(str(self.fit.LBProd)) + self.qleLBDegr = QtWidgets.QLineEdit(str(self.fit.LBDegr)) - self.qleUBD = QtGui.QLineEdit(str(self.fit.UBD)) - self.qleUBProd = QtGui.QLineEdit(str(self.fit.UBProd)) - self.qleUBDegr = QtGui.QLineEdit(str(self.fit.UBDegr)) + self.qleUBD = QtWidgets.QLineEdit(str(self.fit.UBD)) + self.qleUBProd = QtWidgets.QLineEdit(str(self.fit.UBProd)) + self.qleUBDegr = QtWidgets.QLineEdit(str(self.fit.UBDegr)) - self.qleKinetic = QtGui.QLineEdit(str(self.fit.kineticTimeScale)) + self.qleKinetic = QtWidgets.QLineEdit(str(self.fit.kineticTimeScale)) - self.qleCutOffT = QtGui.QLineEdit(str(self.fit.cutOffT)) + self.qleCutOffT = QtWidgets.QLineEdit(str(self.fit.cutOffT)) self.doubleValid=QtGui.QDoubleValidator() self.intValid=QtGui.QIntValidator() @@ -160,7 +160,7 @@ def __init__(self,fit,parent): self.qleCutOffT.editingFinished.connect(self.setCutOffT) #ComboBox - self.comboMeth = QtGui.QComboBox(self) + self.comboMeth = QtWidgets.QComboBox(self) self.comboMeth.addItem("Constrained Nelder-Mead") self.comboMeth.addItem("TNC") self.comboMeth.addItem("Nelder-Mead") @@ -175,34 +175,34 @@ def __init__(self,fit,parent): self.comboMeth.activated[str].connect(self.setOptMeth) #Checkboxes - self.cbFitProd = QtGui.QCheckBox('', self) - self.cbFitDegr = QtGui.QCheckBox('', self) - self.cbFitPinned = QtGui.QCheckBox('', self) - self.cbEquOn = QtGui.QCheckBox('', self) - self.cbFitCutOffT = QtGui.QCheckBox('', self) - self.cbSaveTrack = QtGui.QCheckBox('', self) + self.cbFitProd = QtWidgets.QCheckBox('', self) + self.cbFitDegr = QtWidgets.QCheckBox('', self) + self.cbFitPinned = QtWidgets.QCheckBox('', self) + self.cbEquOn = QtWidgets.QCheckBox('', self) + self.cbFitCutOffT = QtWidgets.QCheckBox('', self) + self.cbSaveTrack = QtWidgets.QCheckBox('', self) self.updateCBs() - self.connect(self.cbFitProd, QtCore.SIGNAL('stateChanged(int)'), self.checkFitProd) - self.connect(self.cbFitDegr, QtCore.SIGNAL('stateChanged(int)'), self.checkFitDegr) - self.connect(self.cbFitPinned, QtCore.SIGNAL('stateChanged(int)'), self.checkFitPinned) - self.connect(self.cbFitCutOffT, QtCore.SIGNAL('stateChanged(int)'), self.checkFitCutOffT) - self.connect(self.cbEquOn, QtCore.SIGNAL('stateChanged(int)'), self.checkEquOn) - self.connect(self.cbSaveTrack, QtCore.SIGNAL('stateChanged(int)'), self.checkSaveTrack) + self.cbFitProd.stateChanged.connect(self.checkFitProd) + self.cbFitDegr.stateChanged.connect(self.checkFitDegr) + self.cbFitPinned.stateChanged.connect(self.checkFitPinned) + self.cbFitCutOffT.stateChanged.connect(self.checkFitCutOffT) + self.cbEquOn.stateChanged.connect(self.checkEquOn) + self.cbSaveTrack.stateChanged.connect(self.checkSaveTrack) #TreeWigget - self.ROIList=QtGui.QTreeWidget() + self.ROIList=QtWidgets.QTreeWidget() self.ROIList.setHeaderLabels(["Name"]) self.ROIList.setColumnWidth(0,100) self.updateROIList() #Buttons - self.btnAddROI=QtGui.QPushButton('Add') - self.btnDone.connect(self.btnAddROI, QtCore.SIGNAL('clicked()'), self.addROI) + self.btnAddROI=QtWidgets.QPushButton('Add') + self.btnAddROI.clicked.connect(self.addROI) - self.btnRemoveROI=QtGui.QPushButton('Remove') - self.btnRemoveROI.connect(self.btnRemoveROI, QtCore.SIGNAL('clicked()'), self.removeROI) + self.btnRemoveROI=QtWidgets.QPushButton('Remove') + self.btnRemoveROI.clicked.connect(self.removeROI) #Layout self.grid.addWidget(self.lblHeadGeneral,0,1,1,2,QtCore.Qt.AlignHCenter) @@ -282,7 +282,7 @@ def updateROIList(self): self.ROIList.clear() for r in self.fit.ROIsFitted: - QtGui.QTreeWidgetItem(self.ROIList,[r.name]) + QtWidgets.QTreeWidgetItem(self.ROIList,[r.name]) return self.ROIList def initComboMeth(self): diff --git a/pyfrp/gui/pyfrp_gui_geometry_dialogs.py b/pyfrp/gui/pyfrp_gui_geometry_dialogs.py old mode 100644 new mode 100755 index efa98dd..8b2d4c2 --- a/pyfrp/gui/pyfrp_gui_geometry_dialogs.py +++ b/pyfrp/gui/pyfrp_gui_geometry_dialogs.py @@ -32,10 +32,10 @@ #=========================================================================================================================================================================== #QT -from PyQt4 import QtGui, QtCore +from PyQt5 import QtGui, QtCore, QtWidgets #PyFRAP GUI classes -import pyfrp_gui_basics +from . import pyfrp_gui_basics #PyFRAP modules from pyfrp.modules.pyfrp_term_module import * @@ -68,23 +68,23 @@ def __init__(self,geometry,parent): self.ann=0 #Labels - self.lblTyp = QtGui.QLabel("Typ:", self) - self.lblCenter = QtGui.QLabel("Center (px):", self) - self.lblFnGeo = QtGui.QLabel("Geo File:", self) + self.lblTyp = QtWidgets.QLabel("Typ:", self) + self.lblCenter = QtWidgets.QLabel("Center (px):", self) + self.lblFnGeo = QtWidgets.QLabel("Geo File:", self) - self.lblTypVal = QtGui.QLabel(self.geometry.typ, self) - self.lblFnGeoVal = QtGui.QLabel(self.geometry.fnGeo, self) + self.lblTypVal = QtWidgets.QLabel(self.geometry.typ, self) + self.lblFnGeoVal = QtWidgets.QLabel(self.geometry.fnGeo, self) #LineEdits self.doubleValid=QtGui.QDoubleValidator() - self.qleCenterX = QtGui.QLineEdit(str(self.geometry.center[0])) - self.qleCenterY = QtGui.QLineEdit(str(self.geometry.center[1])) + self.qleCenterX = QtWidgets.QLineEdit(str(self.geometry.center[0])) + self.qleCenterY = QtWidgets.QLineEdit(str(self.geometry.center[1])) self.qleCenterX.setValidator(self.doubleValid) self.qleCenterY.setValidator(self.doubleValid) - self.centerGrid = QtGui.QGridLayout() + self.centerGrid = QtWidgets.QGridLayout() self.centerGrid.addWidget(self.qleCenterX) self.centerGrid.addWidget(self.qleCenterY) @@ -93,23 +93,23 @@ def __init__(self,geometry,parent): self.qleCenterY.editingFinished.connect(self.setCenter) #Buttons - self.btnFnGeo=QtGui.QPushButton('Change') - self.btnFnGeo.connect(self.btnFnGeo, QtCore.SIGNAL('clicked()'), self.setFnGeo) + self.btnFnGeo=QtWidgets.QPushButton('Change') + self.btnFnGeo.clicked.connect(self.setFnGeo) - self.btnGetCenterFromROI=QtGui.QPushButton('Grab from ROI') - self.btnGetCenterFromROI.connect(self.btnGetCenterFromROI, QtCore.SIGNAL('clicked()'), self.getCenterFromROI) + self.btnGetCenterFromROI=QtWidgets.QPushButton('Grab from ROI') + self.btnGetCenterFromROI.clicked.connect(self.getCenterFromROI) - self.btnUpdateAll=QtGui.QPushButton('Update optimal All ROI') - self.btnUpdateAll.connect(self.btnUpdateAll, QtCore.SIGNAL('clicked()'), self.updateAllROI) + self.btnUpdateAll=QtWidgets.QPushButton('Update optimal All ROI') + self.btnUpdateAll.clicked.connect(self.updateAllROI) #Checkboxes - self.cbAnn = QtGui.QCheckBox('Annotate?', self) + self.cbAnn = QtWidgets.QCheckBox('Annotate?', self) self.cbAnn.setCheckState(2*int(self.ann)) - self.connect(self.cbAnn, QtCore.SIGNAL('stateChanged(int)'), self.setAnnotate) + self.cbAnn.stateChanged.connect(self.setAnnotate) #Layout - self.fnGeoGrid = QtGui.QGridLayout() + self.fnGeoGrid = QtWidgets.QGridLayout() self.fnGeoGrid.addWidget(self.lblFnGeoVal,1,1) self.fnGeoGrid.addWidget(self.btnFnGeo,1,2) @@ -148,7 +148,7 @@ def setCenter(self): def setFnGeo(self): mdir=pyfrp_misc_module.getMeshfilesDir() - fn = str(QtGui.QFileDialog.getOpenFileName(self, 'Open file', mdir,"*.geo",)) + fn = str(QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', mdir,"*.geo",)) if fn=='': return @@ -246,14 +246,14 @@ def __init__(self,geometry,parent): super(zebrafishDomeStageDialog,self).__init__(geometry,parent) #Labels - self.lblRadius = QtGui.QLabel("Imaging Radius (px):", self) - self.lblScale = QtGui.QLabel("Radius Scale:", self) - self.lblHeight = QtGui.QLabel("Imaging Height (px):", self) + self.lblRadius = QtWidgets.QLabel("Imaging Radius (px):", self) + self.lblScale = QtWidgets.QLabel("Radius Scale:", self) + self.lblHeight = QtWidgets.QLabel("Imaging Height (px):", self) #LineEdits - self.qleRadius = QtGui.QLineEdit(str(self.geometry.imagingRadius)) - self.qleScale = QtGui.QLineEdit(str(self.geometry.radiusScale)) - self.qleHeight = QtGui.QLineEdit(str(self.geometry.imagingHeight)) + self.qleRadius = QtWidgets.QLineEdit(str(self.geometry.imagingRadius)) + self.qleScale = QtWidgets.QLineEdit(str(self.geometry.radiusScale)) + self.qleHeight = QtWidgets.QLineEdit(str(self.geometry.imagingHeight)) self.qleRadius.setValidator(self.doubleValid) self.qleScale.setValidator(self.doubleValid) @@ -264,11 +264,11 @@ def __init__(self,geometry,parent): self.qleHeight.editingFinished.connect(self.setHeight) #Buttons - self.btnRestoreDefaults=QtGui.QPushButton('Restore Defaults') - self.btnRestoreDefaults.connect(self.btnRestoreDefaults, QtCore.SIGNAL('clicked()'), self.restoreDefaults) + self.btnRestoreDefaults=QtWidgets.QPushButton('Restore Defaults') + self.btnRestoreDefaults.clicked.connect(self.restoreDefaults) - self.btnGetRadiusFromROI=QtGui.QPushButton('Grab from ROI') - self.btnGetRadiusFromROI.connect(self.btnGetRadiusFromROI, QtCore.SIGNAL('clicked()'), self.getRadiusFromROI) + self.btnGetRadiusFromROI=QtWidgets.QPushButton('Grab from ROI') + self.btnGetRadiusFromROI.clicked.connect(self.getRadiusFromROI) #Layout nRows=self.grid.rowCount() @@ -337,12 +337,12 @@ def __init__(self,geometry,parent): super(cylinderDialog,self).__init__(geometry,parent) #Labels - self.lblRadius = QtGui.QLabel("Radius (px):", self) - self.lblHeight = QtGui.QLabel("Height (px):", self) + self.lblRadius = QtWidgets.QLabel("Radius (px):", self) + self.lblHeight = QtWidgets.QLabel("Height (px):", self) #LineEdits - self.qleRadius = QtGui.QLineEdit(str(self.geometry.radius)) - self.qleHeight = QtGui.QLineEdit(str(self.geometry.height)) + self.qleRadius = QtWidgets.QLineEdit(str(self.geometry.radius)) + self.qleHeight = QtWidgets.QLineEdit(str(self.geometry.height)) self.qleRadius.setValidator(self.doubleValid) self.qleHeight.setValidator(self.doubleValid) @@ -401,15 +401,15 @@ def __init__(self,geometry,parent): super(coneDialog,self).__init__(geometry,parent) #Labels - self.lblUpperRadius = QtGui.QLabel("Upper Radius (px):", self) - self.lblLowerRadius = QtGui.QLabel("Lower Radius (px):", self) + self.lblUpperRadius = QtWidgets.QLabel("Upper Radius (px):", self) + self.lblLowerRadius = QtWidgets.QLabel("Lower Radius (px):", self) - self.lblHeight = QtGui.QLabel("Height (px):", self) + self.lblHeight = QtWidgets.QLabel("Height (px):", self) #LineEdits - self.qleUpperRadius = QtGui.QLineEdit(str(self.geometry.upperRadius)) - self.qleLowerRadius = QtGui.QLineEdit(str(self.geometry.lowerRadius)) - self.qleHeight = QtGui.QLineEdit(str(self.geometry.height)) + self.qleUpperRadius = QtWidgets.QLineEdit(str(self.geometry.upperRadius)) + self.qleLowerRadius = QtWidgets.QLineEdit(str(self.geometry.lowerRadius)) + self.qleHeight = QtWidgets.QLineEdit(str(self.geometry.height)) self.qleUpperRadius.setValidator(self.doubleValid) self.qleLowerRadius.setValidator(self.doubleValid) @@ -458,12 +458,12 @@ def __init__(self,geometry,parent): super(xenopusBallDialog,self).__init__(geometry,parent) #Labels - self.lblRadius = QtGui.QLabel("Imaging Radius (px):", self) - self.lblHeight = QtGui.QLabel("Imaging Height (px):", self) + self.lblRadius = QtWidgets.QLabel("Imaging Radius (px):", self) + self.lblHeight = QtWidgets.QLabel("Imaging Height (px):", self) #LineEdits - self.qleRadius = QtGui.QLineEdit(str(self.geometry.imagingRadius)) - self.qleHeight = QtGui.QLineEdit(str(self.geometry.imagingHeight)) + self.qleRadius = QtWidgets.QLineEdit(str(self.geometry.imagingRadius)) + self.qleHeight = QtWidgets.QLineEdit(str(self.geometry.imagingHeight)) self.qleRadius.setValidator(self.doubleValid) self.qleHeight.setValidator(self.doubleValid) @@ -472,11 +472,11 @@ def __init__(self,geometry,parent): self.qleHeight.editingFinished.connect(self.setHeight) #Buttons - self.btnRestoreDefaults=QtGui.QPushButton('Restore Defaults') - self.btnRestoreDefaults.connect(self.btnRestoreDefaults, QtCore.SIGNAL('clicked()'), self.restoreDefaults) + self.btnRestoreDefaults=QtWidgets.QPushButton('Restore Defaults') + self.btnRestoreDefaults.clicked.connect(self.restoreDefaults) - self.btnGetRadiusFromROI=QtGui.QPushButton('Grab from ROI') - self.btnGetRadiusFromROI.connect(self.btnGetRadiusFromROI, QtCore.SIGNAL('clicked()'), self.getRadiusFromROI) + self.btnGetRadiusFromROI=QtWidgets.QPushButton('Grab from ROI') + self.btnGetRadiusFromROI.clicked.connect(self.getRadiusFromROI) #Layout nRows=self.grid.rowCount() @@ -532,7 +532,7 @@ def updateRadiusQle(self): self.qleRadius.setText(str(self.geometry.getImagingRadius())) self.setRadius() -class geometrySelectDialog(QtGui.QDialog): +class geometrySelectDialog(QtWidgets.QDialog): def __init__(self,embryo,parent): @@ -543,10 +543,10 @@ def __init__(self,embryo,parent): #Labels - self.lblTyp = QtGui.QLabel("Geometry Type:", self) + self.lblTyp = QtWidgets.QLabel("Geometry Type:", self) #Combo - self.comboGeometry = QtGui.QComboBox(self) + self.comboGeometry = QtWidgets.QComboBox(self) self.comboGeometry.addItem("zebraFishDomeStage") self.comboGeometry.addItem("cylinder") self.comboGeometry.addItem("xenopusBall") @@ -561,11 +561,11 @@ def __init__(self,embryo,parent): self.comboGeometry.activated[str].connect(self.setGeometry) #Buttons - self.btnDone=QtGui.QPushButton('Done') - self.btnDone.connect(self.btnDone, QtCore.SIGNAL('clicked()'), self.donePressed) + self.btnDone=QtWidgets.QPushButton('Done') + self.btnDone.clicked.connect(self.donePressed) #Layout - self.grid = QtGui.QGridLayout() + self.grid = QtWidgets.QGridLayout() self.grid.addWidget(self.lblTyp,1,1) @@ -693,4 +693,4 @@ def donePressed(self): - \ No newline at end of file + diff --git a/pyfrp/gui/pyfrp_gui_gmsh_editor.py b/pyfrp/gui/pyfrp_gui_gmsh_editor.py old mode 100644 new mode 100755 index 4a0992d..08386c2 --- a/pyfrp/gui/pyfrp_gui_gmsh_editor.py +++ b/pyfrp/gui/pyfrp_gui_gmsh_editor.py @@ -34,7 +34,7 @@ #=========================================================================================================================================================================== #QT -from PyQt4 import QtGui, QtCore +from PyQt5 import QtGui, QtCore, QtWidgets #PyFRAP modules from pyfrp.modules.pyfrp_term_module import * @@ -45,7 +45,7 @@ -class gmshFileEditor(QtGui.QDialog): +class gmshFileEditor(QtWidgets.QDialog): def __init__(self,geometry,parent): @@ -57,33 +57,33 @@ def __init__(self,geometry,parent): self.currFn=None #Buttons - self.btnDone=QtGui.QPushButton('Done') - self.btnDone.connect(self.btnDone, QtCore.SIGNAL('clicked()'), self.donePressed) + self.btnDone=QtWidgets.QPushButton('Done') + self.btnDone.clicked.connect(self.donePressed) - self.btnNew=QtGui.QPushButton('New') - self.btnNew.connect(self.btnNew, QtCore.SIGNAL('clicked()'), self.newFile) + self.btnNew=QtWidgets.QPushButton('New') + self.btnNew.clicked.connect(self.newFile) - self.btnOpen=QtGui.QPushButton('Open') - self.btnOpen.connect(self.btnOpen, QtCore.SIGNAL('clicked()'), self.openFile) + self.btnOpen=QtWidgets.QPushButton('Open') + self.btnOpen.clicked.connect(self.openFile) - self.btnSave=QtGui.QPushButton('Save') - self.btnSave.connect(self.btnSave, QtCore.SIGNAL('clicked()'), self.saveFile) + self.btnSave=QtWidgets.QPushButton('Save') + self.btnSave.clicked.connect(self.saveFile) - self.btnSaveAs=QtGui.QPushButton('Save As') - self.btnSaveAs.connect(self.btnSaveAs, QtCore.SIGNAL('clicked()'), self.saveFileAs) + self.btnSaveAs=QtWidgets.QPushButton('Save As') + self.btnSaveAs.clicked.connect(self.saveFileAs) - self.btnUse=QtGui.QPushButton('Use for geometry') - self.btnUse.connect(self.btnUse, QtCore.SIGNAL('clicked()'), self.useForGeometry) + self.btnUse=QtWidgets.QPushButton('Use for geometry') + self.btnUse.clicked.connect(self.useForGeometry) #QTextEdit - self.editor = QtGui.QTextEdit() + self.editor = QtWidgets.QTextEdit() #QHighLight self.highlighter=gmshHighlighter(self.editor,'Classic') #Layout - self.hbox = QtGui.QHBoxLayout() + self.hbox = QtWidgets.QHBoxLayout() self.hbox.addWidget(self.btnNew) self.hbox.addWidget(self.btnOpen) self.hbox.addWidget(self.btnSave) @@ -92,7 +92,7 @@ def __init__(self,geometry,parent): self.hbox.addWidget(self.btnUse) self.hbox.addWidget(self.btnDone) - self.vbox = QtGui.QVBoxLayout() + self.vbox = QtWidgets.QVBoxLayout() self.vbox.addWidget(self.editor) self.vbox.addLayout(self.hbox) @@ -108,7 +108,7 @@ def __init__(self,geometry,parent): def openFile(self): mdir=pyfrp_misc_module.getMeshfilesDir() - fn = str(QtGui.QFileDialog.getOpenFileName(self, 'Open file', mdir,"*.geo",)) + fn = str(QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', mdir,"*.geo",)) if fn=='': return @@ -126,7 +126,7 @@ def saveFile(self): def saveFileAs(self): mdir=pyfrp_misc_module.getMeshfilesDir() - fn=str(QtGui.QFileDialog.getSaveFileName(self, 'Save file', mdir+"newGeo.geo","*.geo",)) + fn=str(QtWidgets.QFileDialog.getSaveFileName(self, 'Save file', mdir+"newGeo.geo","*.geo",)) self.writeFile(fn) @@ -198,18 +198,18 @@ def __init__( self, parent, theme ): super(gmshHighlighter,self).__init__(parent) self.parent = parent - mathExpr = QtGui.QTextCharFormat() - geomObj = QtGui.QTextCharFormat() - delimiter = QtGui.QTextCharFormat() - number = QtGui.QTextCharFormat() - comment = QtGui.QTextCharFormat() - string = QtGui.QTextCharFormat() - singleQuotedString = QtGui.QTextCharFormat() + mathExpr = QtWidgets.QTextCharFormat() + geomObj = QtWidgets.QTextCharFormat() + delimiter = QtWidgets.QTextCharFormat() + number = QtWidgets.QTextCharFormat() + comment = QtWidgets.QTextCharFormat() + string = QtWidgets.QTextCharFormat() + singleQuotedString = QtWidgets.QTextCharFormat() self.highlightingRules = [] # Math Expr - brush = QtGui.QBrush( QtCore.Qt.darkBlue, QtCore.Qt.SolidPattern ) + brush = QtWidgets.QBrush( QtCore.Qt.darkBlue, QtCore.Qt.SolidPattern ) mathExpr.setForeground( brush ) mathExpr.setFontWeight( QtGui.QFont.Bold ) keywords = QtCore.QStringList( [ "Sqrt","Cos","Sin","Arcos","Arsin","Abs"] ) @@ -219,7 +219,7 @@ def __init__( self, parent, theme ): self.highlightingRules.append( rule ) # GeomObjects - brush = QtGui.QBrush( QtCore.Qt.green, QtCore.Qt.SolidPattern ) + brush = QtWidgets.QBrush( QtCore.Qt.green, QtCore.Qt.SolidPattern ) geomObj.setForeground( brush ) geomObj.setFontWeight( QtGui.QFont.Bold ) keywords = QtCore.QStringList( [ "Point","Circle","Line","Surface","Volume","Line Loop","Surface Loop","Ruled Surface"] ) @@ -229,7 +229,7 @@ def __init__( self, parent, theme ): self.highlightingRules.append( rule ) # delimiter - brush = QtGui.QBrush( QtCore.Qt.gray, QtCore.Qt.SolidPattern ) + brush = QtWidgets.QBrush( QtCore.Qt.gray, QtCore.Qt.SolidPattern ) pattern = QtCore.QRegExp( "[\)\(]+|[\{\}]+|[][]+" ) delimiter.setForeground( brush ) delimiter.setFontWeight( QtGui.QFont.Bold ) @@ -237,7 +237,7 @@ def __init__( self, parent, theme ): self.highlightingRules.append( rule ) # number - brush = QtGui.QBrush( QtCore.Qt.magenta, QtCore.Qt.SolidPattern ) + brush = QtWidgets.QBrush( QtCore.Qt.magenta, QtCore.Qt.SolidPattern ) pattern = QtCore.QRegExp( "[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?" ) pattern.setMinimal( True ) number.setForeground( brush ) @@ -245,14 +245,14 @@ def __init__( self, parent, theme ): self.highlightingRules.append( rule ) # comment - brush = QtGui.QBrush( QtCore.Qt.blue, QtCore.Qt.SolidPattern ) + brush = QtWidgets.QBrush( QtCore.Qt.blue, QtCore.Qt.SolidPattern ) pattern = QtCore.QRegExp( "//[^\n]*" ) comment.setForeground( brush ) rule = HighlightingRule( pattern, comment ) self.highlightingRules.append( rule ) # string - brush = QtGui.QBrush( QtCore.Qt.red, QtCore.Qt.SolidPattern ) + brush = QtWidgets.QBrush( QtCore.Qt.red, QtCore.Qt.SolidPattern ) pattern = QtCore.QRegExp( "\".*\"" ) pattern.setMinimal( True ) string.setForeground( brush ) diff --git a/pyfrp/gui/pyfrp_gui_mesh_dialogs.py b/pyfrp/gui/pyfrp_gui_mesh_dialogs.py old mode 100644 new mode 100755 index 1e06458..f6f2857 --- a/pyfrp/gui/pyfrp_gui_mesh_dialogs.py +++ b/pyfrp/gui/pyfrp_gui_mesh_dialogs.py @@ -32,11 +32,11 @@ #=========================================================================================================================================================================== #QT -from PyQt4 import QtGui, QtCore +from PyQt5 import QtGui, QtCore, QtWidgets #PyFRAP GUI classes -import pyfrp_gui_basics -import pyfrp_gui_builder +from . import pyfrp_gui_basics +from . import pyfrp_gui_builder #PyFRAP modules from pyfrp.modules.pyfrp_term_module import * @@ -65,32 +65,32 @@ def __init__(self,mesh,parent): self.nCharDisplayed=50 #Labels - self.lblVolSizePx = QtGui.QLabel("Element Size (px):", self) - self.lblFromFile = QtGui.QLabel("From File?:", self) - self.lblFnMesh = QtGui.QLabel("Filename mesh:", self) + self.lblVolSizePx = QtWidgets.QLabel("Element Size (px):", self) + self.lblFromFile = QtWidgets.QLabel("From File?:", self) + self.lblFnMesh = QtWidgets.QLabel("Filename mesh:", self) - self.lblFnMeshVal = QtGui.QLabel("", self) + self.lblFnMeshVal = QtWidgets.QLabel("", self) self.updateFnMeshLbl() #LineEdits - self.qleVolSizePx = QtGui.QLineEdit(str(self.mesh.volSizePx)) + self.qleVolSizePx = QtWidgets.QLineEdit(str(self.mesh.volSizePx)) self.qleVolSizePx.setValidator(self.doubleValid) self.qleVolSizePx.editingFinished.connect(self.setVolSizePx) #CheckBox - self.cbFromFile = QtGui.QCheckBox('', self) + self.cbFromFile = QtWidgets.QCheckBox('', self) self.updateCBs() - self.connect(self.cbFromFile, QtCore.SIGNAL('stateChanged(int)'), self.checkFromFile) + self.cbFromFile.stateChanged.connect(self.checkFromFile) #Buttons - self.btnFnMesh=QtGui.QPushButton('Change') + self.btnFnMesh=QtWidgets.QPushButton('Change') - self.btnFnMesh.connect(self.btnFnMesh, QtCore.SIGNAL('clicked()'), self.setFnMesh) + self.btnFnMesh.clicked.connect(self.setFnMesh) #Layout - self.fnMeshGrid = QtGui.QGridLayout() + self.fnMeshGrid = QtWidgets.QGridLayout() self.fnMeshGrid.addWidget(self.lblFnMeshVal,1,1) self.fnMeshGrid.addWidget(self.btnFnMesh,1,2) self.fnMeshGrid.setColumnMinimumWidth(1,150) @@ -112,7 +112,7 @@ def setVolSizePx(self): def setFnMesh(self): - fn = str(QtGui.QFileDialog.getExistingFile(self, "Select Mesh File", self.parent.lastopen,"*.msh",)) + fn = str(QtWidgets.QFileDialog.getExistingFile(self, "Select Mesh File", self.parent.lastopen,"*.msh",)) if fn=='': return @@ -209,26 +209,26 @@ def __init__(self,mesh,parent): self.findIdxs=True #Labels - self.lblROI = QtGui.QLabel("ROI used:", self) - self.lblDebug = QtGui.QLabel("Print debugging output:", self) - self.lblFindIdxs = QtGui.QLabel("Update Indices?:", self) + self.lblROI = QtWidgets.QLabel("ROI used:", self) + self.lblDebug = QtWidgets.QLabel("Print debugging output:", self) + self.lblFindIdxs = QtWidgets.QLabel("Update Indices?:", self) #LineEdits self.doubleValid=QtGui.QDoubleValidator() self.intValid=QtGui.QIntValidator() #Combobox - self.comboROI = QtGui.QComboBox(self) + self.comboROI = QtWidgets.QComboBox(self) self.updateROICombo() self.comboROI.activated[str].connect(self.setROI) #CheckBox - self.cbDebug = QtGui.QCheckBox('', self) - self.cbFindIdxs = QtGui.QCheckBox('', self) + self.cbDebug = QtWidgets.QCheckBox('', self) + self.cbFindIdxs = QtWidgets.QCheckBox('', self) - self.connect(self.cbDebug, QtCore.SIGNAL('stateChanged(int)'), self.checkDebug) - self.connect(self.cbFindIdxs, QtCore.SIGNAL('stateChanged(int)'), self.checkFindIdxs) + self.cbDebug.stateChanged.connect(self.checkDebug) + self.cbFindIdxs.stateChanged.connect(self.checkFindIdxs) #Layout @@ -274,15 +274,15 @@ def __init__(self,mesh,parent): self.maxCells=100000 #Labels - self.lblDensity = QtGui.QLabel("Desired Mesh Density:", self) - self.lblStepPercentage = QtGui.QLabel("Step Size (%):", self) - self.lblMethod = QtGui.QLabel("Method:", self) - self.lblMaxCells = QtGui.QLabel("Maximum number of cells:", self) + self.lblDensity = QtWidgets.QLabel("Desired Mesh Density:", self) + self.lblStepPercentage = QtWidgets.QLabel("Step Size (%):", self) + self.lblMethod = QtWidgets.QLabel("Method:", self) + self.lblMaxCells = QtWidgets.QLabel("Maximum number of cells:", self) #LineEdits - self.qleDensity = QtGui.QLineEdit("0") - self.qleMaxCells = QtGui.QLineEdit(str(self.maxCells)) - self.qleStepPercentage = QtGui.QLineEdit(str(self.stepPercentage)) + self.qleDensity = QtWidgets.QLineEdit("0") + self.qleMaxCells = QtWidgets.QLineEdit(str(self.maxCells)) + self.qleStepPercentage = QtWidgets.QLineEdit(str(self.stepPercentage)) self.qleDensity.setValidator(self.doubleValid) self.qleMaxCells.setValidator(self.intValid) @@ -293,7 +293,7 @@ def __init__(self,mesh,parent): self.qleStepPercentage.editingFinished.connect(self.setStepPercentage) #Combobox - self.comboMethod = QtGui.QComboBox(self) + self.comboMethod = QtWidgets.QComboBox(self) self.addItem("refine") self.addWidget("method") @@ -353,12 +353,12 @@ def __init__(self,mesh,parent): self.addZ=15 #Labels - self.lblFactor = QtGui.QLabel("Factor :", self) - self.lblAddZ = QtGui.QLabel("Extend Box Mesh by z(px):", self) + self.lblFactor = QtWidgets.QLabel("Factor :", self) + self.lblAddZ = QtWidgets.QLabel("Extend Box Mesh by z(px):", self) #LineEdits - self.qleFactor = QtGui.QLineEdit(str(self.factor)) - self.qleAddZ = QtGui.QLineEdit(str(self.addZ)) + self.qleFactor = QtWidgets.QLineEdit(str(self.factor)) + self.qleAddZ = QtWidgets.QLineEdit(str(self.addZ)) self.qleAddZ.setValidator(self.doubleValid) self.qleFactor.setValidator(self.doubleValid) @@ -542,7 +542,7 @@ def setROI(self): def setFnOut(self): - fn=QtGui.QFileDialog.getSaveFileName(self, 'Path to boundary layer geo file', self.fnOut,"*.geo",) + fn=QtWidgets.QFileDialog.getSaveFileName(self, 'Path to boundary layer geo file', self.fnOut,"*.geo",) self.fnOut=str(fn) def getVals(self): @@ -603,4 +603,4 @@ def runTask(self,roi,debug=False): - \ No newline at end of file + diff --git a/pyfrp/gui/pyfrp_gui_molecule_dialogs.py b/pyfrp/gui/pyfrp_gui_molecule_dialogs.py old mode 100644 new mode 100755 index 522d8b3..9b63220 --- a/pyfrp/gui/pyfrp_gui_molecule_dialogs.py +++ b/pyfrp/gui/pyfrp_gui_molecule_dialogs.py @@ -1,74 +1,78 @@ -#===================================================================================================================================== -#Copyright -#===================================================================================================================================== +# ===================================================================================================================================== +# Copyright +# ===================================================================================================================================== -#Copyright (C) 2014 Alexander Blaessle, Patrick Mueller and the Friedrich Miescher Laboratory of the Max Planck Society -#This software is distributed under the terms of the GNU General Public License. +# Copyright (C) 2014 Alexander Blaessle, Patrick Mueller and the Friedrich Miescher Laboratory of the Max Planck Society +# This software is distributed under the terms of the GNU General Public +# License. -#This file is part of PyFRAP. +# This file is part of PyFRAP. -#PyFRAP is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License as published by -#the Free Software Foundation, either version 3 of the License, or -#(at your option) any later version. +# PyFRAP is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -#GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. -#You should have received a copy of the GNU General Public License -#along with this program. If not, see . +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . -#=========================================================================================================================================================================== -#Module Description -#=========================================================================================================================================================================== +# =========================================================================================================================================================================== +# Module Description +# =========================================================================================================================================================================== -#PyQT Dialogs for editing molecule objects -#(1) moleculeDialog +# PyQT Dialogs for editing molecule objects +# (1) moleculeDialog -#=========================================================================================================================================================================== -#Importing necessary modules -#=========================================================================================================================================================================== +# =========================================================================================================================================================================== +# Importing necessary modules +# =========================================================================================================================================================================== -#QT -from PyQt4 import QtGui, QtCore +# QT +from PyQt5 import QtGui, QtCore, QtWidgets -#=================================================================================================================================== -#Dialog for select/edit molecule -#=================================================================================================================================== +# =================================================================================================================================== +# Dialog for select/edit molecule +# =================================================================================================================================== -class moleculeDialog(QtGui.QDialog): - - def __init__(self,molecule,parent): - - super(moleculeDialog,self).__init__(parent) - - #Pass molecule - self.molecule=molecule - - #Buttons - self.btnDone=QtGui.QPushButton('Done') - self.btnDone.connect(self.btnDone, QtCore.SIGNAL('clicked()'), self.donePressed) - - #Labels - self.lblName = QtGui.QLabel("Name:", self) - - #LineEdit - self.qleName = QtGui.QLineEdit(self.molecule.name) + +class moleculeDialog(QtWidgets.QDialog): + + def __init__(self, molecule, parent): + + super(moleculeDialog, self).__init__(parent) + + # Pass molecule + self.molecule = molecule + + # Buttons + self.btnDone = QtWidgets.QPushButton('Done') + + + self.btnDone.clicked.connect(self.donePressed) + + # Labels + self.lblName = QtWidgets.QLabel("Name:", self) + + # LineEdit + self.qleName = QtWidgets.QLineEdit(self.molecule.name) self.qleName.editingFinished.connect(self.setName) - - #Layout - grid = QtGui.QGridLayout() - grid.addWidget(self.lblName,1,1) - grid.addWidget(self.qleName,2,1) - grid.addWidget(self.btnDone,2,2) - - self.setLayout(grid) - - self.setWindowTitle('Edit Molecule') + + # Layout + grid = QtWidgets.QGridLayout() + grid.addWidget(self.lblName, 1, 1) + grid.addWidget(self.qleName, 2, 1) + grid.addWidget(self.btnDone, 2, 2) + + self.setLayout(grid) + + self.setWindowTitle('Edit Molecule') self.show() - + def setName(self): text=self.qleName.text() self.molecule.setName(str(text)) @@ -77,4 +81,4 @@ def setName(self): def donePressed(self): self.done(1) - return self.molecule \ No newline at end of file + return self.molecule diff --git a/pyfrp/gui/pyfrp_gui_pinning_dialogs.py b/pyfrp/gui/pyfrp_gui_pinning_dialogs.py old mode 100644 new mode 100755 index 7e8fd8b..63f7510 --- a/pyfrp/gui/pyfrp_gui_pinning_dialogs.py +++ b/pyfrp/gui/pyfrp_gui_pinning_dialogs.py @@ -32,10 +32,10 @@ #=========================================================================================================================================================================== #QT -from PyQt4 import QtGui, QtCore +from PyQt5 import QtGui, QtCore, QtWidgets #PyFRAP GUI classes -import pyfrp_gui_basics +from . import pyfrp_gui_basics #PyFRAP modules from pyfrp.modules.pyfrp_term_module import * @@ -65,20 +65,20 @@ def __init__(self,embryo,parent): self.debug=False #Labels - self.lblUseMin = QtGui.QLabel("Use Min. Value for Background:", self) - self.lblUseMax = QtGui.QLabel("Use Max. Value for Norming:", self) - self.lblDebug = QtGui.QLabel("Show Debugging Output:", self) + self.lblUseMin = QtWidgets.QLabel("Use Min. Value for Background:", self) + self.lblUseMax = QtWidgets.QLabel("Use Max. Value for Norming:", self) + self.lblDebug = QtWidgets.QLabel("Show Debugging Output:", self) #Checkboxes - self.cbUseMax = QtGui.QCheckBox('', self) - self.cbUseMin = QtGui.QCheckBox('', self) - self.cbDebug = QtGui.QCheckBox('', self) + self.cbUseMax = QtWidgets.QCheckBox('', self) + self.cbUseMin = QtWidgets.QCheckBox('', self) + self.cbDebug = QtWidgets.QCheckBox('', self) self.updateCBs() - self.connect(self.cbUseMax, QtCore.SIGNAL('stateChanged(int)'), self.checkUseMax) - self.connect(self.cbUseMin, QtCore.SIGNAL('stateChanged(int)'), self.checkUseMin) - self.connect(self.cbDebug, QtCore.SIGNAL('stateChanged(int)'), self.checkDebug) + self.cbUseMax.stateChanged.connect(self.checkUseMax) + self.cbUseMin.stateChanged.connect(self.checkUseMin) + self.cbDebug.stateChanged.connect(self.checkDebug) #layout self.grid.addWidget(self.lblUseMin,1,1) @@ -129,37 +129,37 @@ def __init__(self,embryo,parent): self.sepSim=True #Labels - self.lblBkgd = QtGui.QLabel("ROI for Background Calculation:", self) - self.lblNorm = QtGui.QLabel("ROI for Norm Calculation:", self) + self.lblBkgd = QtWidgets.QLabel("ROI for Background Calculation:", self) + self.lblNorm = QtWidgets.QLabel("ROI for Norm Calculation:", self) - self.lblBkgdVal = QtGui.QLabel("", self) - self.lblNormVal = QtGui.QLabel("", self) + self.lblBkgdVal = QtWidgets.QLabel("", self) + self.lblNormVal = QtWidgets.QLabel("", self) - self.lblSepSim = QtGui.QLabel("Pin simulation seperately:", self) - self.lblSwitchThresh = QtGui.QLabel("Switch Threshold:", self) + self.lblSepSim = QtWidgets.QLabel("Pin simulation seperately:", self) + self.lblSwitchThresh = QtWidgets.QLabel("Switch Threshold:", self) self.updateBkgdROILbl() self.updateNormROILbl() #LineEdits self.doubleValid=QtGui.QDoubleValidator() - self.qleSwitchThresh = QtGui.QLineEdit(str(self.switchThresh)) + self.qleSwitchThresh = QtWidgets.QLineEdit(str(self.switchThresh)) self.qleSwitchThresh.setValidator(self.doubleValid) self.qleSwitchThresh.editingFinished.connect(self.setSwitchThresh) #Buttons - self.btnSetBkgdROI=QtGui.QPushButton('Change') - self.btnSetBkgdROI.connect(self.btnSetBkgdROI, QtCore.SIGNAL('clicked()'), self.setBkgdROI) + self.btnSetBkgdROI=QtWidgets.QPushButton('Change') + self.btnSetBkgdROI.clicked.connect(self.setBkgdROI) - self.btnSetNormROI=QtGui.QPushButton('Change') - self.btnSetNormROI.connect(self.btnSetNormROI, QtCore.SIGNAL('clicked()'), self.setNormROI) + self.btnSetNormROI=QtWidgets.QPushButton('Change') + self.btnSetNormROI.clicked.connect(self.setNormROI) #Checkboxes - self.cbSepSim = QtGui.QCheckBox('', self) + self.cbSepSim = QtWidgets.QCheckBox('', self) self.cbSepSim.setCheckState(2*int(self.sepSim)) - self.connect(self.cbSepSim, QtCore.SIGNAL('stateChanged(int)'), self.checkSepSim) + self.cbSepSim.stateChanged.connect(self.checkSepSim) #Layout nRows=self.grid.rowCount() @@ -236,4 +236,4 @@ def donePressed(self): self.done(1) return - \ No newline at end of file + diff --git a/pyfrp/gui/pyfrp_gui_settings_dialogs.py b/pyfrp/gui/pyfrp_gui_settings_dialogs.py old mode 100644 new mode 100755 index 7c417c4..42fede1 --- a/pyfrp/gui/pyfrp_gui_settings_dialogs.py +++ b/pyfrp/gui/pyfrp_gui_settings_dialogs.py @@ -32,13 +32,13 @@ #=========================================================================================================================================================================== #QT -from PyQt4 import QtGui, QtCore +from PyQt5 import QtGui, QtCore, QtWidgets #=================================================================================================================================== #Dialog for select/edit molecule #=================================================================================================================================== -class pathDialog(QtGui.QDialog): +class pathDialog(QtWidgets.QDialog): """Dialog to modify path settings. @@ -48,30 +48,30 @@ class pathDialog(QtGui.QDialog): def __init__(self,identifier,path, parent): - QtGui.QDialog.__init__(self, parent) + QtWidgets.QDialog.__init__(self, parent) self.parent=parent self.identifier=identifier self.path=path #Labels - self.lblIdentifier=QtGui.QLabel("Identifier:", self) - self.lblPath=QtGui.QLabel("Path:", self) - self.lblPathVal=QtGui.QLabel(self.path, self) + self.lblIdentifier=QtWidgets.QLabel("Identifier:", self) + self.lblPath=QtWidgets.QLabel("Path:", self) + self.lblPathVal=QtWidgets.QLabel(self.path, self) #QLEs - self.qleIdentifier = QtGui.QLineEdit(str(self.identifier)) + self.qleIdentifier = QtWidgets.QLineEdit(str(self.identifier)) self.qleIdentifier.editingFinished.connect(self.setIdentifier) #Button - self.btnPath=QtGui.QPushButton('Change') - self.btnPath.connect(self.btnPath, QtCore.SIGNAL('clicked()'), self.setPath) + self.btnPath=QtWidgets.QPushButton('Change') + self.btnPath.clicked.connect(self.setPath) - self.btnDone=QtGui.QPushButton('Done') - self.btnDone.connect(self.btnDone, QtCore.SIGNAL('clicked()'), self.donePressed) + self.btnDone=QtWidgets.QPushButton('Done') + self.btnDone.clicked.connect(self.donePressed) #Layout - self.grid = QtGui.QGridLayout() + self.grid = QtWidgets.QGridLayout() self.grid.setColumnMinimumWidth(2,200) self.grid.addWidget(self.lblIdentifier,1,1) @@ -98,7 +98,7 @@ def getPath(self): def setPath(self): - fn = str(QtGui.QFileDialog.getOpenFileName(self, 'Open file',self.parent.lastopen,)) + fn = str(QtWidgets.QFileDialog.getOpenFileName(self, 'Open file',self.parent.lastopen,)) if fn=='': return diff --git a/pyfrp/gui/pyfrp_gui_simulation_dialogs.py b/pyfrp/gui/pyfrp_gui_simulation_dialogs.py old mode 100644 new mode 100755 index 93be7f1..f1856ec --- a/pyfrp/gui/pyfrp_gui_simulation_dialogs.py +++ b/pyfrp/gui/pyfrp_gui_simulation_dialogs.py @@ -32,10 +32,10 @@ #=========================================================================================================================================================================== #QT -from PyQt4 import QtGui, QtCore +from PyQt5 import QtGui, QtCore, QtWidgets #PyFRAP GUI classes -import pyfrp_gui_basics +from . import pyfrp_gui_basics #PyFRAP modules from pyfrp.modules.pyfrp_term_module import * @@ -62,28 +62,28 @@ def __init__(self,simulation,parent): self.simulation = simulation #Buttons - self.btnOptTvec=QtGui.QPushButton('opt. tEnd from D') - self.btnOptTvec.connect(self.btnOptTvec, QtCore.SIGNAL('clicked()'), self.getOptTvecSim) + self.btnOptTvec=QtWidgets.QPushButton('opt. tEnd from D') + self.btnOptTvec.clicked.connect(self.getOptTvecSim) #Labels - self.lblD = QtGui.QLabel("D:", self) - self.lblProd = QtGui.QLabel("Prod:", self) - self.lblDegr = QtGui.QLabel("Degr:", self) + self.lblD = QtWidgets.QLabel("D:", self) + self.lblProd = QtWidgets.QLabel("Prod:", self) + self.lblDegr = QtWidgets.QLabel("Degr:", self) - self.lblSteps = QtGui.QLabel("Timesteps:", self) - self.lblICmode = QtGui.QLabel("IC Mode:", self) - self.lblTimeScale = QtGui.QLabel("Time Scaling:", self) + self.lblSteps = QtWidgets.QLabel("Timesteps:", self) + self.lblICmode = QtWidgets.QLabel("IC Mode:", self) + self.lblTimeScale = QtWidgets.QLabel("Time Scaling:", self) - self.lblTEnd = QtGui.QLabel("TEnd:", self) + self.lblTEnd = QtWidgets.QLabel("TEnd:", self) #LineEdits - self.qleD = QtGui.QLineEdit(str(self.simulation.D)) - self.qleProd = QtGui.QLineEdit(str(self.simulation.prod)) - self.qleDegr = QtGui.QLineEdit(str(self.simulation.degr)) + self.qleD = QtWidgets.QLineEdit(str(self.simulation.D)) + self.qleProd = QtWidgets.QLineEdit(str(self.simulation.prod)) + self.qleDegr = QtWidgets.QLineEdit(str(self.simulation.degr)) - self.qleSteps = QtGui.QLineEdit(str(self.simulation.stepsSim)) + self.qleSteps = QtWidgets.QLineEdit(str(self.simulation.stepsSim)) - self.qleTEnd = QtGui.QLineEdit(str(self.simulation.tvecSim[-1])) + self.qleTEnd = QtWidgets.QLineEdit(str(self.simulation.tvecSim[-1])) self.doubleValid=QtGui.QDoubleValidator() self.intValid=QtGui.QIntValidator() @@ -102,13 +102,13 @@ def __init__(self,simulation,parent): self.qleTEnd.editingFinished.connect(self.setTEnd) #ComboBox - self.comboIC = QtGui.QComboBox(self) + self.comboIC = QtWidgets.QComboBox(self) self.comboIC.addItem("By ROI") self.comboIC.addItem("Radial") self.comboIC.addItem("Interpolation") self.comboIC.addItem("Ideal") - self.comboTS = QtGui.QComboBox(self) + self.comboTS = QtWidgets.QComboBox(self) self.comboTS.addItem("Linear") self.comboTS.addItem("Logarithmic") @@ -181,7 +181,7 @@ def setTEnd(self): self.simulation.setTEnd(float(str(self.qleTEnd.text()))) def getOptTvecSim(self): - maxExp, ok = QtGui.QInputDialog.getDouble(self, "Maximum expected diffusion coefficient","Enter expected diffusion coefficient (px^2/s):", 50, 0) + maxExp, ok = QtWidgets.QInputDialog.getDouble(self, "Maximum expected diffusion coefficient","Enter expected diffusion coefficient (px^2/s):", 50, 0) if ok: self.simulation.getOptTvecSim(maxExp) @@ -219,4 +219,4 @@ def runTask(self,debug=False): - \ No newline at end of file + diff --git a/pyfrp/gui/pyfrp_gui_statistics_dialogs.py b/pyfrp/gui/pyfrp_gui_statistics_dialogs.py old mode 100644 new mode 100755 index 8943379..965bd94 --- a/pyfrp/gui/pyfrp_gui_statistics_dialogs.py +++ b/pyfrp/gui/pyfrp_gui_statistics_dialogs.py @@ -1,293 +1,340 @@ -#===================================================================================================================================== -#Copyright -#===================================================================================================================================== +# ===================================================================================================================================== +# Copyright +# ===================================================================================================================================== -#Copyright (C) 2014 Alexander Blaessle, Patrick Mueller and the Friedrich Miescher Laboratory of the Max Planck Society -#This software is distributed under the terms of the GNU General Public License. +# Copyright (C) 2014 Alexander Blaessle, Patrick Mueller and the Friedrich Miescher Laboratory of the Max Planck Society +# This software is distributed under the terms of the GNU General Public License. -#This file is part of PyFRAP. +# This file is part of PyFRAP. -#PyFRAP is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License as published by -#the Free Software Foundation, either version 3 of the License, or -#(at your option) any later version. +# PyFRAP is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -#GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. -#You should have received a copy of the GNU General Public License -#along with this program. If not, see . +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . -#=========================================================================================================================================================================== -#Module Description -#=========================================================================================================================================================================== +# =========================================================================================================================================================================== +# Module Description +# =========================================================================================================================================================================== -#PyQT Dialogs for mesh class -#(1) +# PyQT Dialogs for mesh class +# (1) -#=========================================================================================================================================================================== -#Importing necessary modules -#=========================================================================================================================================================================== +# =========================================================================================================================================================================== +# Importing necessary modules +# =========================================================================================================================================================================== -#QT -from PyQt4 import QtGui, QtCore +# QT +from PyQt5 import QtGui, QtCore, QtWidgets -#PyFRAP GUI classes -import pyfrp_gui_basics +# PyFRAP GUI classes +from . import pyfrp_gui_basics -#PyFRAP modules +# PyFRAP modules from pyfrp.modules.pyfrp_term_module import * from pyfrp.modules import pyfrp_misc_module -#Numpy/Scipy +# Numpy/Scipy import numpy as np -#Misc +# Misc import os -#=================================================================================================================================== -#Dialog for selecting fits -#=================================================================================================================================== - +# =================================================================================================================================== +# Dialog for selecting fits +# =================================================================================================================================== + + class fitSelector(pyfrp_gui_basics.listSelectorDialog): - - def __init__(self,molecule,singleFit,parent): - - self.molecule=molecule - self.embryosInRightList=[] - self.fitsInRightList=[] - - self.singleFit=singleFit - - pyfrp_gui_basics.listSelectorDialog.__init__(self,parent,[],leftTitle="Available Fits",rightTitle="Selected Fits") - - - - #self.initLeftList() - self.resize(400,500) - - self.setWindowTitle("Fit Selector") - self.show() - - def initLeftList(self): - - """Sets up left list of selector.""" - - for emb in self.molecule.embryos: - - self.currEmbryoNode=QtGui.QTreeWidgetItem(self.leftList,[emb.name]) - - for fit in emb.fits: - if fit.isFitted(): - if fit not in self.molecule.selFits: - QtGui.QTreeWidgetItem(self.currEmbryoNode,[fit.name]) - - self.leftList.expandItem(self.currEmbryoNode) - - def initRightList(self): - - """Sets up right list of selector.""" - - for fit in self.molecule.selFits: - - if fit.embryo not in self.embryosInRightList: - self.currEmbryoNode=QtGui.QTreeWidgetItem(self.rightList,[fit.embryo.name]) - self.embryosInRightList.append(fit.embryo) - - QtGui.QTreeWidgetItem(self.currEmbryoNode,[fit.name]) - self.fitsInRightList.append(fit) - - def addItem(self): - - self.getLeftSelections() - - if self.leftList.currentItem()==None or self.leftList.currentItem().parent()==None: - QtGui.QMessageBox.critical(None, "Error","No fit selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return - - else: - - #Check if current embryo is already in right list - if self.currEmbryo in self.embryosInRightList: - - #Check if fit is already in right list - if self.currFit in self.fitsInRightList: - pass - else: - - self.getRightInd(embryoName=self.currEmbryo.name) - - if self.singleFit: - #Check if target embr already has a fit, if so, remove it - if self.currTargetEmbryoNode.childCount()>0: - self.getRightInd(fitName=self.currTargetEmbryoNode.child(0).data(0,0).toString()) - self.currTargetEmbryoNode.takeChild(0) - self.fitsInRightList.remove(self.currTargetFit) - - #Add to list of fits on right side - self.fitsInRightList.append(self.currFit) - newNode=QtGui.QTreeWidgetItem(self.currTargetEmbryoNode,[self.currFit.name]) - self.rightList.expandItem(self.currTargetEmbryoNode) - - # Remove in left list - #self.leftList.removeItemWidget(self.currFitNode,0) - ind=self.currEmbryoNode.indexOfChild(self.leftList.currentItem()) - self.currEmbryoNode.takeChild(ind) - #self.currEmbryoNode.takeChild() - - else: - - #Add currEmbryo to list - self.embryosInRightList.append(self.currEmbryo) - newNode=QtGui.QTreeWidgetItem(self.rightList,[self.currEmbryo.name]) - - #Add to list of fits on right side - self.fitsInRightList.append(self.currFit) - QtGui.QTreeWidgetItem(newNode,[self.currFit.name]) - self.rightList.expandItem(newNode) - - - def removeItem(self): - - """Removes item from right list.""" - - # Get selection - self.getRightSelections() - - # Check selection - if self.rightList.currentItem()==None or self.rightList.currentItem().parent()==None: - QtGui.QMessageBox.critical(None, "Error","No fit selected.",QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default) - return - else: - - # Remove - ind=self.currEmbryoNode.indexOfChild(self.rightList.currentItem()) - self.currEmbryoNode.takeChild(ind) - self.fitsInRightList.remove(self.currFit) - - # Add to left list - self.getLeftInd(embryoName=self.currFit.embryo.name) - QtGui.QTreeWidgetItem(self.currTargetEmbryoNode,[self.currFit.name]) - - - def getLeftSelections(self): - - #Get current embryo selection - for emb in self.molecule.embryos: - if self.leftList.currentItem().parent()==None: - - #This is a embryo - if self.leftList.currentItem().data(0,0).toString()==emb.name: - self.currEmbryo=emb - self.currEmbryoNode=self.leftList.currentItem() - self.currFit=None - self.currFitNode=None - break - else: - #This is a fit - if self.leftList.currentItem().parent().data(0,0).toString()==emb.name: - self.currEmbryo=emb - self.currEmbryoNode=self.leftList.currentItem().parent() - for fit in self.currEmbryo.fits: - if fit.name==self.leftList.currentItem().data(0,0).toString(): - self.currFit=fit - self.currFitNode=self.leftList.currentItem() - break - - def getRightSelections(self): - - #Get current embryo selection - for emb in self.molecule.embryos: - if self.rightList.currentItem().parent()==None: - - #This is a embryo - if self.rightList.currentItem().data(0,0).toString()==emb.name: - self.currEmbryo=emb - self.currEmbryoNode=self.rightList.currentItem() - self.currFit=None - self.currFitNode=None - break - else: - #This is a fit - if self.rightList.currentItem().parent().data(0,0).toString()==emb.name: - self.currEmbryo=emb - self.currEmbryoNode=self.rightList.currentItem().parent() - for fit in self.currEmbryo.fits: - if fit.name==self.rightList.currentItem().data(0,0).toString(): - self.currFit=fit - self.currFitNode=self.rightList.currentItem() - break - - def getLeftInd(self,embryoName=None,fitName=None): - if embryoName!=None: - self.currTargetEmbryoNode=self.leftList.findItems(embryoName,QtCore.Qt.MatchExactly,0) - self.currTargetEmbryoNode=self.currTargetEmbryoNode[0] - if fitName!=None: - self.currTargetFit_node=self.leftList.findItems(fitName,QtCore.Qt.MatchExactly,0) - for fit in self.currEmbryo.fits: - if fit.name==fitName: - self.currTargetFit=fit - - def getRightInd(self,embryoName=None,fitName=None): - if embryoName!=None: - self.currTargetEmbryoNode=self.rightList.findItems(embryoName,QtCore.Qt.MatchExactly,0) - self.currTargetEmbryoNode=self.currTargetEmbryoNode[0] - if fitName!=None: - self.currTargetFit_node=self.rightList.findItems(fitName,QtCore.Qt.MatchExactly,0) - for fit in self.currEmbryo.fits: - if fit.name==fitName: - self.currTargetFit=fit - - def getSelectedFits(self): - return self.fitsInRightList - - def donePressed(self): - self.molecule.selFits=self.fitsInRightList - self.done(1) - -#=================================================================================================================================== -#Dialog for selecting crucial Parameters -#=================================================================================================================================== - + def __init__(self, molecule, singleFit, parent): + + self.molecule = molecule + self.embryosInRightList = [] + self.fitsInRightList = [] + + self.singleFit = singleFit + + pyfrp_gui_basics.listSelectorDialog.__init__( + self, parent, [], leftTitle="Available Fits", rightTitle="Selected Fits" + ) + + # self.initLeftList() + self.resize(400, 500) + + self.setWindowTitle("Fit Selector") + self.show() + + def initLeftList(self): + + """Sets up left list of selector.""" + + for emb in self.molecule.embryos: + + self.currEmbryoNode = QtWidgets.QTreeWidgetItem(self.leftList, [emb.name]) + + for fit in emb.fits: + if fit.isFitted(): + if fit not in self.molecule.selFits: + QtWidgets.QTreeWidgetItem(self.currEmbryoNode, [fit.name]) + + self.leftList.expandItem(self.currEmbryoNode) + + def initRightList(self): + + """Sets up right list of selector.""" + + for fit in self.molecule.selFits: + + if fit.embryo not in self.embryosInRightList: + self.currEmbryoNode = QtWidgets.QTreeWidgetItem( + self.rightList, [fit.embryo.name] + ) + self.embryosInRightList.append(fit.embryo) + + QtWidgets.QTreeWidgetItem(self.currEmbryoNode, [fit.name]) + self.fitsInRightList.append(fit) + + def addItem(self): + + self.getLeftSelections() + + if ( + self.leftList.currentItem() == None + or self.leftList.currentItem().parent() == None + ): + QtWidgets.QMessageBox.critical( + None, + "Error", + "No fit selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return + + else: + + # Check if current embryo is already in right list + if self.currEmbryo in self.embryosInRightList: + + # Check if fit is already in right list + if self.currFit in self.fitsInRightList: + pass + else: + + self.getRightInd(embryoName=self.currEmbryo.name) + + if self.singleFit: + # Check if target embr already has a fit, if so, remove it + if self.currTargetEmbryoNode.childCount() > 0: + self.getRightInd( + fitName=self.currTargetEmbryoNode.child(0) + .data(0, 0) + .toString() + ) + self.currTargetEmbryoNode.takeChild(0) + self.fitsInRightList.remove(self.currTargetFit) + + # Add to list of fits on right side + self.fitsInRightList.append(self.currFit) + newNode = QtWidgets.QTreeWidgetItem( + self.currTargetEmbryoNode, [self.currFit.name] + ) + self.rightList.expandItem(self.currTargetEmbryoNode) + + # Remove in left list + # self.leftList.removeItemWidget(self.currFitNode,0) + ind = self.currEmbryoNode.indexOfChild(self.leftList.currentItem()) + self.currEmbryoNode.takeChild(ind) + # self.currEmbryoNode.takeChild() + + else: + + # Add currEmbryo to list + self.embryosInRightList.append(self.currEmbryo) + newNode = QtWidgets.QTreeWidgetItem( + self.rightList, [self.currEmbryo.name] + ) + + # Add to list of fits on right side + self.fitsInRightList.append(self.currFit) + QtWidgets.QTreeWidgetItem(newNode, [self.currFit.name]) + self.rightList.expandItem(newNode) + + def removeItem(self): + + """Removes item from right list.""" + + # Get selection + self.getRightSelections() + + # Check selection + if ( + self.rightList.currentItem() == None + or self.rightList.currentItem().parent() == None + ): + QtWidgets.QMessageBox.critical( + None, + "Error", + "No fit selected.", + QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, + ) + return + else: + + # Remove + ind = self.currEmbryoNode.indexOfChild(self.rightList.currentItem()) + self.currEmbryoNode.takeChild(ind) + self.fitsInRightList.remove(self.currFit) + + # Add to left list + self.getLeftInd(embryoName=self.currFit.embryo.name) + QtWidgets.QTreeWidgetItem(self.currTargetEmbryoNode, [self.currFit.name]) + + def getLeftSelections(self): + + # Get current embryo selection + for emb in self.molecule.embryos: + if self.leftList.currentItem().parent() == None: + + # This is a embryo + if self.leftList.currentItem().data(0, 0).toString() == emb.name: + self.currEmbryo = emb + self.currEmbryoNode = self.leftList.currentItem() + self.currFit = None + self.currFitNode = None + break + else: + # This is a fit + if ( + self.leftList.currentItem().parent().data(0, 0).toString() + == emb.name + ): + self.currEmbryo = emb + self.currEmbryoNode = self.leftList.currentItem().parent() + for fit in self.currEmbryo.fits: + if ( + fit.name + == self.leftList.currentItem().data(0, 0).toString() + ): + self.currFit = fit + self.currFitNode = self.leftList.currentItem() + break + + def getRightSelections(self): + + # Get current embryo selection + for emb in self.molecule.embryos: + if self.rightList.currentItem().parent() == None: + + # This is a embryo + if self.rightList.currentItem().data(0, 0).toString() == emb.name: + self.currEmbryo = emb + self.currEmbryoNode = self.rightList.currentItem() + self.currFit = None + self.currFitNode = None + break + else: + # This is a fit + if ( + self.rightList.currentItem().parent().data(0, 0).toString() + == emb.name + ): + self.currEmbryo = emb + self.currEmbryoNode = self.rightList.currentItem().parent() + for fit in self.currEmbryo.fits: + if ( + fit.name + == self.rightList.currentItem().data(0, 0).toString() + ): + self.currFit = fit + self.currFitNode = self.rightList.currentItem() + break + + def getLeftInd(self, embryoName=None, fitName=None): + if embryoName != None: + self.currTargetEmbryoNode = self.leftList.findItems( + embryoName, QtCore.Qt.MatchExactly, 0 + ) + self.currTargetEmbryoNode = self.currTargetEmbryoNode[0] + if fitName != None: + self.currTargetFit_node = self.leftList.findItems( + fitName, QtCore.Qt.MatchExactly, 0 + ) + for fit in self.currEmbryo.fits: + if fit.name == fitName: + self.currTargetFit = fit + + def getRightInd(self, embryoName=None, fitName=None): + if embryoName != None: + self.currTargetEmbryoNode = self.rightList.findItems( + embryoName, QtCore.Qt.MatchExactly, 0 + ) + self.currTargetEmbryoNode = self.currTargetEmbryoNode[0] + if fitName != None: + self.currTargetFit_node = self.rightList.findItems( + fitName, QtCore.Qt.MatchExactly, 0 + ) + for fit in self.currEmbryo.fits: + if fit.name == fitName: + self.currTargetFit = fit + + def getSelectedFits(self): + return self.fitsInRightList + + def donePressed(self): + self.molecule.selFits = self.fitsInRightList + self.done(1) + + +# =================================================================================================================================== +# Dialog for selecting crucial Parameters +# =================================================================================================================================== + + class crucialParameterSelector(pyfrp_gui_basics.listSelectorDialog): - - def __init__(self,molecule,parent): - - self.molecule=molecule - - fittingParms=self.getFittingParms() - - pyfrp_gui_basics.listSelectorDialog.__init__(self,parent,fittingParms,leftTitle="Available Parameters",rightTitle="Selected Parameters",itemsRight=self.molecule.crucialParameters) - - self.setWindowTitle("Select crucial parameters") - self.show() - - def getFittingParms(self): - - fit=None - - for embryo in self.molecule.embryos: - if embryo.isFitted(): - try: - fit=embryo.fits[0] - except IndexError: - pass - - if fit==None: - printError("No suitable fit found to select fitting parameters from, will not be able to iniate widget.") - self.done(1) - - return vars(fit).keys() - - def donePressed(self): - self.molecule.crucialParameters=self.itemsRight - self.done(1) - - - - - - - \ No newline at end of file + def __init__(self, molecule, parent): + + self.molecule = molecule + + fittingParms = self.getFittingParms() + + pyfrp_gui_basics.listSelectorDialog.__init__( + self, + parent, + fittingParms, + leftTitle="Available Parameters", + rightTitle="Selected Parameters", + itemsRight=self.molecule.crucialParameters, + ) + + self.setWindowTitle("Select crucial parameters") + self.show() + + def getFittingParms(self): + + fit = None + + for embryo in self.molecule.embryos: + if embryo.isFitted(): + try: + fit = embryo.fits[0] + except IndexError: + pass + + if fit == None: + printError( + "No suitable fit found to select fitting parameters from, will not be able to iniate widget." + ) + self.done(1) + + return list(vars(fit).keys()) + + def donePressed(self): + self.molecule.crucialParameters = self.itemsRight + self.done(1) diff --git a/pyfrp/gui/pyfrp_gui_vtk.py b/pyfrp/gui/pyfrp_gui_vtk.py old mode 100644 new mode 100755 index 7db9a67..eb36f1f --- a/pyfrp/gui/pyfrp_gui_vtk.py +++ b/pyfrp/gui/pyfrp_gui_vtk.py @@ -1,58 +1,55 @@ -#===================================================================================================================================== -#Copyright -#===================================================================================================================================== +# ===================================================================================================================================== +# Copyright +# ===================================================================================================================================== -#Copyright (C) 2014 Alexander Blaessle, Patrick Mueller and the Friedrich Miescher Laboratory of the Max Planck Society -#This software is distributed under the terms of the GNU General Public License. +# Copyright (C) 2014 Alexander Blaessle, Patrick Mueller and the Friedrich Miescher Laboratory of the Max Planck Society +# This software is distributed under the terms of the GNU General Public License. -#This file is part of PyFRAP. +# This file is part of PyFRAP. -#PyFRAP is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License as published by -#the Free Software Foundation, either version 3 of the License, or -#(at your option) any later version. +# PyFRAP is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -#GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. -#You should have received a copy of the GNU General Public License -#along with this program. If not, see . +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . -#=========================================================================================================================================================================== -#Module Description -#=========================================================================================================================================================================== +# =========================================================================================================================================================================== +# Module Description +# =========================================================================================================================================================================== -#Module containing vtk visualizing classes: +# Module containing vtk visualizing classes: +# =========================================================================================================================================================================== +# Importing necessary modules +# =========================================================================================================================================================================== - -#=========================================================================================================================================================================== -#Importing necessary modules -#=========================================================================================================================================================================== - -#Misc +# Misc import sys import time import os, os.path -#PyFRAP modules +# PyFRAP modules from pyfrp.modules.pyfrp_term_module import * -#PyQT -from PyQt4 import QtGui, QtCore +# PyQT +from PyQt5 import QtGui, QtCore, QtWidgets # VTK import vtk -from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor +from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor +class vtkSimVisualizer(QtWidgets.QMainWindow): -class vtkSimVisualizer(QtGui.QMainWindow): - - """Basic simulation visualizing class. + """Basic simulation visualizing class. .. note:: Only works if the simulation results are saved in embryo via ``embryo.simulation.saveSim=True``. @@ -63,54 +60,58 @@ class vtkSimVisualizer(QtGui.QMainWindow): embryo (pyfrp.subclasses.pyfrp_embryo.embryo): An embryo """ - - def __init__(self, embryo, parent=None): - - super(vtkSimVisualizer, self).__init__(parent) - - # Load embryo - self.embryo=embryo - - # Check if simulation is saved - if len(self.embryo.simulation.vals)==0: - printWarning("Embryo does not have saved simulation. Rerun simulation with saveSim=True.") - return - - # To numpy array - self.embryo.simulation.vals=np.array(self.embryo.simulation.vals) - - # Frame - self.frame = QtGui.QFrame() - - # Vtk widgets - self.vtkWidget,self.ren,self.iren=self.initVTKWidget(self.frame) - - # Add slider for 3D - self.slider,self.label=self.initSlider(0, len(self.embryo.simulation.tvecSim)-1,self.sliderCallback) - - # Show simulation visualization - self.initSimVis() - - # Add Layout - self.layout=QtGui.QGridLayout() - self.layout.addWidget(self.vtkWidget,1,1) - self.layout.addWidget(self.slider,2,1) - self.layout.addWidget(self.label,3,1) - - # Set central widget - self.frame.setLayout(self.layout) - self.setCentralWidget(self.frame) - - # Window title - self.setWindowTitle('vtkSimVisualizer of embryo ' + self.embryo.name) - - # Show everything - self.show() - self.iren.Initialize() - def initSlider(self,sMin,sMax,callback): - - """Sets up slider and corresponding label with given limits and callback. + def __init__(self, embryo, parent=None): + + super(vtkSimVisualizer, self).__init__(parent) + + # Load embryo + self.embryo = embryo + + # Check if simulation is saved + if len(self.embryo.simulation.vals) == 0: + printWarning( + "Embryo does not have saved simulation. Rerun simulation with saveSim=True." + ) + return + + # To numpy array + self.embryo.simulation.vals = np.array(self.embryo.simulation.vals) + + # Frame + self.frame = QtWidgets.QFrame() + + # Vtk widgets + self.vtkWidget, self.ren, self.iren = self.initVTKWidget(self.frame) + + # Add slider for 3D + self.slider, self.label = self.initSlider( + 0, len(self.embryo.simulation.tvecSim) - 1, self.sliderCallback + ) + + # Show simulation visualization + self.initSimVis() + + # Add Layout + self.layout = QtWidgets.QGridLayout() + self.layout.addWidget(self.vtkWidget, 1, 1) + self.layout.addWidget(self.slider, 2, 1) + self.layout.addWidget(self.label, 3, 1) + + # Set central widget + self.frame.setLayout(self.layout) + self.setCentralWidget(self.frame) + + # Window title + self.setWindowTitle("vtkSimVisualizer of embryo " + self.embryo.name) + + # Show everything + self.show() + self.iren.Initialize() + + def initSlider(self, sMin, sMax, callback): + + """Sets up slider and corresponding label with given limits and callback. Args: sMin (int): Minimum index of slider. @@ -120,73 +121,80 @@ def initSlider(self,sMin,sMax,callback): Returns: tuple: Tuple containing: - * slider (QtGui.QSlider) - * lbl (QtGui.QLabel) + * slider (QtWidgets.QSlider) + * lbl (QtWidgets.QLabel) """ - - slider = QtGui.QSlider() - slider.setRange(sMin,sMax) - slider.valueChanged.connect(callback) - slider.setOrientation(QtCore.Qt.Horizontal) - lbl=QtGui.QLabel("") - return slider,lbl - - def initVTKWidget(self,frame): - - """Sets up vtkWidget inside frame. + + slider = QtWidgets.QSlider() + slider.setRange(sMin, sMax) + slider.valueChanged.connect(callback) + slider.setOrientation(QtCore.Qt.Horizontal) + lbl = QtWidgets.QLabel("") + return slider, lbl + + def initVTKWidget(self, frame): + + """Sets up vtkWidget inside frame. Also sets up corresponding renderer and interactor. Args: - frame (QtGui.QFrame): Parenting frame. + frame (QtWidgets.QFrame): Parenting frame. Returns: tuple: Tuple containing: - * vtkWidget (vtk.qt4.QVTKRenderWindowInteractor.QVTKRenderWindowInteractor): Qt vtk window interactor. + * vtkWidget (vtk.qt.QVTKRenderWindowInteractor.QVTKRenderWindowInteractor): Qt vtk window interactor. * ren (vtk.vtkRenderer) * iren (vtk.vtkRenderWindowInteractor) """ - - vtkWidget = QVTKRenderWindowInteractor(frame) - ren = vtk.vtkRenderer() - vtkWidget.GetRenderWindow().AddRenderer(ren) - iren = vtkWidget.GetRenderWindow().GetInteractor() - iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) - ren.ResetCamera() - - return vtkWidget, ren, iren - - def showVals(self,idx): - - """Updates simulation values in renderer. + + vtkWidget = QVTKRenderWindowInteractor(frame) + ren = vtk.vtkRenderer() + vtkWidget.GetRenderWindow().AddRenderer(ren) + iren = vtkWidget.GetRenderWindow().GetInteractor() + iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) + ren.ResetCamera() + + return vtkWidget, ren, iren + + def showVals(self, idx): + + """Updates simulation values in renderer. Args: idx (int): Index of timepoint. """ - - # Convert to right cmap - vals=self.embryo.simulation.vals[idx]/self.embryo.simulation.vals.max() - vals=255*self.cm(vals) - vals=vals[:,:3] - - self.initScalarArray() - for i,val in enumerate(vals): - self.scalar.InsertNextTupleValue(val) - self.grid.GetCellData().SetScalars(self.scalar) - self.grid.Modified() - self.iren.Render() - - try: - self.CutMesh() - except AttributeError: - pass - - def initSimVis(self): - - """Inits the simulation renderer. + + # Convert to right cmap + vals = self.embryo.simulation.vals[idx] / self.embryo.simulation.vals.max() + vals = 255 * self.cm(vals) + vals = vals[:, :3] + vals = vals.astype(int) + + self.initScalarArray() + for i, val in enumerate(vals): + # print(val,type(val)) + val=list(val) + try: + self.scalar.InsertNextTupleValue(val) + except AttributeError: + self.scalar.InsertNextTypedTuple(val) + + self.grid.GetCellData().SetScalars(self.scalar) + self.grid.Modified() + self.iren.Render() + + try: + self.CutMesh() + except AttributeError: + pass + + def initSimVis(self): + + """Inits the simulation renderer. This contains the following steps: @@ -199,135 +207,135 @@ def initSimVis(self): * Shows initial time point in renderer. """ - - self.initPoints() - self.initGrid() - if self.embryo.geometry.dim==2: - self.initTriangles() - else: - self.initTetras() - self.initScalarArray() - self.initMapper() - self.initActor() - self.initColorTable() - self.showVals(0) - - def initActor(self): - - """Sets up simulation actor.""" - - self.actor = vtk.vtkActor() - self.actor.SetMapper(self.mapper) - self.ren.AddActor(self.actor) - - def initMapper(self): - - """Sets up simulation mapper.""" - - self.mapper = vtk.vtkDataSetMapper() - if vtk.VTK_MAJOR_VERSION <= 5: - self.mapper.SetInputConnection(self.grid.GetProducerPort()) - else: - self.mapper.SetInputData(self.grid) - - def initGrid(self): - - """Sets up simulation grid.""" - - self.grid = vtk.vtkUnstructuredGrid() - self.grid.SetPoints(self.points) - - return self.grid - - def initTetras(self): - - """Sets up tetrahedras describing mesh.""" - - verts=self.embryo.simulation.mesh.mesh._getOrderedCellVertexIDs().T - - cellArray = vtk.vtkCellArray() - for j,vert in enumerate(verts): - tetra = vtk.vtkTetra() - - for i,v in enumerate(vert): - tetra.GetPointIds().SetId(i, v) - cellArray.InsertNextCell(tetra) - - self.grid.SetCells(vtk.VTK_TETRA, cellArray) - - def initTriangles(self): - - """Sets up triangles describing mesh.""" - - verts=self.embryo.simulation.mesh.mesh._getOrderedCellVertexIDs().T - - cellArray = vtk.vtkCellArray() - for j,vert in enumerate(verts): + self.initPoints() + self.initGrid() + if self.embryo.geometry.dim == 2: + self.initTriangles() + else: + self.initTetras() + self.initScalarArray() + self.initMapper() + self.initActor() + self.initColorTable() + self.showVals(0) - tetra = vtk.vtkTriangle() - - for i,v in enumerate(vert): - tetra.GetPointIds().SetId(i, v) - cellArray.InsertNextCell(tetra) - - self.grid.SetCells(vtk.VTK_TRIANGLE, cellArray) - - def initScalarArray(self): - - """Sets up scalar array describing tetrahedra values.""" - - self.scalar = vtk.vtkUnsignedCharArray() - self.scalar.SetNumberOfComponents(3) - self.scalar.SetName("Colors") - - return self.scalar - - def initPoints(self): - - """Sets up point array.""" - - if self.embryo.geometry.dim==2: - x,y=self.embryo.simulation.mesh.mesh.vertexCoords - else: - x,y,z=self.embryo.simulation.mesh.mesh.vertexCoords - - self.points = vtk.vtkPoints() - for i in range(len(x)): - if self.embryo.geometry.dim==2: - self.points.InsertNextPoint(x[i], y[i],0) - else: - self.points.InsertNextPoint(x[i], y[i],z[i]) - - return self.points - - def getRenderer(self): - - """Returns renderer.""" - - return self.ren - - def sliderCallback(self): - - """Call back function for slider movement.""" - - index = self.sender().value() - self.label.setText("t = "+str(self.embryo.simulation.tvecSim[index])) - self.showVals(index) - return - - def initColorTable(self): - - """Sets up color table.""" - - from matplotlib import cm - - self.cm=cm.jet + def initActor(self): + """Sets up simulation actor.""" -class vtkSimVisualizerCutter(QtGui.QMainWindow): - - """Simulation visualizing class that allows to draw the simulation in 3D and slice a plane + self.actor = vtk.vtkActor() + self.actor.SetMapper(self.mapper) + self.ren.AddActor(self.actor) + + def initMapper(self): + + """Sets up simulation mapper.""" + + self.mapper = vtk.vtkDataSetMapper() + if vtk.VTK_MAJOR_VERSION <= 5: + self.mapper.SetInputConnection(self.grid.GetProducerPort()) + else: + self.mapper.SetInputData(self.grid) + + def initGrid(self): + + """Sets up simulation grid.""" + + self.grid = vtk.vtkUnstructuredGrid() + self.grid.SetPoints(self.points) + + return self.grid + + def initTetras(self): + + """Sets up tetrahedras describing mesh.""" + + verts = self.embryo.simulation.mesh.getOrderedCellVertexIDs().T + + cellArray = vtk.vtkCellArray() + for j, vert in enumerate(verts): + + tetra = vtk.vtkTetra() + + for i, v in enumerate(vert): + tetra.GetPointIds().SetId(i, v) + cellArray.InsertNextCell(tetra) + + self.grid.SetCells(vtk.VTK_TETRA, cellArray) + + def initTriangles(self): + + """Sets up triangles describing mesh.""" + + verts = self.embryo.simulation.mesh.getOrderedCellVertexIDs().T + + cellArray = vtk.vtkCellArray() + for j, vert in enumerate(verts): + + tetra = vtk.vtkTriangle() + + for i, v in enumerate(vert): + tetra.GetPointIds().SetId(i, v) + cellArray.InsertNextCell(tetra) + + self.grid.SetCells(vtk.VTK_TRIANGLE, cellArray) + + def initScalarArray(self): + + """Sets up scalar array describing tetrahedra values.""" + + self.scalar = vtk.vtkUnsignedCharArray() + self.scalar.SetNumberOfComponents(3) + self.scalar.SetName("Colors") + + return self.scalar + + def initPoints(self): + + """Sets up point array.""" + + if self.embryo.geometry.dim == 2: + x, y = self.embryo.simulation.mesh.mesh.vertexCoords + else: + x, y, z = self.embryo.simulation.mesh.mesh.vertexCoords + + self.points = vtk.vtkPoints() + for i in range(len(x)): + if self.embryo.geometry.dim == 2: + self.points.InsertNextPoint(x[i], y[i], 0) + else: + self.points.InsertNextPoint(x[i], y[i], z[i]) + + return self.points + + def getRenderer(self): + + """Returns renderer.""" + + return self.ren + + def sliderCallback(self): + + """Call back function for slider movement.""" + + index = self.sender().value() + self.label.setText("t = " + str(self.embryo.simulation.tvecSim[index])) + self.showVals(index) + return + + def initColorTable(self): + + """Sets up color table.""" + + from matplotlib import cm + + self.cm = cm.jet + + +class vtkSimVisualizerCutter(QtWidgets.QMainWindow): + + """Simulation visualizing class that allows to draw the simulation in 3D and slice a plane out of the 3D simulation. .. note:: Only works for 3D embryos that already have been simulated and the simulation results @@ -339,74 +347,80 @@ class vtkSimVisualizerCutter(QtGui.QMainWindow): embryo (pyfrp.subclasses.pyfrp_embryo.embryo): An embryo """ - - def __init__(self, embryo, parent=None): - - super(vtkSimVisualizerCutter, self).__init__(parent) - - # Load embryo - self.embryo=embryo - - # Check if simulation is saved - if len(self.embryo.simulation.vals)==0: - printWarning("Embryo does not have saved simulation. Rerun simulation with saveSim=True.") - - # Check if 3D embryo - if self.embryo.geometry.dim==2: - printError("vtkSimVisualizerCutter does only work and make sense for 3D geometries. Use vtkSimVisualizer instead.") - - # To numpy array - self.embryo.simulation.vals=np.array(self.embryo.simulation.vals) - - # Frame - self.frame = QtGui.QFrame() - - # Vtk widgets - self.vtkWidget,self.ren,self.iren=self.initVTKWidget(self.frame) - self.vtkWidgetCut,self.renCut,self.irenCut=self.initVTKWidget(self.frame) - - # Add slider for 3D - self.slider,self.label=self.initSlider(0, len(self.embryo.simulation.tvecSim)-1,self.sliderCallback) - - # Setup 3D simulation plot - self.init3D() - - # Plane used for cutting - self.plane = vtk.vtkPlane() - - # Cutter - self.cutter = vtk.vtkCutter() - - # Plane widget - self.initPlaneWidget() - - # Add Layout - self.layout=QtGui.QGridLayout() - self.layout.addWidget(self.vtkWidget,1,1) - self.layout.addWidget(self.vtkWidgetCut,1,2) - self.layout.addWidget(self.slider,2,1) - self.layout.addWidget(self.label,3,1) - - # Set central widget - self.frame.setLayout(self.layout) - self.setCentralWidget(self.frame) - - self.setWindowTitle('vtkSimVisualizerCutter of embryo ' + self.embryo.name) - - # Run cut mesh once - self.CutMesh() - - # Show everything - self.show() - self.iren.Initialize() - self.irenCut.Initialize() - - def closeIt(self): - self.close() - - def initSlider(self,sMin,sMax,callback): - - """Sets up slider and corresponding label with given limits and callback. + + def __init__(self, embryo, parent=None): + + super(vtkSimVisualizerCutter, self).__init__(parent) + + # Load embryo + self.embryo = embryo + + # Check if simulation is saved + if len(self.embryo.simulation.vals) == 0: + printWarning( + "Embryo does not have saved simulation. Rerun simulation with saveSim=True." + ) + + # Check if 3D embryo + if self.embryo.geometry.dim == 2: + printError( + "vtkSimVisualizerCutter does only work and make sense for 3D geometries. Use vtkSimVisualizer instead." + ) + + # To numpy array + self.embryo.simulation.vals = np.array(self.embryo.simulation.vals) + + # Frame + self.frame = QtWidgets.QFrame() + + # Vtk widgets + self.vtkWidget, self.ren, self.iren = self.initVTKWidget(self.frame) + self.vtkWidgetCut, self.renCut, self.irenCut = self.initVTKWidget(self.frame) + + # Add slider for 3D + self.slider, self.label = self.initSlider( + 0, len(self.embryo.simulation.tvecSim) - 1, self.sliderCallback + ) + + # Setup 3D simulation plot + self.init3D() + + # Plane used for cutting + self.plane = vtk.vtkPlane() + + # Cutter + self.cutter = vtk.vtkCutter() + + # Plane widget + self.initPlaneWidget() + + # Add Layout + self.layout = QtWidgets.QGridLayout() + self.layout.addWidget(self.vtkWidget, 1, 1) + self.layout.addWidget(self.vtkWidgetCut, 1, 2) + self.layout.addWidget(self.slider, 2, 1) + self.layout.addWidget(self.label, 3, 1) + + # Set central widget + self.frame.setLayout(self.layout) + self.setCentralWidget(self.frame) + + self.setWindowTitle("vtkSimVisualizerCutter of embryo " + self.embryo.name) + + # Run cut mesh once + self.CutMesh() + + # Show everything + self.show() + self.iren.Initialize() + self.irenCut.Initialize() + + def closeIt(self): + self.close() + + def initSlider(self, sMin, sMax, callback): + + """Sets up slider and corresponding label with given limits and callback. Args: sMin (int): Minimum index of slider. @@ -416,47 +430,47 @@ def initSlider(self,sMin,sMax,callback): Returns: tuple: Tuple containing: - * slider (QtGui.QSlider) - * lbl (QtGui.QLabel) + * slider (QtWidgets.QSlider) + * lbl (QtWidgets.QLabel) """ - - slider = QtGui.QSlider() - slider.setRange(sMin,sMax) - slider.valueChanged.connect(callback) - slider.setOrientation(QtCore.Qt.Horizontal) - lbl=QtGui.QLabel("") - return slider,lbl - - def initVTKWidget(self,frame): - - """Sets up vtkWidget inside frame. + + slider = QtWidgets.QSlider() + slider.setRange(sMin, sMax) + slider.valueChanged.connect(callback) + slider.setOrientation(QtCore.Qt.Horizontal) + lbl = QtWidgets.QLabel("") + return slider, lbl + + def initVTKWidget(self, frame): + + """Sets up vtkWidget inside frame. Also sets up corresponding renderer and interactor. Args: - frame (QtGui.QFrame): Parenting frame. + frame (QtWidgets.QFrame): Parenting frame. Returns: tuple: Tuple containing: - * vtkWidget (vtk.qt4.QVTKRenderWindowInteractor.QVTKRenderWindowInteractor): Qt vtk window interactor. + * vtkWidget (vtk.qt.QVTKRenderWindowInteractor.QVTKRenderWindowInteractor): Qt vtk window interactor. * ren (vtk.vtkRenderer) * iren (vtk.vtkRenderWindowInteractor) """ - - vtkWidget = QVTKRenderWindowInteractor(frame) - ren = vtk.vtkRenderer() - vtkWidget.GetRenderWindow().AddRenderer(ren) - iren = vtkWidget.GetRenderWindow().GetInteractor() - iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) - ren.ResetCamera() - - return vtkWidget, ren, iren - - def initPlaneWidget(self): - - """Sets up vtkImplicitPlaneWidget for plane selection. + + vtkWidget = QVTKRenderWindowInteractor(frame) + ren = vtk.vtkRenderer() + vtkWidget.GetRenderWindow().AddRenderer(ren) + iren = vtkWidget.GetRenderWindow().GetInteractor() + iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) + ren.ResetCamera() + + return vtkWidget, ren, iren + + def initPlaneWidget(self): + + """Sets up vtkImplicitPlaneWidget for plane selection. Sets also up necessary actor and mapper. @@ -464,107 +478,106 @@ def initPlaneWidget(self): vtk.vtkImplicitPlaneWidget: Widget. """ - - # Initialize a plane widget - self.planeWidget = vtk.vtkImplicitPlaneWidget() - self.planeWidget.SetInteractor(self.iren) - self.planeWidget.SetPlaceFactor(1.25) - self.planeWidget.SetInput(self.grid) - self.planeWidget.PlaceWidget() - - # Callback connection of interaction event - self.planeWidget.AddObserver("InteractionEvent", self.StartPlaneCallback) - self.planeWidget.AddObserver("EndInteractionEvent",self.EndPlaneCallback) - - # Mapper - self.selectMapper = vtk.vtkDataSetMapper() - self.selectMapper.SetInput(self.grid) - - # Actor - self.selectActor = vtk.vtkLODActor() - self.selectActor.SetMapper(self.selectMapper) - self.selectActor.GetProperty().SetColor(0, 1, 0) - self.selectActor.VisibilityOff() - self.selectActor.SetScale(1.01, 1.01, 1.01) - - self.ren.AddActor(self.selectActor) - - # Place widget at right position - self.planeWidget.SetNormal(0,0,1) - self.planeWidget.SetOrigin(self.grid.GetCenter()) - - - return self.planeWidget - - def StartPlaneCallback(self,obj, event): - - """Callback for interaction event. + + # Initialize a plane widget + self.planeWidget = vtk.vtkImplicitPlaneWidget() + self.planeWidget.SetInteractor(self.iren) + self.planeWidget.SetPlaceFactor(1.25) + self.planeWidget.SetInput(self.grid) + self.planeWidget.PlaceWidget() + + # Callback connection of interaction event + self.planeWidget.AddObserver("InteractionEvent", self.StartPlaneCallback) + self.planeWidget.AddObserver("EndInteractionEvent", self.EndPlaneCallback) + + # Mapper + self.selectMapper = vtk.vtkDataSetMapper() + self.selectMapper.SetInput(self.grid) + + # Actor + self.selectActor = vtk.vtkLODActor() + self.selectActor.SetMapper(self.selectMapper) + self.selectActor.GetProperty().SetColor(0, 1, 0) + self.selectActor.VisibilityOff() + self.selectActor.SetScale(1.01, 1.01, 1.01) + + self.ren.AddActor(self.selectActor) + + # Place widget at right position + self.planeWidget.SetNormal(0, 0, 1) + self.planeWidget.SetOrigin(self.grid.GetCenter()) + + return self.planeWidget + + def StartPlaneCallback(self, obj, event): + + """Callback for interaction event. """ - - obj.GetPlane(self.plane) - self.selectActor.VisibilityOn() - - def EndPlaneCallback(self,widget,event_string): - - """Callback for end of interaction event. + + obj.GetPlane(self.plane) + self.selectActor.VisibilityOn() + + def EndPlaneCallback(self, widget, event_string): + + """Callback for end of interaction event. """ - - self.CutMesh() - - def CutMesh(self): - - """Cuts plane out of 3D simulation object. + + self.CutMesh() + + def CutMesh(self): + + """Cuts plane out of 3D simulation object. Grabs plane and creates and actor and mapper to display cut out plane in second renderer. """ - - self.cutter.SetInput(self.grid) - self.planeWidget.GetPlane(self.plane) - self.cutter.SetCutFunction(self.plane) - self.cutter.Update() - - self.Actor = vtk.vtkActor() - - mapper = vtk.vtkPolyDataMapper() - - mapper.SetInputConnection(self.cutter.GetOutputPort()) - self.Actor.SetMapper(mapper) - self.renCut.AddActor(self.Actor) - - self.cutter.GetOutput().Modified() - self.irenCut.Render() - - def showVals(self,idx): - - """Updates simulation values in renderer. + + self.cutter.SetInput(self.grid) + self.planeWidget.GetPlane(self.plane) + self.cutter.SetCutFunction(self.plane) + self.cutter.Update() + + self.Actor = vtk.vtkActor() + + mapper = vtk.vtkPolyDataMapper() + + mapper.SetInputConnection(self.cutter.GetOutputPort()) + self.Actor.SetMapper(mapper) + self.renCut.AddActor(self.Actor) + + self.cutter.GetOutput().Modified() + self.irenCut.Render() + + def showVals(self, idx): + + """Updates simulation values in renderer. Args: idx (int): Index of timepoint. """ - - # Convert to right cmap - vals=self.embryo.simulation.vals[idx]/self.embryo.simulation.vals.max() - vals=255*self.cm(vals) - vals=vals[:,:3] - - self.initScalarArray() - for i,val in enumerate(vals): - self.scalar.InsertNextTupleValue(val) - self.grid.GetCellData().SetScalars(self.scalar) - self.grid.Modified() - self.iren.Render() - - try: - self.CutMesh() - except AttributeError: - pass - - def init3D(self): - - """Inits the simulation renderer. + + # Convert to right cmap + vals = self.embryo.simulation.vals[idx] / self.embryo.simulation.vals.max() + vals = 255 * self.cm(vals) + vals = vals[:, :3] + + self.initScalarArray() + for i, val in enumerate(vals): + self.scalar.InsertNextTupleValue(val) + self.grid.GetCellData().SetScalars(self.scalar) + self.grid.Modified() + self.iren.Render() + + try: + self.CutMesh() + except AttributeError: + pass + + def init3D(self): + + """Inits the simulation renderer. This contains the following steps: @@ -577,109 +590,109 @@ def init3D(self): * Shows initial time point in renderer. """ - - self.initPoints() - self.initGrid() - self.initTetras() - self.initScalarArray() - self.initMapper() - self.initActor() - self.initColorTable() - self.showVals(0) - - def initActor(self): - - """Sets up simulation actor.""" - - self.actor = vtk.vtkActor() - self.actor.SetMapper(self.mapper) - self.ren.AddActor(self.actor) - - def initMapper(self): - - """Sets up simulation mapper.""" - - self.mapper = vtk.vtkDataSetMapper() - if vtk.VTK_MAJOR_VERSION <= 5: - self.mapper.SetInputConnection(self.grid.GetProducerPort()) - else: - self.mapper.SetInputData(self.grid) - - def initGrid(self): - - """Sets up simulation grid.""" - - self.grid = vtk.vtkUnstructuredGrid() - self.grid.SetPoints(self.points) - - return self.grid - - def initTetras(self): - - """Sets up tetrahedras describing mesh.""" - - verts=self.embryo.simulation.mesh.mesh._getOrderedCellVertexIDs().T - - cellArray = vtk.vtkCellArray() - for j,vert in enumerate(verts): - tetra = vtk.vtkTetra() - - for i,v in enumerate(vert): - tetra.GetPointIds().SetId(i, v) - cellArray.InsertNextCell(tetra) - - self.grid.SetCells(vtk.VTK_TETRA, cellArray) - - def initScalarArray(self): - - """Sets up scalar array describing tetrahedra values.""" - - self.scalar = vtk.vtkUnsignedCharArray() - self.scalar.SetNumberOfComponents(3) - self.scalar.SetName("Colors") - - return self.scalar - - def initPoints(self): - - """Sets up point array.""" - - x,y,z=self.embryo.simulation.mesh.mesh.vertexCoords - - self.points = vtk.vtkPoints() - for i in range(len(x)): - self.points.InsertNextPoint(x[i], y[i],z[i]) - - return self.points - - def getRenderer(self): - - """Returns renderer.""" - - return self.ren - - def sliderCallback(self): - - """Call back function for slider movement.""" - - index = self.sender().value() - self.label.setText("t = "+str(self.embryo.simulation.tvecSim[index])) - self.showVals(index) - return - - def initColorTable(self): - - """Sets up color table.""" - - from matplotlib import cm - - self.cm=cm.jet + self.initPoints() + self.initGrid() + self.initTetras() + self.initScalarArray() + self.initMapper() + self.initActor() + self.initColorTable() + self.showVals(0) + + def initActor(self): + + """Sets up simulation actor.""" + + self.actor = vtk.vtkActor() + self.actor.SetMapper(self.mapper) + self.ren.AddActor(self.actor) + + def initMapper(self): + + """Sets up simulation mapper.""" + + self.mapper = vtk.vtkDataSetMapper() + if vtk.VTK_MAJOR_VERSION <= 5: + self.mapper.SetInputConnection(self.grid.GetProducerPort()) + else: + self.mapper.SetInputData(self.grid) + + def initGrid(self): + + """Sets up simulation grid.""" + + self.grid = vtk.vtkUnstructuredGrid() + self.grid.SetPoints(self.points) + + return self.grid + + def initTetras(self): + + """Sets up tetrahedras describing mesh.""" + + verts = self.embryo.simulation.mesh.mesh._getOrderedCellVertexIDs().T + + cellArray = vtk.vtkCellArray() + for j, vert in enumerate(verts): + + tetra = vtk.vtkTetra() + + for i, v in enumerate(vert): + tetra.GetPointIds().SetId(i, v) + cellArray.InsertNextCell(tetra) + + self.grid.SetCells(vtk.VTK_TETRA, cellArray) + + def initScalarArray(self): + + """Sets up scalar array describing tetrahedra values.""" + + self.scalar = vtk.vtkUnsignedCharArray() + self.scalar.SetNumberOfComponents(3) + self.scalar.SetName("Colors") + + return self.scalar + + def initPoints(self): + + """Sets up point array.""" + + x, y, z = self.embryo.simulation.mesh.mesh.vertexCoords + + self.points = vtk.vtkPoints() + for i in range(len(x)): + self.points.InsertNextPoint(x[i], y[i], z[i]) + + return self.points + + def getRenderer(self): + + """Returns renderer.""" + + return self.ren + + def sliderCallback(self): + + """Call back function for slider movement.""" + + index = self.sender().value() + self.label.setText("t = " + str(self.embryo.simulation.tvecSim[index])) + self.showVals(index) + return + + def initColorTable(self): + + """Sets up color table.""" + + from matplotlib import cm + + self.cm = cm.jet class vtkSimVisualizerCutterBySub(vtkSimVisualizer): - - """Simulation visualizing class that allows to draw the simulation in 3D and slice a plane + + """Simulation visualizing class that allows to draw the simulation in 3D and slice a plane out of the 3D simulation. This one subclasses from vtkSimVisualizer. @@ -691,39 +704,41 @@ class vtkSimVisualizerCutterBySub(vtkSimVisualizer): embryo (pyfrp.subclasses.pyfrp_embryo.embryo): An embryo """ - - def __init__(self, embryo, parent=None): - - #super(vtkSimVisualizerCutter, self).__init__(embryo,parent) - vtkSimVisualizer.__init__(self,embryo,parent=parent) - - # Check if 3D embryo - if self.embryo.geometry.dim==2: - printWarning("vtkSimVisualizerCutter does only work and make sense for 3D geometries. Will not initialize cutter and fall back tostandad vtkSimVisualizer.") - return - - self.vtkWidgetCut,self.renCut,self.irenCut=self.initVTKWidget(self.frame) - - # Plane used for cutting - self.plane = vtk.vtkPlane() - - # Cutter - self.cutter = vtk.vtkCutter() - - # Plane widget - self.initPlaneWidget() - - # Add Layout - self.layout.addWidget(self.vtkWidgetCut,1,2) - - # Run cut mesh once - self.CutMesh() - - self.irenCut.Initialize() - - def initPlaneWidget(self): - - """Sets up vtkImplicitPlaneWidget for plane selection. + + def __init__(self, embryo, parent=None): + + # super(vtkSimVisualizerCutter, self).__init__(embryo,parent) + vtkSimVisualizer.__init__(self, embryo, parent=parent) + + # Check if 3D embryo + if self.embryo.geometry.dim == 2: + printWarning( + "vtkSimVisualizerCutter does only work and make sense for 3D geometries. Will not initialize cutter and fall back tostandad vtkSimVisualizer." + ) + return + + self.vtkWidgetCut, self.renCut, self.irenCut = self.initVTKWidget(self.frame) + + # Plane used for cutting + self.plane = vtk.vtkPlane() + + # Cutter + self.cutter = vtk.vtkCutter() + + # Plane widget + self.initPlaneWidget() + + # Add Layout + self.layout.addWidget(self.vtkWidgetCut, 1, 2) + + # Run cut mesh once + self.CutMesh() + + self.irenCut.Initialize() + + def initPlaneWidget(self): + + """Sets up vtkImplicitPlaneWidget for plane selection. Sets also up necessary actor and mapper. @@ -731,76 +746,73 @@ def initPlaneWidget(self): vtk.vtkImplicitPlaneWidget: Widget. """ - - # Initialize a plane widget - self.planeWidget = vtk.vtkImplicitPlaneWidget() - self.planeWidget.SetInteractor(self.iren) - self.planeWidget.SetPlaceFactor(1.25) - self.planeWidget.SetInput(self.grid) - self.planeWidget.PlaceWidget() - - # Callback connection of interaction event - self.planeWidget.AddObserver("InteractionEvent", self.StartPlaneCallback) - self.planeWidget.AddObserver("EndInteractionEvent",self.EndPlaneCallback) - - # Mapper - self.selectMapper = vtk.vtkDataSetMapper() - self.selectMapper.SetInput(self.grid) - - # Actor - self.selectActor = vtk.vtkLODActor() - self.selectActor.SetMapper(self.selectMapper) - self.selectActor.GetProperty().SetColor(0, 1, 0) - self.selectActor.VisibilityOff() - self.selectActor.SetScale(1.01, 1.01, 1.01) - - self.ren.AddActor(self.selectActor) - - # Place widget at right position - self.planeWidget.SetNormal(0,0,1) - self.planeWidget.SetOrigin(self.grid.GetCenter()) - - - return self.planeWidget - - def StartPlaneCallback(self,obj, event): - - """Callback for interaction event. + + # Initialize a plane widget + self.planeWidget = vtk.vtkImplicitPlaneWidget() + self.planeWidget.SetInteractor(self.iren) + self.planeWidget.SetPlaceFactor(1.25) + self.planeWidget.SetInput(self.grid) + self.planeWidget.PlaceWidget() + + # Callback connection of interaction event + self.planeWidget.AddObserver("InteractionEvent", self.StartPlaneCallback) + self.planeWidget.AddObserver("EndInteractionEvent", self.EndPlaneCallback) + + # Mapper + self.selectMapper = vtk.vtkDataSetMapper() + self.selectMapper.SetInput(self.grid) + + # Actor + self.selectActor = vtk.vtkLODActor() + self.selectActor.SetMapper(self.selectMapper) + self.selectActor.GetProperty().SetColor(0, 1, 0) + self.selectActor.VisibilityOff() + self.selectActor.SetScale(1.01, 1.01, 1.01) + + self.ren.AddActor(self.selectActor) + + # Place widget at right position + self.planeWidget.SetNormal(0, 0, 1) + self.planeWidget.SetOrigin(self.grid.GetCenter()) + + return self.planeWidget + + def StartPlaneCallback(self, obj, event): + + """Callback for interaction event. """ - - obj.GetPlane(self.plane) - self.selectActor.VisibilityOn() - - def EndPlaneCallback(self,widget,event_string): - - """Callback for end of interaction event. + + obj.GetPlane(self.plane) + self.selectActor.VisibilityOn() + + def EndPlaneCallback(self, widget, event_string): + + """Callback for end of interaction event. """ - - self.CutMesh() - - def CutMesh(self): - - """Cuts plane out of 3D simulation object. + + self.CutMesh() + + def CutMesh(self): + + """Cuts plane out of 3D simulation object. Grabs plane and creates and actor and mapper to display cut out plane in second renderer. """ - - self.cutter.SetInput(self.grid) - self.planeWidget.GetPlane(self.plane) - self.cutter.SetCutFunction(self.plane) - self.cutter.Update() - - self.Actor = vtk.vtkActor() - - mapper = vtk.vtkPolyDataMapper() - - mapper.SetInputConnection(self.cutter.GetOutputPort()) - self.Actor.SetMapper(mapper) - self.renCut.AddActor(self.Actor) - - self.cutter.GetOutput().Modified() - self.irenCut.Render() - + self.cutter.SetInput(self.grid) + self.planeWidget.GetPlane(self.plane) + self.cutter.SetCutFunction(self.plane) + self.cutter.Update() + + self.Actor = vtk.vtkActor() + + mapper = vtk.vtkPolyDataMapper() + + mapper.SetInputConnection(self.cutter.GetOutputPort()) + self.Actor.SetMapper(mapper) + self.renCut.AddActor(self.Actor) + + self.cutter.GetOutput().Modified() + self.irenCut.Render() diff --git a/pyfrp/gui/pyfrp_term.py b/pyfrp/gui/pyfrp_term.py old mode 100644 new mode 100755 index c98f1d6..faecb0d --- a/pyfrp/gui/pyfrp_term.py +++ b/pyfrp/gui/pyfrp_term.py @@ -1,35 +1,35 @@ -#===================================================================================================================================== -#Copyright -#===================================================================================================================================== +# ===================================================================================================================================== +# Copyright +# ===================================================================================================================================== -#Copyright (C) 2014 Alexander Blaessle, Patrick Mueller and the Friedrich Miescher Laboratory of the Max Planck Society -#This software is distributed under the terms of the GNU General Public License. +# Copyright (C) 2014 Alexander Blaessle, Patrick Mueller and the Friedrich Miescher Laboratory of the Max Planck Society +# This software is distributed under the terms of the GNU General Public License. -#This file is part of PyFDAP. +# This file is part of PyFDAP. -#PyFDAP is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License as published by -#the Free Software Foundation, either version 3 of the License, or -#(at your option) any later version. +# PyFDAP is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -#GNU General Public License for more details. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. -#You should have received a copy of the GNU General Public License -#along with this program. If not, see . +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . -#=========================================================================================================================================================================== -#Module Description -#=========================================================================================================================================================================== +# =========================================================================================================================================================================== +# Module Description +# =========================================================================================================================================================================== -#Module containing classes to emulate Python terminal in PyQT GUI for PyFRAP. -#Modified from http://stackoverflow.com/questions/2758159/how-to-embed-a-python-interpreter-in-a-pyqt-widget/8219536#8219536 +# Module containing classes to emulate Python terminal in PyQT GUI for PyFRAP. +# Modified from http://stackoverflow.com/questions/2758159/how-to-embed-a-python-interpreter-in-a-pyqt-widget/8219536#8219536 -#=========================================================================================================================================================================== -#Importing necessary modules -#=========================================================================================================================================================================== +# =========================================================================================================================================================================== +# Importing necessary modules +# =========================================================================================================================================================================== import os import re @@ -37,320 +37,388 @@ import code import colorama -from PyQt4 import QtGui, QtCore - - -#=========================================================================================================================================================================== -#Module classes -#=========================================================================================================================================================================== - -class PyInterp(QtGui.QTextEdit): - - class InteractiveInterpreter(code.InteractiveInterpreter): - - def __init__(self, locals): - code.InteractiveInterpreter.__init__(self, locals) - - def runIt(self, command): - code.InteractiveInterpreter.runsource(self, command) - - - def __init__(self, parent,redirect=True): - super(PyInterp, self).__init__(parent) - - if redirect: - sys.stdout = self - sys.stderr = self - - self.refreshMarker = False # to change back to >>> from ... - self.multiLine = False # code spans more than one line - self.command = '' # command to be ran - - self.history = [] # list of commands entered - self.historyIndex = -1 - self.interpreterLocals = {} - - self.colorKeys = {} - - #self.greenKey = '[32m' - - - # setting the color for bg and text - palette = QtGui.QPalette() - palette.setColor(QtGui.QPalette.Base, QtGui.QColor(255, 255, 255)) - palette.setColor(QtGui.QPalette.Text, QtGui.QColor(0, 0, 0)) - self.setPalette(palette) - self.setFont(QtGui.QFont('Courier', 12)) - - # initilize interpreter with self locals - self.initInterpreter(locals()) - - #Import some standard classes that might be useful - #self.interpreter.runIt('import pyfrp_img_module as img') - #self.interpreter.runIt('import pyfrp_fit_module as fit') - #self.interpreter.runIt('import pyfrp_misc_module as misc') - self.interpreter.runIt('import numpy as np') - self.interpreter.runIt('import colorama') - self.interpreter.runIt('from pyfrp.modules.pyfrp_term_module import *') - - self.initColorKeys() - - #Print banner and initialize - self.printBanner() - self.marker() # make the >>> or ... marker - - def printBanner(self): - self.write(sys.version) - self.write(' on ' + sys.platform + '\n') - self.write('PyQt4 ' + QtCore.PYQT_VERSION_STR + '\n') - - - #self.write('PyFrap Version' + pyfrp_version + '\n') - #self.write("---------------------------------------"+ '\n') - #msg = 'Type !hist for a history view and !hist(n) history index recall' - #self.write(msg + '\n') - #msg2 = 'To access local variables, type pyfdp.variable. For example, to access the currently selected molecule, type pyfdp.curr_mol. For more details, see the documentation.' - #self.write(msg2 + '\n') - #msg3 = 'To access functions of the pyfdp modules, type modulename.function(). Available modulenames are "fit", "img" and "misc".' - #self.write(msg3 + '\n') - #self.write("---------------------------------------" + '\n') - - def marker(self): - if self.multiLine: - self.insertPlainText('... ') - else: - self.insertPlainText('>>> ') - - def initInterpreter(self, interpreterLocals=None): - - if interpreterLocals: - # when we pass in locals, we don't want it to be named "self" - # so we rename it with the name of the class that did the passing - # and reinsert the locals back into the interpreter dictionary - - selfName = interpreterLocals['self'].__class__.__name__ - - interpreterLocalVars = interpreterLocals.pop('self') - self.interpreterLocals[selfName] = interpreterLocalVars - - else: - self.interpreterLocals = interpreterLocals - self.interpreter = self.InteractiveInterpreter(self.interpreterLocals) - - def initColorKeys(self): - self.colorKeys['[32m']='green' - self.colorKeys['[39m']='black' - self.colorKeys['[33m']='orange' - self.colorKeys['[31m']='red' - return self.colorKeys - - def updateInterpreterLocals(self, newLocals): - className = newLocals.__class__.__name__ - self.interpreterLocals[className] = newLocals - - def write(self, line): - colors,strings=self.findColors(line,self.colorKeys) - - if len(colors)==0: - self.insertPlainText(line) - else: - txt="" - - for i in range(len(colors)): - txt=txt+self.makeColoredText(strings[i],colors[i]) - self.insertHtml(txt) - - self.ensureCursorVisible() - - def makeColoredText(self,txt,color): - coloredText=redText = "" + txt + "" - return coloredText - - def findColors(self,line,colorDic): - - found=0 - - colors=[] - strings=[] - - while found!=-1: - - fs=[] - cs=[] - for key in colorDic.keys(): - ind=line.find(key,found) - if ind!=-1: - fs.append(ind) - else: - fs.append(str(ind)) - - foundOld=found - found=min(fs) - - if len(colors)==0 and found!='-1': - colors.append(colorDic.values()[fs.index(found)]) - elif len(colors)>0: - offset=len(colorDic.keys()[fs.index(found)])-1 - if found=='-1': - strings.append(line[foundOld+offset:]) - else: - strings.append(line[foundOld+offset:found].strip('\x1b')) - colors.append(colorDic.values()[fs.index(found)]) - - found=int(found) - if found!=-1: - found=found+1 - - return colors,strings - - def clearCurrentBlock(self): - # block being current row - length = len(self.document().lastBlock().text()[4:]) - if length == 0: - return None - else: - # should have a better way of doing this but I can't find it - [self.textCursor().deletePreviousChar() for x in xrange(length)] - return True - - - def recallHistory(self): - # used when using the arrow keys to scroll through history - self.clearCurrentBlock() - if self.historyIndex <> -1: - self.insertPlainText(self.history[self.historyIndex]) - return True - - def customCommands(self, command): - - if command == '!hist': # display history - self.append('') # move down one line - # vars that are in the command are prefixed with ____CC and deleted - # once the command is done so they don't show up in dir() - backup = self.interpreterLocals.copy() - history = self.history[:] - history.reverse() - for i, x in enumerate(history): - iSize = len(str(i)) - delta = len(str(len(history))) - iSize - line = line = ' ' * delta + '%i: %s' % (i, x) + '\n' - self.write(line) - - self.updateInterpreterLocals(backup) - self.marker() - return True - - if re.match('!hist\(\d+\)', command): # recall command from history - backup = self.interpreterLocals.copy() - history = self.history[:] - history.reverse() - index = int(command[6:-1]) - self.clearCurrentBlock() - command = history[index] - if command[-1] == ':': - self.multiLine = True - self.write(command) - self.updateInterpreterLocals(backup) - return True - - return False - - def keyPressEvent(self, event): - - if event.key() == QtCore.Qt.Key_Escape: - # proper exit - self.interpreter.runIt('exit()') - - if event.key() == QtCore.Qt.Key_Down: - if self.historyIndex == len(self.history): - self.historyIndex -= 1 - try: - if self.historyIndex > -1: - self.historyIndex -= 1 - self.recallHistory() - else: - self.clearCurrentBlock() - except: - pass - return None - - if event.key() == QtCore.Qt.Key_Up: - try: - if len(self.history) - 1 > self.historyIndex: - self.historyIndex += 1 - self.recallHistory() - else: - self.historyIndex = len(self.history) - except: - pass - return None - - if event.key() == QtCore.Qt.Key_Home: - # set cursor to position 4 in current block. 4 because that's where - # the marker stops - blockLength = len(self.document().lastBlock().text()[4:]) - lineLength = len(self.document().toPlainText()) - position = lineLength - blockLength - textCursor = self.textCursor() - textCursor.setPosition(position) - self.setTextCursor(textCursor) - return None - - if event.key() in [QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace]: - # don't allow deletion of marker - if self.textCursor().positionInBlock() == 4: - return None - - if event.key() in [QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter]: - # set cursor to end of line to avoid line splitting - textCursor = self.textCursor() - position = len(self.document().toPlainText()) - textCursor.setPosition(position) - self.setTextCursor(textCursor) - - line = str(self.document().lastBlock().text())[4:] # remove marker - line.rstrip() - self.historyIndex = -1 - - if self.customCommands(line): - return None - else: - try: - line[-1] - self.haveLine = True - if line[-1] == ':': - self.multiLine = True - self.history.insert(0, line) - except: - self.haveLine = False - - if self.haveLine and self.multiLine: # multi line command - self.command += line + '\n' # + command and line - self.append('') # move down one line - self.marker() # handle marker style - return None - - if self.haveLine and not self.multiLine: # one line command - self.command = line # line is the command - self.append('') # move down one line - self.interpreter.runIt(self.command) - self.command = '' # clear command - self.marker() # handle marker style - return None - - if self.multiLine and not self.haveLine: # multi line done - self.append('') # move down one line - self.interpreter.runIt(self.command) - self.command = '' # clear command - self.multiLine = False # back to single line - self.marker() # handle marker style - return None - - if not self.haveLine and not self.multiLine: # just enter - self.append('') - self.marker() - return None - return None - - # allow all other key events - super(PyInterp, self).keyPressEvent(event) \ No newline at end of file +from PyQt5 import QtGui, QtCore, QtWidgets + + +# =========================================================================================================================================================================== +# Module classes +# =========================================================================================================================================================================== + + +class PyInterp(QtWidgets.QTextEdit): + class InteractiveInterpreter(code.InteractiveInterpreter): + def __init__(self, locals): + code.InteractiveInterpreter.__init__(self, locals) + + def runIt(self, command): + code.InteractiveInterpreter.runsource(self, command) + + def __init__(self, parent, redirect=True): + super(PyInterp, self).__init__(parent) + + if redirect: + sys.stdout = self + # sys.stderr = self + + self.refreshMarker = False # to change back to >>> from ... + self.multiLine = False # code spans more than one line + self.command = "" # command to be ran + + self.history = [] # list of commands entered + self.historyIndex = -1 + self.interpreterLocals = {} + + self.colorKeys = {} + + # self.greenKey = '[32m' + + # setting the color for bg and text + palette = QtGui.QPalette() + palette.setColor(QtGui.QPalette.Base, QtGui.QColor(255, 255, 255)) + palette.setColor(QtGui.QPalette.Text, QtGui.QColor(0, 0, 0)) + self.setPalette(palette) + self.setFont(QtGui.QFont("Courier", 12)) + + # initilize interpreter with self locals + self.initInterpreter(locals()) + + # Import some standard classes that might be useful + # self.interpreter.runIt('import pyfrp_img_module as img') + # self.interpreter.runIt('import pyfrp_fit_module as fit') + # self.interpreter.runIt('import pyfrp_misc_module as misc') + self.interpreter.runIt("import numpy as np") + self.interpreter.runIt("import colorama") + self.interpreter.runIt("from pyfrp.modules.pyfrp_term_module import *") + + self.initColorKeys() + + # Print banner and initialize + self.printBanner() + self.marker() # make the >>> or ... marker + + def printBanner(self): + self.write(sys.version) + self.write(" on " + sys.platform + "\n") + self.write("PyQt5 " + QtCore.PYQT_VERSION_STR + "\n") + + # self.write('PyFrap Version' + pyfrp_version + '\n') + # self.write("---------------------------------------"+ '\n') + # msg = 'Type !hist for a history view and !hist(n) history index recall' + # self.write(msg + '\n') + # msg2 = 'To access local variables, type pyfdp.variable. For example, to access the currently selected molecule, type pyfdp.curr_mol. For more details, see the documentation.' + # self.write(msg2 + '\n') + # msg3 = 'To access functions of the pyfdp modules, type modulename.function(). Available modulenames are "fit", "img" and "misc".' + # self.write(msg3 + '\n') + # self.write("---------------------------------------" + '\n') + + def marker(self): + if self.multiLine: + self.insertPlainText("... ") + else: + self.insertPlainText(">>> ") + + def initInterpreter(self, interpreterLocals=None): + + if interpreterLocals: + # when we pass in locals, we don't want it to be named "self" + # so we rename it with the name of the class that did the passing + # and reinsert the locals back into the interpreter dictionary + + selfName = interpreterLocals["self"].__class__.__name__ + + interpreterLocalVars = interpreterLocals.pop("self") + self.interpreterLocals[selfName] = interpreterLocalVars + + else: + self.interpreterLocals = interpreterLocals + self.interpreter = self.InteractiveInterpreter(self.interpreterLocals) + + def initColorKeys(self): + self.colorKeys["[32m"] = "green" + self.colorKeys["[39m"] = "black" + self.colorKeys["[33m"] = "orange" + self.colorKeys["[31m"] = "red" + return self.colorKeys + + def updateInterpreterLocals(self, newLocals): + className = newLocals.__class__.__name__ + self.interpreterLocals[className] = newLocals + + def write(self, line): + + # Find out if we need to color things + colors, strings = self.findColors(line, self.colorKeys) + + # Write + if len(colors) == 0: + self.insertPlainText(line) + else: + txt = "" + for i in range(len(colors)): + txt = txt + self.makeColoredText(strings[i], colors[i]) + self.insertHtml(txt) + + self.ensureCursorVisible() + + def makeColoredText(self, txt, color): + coloredText = redText = ( + '' + txt + "" + ) + return coloredText + + # def findColors(self,line,colorDic): + # ind=-1 + # for key in list(colorDic.keys()): + # ind=line.find(key,ind) + ##print(key,ind) + + # if ind>=0: + # break + + # return [colorDic[key]],line[ind] + + # def findColors_old(self,line,colorDic): + + # found=0 + + # colors=[] + # strings=[] + + # i=0 + # while found!=-1: + + # i+=1 + + # fs=[] + # cs=[] + # for key in list(colorDic.keys()): + # ind=line.find(key,found) + # if ind!=-1: + # fs.append(ind) + # else: + # fs.append(str(ind)) + + ##if i>3: + ##break + + # foundOld=found + ##print(fs) + ##print(colorDic) + ##print(line) + + # found=min(fs) + # offset=len(list(colorDic.keys())[fs.index(found)])-1 + + # if len(colors)==0 and found!=-1: + # colors.append(list(colorDic.values())[fs.index(found)]) + # strings.append(line[foundOld+offset:]) + # elif len(colors)>0: + # offset=len(list(colorDic.keys())[fs.index(found)])-1 + # if found==-1: + # strings.append(line[foundOld+offset:]) + # else: + # strings.append(line[foundOld+offset:found].strip('\x1b')) + # colors.append(list(colorDic.values())[fs.index(found)]) + + # found=int(found) + # if found!=-1: + # found=found+1 + + # return colors,strings + + def findColors(self, line, colorDic): + + strings = [] + colors = [] + curr_index = 0 + + while curr_index <= len(line): + + # Search for remaining + fs = [] + curr_color_keys = [] + for key in list(colorDic.keys()): + + ind = line.find(key, curr_index) + if ind >= 0: + fs.append(ind) + curr_color_keys.append(key) + + # If nothing is found, break + if len(fs) == 0: + break + + # Update indices + curr_index = min(fs) + col_index = fs.index(min(fs)) + + # Find out end of string that should be colored + tmp = list(fs) + tmp.remove(curr_index) + if len(tmp) > 0: + next_index = min(tmp) - 1 + else: + next_index = len(line) + 1 + + # Compute length of color string + offset = len(curr_color_keys[col_index]) + + # Extract string and color and append + strings.append(line[curr_index + offset : next_index].strip("\x1b")) + colors.append(colorDic[curr_color_keys[fs.index(curr_index)]]) + + # Increment index to move up in string + curr_index = curr_index + 1 + + return colors, strings + + def clearCurrentBlock(self): + # block being current row + length = len(self.document().lastBlock().text()[4:]) + if length == 0: + return None + else: + # should have a better way of doing this but I can't find it + [self.textCursor().deletePreviousChar() for x in range(length)] + return True + + def recallHistory(self): + # used when using the arrow keys to scroll through history + self.clearCurrentBlock() + if self.historyIndex != -1: + self.insertPlainText(self.history[self.historyIndex]) + return True + + def customCommands(self, command): + + if command == "!hist": # display history + self.append("") # move down one line + # vars that are in the command are prefixed with ____CC and deleted + # once the command is done so they don't show up in dir() + backup = self.interpreterLocals.copy() + history = self.history[:] + history.reverse() + for i, x in enumerate(history): + iSize = len(str(i)) + delta = len(str(len(history))) - iSize + line = line = " " * delta + "%i: %s" % (i, x) + "\n" + self.write(line) + + self.updateInterpreterLocals(backup) + self.marker() + return True + + if re.match("!hist\(\d+\)", command): # recall command from history + backup = self.interpreterLocals.copy() + history = self.history[:] + history.reverse() + index = int(command[6:-1]) + self.clearCurrentBlock() + command = history[index] + if command[-1] == ":": + self.multiLine = True + self.write(command) + self.updateInterpreterLocals(backup) + return True + + return False + + def keyPressEvent(self, event): + + if event.key() == QtCore.Qt.Key_Escape: + # proper exit + self.interpreter.runIt("exit()") + + if event.key() == QtCore.Qt.Key_Down: + if self.historyIndex == len(self.history): + self.historyIndex -= 1 + try: + if self.historyIndex > -1: + self.historyIndex -= 1 + self.recallHistory() + else: + self.clearCurrentBlock() + except: + pass + return None + + if event.key() == QtCore.Qt.Key_Up: + try: + if len(self.history) - 1 > self.historyIndex: + self.historyIndex += 1 + self.recallHistory() + else: + self.historyIndex = len(self.history) + except: + pass + return None + + if event.key() == QtCore.Qt.Key_Home: + # set cursor to position 4 in current block. 4 because that's where + # the marker stops + blockLength = len(self.document().lastBlock().text()[4:]) + lineLength = len(self.document().toPlainText()) + position = lineLength - blockLength + textCursor = self.textCursor() + textCursor.setPosition(position) + self.setTextCursor(textCursor) + return None + + if event.key() in [QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace]: + # don't allow deletion of marker + if self.textCursor().positionInBlock() == 4: + return None + + if event.key() in [QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter]: + # set cursor to end of line to avoid line splitting + textCursor = self.textCursor() + position = len(self.document().toPlainText()) + textCursor.setPosition(position) + self.setTextCursor(textCursor) + + line = str(self.document().lastBlock().text())[4:] # remove marker + line.rstrip() + self.historyIndex = -1 + + if self.customCommands(line): + return None + else: + try: + line[-1] + self.haveLine = True + if line[-1] == ":": + self.multiLine = True + self.history.insert(0, line) + except: + self.haveLine = False + + if self.haveLine and self.multiLine: # multi line command + self.command += line + "\n" # + command and line + self.append("") # move down one line + self.marker() # handle marker style + return None + + if self.haveLine and not self.multiLine: # one line command + self.command = line # line is the command + self.append("") # move down one line + self.interpreter.runIt(self.command) + self.command = "" # clear command + self.marker() # handle marker style + return None + + if self.multiLine and not self.haveLine: # multi line done + self.append("") # move down one line + self.interpreter.runIt(self.command) + self.command = "" # clear command + self.multiLine = False # back to single line + self.marker() # handle marker style + return None + + if not self.haveLine and not self.multiLine: # just enter + self.append("") + self.marker() + return None + return None + + # allow all other key events + super(PyInterp, self).keyPressEvent(event) diff --git a/pyfrp/meshfiles/backup/ball.geo b/pyfrp/meshfiles/backup/ball.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/backup/cone.geo b/pyfrp/meshfiles/backup/cone.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/backup/cylinder.geo b/pyfrp/meshfiles/backup/cylinder.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/backup/cylinder_field_box.geo b/pyfrp/meshfiles/backup/cylinder_field_box.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/backup/dome.geo b/pyfrp/meshfiles/backup/dome.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/backup/dome_field_box.geo b/pyfrp/meshfiles/backup/dome_field_box.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/backup/dome_old.geo b/pyfrp/meshfiles/backup/dome_old.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/backup/emptyTemplate.geo b/pyfrp/meshfiles/backup/emptyTemplate.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/backup/quad_cyl.geo b/pyfrp/meshfiles/backup/quad_cyl.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/backup/quad_cyl_field_box.geo b/pyfrp/meshfiles/backup/quad_cyl_field_box.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/backup/quad_dome.geo b/pyfrp/meshfiles/backup/quad_dome.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/ball.geo b/pyfrp/meshfiles/ball.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/cone.geo b/pyfrp/meshfiles/cone.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/cone.vtk b/pyfrp/meshfiles/cone.vtk old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/cylinder.geo b/pyfrp/meshfiles/cylinder.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/dome.geo b/pyfrp/meshfiles/dome.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/dome.vtk b/pyfrp/meshfiles/dome.vtk old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/emptyTemplate.geo b/pyfrp/meshfiles/emptyTemplate.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/examples/approximated.geo b/pyfrp/meshfiles/examples/approximated.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/examples/make_simplify_surfaces_geo.py b/pyfrp/meshfiles/examples/make_simplify_surfaces_geo.py old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/examples/simplifySurfaces.geo b/pyfrp/meshfiles/examples/simplifySurfaces.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/examples/splineTest.geo b/pyfrp/meshfiles/examples/splineTest.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/gmshLogs/gmsh.sterr b/pyfrp/meshfiles/gmshLogs/gmsh.sterr old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/gmshLogs/gmsh.stout b/pyfrp/meshfiles/gmshLogs/gmsh.stout old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/quad_cylinder.geo b/pyfrp/meshfiles/quad_cylinder.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/quad_dome.geo b/pyfrp/meshfiles/quad_dome.geo old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/tests/readStlFile.stl b/pyfrp/meshfiles/tests/readStlFile.stl old mode 100644 new mode 100755 diff --git a/pyfrp/meshfiles/tests/surfaceFuse.stl b/pyfrp/meshfiles/tests/surfaceFuse.stl old mode 100644 new mode 100755 diff --git a/pyfrp/modules/__init__.py b/pyfrp/modules/__init__.py old mode 100644 new mode 100755 index ed35918..e3330bc --- a/pyfrp/modules/__init__.py +++ b/pyfrp/modules/__init__.py @@ -15,7 +15,7 @@ if platform.system() in ["Darwin"]: import matplotlib - matplotlib.use('qt4agg') + matplotlib.use('qt5agg') #Basic PyFRAP modules from . import pyfrp_term_module diff --git a/pyfrp/modules/pyfrp_IO_module.py b/pyfrp/modules/pyfrp_IO_module.py old mode 100644 new mode 100755 index b25897e..796fce4 --- a/pyfrp/modules/pyfrp_IO_module.py +++ b/pyfrp/modules/pyfrp_IO_module.py @@ -64,16 +64,16 @@ def saveToPickle(obj,fn=None): """ cleanUp() - if fn==None: - if hasattr(obj,"name"): - fn=obj.name+".pk" - else: - fn="unnamed"+".pk" - - with open(fn, 'wb') as output: - pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL) - - return fn + if fn==None: + if hasattr(obj,"name"): + fn=obj.name+".pk" + else: + fn="unnamed"+".pk" + + with open(fn, 'wb') as output: + pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL) + + return fn def loadFromPickle(fn): @@ -93,14 +93,14 @@ def loadFromPickle(fn): sys.path.append(pyfrp_misc_module.getSubclassesDir()+'/') - if platform.system() in ["Darwin","Linux"]: - filehandler=open(fn, 'r') - elif platform.system() in ["Windows"]: - filehandler=open(fn, 'rb') - - loadedFile=pickle.load(filehandler) - - return loadedFile + if platform.system() in ["Darwin","Linux"]: + filehandler=open(fn, 'rb') + elif platform.system() in ["Windows"]: + filehandler=open(fn, 'rb') + + loadedFile=pickle.load(filehandler) + + return loadedFile def loadMolecule(fn,update=True): @@ -185,7 +185,7 @@ def copyMeshFiles(fn,fnGeo,fnMsh,debug=False): # Create meshfile folder if necessary if 'meshfiles'==os.path.split(fn)[-1]: if debug: - print "Folder is already called meshfiles, will leave it as it is." + print("Folder is already called meshfiles, will leave it as it is.") else: fn=pyfrp_misc_module.slashToFn(fn) try: @@ -196,7 +196,7 @@ def copyMeshFiles(fn,fnGeo,fnMsh,debug=False): fn=pyfrp_misc_module.slashToFn(fn+"meshfiles") if debug: - print "Created new folder " + fn + " ." + print("Created new folder " + fn + " .") # Get list of files we want to copy files=[fnGeo,fnMsh] diff --git a/pyfrp/modules/pyfrp_fit_module.py b/pyfrp/modules/pyfrp_fit_module.py old mode 100644 new mode 100755 index 83c1233..1c12e0c --- a/pyfrp/modules/pyfrp_fit_module.py +++ b/pyfrp/modules/pyfrp_fit_module.py @@ -46,11 +46,11 @@ import scipy.optimize as sciopt #PyFRAP -import pyfrp_stats_module -import pyfrp_plot_module -import pyfrp_optimization_module +from . import pyfrp_stats_module +from . import pyfrp_plot_module +from . import pyfrp_optimization_module -from pyfrp_term_module import * +from .pyfrp_term_module import * #matplotlib @@ -233,10 +233,10 @@ def checkInput(x,iteration,fit): if min(x)<0: if iteration==0: #If initial guess is out of bounds, just do nothing - print printWarning("Check your initial guess, some value is negative.") + print(printWarning("Check your initial guess, some value is negative.")) return False else: - print printWarning("One of the values of x is negative") + print(printWarning("One of the values of x is negative")) return False return True @@ -582,8 +582,8 @@ def FRAPObjFunc(x,fit,debug,ax,returnFit): prod,degr = downscaleKinetics(prod,degr,fit.kineticTimeScale) if debug: - print "------------------------------------------" - print "Dnew=",Dnew, "prod=", prod, "degr=", degr, "equFacts", equFacts + print("------------------------------------------") + print("Dnew=",Dnew, "prod=", prod, "degr=", degr, "equFacts", equFacts) #Scale simulation vectors try: diff --git a/pyfrp/modules/pyfrp_geometry_module.py b/pyfrp/modules/pyfrp_geometry_module.py old mode 100644 new mode 100755 index b81e151..6a3f696 --- a/pyfrp/modules/pyfrp_geometry_module.py +++ b/pyfrp/modules/pyfrp_geometry_module.py @@ -41,8 +41,8 @@ import string #PyFRAP modules -from pyfrp_term_module import * -import pyfrp_misc_module +from .pyfrp_term_module import * +from . import pyfrp_misc_module #=========================================================================================================================================================================== #Module Functions @@ -110,16 +110,21 @@ def flipCoordinate(x,destAxis,origAxis='x',debug=False): # Calculate differences between axis - axisDiff=abs(string.lowercase.index(destAxis)-string.lowercase.index(origAxis)) - + try: + axisDiff=abs(string.lowercase.index(destAxis)-string.lowercase.index(origAxis)) + except AttributeError: + axisDiff=abs(string.ascii_lowercase.index(destAxis)-string.ascii_lowercase.index(origAxis)) + + + # Roll xnew=np.roll(x,axisDiff) # Print debugging messages if debug: - print "Transforming coordinate " , x, " from axis ", origAxis, " to axis ", destAxis , "." - print "axisDiff = ", axisDiff - print "xnew = ", xnew + print("Transforming coordinate " , x, " from axis ", origAxis, " to axis ", destAxis , ".") + print("axisDiff = ", axisDiff) + print("xnew = ", xnew) return xnew @@ -304,4 +309,4 @@ def decodeEuclideanBase(d): - \ No newline at end of file + diff --git a/pyfrp/modules/pyfrp_gmsh_IO_module.py b/pyfrp/modules/pyfrp_gmsh_IO_module.py old mode 100644 new mode 100755 index a14d067..7418a33 --- a/pyfrp/modules/pyfrp_gmsh_IO_module.py +++ b/pyfrp/modules/pyfrp_gmsh_IO_module.py @@ -46,11 +46,11 @@ from numpy import * #PyFRAP Modules -import pyfrp_gmsh_geometry -import pyfrp_misc_module -import pyfrp_gmsh_module +from . import pyfrp_gmsh_geometry +from . import pyfrp_misc_module +from . import pyfrp_gmsh_module -from pyfrp_term_module import * +from .pyfrp_term_module import * #Misc import shutil @@ -238,10 +238,10 @@ def sortKeysByLength(dic): """ lengths=[] - for key in dic.keys(): + for key in list(dic.keys()): lengths.append(len(key)) - keys,lengths=pyfrp_misc_module.sortListsWithKey(dic.keys(),lengths) + keys,lengths=pyfrp_misc_module.sortListsWithKey(list(dic.keys()),lengths) return keys,lengths def readParameter(line,parmDic): @@ -1170,7 +1170,7 @@ def writeFieldPropByDict(f,fieldID,dic): """ - for key, value in dic.iteritems(): + for key, value in dic.items(): f=writeFieldProp(f,fieldID,key,value) return f @@ -1212,8 +1212,8 @@ def repairDefaultGeoFiles(debug=False): if debug: cmd = "cp -v " + fnBackup + "*.geo " + pyfrp_misc_module.getMeshfilesDir() - print "Executing command:" - print cmd + print("Executing command:") + print(cmd) else: cmd = "cp " + fnBackup + "*.geo " + pyfrp_misc_module.getMeshfilesDir() @@ -1272,14 +1272,23 @@ def isMergeFile(fn): isMerge=False mergedFiles=[] - with open(fn,'rb') as f: - - for line in f: - if line.startswith("Merge"): - isMerge=True - splitted=line.split('"') - mergedFiles.append(splitted[1]) + try: + with open(fn,'rb') as f: + for line in f: + if line.startswith("Merge"): + isMerge=True + splitted=line.split('"') + mergedFiles.append(splitted[1]) + except TypeError: + with open(fn,'r') as f: + + for line in f: + if line.startswith("Merge"): + isMerge=True + splitted=line.split('"') + mergedFiles.append(splitted[1]) + return isMerge,mergedFiles def genMergeGeoFile(meshFiles,fnGeo): @@ -1385,4 +1394,4 @@ def mergeMeshes(meshFiles,fn,run=True,debug=False,redirect=False,fnStout=None,fn - \ No newline at end of file + diff --git a/pyfrp/modules/pyfrp_gmsh_geometry.py b/pyfrp/modules/pyfrp_gmsh_geometry.py old mode 100644 new mode 100755 index aa9280c..479e7f1 --- a/pyfrp/modules/pyfrp_gmsh_geometry.py +++ b/pyfrp/modules/pyfrp_gmsh_geometry.py @@ -56,14 +56,14 @@ import string #PyFRAP modules -import pyfrp_plot_module -from pyfrp_term_module import * -import pyfrp_misc_module -import pyfrp_gmsh_IO_module -import pyfrp_idx_module -import pyfrp_geometry_module -import pyfrp_IO_module -import pyfrp_vtk_module +from . import pyfrp_plot_module +from .pyfrp_term_module import * +from . import pyfrp_misc_module +from . import pyfrp_gmsh_IO_module +from . import pyfrp_idx_module +from . import pyfrp_geometry_module +from . import pyfrp_IO_module +from . import pyfrp_vtk_module #Matplotlib from mpl_toolkits.mplot3d.art3d import Poly3DCollection @@ -111,6 +111,7 @@ def __init__(self): self.volumes=[] self.fields=[] self.bkgdField=None + self.ellipses=[] #Some settings for plotting self.annXOffset=3. @@ -205,6 +206,36 @@ def addArc(self,vstart,vcenter,vend,Id=None): return a + def addEllipse(self,vstart,vcenter,vend,vmajor=None,Id=None): + + """Adds new :py:class:`pyfrp.modules.pyfrp_gmsh_geometry.ellipse` instance + at point ``x`` and appends it to ``edges`` and ``ellipses`` list. + + Args: + vstart (pyfrp.modules.pyfrp_gmsh_geometry.vertex): Start vertex. + vcenter (pyfrp.modules.pyfrp_gmsh_geometry.vertex): Center vertex. + vend (pyfrp.modules.pyfrp_gmsh_geometry.vertex): End vertex. + + Keyword Args: + vmajor (pyfrp.modules.pyfrp_gmsh_geometry.vertex): Major vertex. + Id (int): ID of arc. + + Returns: + pyfrp.modules.pyfrp_gmsh_geometry.ellipse: New ellipse instance. + + """ + + newId=self.getNewId(self.edges,Id) + + if vmajor is None: + vmajor=vend + + a=ellipse(self,vstart,vcenter,vend,vmajor,newId) + self.ellipses.append(a) + self.edges.append(a) + + return a + def addBSpline(self,vertices,Id=None): """Adds new :py:class:`pyfrp.modules.pyfrp_gmsh_geometry.line` instance @@ -1198,6 +1229,10 @@ def getNewId(self,objList,Id=None): else: newId=Id + if self.checkIdExists(newId,objList): + IdList=pyfrp_misc_module.objAttrToList(objList,'Id') + newId=max(IdList)+1 + return newId def incrementID(self,objList): @@ -1609,6 +1644,8 @@ def addRuledSurface(self,Id=None,lineLoopID=None): newId=self.getNewId(self.ruledSurfaces,Id) l=ruledSurface(self,lineLoopID,newId) + # if not l.createdSurfaces: + l.Id=self.getNewId(self.ruledSurfaces,Id) self.ruledSurfaces.append(l) return l @@ -1769,11 +1806,12 @@ def writeToFile(self,fn): """ - with open(fn,'wb') as f: + with open(fn,'w') as f: self.writeElements("vertices",f) self.writeElements("lines",f) self.writeElements("arcs",f) + self.writeElements("ellipses",f) self.writeElements("bSplines",f) self.writeElements("lineLoops",f) self.writeElements("ruledSurfaces",f) @@ -1820,6 +1858,7 @@ def incrementAllIDs(self,offset): self.incrementIDs(offset,"vertices") self.incrementIDs(offset,"lines") self.incrementIDs(offset,"arcs") + self.incrementIDs(offset,"ellipses") self.incrementIDs(offset,"bSplines") self.incrementIDs(offset,"lineLoops") self.incrementIDs(offset,"ruledSurfaces") @@ -1860,6 +1899,7 @@ def setDomainGlobally(self): self.setDomainForElementType("vertices") self.setDomainForElementType("lines") self.setDomainForElementType("arcs") + self.setDomainForElementType("ellipses") self.setDomainForElementType("bSplines") self.setDomainForElementType("lineLoops") self.setDomainForElementType("ruledSurfaces") @@ -1937,6 +1977,7 @@ def getAllMaxID(self): IDs.append(self.getMaxID("vertices")) IDs.append(self.getMaxID("lines")) IDs.append(self.getMaxID("arcs")) + IDs.append(self.getMaxID("ellipses")) IDs.append(self.getMaxID("lineLoops")) IDs.append(self.getMaxID("ruledSurfaces")) IDs.append(self.getMaxID("surfaceLoops")) @@ -2097,16 +2138,16 @@ def simplifySurfaces(self,iterations=3,triangIterations=2,addPoints=False,fixSur #Fuse if surface.fuse(sN,debug=debug): if debug: - print "Successfully fused ", surface.Id, sN.Id + print("Successfully fused ", surface.Id, sN.Id) #Clean up edges self.cleanUpUnusedEdges(debug=debug) #Print some final statistics if debug: - print "Surfaces: Before =" , x , " After:" , len(self.ruledSurfaces) - print "lineLoops: Before =" , y , " After:" , len(self.lineLoops) - print "Edges: Before =" , z , " After:" , len(self.edges) + print("Surfaces: Before =" , x , " After:" , len(self.ruledSurfaces)) + print("lineLoops: Before =" , y , " After:" , len(self.lineLoops)) + print("Edges: Before =" , z , " After:" , len(self.edges)) #raw_input() @@ -2250,15 +2291,15 @@ def removeDuplicateEdgeIDs(self,debug=False): """ edgeIDs=pyfrp_misc_module.objAttrToList(self.edges,'Id') - print edgeIDs + print(edgeIDs) # Loop through edges for i,e in enumerate(self.edges): for j in range(i+1,len(self.edges)): - print i,j,self.edges[i].Id,self.edges[j].Id + print(i,j,self.edges[i].Id,self.edges[j].Id) # Check if same ID if self.edges[j].Id==self.edges[i].Id: - print "same id",self.edges[j].Id + print("same id",self.edges[j].Id) # Check if same start/end vertex if (self.edges[j].getFirstVertex()==self.edges[i].getFirstVertex()) and (self.edges[j].getLastVertex()==self.edges[i].getLastVertex()): @@ -2834,6 +2875,8 @@ def delete(self,debug=False): self.domain.arcs.remove(self) if self.typ==2: self.domain.bSplines.remove(self) + if selt.typ==3: + self.domain.ellipses.remove(self) self.domain.edges.remove(self) except ValueError: @@ -3900,7 +3943,7 @@ def printLoop(self): ids=np.array(pyfrp_misc_module.objAttrToList(self.edges,"Id")) orients=np.array(self.orientations) - print "Line Loop with ID = "+ str(self.Id)+": "+str(ids*orients) + print("Line Loop with ID = "+ str(self.Id)+": "+str(ids*orients)) def fix(self): @@ -3935,7 +3978,7 @@ def fix(self): if j==len(self.edges)-1: printWarning("Could not fix loop with ID" + str(self.Id)) - print "Edge with ID " +str(lastEdge.Id) + " is not matching with any other edge." + print("Edge with ID " +str(lastEdge.Id) + " is not matching with any other edge.") return False self.edges=edgesNew @@ -3981,12 +4024,12 @@ def checkClosed(self,fix=False,debug=False): b=True if debug: - print "Edge with ID " +str(edge1Temp.Id) + " was not matching edge with ID " + str(edge2Temp.Id) + ". \n Fixed this." + print("Edge with ID " +str(edge1Temp.Id) + " was not matching edge with ID " + str(edge2Temp.Id) + ". \n Fixed this.") if debug: printWarning("lineLoop with ID " + str(self.Id) + " does not close." ) - print "Edge with ID " +str(edge1Temp.Id) + " is not matching edge with ID " + str(edge2Temp.Id) + print("Edge with ID " +str(edge1Temp.Id) + " is not matching edge with ID " + str(edge2Temp.Id)) return b @@ -4211,7 +4254,7 @@ def approxBySpline(self,angleThresh=0.314,debug=False): if j>0: if loops.sort()!=oldLoops.sort(): noSpline=True - print "cannot turn into spline because ", edgesSubst[j-1].Id , " and ",edgesSubst[j].Id + print("cannot turn into spline because ", edgesSubst[j-1].Id , " and ",edgesSubst[j].Id) oldLoops=list(loops) @@ -4262,7 +4305,7 @@ def approxBySpline(self,angleThresh=0.314,debug=False): loop.edges.insert(idxInsert,sub[1]) if debug: - print "Substituted edges ", sub[0][0].Id , "-", sub[0][-1].Id, " with spline ", sub[1].Id + print("Substituted edges ", sub[0][0].Id , "-", sub[0][-1].Id, " with spline ", sub[1].Id) # Remove edges from domain. @@ -4406,6 +4449,7 @@ class ruledSurface(gmshElement): def __init__(self,domain,loopID,ID): gmshElement.__init__(self,domain,ID) + self.createdSurfaces=False self.initLineLoop(loopID) def initLineLoop(self,loopID,debug=False,addPoints=False,iterations=2): @@ -4423,7 +4467,9 @@ def initLineLoop(self,loopID,debug=False,addPoints=False,iterations=2): #Check length if len(self.lineLoop.edges)<=4: return False,[] - + + self.createdSurfaces=True + #Compute normal vector oldNormal=self.getNormal() @@ -4573,12 +4619,12 @@ def getNormal(self,method='cross'): break if idx==None: printError("All points in surface "+str(self.Id) + " seem to be colinear. Will not be able to compute normal.") - print self.Id + print(self.Id) self.draw(ann=True) - print pyfrp_misc_module.objAttrToList(self.lineLoop.getVertices(),'Id') + print(pyfrp_misc_module.objAttrToList(self.lineLoop.getVertices(),'Id')) - raw_input() + input() return np.zeros((3,)) @@ -4804,7 +4850,7 @@ def draw(self,ax=None,color='b',edgeColor='k',drawLoop=True,ann=None,alpha=0.2,b vertices=self.lineLoop.getVertices() coords=pyfrp_misc_module.objAttrToList(vertices,'x') coords=np.asarray(coords) - coords = zip(coords[:,0], coords[:,1], coords[:,2]) + coords = list(zip(coords[:,0], coords[:,1], coords[:,2])) coordsNew=[] coordsNew.append(list(coords)) @@ -5143,7 +5189,7 @@ def setFieldAttributes(self,**kwargs): """Sets multiple field attributes. """ - for key, value in kwargs.iteritems(): + for key, value in kwargs.items(): self.setFieldAttributes(key,value) def getSubElements(self): @@ -5816,4 +5862,137 @@ def setFieldAttr(self,name,val): else: setattr(self,name,val) - \ No newline at end of file + +class ellipse(edge): + + """Ellipse class storing information from gmsh .geo ellipse. + + .. warning: Experimental + + Args: + domain (pyfrp.modules.pyfrp_gmsh_geometry.domain): Domain arc belongs to. + vstart (pyfrp.modules.pyfrp_gmsh_geometry.vertex): Start vertex. + vcenter (pyfrp.modules.pyfrp_gmsh_geometry.vertex): Center vertex. + vend (pyfrp.modules.pyfrp_gmsh_geometry.vertex): End vertex. + vmajor (pyfrp.modules.pyfrp_gmsh_geometry.vertex): Major axis vertex. + Id (int): ID of arc. + + """ + + def __init__(self,domain,vstart,vcenter,vend,vmajor,Id): + + edge.__init__(self,domain,Id,3) + + self.vcenter=vcenter + self.vstart=vstart + self.vend=vend + self.vmajor=vmajor + + def writeToFile(self,f): + + """Writes ellipse to file. + + Args: + f (file): File to write to. + + Returns: + file: File. + + """ + + f.write("Ellipse("+str(self.Id)+")= {" + str(self.vstart.Id) + ","+ str(self.vcenter.Id)+ "," + str(self.vmajor.Id) + "," + str(self.vend.Id) + "};\n" ) + + return f + + def getVstart(self): + + """Returns start vertex of arc.""" + + return self.vstart + + def getVend(self): + + """Returns end vertex of arc.""" + + return self.vend + + def getXstart(self): + + """Returns start coordinate of arc.""" + + return self.vstart.x + + def getXend(self): + + """Returns end coordinate of arc.""" + + return self.vend.x + + def getVcenter(self): + + """Returns center vertex of arc.""" + + return self.vcenter + + def getXcenter(self): + + """Returns center coordinate of arc.""" + + return self.vcenter.x + + def getVmajor(self): + + """Returns center vertex of arc.""" + + return self.vcenter + + def getXmajor(self): + + """Returns center coordinate of arc.""" + + return self.vmajor.x + + def getLastVertex(self,orientation): + + """Returns last vertex of arc given a orientation. + + Orientation can be either forward (1), or reverse (-1). + + Args: + orientation (int): Orientation of arc. + + Returns: + pyfrp.pyfrp_gmsh_geometry.vertex: Vertex. + + """ + + if orientation==1: + return self.getVend() + elif orientation==-1: + return self.getVstart() + else: + printError("Cannot return last vertex. Orientation " + str(orientation) + " unknown.") + return None + + def getFirstVertex(self,orientation): + + """Returns first vertex of arc given a orientation. + + Orientation can be either forward (1), or reverse (-1). + + Args: + orientation (int): Orientation of arc. + + Returns: + pyfrp.pyfrp_gmsh_geometry.vertex: Vertex. + + """ + + if orientation==-1: + return self.getVend() + elif orientation==1: + return self.getVstart() + else: + printError("Cannot return first vertex. Orientation " + str(orientation) + " unknown.") + return None + diff --git a/pyfrp/modules/pyfrp_gmsh_module.py b/pyfrp/modules/pyfrp_gmsh_module.py old mode 100644 new mode 100755 index c701414..235e872 --- a/pyfrp/modules/pyfrp_gmsh_module.py +++ b/pyfrp/modules/pyfrp_gmsh_module.py @@ -52,9 +52,9 @@ import platform #PyFRAP -import pyfrp_gmsh_IO_module -import pyfrp_misc_module -from pyfrp_term_module import * +from . import pyfrp_gmsh_IO_module +from . import pyfrp_misc_module +from .pyfrp_term_module import * #=========================================================================================================================================================================== #Module Functions @@ -300,7 +300,7 @@ def refineMsh(fn,debug=False): os.system(gmshBin+" -v "+ str(v) + " -refine " + fn) return fn -def runGmsh(fn,fnOut=None,debug=False,redirect=False,fnStout=None,fnSterr=None,volSizeMax=None,dim=3): +def runGmsh(fn,fnOut=None,debug=False,redirect=False,fnStout=None,fnSterr=None,volSizeMax=None,dim=3,gmshBin=None): """Runs Gmsh generating mesh from .geo file. @@ -350,9 +350,10 @@ def runGmsh(fn,fnOut=None,debug=False,redirect=False,fnStout=None,fnSterr=None,v fnOut=pyfrp_misc_module.win2linPath(fnOut) # Add Gmsh to PATH and grab gmshBin location - gmshBin=getGmshBin() - addGmshToPATHs() - + if gmshBin is None: + gmshBin=getGmshBin() + addGmshToPATHs() + #Define which command to execute cmd = gmshBin + " -v " + str(v) +" -"+str(dim)+ " -optimize -algo del3d" if volSizeMax!=None: @@ -365,8 +366,8 @@ def runGmsh(fn,fnOut=None,debug=False,redirect=False,fnStout=None,fnSterr=None,v #Print out what will be done if debug: - print "Will execute:" - print cmd + print("Will execute:") + print(cmd) #Split command in list for subprocess args = shlex.split(cmd) @@ -426,4 +427,4 @@ def addGmshToPATHs(fnPath=None): - \ No newline at end of file + diff --git a/pyfrp/modules/pyfrp_idx_module.py b/pyfrp/modules/pyfrp_idx_module.py old mode 100644 new mode 100755 index 4837243..454d7b4 --- a/pyfrp/modules/pyfrp_idx_module.py +++ b/pyfrp/modules/pyfrp_idx_module.py @@ -66,8 +66,8 @@ from scipy.spatial import Delaunay #PyFRAP modules -import pyfrp_misc_module as pyfrp_misc -import pyfrp_plot_module as pyfrp_plt +from . import pyfrp_misc_module as pyfrp_misc +from . import pyfrp_plot_module as pyfrp_plt #=========================================================================================================================================================================== #Module Functions @@ -105,7 +105,7 @@ def getCircleIdxImg(center,radius,res,debug=False): for j in range(int(res)): #Check if in circle - if checkInsideCircle(i+1,j+1,center,radius): + if checkInsideCircle(i,j,center,radius): ind_circ_x.append(i) ind_circ_y.append(j) if debug: @@ -149,7 +149,7 @@ def getRectangleIdxImg(offset,sidelengthX,sidelengthY,res,debug=False): for j in range(int(res)): #Check if in square - if checkInsideRectangle(i+1,j+1,offset,sidelengthX,sidelengthY): + if checkInsideRectangle(i,j,offset,sidelengthX,sidelengthY): indX.append(i) indY.append(j) @@ -189,13 +189,13 @@ def getSquareIdxImg(offset,sidelength,res,debug=False): indX=[] indY=[] - + indDebug=np.zeros((res,res)) #Go through all pixels for i in range(int(res)): for j in range(int(res)): #Check if in square - if checkInsideSquare(i+1,j+1,offset,sidelength): + if checkInsideSquare(i,j,offset,sidelength): indX.append(i) indY.append(j) @@ -206,7 +206,7 @@ def getSquareIdxImg(offset,sidelength,res,debug=False): #Create figure fig,axes = pyfrp_plt.make_subplot([1,1],titles=["Square"],sup="getSquareIdxImg debugging output") - axes[0].contourf(ind_circ_debug) + axes[0].contourf(indDebug) return indX,indY @@ -253,7 +253,7 @@ def getAllIdxImg(res,debug=False): return indX,indY -def getPolyIdxImg(corners,res,debug=False): +def getPolyIdxImg(corners,res,debug=False,swap=True): """Returns all indices of image that lie within given polygon. @@ -279,8 +279,8 @@ def getPolyIdxImg(corners,res,debug=False): poly = ptc.Polygon(corners,edgecolor='r',facecolor=(1,0,0,.2),) #Create grid - x_int=np.arange(1,res+1,1) - y_int=np.arange(1,res+1,1) + x_int=np.arange(0,res,1) + y_int=np.arange(0,res,1) g = np.meshgrid(x_int, y_int) #Zip them into coordinate tuples @@ -288,8 +288,11 @@ def getPolyIdxImg(corners,res,debug=False): #Check which point is inside pts = np.vstack([p for p in coords if poly.contains_point(p, radius=0)]) - - indX,indY= pts[0,:],pts[1,:] + + indX,indY= pts[:,0],pts[:,1] + + #if swap: + #indX,indY=indY,indX return indX,indY @@ -439,7 +442,7 @@ def getSquareIdxMesh(sidelength,offset,mesh,zmin="-inf",zmax="inf",debug=False): return indFinal -def getPolyIdxMesh(corners,mesh,zmin="-inf",zmax="inf",debug=False): +def getPolyIdxMesh(corners,mesh,zmin="-inf",zmax="inf",debug=False,swap=True): """Returns all indices of mesh that lie within given polygon and between ``zmin`` and ``zmax``. @@ -465,13 +468,28 @@ def getPolyIdxMesh(corners,mesh,zmin="-inf",zmax="inf",debug=False): #Grabbing cellCenters of mesh x,y,z=mesh.getCellCenters() + #if swap: + #coords=list(zip(np.array(y),np.array(x))) + #else: + coords=list(zip(np.array(x),np.array(y))) + #Bookkeeping list - indPoly=[] + #indPoly=[] + + + + + #coords = list(zip(*(c.flat for c in g))) + #Define polygonial patch + poly = ptc.Polygon(corners,edgecolor='r',facecolor=(1,0,0,.2),) + + #Check which point is inside + indPoly = [i for i,p in enumerate(coords) if poly.contains_point(p, radius=0)] #Loop through coordinates and check if inside - for i in range(len(x)): - if checkInsidePoly(x[i],y[i],corners): - indPoly.append(i) + #for i in range(len(x)): + #if checkInsidePoly(x[i],y[i],corners): + #indPoly.append(i) #Get indices in Slice indSlice=getSliceIdxMesh(z,zmin,zmax) @@ -593,7 +611,7 @@ def checkInsidePolyVec(x,y,poly): return vec -def checkInsidePoly(x,y,poly): +def checkInsidePolyOld(x,y,poly): """Checks if coordinate (x,y) is inside polyogn. @@ -630,6 +648,46 @@ def checkInsidePoly(x,y,poly): return inside +def checkInsidePoly(x,y,poly): + + """Checks if coordinate (x,y) is inside polyogn. + + Adapted from http://www.ariel.com.au/a/python-point-int-poly.html. + + .. note:: If ``x`` and ``y`` are ``float``, will return ``bool``, otherwise + ``numpy.ndarray`` of booleans. + + Args: + poly (list): List of (x,y)-coordinates of corners. + x (float): x-coordinate. + y (float): y-coordinate. + + Returns: + bool: True if inside, otherwise False. + + """ + + try: + x[0] + wasVec=True + except: + x=[x] + y=[y] + wasVec=False + + coords=list(zip(np.array(x),np.array(y))) + + #Define polygonial patch + poly = ptc.Polygon(poly,edgecolor='r',facecolor=(1,0,0,.2),) + + #Check which point is inside + ret= [poly.contains_point(p, radius=0) for i,p in enumerate(coords)] + + if not wasVec: + ret=ret[0] + + return ret + def checkQuad(x,y,res): """Checks if coordinate (x,y) is inside first quadrant. @@ -816,17 +874,10 @@ def mask2ind(mask,res): #To bool mask=mask.astype(bool) - - #idx grid - x=np.arange(res) - y=np.arange(res) - X,Y=np.meshgrid(x,y) - - #Slice idx grid - idxX_new=X[mask].flatten().astype(int) - idxY_new=Y[mask].flatten().astype(int) - return idxX_new, idxY_new + ret=np.where(mask>0) + + return ret[0],ret[1] def getExtendedPixelsSquare(offset,sidelength,res,debug=False): @@ -1057,8 +1108,8 @@ def getCommonXYExtend(ROIs,debug=False): yExtend=[yExtends[:,0].min(),yExtends[:,1].max()] if debug: - print "xExtend = ", xExtend - print "yExtend = ", yExtend + print("xExtend = ", xExtend) + print("yExtend = ", yExtend) return xExtend, yExtend @@ -1081,7 +1132,7 @@ def remRepeatedImgIdxs(idxX,idxY,debug=False): """ - idx=zip(idxX,idxY) + idx=list(zip(idxX,idxY)) idx=pyfrp_misc.remRepeatsList(idx) idxX,idxY=pyfrp_misc.unzipLists(idx) return idxX,idxY @@ -1222,7 +1273,7 @@ def triangulatePoly(coords,addPoints=False,iterations=2,debug=False): coordsOrg=list(coords) if debug: - print "Found ", len(tri.simplices.copy()), "triangles in initial call." + print("Found ", len(tri.simplices.copy()), "triangles in initial call.") #Incrementally refine triangulation if addPoints: @@ -1237,7 +1288,7 @@ def triangulatePoly(coords,addPoints=False,iterations=2,debug=False): tri.add_points(mids,restart=True) if debug: - print "Found ", len(tri.simplices.copy()), "triangles after iterations." + print("Found ", len(tri.simplices.copy()), "triangles after iterations.") #Remember assigment of points by traingulation function @@ -1263,8 +1314,8 @@ def triangulatePoly(coords,addPoints=False,iterations=2,debug=False): midsOut.append(mid) if debug: - print "Removed ", len(tri.simplices.copy())-len(triFinal), "triangles through COM criteria." - print "Returning ", len(triFinal), "triangles." + print("Removed ", len(tri.simplices.copy())-len(triFinal), "triangles through COM criteria.") + print("Returning ", len(triFinal), "triangles.") return triFinal,coordsTri @@ -1307,4 +1358,4 @@ def getCenterOfMass(xs,axis=0,masses=None): - \ No newline at end of file + diff --git a/pyfrp/modules/pyfrp_img_module.py b/pyfrp/modules/pyfrp_img_module.py old mode 100644 new mode 100755 index 81b0d4e..72ee64f --- a/pyfrp/modules/pyfrp_img_module.py +++ b/pyfrp/modules/pyfrp_img_module.py @@ -54,20 +54,26 @@ import os import platform -#Bioformats -#import javabridge -import bioformats + #PyFRAP modules -import pyfrp_misc_module -import pyfrp_plot_module -import pyfrp_idx_module -from pyfrp_term_module import * +from . import pyfrp_misc_module +from . import pyfrp_plot_module +from . import pyfrp_idx_module +from .pyfrp_term_module import * + +#Bioformats +#import javabridge +try: + import bioformats +except: + printWarning("Cannot import bioformats") #Image processing import skimage import skimage.morphology import skimage.io +import imp #skimageVersion=skimage.__version__ try: if int(skimage.__version__.split('.')[1])<11: @@ -99,7 +105,7 @@ def analyzeDataset(analysis,signal=None,embCount=None,debug=False,debugAll=False analysis (pyfrp.subclasses.pyfrp_analysis): Object containing all necessary information for analysis. Keyword Args: - signal (PyQt4.QtCore.pyqtSignal): PyQT signal to send progress to GUI. + signal (PyQt5.QtCore.pyqtSignal): PyQT signal to send progress to GUI. embCount (int): Counter of counter process if multiple datasets are analyzed. debug (bool): Print final debugging messages and show debugging plots. debugAll (bool): Print debugging messages and show debugging plots of each step. @@ -110,31 +116,31 @@ def analyzeDataset(analysis,signal=None,embCount=None,debug=False,debugAll=False """ if debug or signal==None: - print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" - print "Starting analyzing dataset " + analysis.embryo.name + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") + print("Starting analyzing dataset " + analysis.embryo.name) if debug: - print 'Anaylsis options:' + print('Anaylsis options:') printDict(analysis.process) - print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") #Set back all timeseries vectors for r in analysis.embryo.ROIs: r.resetDataVec() #Compute flattening mask if needed - if 'flatten' in analysis.process.keys(): + if 'flatten' in list(analysis.process.keys()): flatteningMask=analysis.computeFlatteningMask() else: flatteningMask=None #Compute background mask if needed - if 'bkgd' in analysis.process.keys(): + if 'bkgd' in list(analysis.process.keys()): bkgdMask = analysis.computeBkgdMask(flatteningMask) else: bkgdMask = None #Load preimage if needed - if 'norm' in analysis.process.keys(): + if 'norm' in list(analysis.process.keys()): preMask = analysis.computePreMask(flatteningMask,bkgdMask) else: preMask = None @@ -180,7 +186,7 @@ def analyzeDataset(analysis,signal=None,embCount=None,debug=False,debugAll=False if i==0: if analysis.embryo.simulation!=None: - if 'quad' in analysis.process.keys(): + if 'quad' in list(analysis.process.keys()): analysis.embryo.simulation.ICimg=np.flipud(convSkio2NP(flipQuad(img))) else: analysis.embryo.simulation.ICimg=convSkio2NP(img) @@ -202,7 +208,7 @@ def analyzeDataset(analysis,signal=None,embCount=None,debug=False,debugAll=False signal.emit(currPerc) else: signal.emit(currPerc,embCount) - print + print() #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Final debugging plots #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -359,10 +365,10 @@ def meanConc(idxX,idxY,vals,debug=False): """ if debug: - print "======= mean_conc debugging output =======" - print "len(idxX)", len(idxX) - print "vals.min(), vals.max(), mean(vals)",vals.min(), vals.max(), mean(vals) - print "vals[idxX,idxY].min(), vals[idxX,idxY].max(), mean(vals[idxX,idxY]) ",vals[idxX,idxY].min(), vals[idxX,idxY].max(), mean(vals[idxX,idxY]) + print("======= mean_conc debugging output =======") + print("len(idxX)", len(idxX)) + print("vals.min(), vals.max(), mean(vals)",vals.min(), vals.max(), mean(vals)) + print("vals[idxX,idxY].min(), vals[idxX,idxY].max(), mean(vals[idxX,idxY]) ",vals[idxX,idxY].min(), vals[idxX,idxY].max(), mean(vals[idxX,idxY])) return np.mean(vals[idxX,idxY]) @@ -386,9 +392,25 @@ def meanExtConc(idxX,idxY,img,concRim,numExt,addRimImg,debug=False): """ #Adding up concentrations of all selected indices (can't use mean conc since addRimImg could be True) + # fig,ax=plt.subplots() + # fig.show() + + + # tmp=img.copy() + # # tmp=np.nan*np.ones(img.shape) + # # tmp[idxX,idxY]=img[idxX,idxY] + # tmp[idxX,idxY]=np.nan + + + # ax.imshow(tmp,vmin=0) + # plt.draw() + # input() + concSum=img[idxX,idxY].sum() concNum=len(idxX) + #print('before',concSum,concNum) + #Check if I want to add rim if addRimImg: @@ -396,8 +418,14 @@ def meanExtConc(idxX,idxY,img,concRim,numExt,addRimImg,debug=False): concSum=concSum+numExt*concRim concNum=concNum+numExt + #print(concSum,concNum) + #Return final concentration - return float(concSum)/float(concNum) + try: + ret=float(concSum)/(float(concNum)+1E-5) + except ZeroDivisionError: + ret=np.nan + return ret def getRimConc(ROIs,img,debug=False): @@ -457,7 +485,7 @@ def flipQuad(img,debug=False,testimg=False): #Check symmetry if not symmetryTest(img,debug=debug): - raw_input() + input() #Grab max/min values of original image orgMax=img.max() @@ -495,21 +523,21 @@ def flipQuad(img,debug=False,testimg=False): plt.colorbar(a) - print "======= flipQuad debugging output =======" - print "Corner check: " - print "Original Image corners: ", orgImg[0,0],orgImg[0,-1],orgImg[-1,0],orgImg[-1,-1] - print "Original Image average: ", (orgImg[0,0]+orgImg[0,-1]+orgImg[-1,0]+orgImg[-1,-1])/4. - print "Flipped Image corners: ", img[0,0],img[0,-1],img[-1,0],img[-1,-1] - print "Flipped image: ", img[-1,-1] + print("======= flipQuad debugging output =======") + print("Corner check: ") + print("Original Image corners: ", orgImg[0,0],orgImg[0,-1],orgImg[-1,0],orgImg[-1,-1]) + print("Original Image average: ", (orgImg[0,0]+orgImg[0,-1]+orgImg[-1,0]+orgImg[-1,-1])/4.) + print("Flipped Image corners: ", img[0,0],img[0,-1],img[-1,0],img[-1,-1]) + print("Flipped image: ", img[-1,-1]) - print + print() - print "Unique check: " - print "Original Image #values ", unique(orgImg) - print "Flipped Image #values ", unique(img) + print("Unique check: ") + print("Original Image #values ", unique(orgImg)) + print("Flipped Image #values ", unique(img)) - raw_input() + input() return img @@ -630,8 +658,8 @@ def symmetryTest(img,debug=False): if (lr.sum()+ud.sum())==0: pass else: - print "======= symmetry_test debugging output =======" - print "Image is not symmetric" + print("======= symmetry_test debugging output =======") + print("Image is not symmetric") #Return 1 if symmetric for both UD and LR @@ -667,11 +695,11 @@ def getMaxRangeChannel(img,debug=False): img=img[:,:,ind_max] if debug: - print "Warning, images are not monochromatic, going to choose channel number", ind_max+1,"!" + print("Warning, images are not monochromatic, going to choose channel number", ind_max+1,"!") return img,ind_max -def loadImg(fn,enc,dtype='float'): +def loadImg(fn,enc,dtype='float',channel=None,max_range=True,debug=False): """Loads image from filename fn with encoding enc and returns it as with given dtype. @@ -689,6 +717,13 @@ def loadImg(fn,enc,dtype='float'): #Load image img = skimage.io.imread(fn).astype(enc) + # Get channel with max range + + if max_range: + if len(np.shape(img))>2: + + img,ind_max=getMaxRangeChannel(img,debug=debug) + #Getting img values img=img.real img=img.astype(dtype) @@ -973,33 +1008,33 @@ def processImg(img,processDic,flatteningMask,bkgdMask,preMask,dataOffset=1.,axes #Flip image in case of quad_red and flip_before_process - if 'quad' in processDic.keys(): - if 'flipBeforeProcess' in processDic.keys(): + if 'quad' in list(processDic.keys()): + if 'flipBeforeProcess' in list(processDic.keys()): img=flipQuad(img,debug=debug) #Apply median filter for denoising - if 'median' in processDic.keys(): + if 'median' in list(processDic.keys()): img = medianFilter(img,radius=processDic['median'],debug=debug) #Apply gaussian blur to smooth out image - if 'gaussian' in processDic.keys() and 'norm' not in processDic.keys(): + if 'gaussian' in list(processDic.keys()) and 'norm' not in list(processDic.keys()): img = gaussianFilter(img,sigma=processDic['gaussian'],debug=debug) #Flatten img - if 'flatten' in processDic.keys(): + if 'flatten' in list(processDic.keys()): img = flattenImg(img,flatteningMask) #Background Substraction - if 'bkgd' in processDic.keys(): + if 'bkgd' in list(processDic.keys()): img = substractBkgd(img,bkgdMask,substractMean=False) #Normalize by pre image - if 'norm' in processDic.keys(): + if 'norm' in list(processDic.keys()): img = normImg(img,preMask,dataOffset=dataOffset,debug=debug) #Quad reduction - if 'quad' in processDic.keys(): - if 'flipBeforeProcess' in processDic.keys(): + if 'quad' in list(processDic.keys()): + if 'flipBeforeProcess' in list(processDic.keys()): #Flip image back in case of quad_red and flip_before_process (Need to unflip so that indices found by get_ind_regions still fit with image size) img=unflipQuad(img,debug=debug) else: @@ -1675,15 +1710,15 @@ def findMinOffset(fnFolder,fileList,dataEnc,oldOffset=None,defaultAdd=1.,debug=F #Some debugging output if debug: - print "Minimum value over all images in ", fnFolder ," = ", minVal - print "Proposed offset is hence = ", abs(minVal)+defaultAdd + print("Minimum value over all images in ", fnFolder ," = ", minVal) + print("Proposed offset is hence = ", abs(minVal)+defaultAdd) if oldOffset!=None: - print "Old offset was ", oldOffset + print("Old offset was ", oldOffset) if oldOffset>abs(minVal)+defaultAdd: - print "Going to return ", oldOffset + print("Going to return ", oldOffset) else: - print "Going to return ", abs(minVal)+defaultAdd + print("Going to return ", abs(minVal)+defaultAdd) if oldOffset!=None: if oldOffset>abs(minVal)+defaultAdd: @@ -1782,14 +1817,14 @@ def otsuImageJ(img,maxVal,minVal,debug=False): binImg[i,j]=maxVal if debug: - print "Optimal threshold = ", kStar - print "#Pixels above threshold = ", sum(binImg)/float(maxVal) - print "#Pixels below threshold = ", np.shape(img)[0]**2-sum(binImg)/float(maxVal) + print("Optimal threshold = ", kStar) + print("#Pixels above threshold = ", sum(binImg)/float(maxVal)) + print("#Pixels below threshold = ", np.shape(img)[0]**2-sum(binImg)/float(maxVal)) ax2=fig.add_subplot(122) ax2.contourf(binImg) plt.draw() - raw_input() + input() return kStar,binImg @@ -1882,8 +1917,15 @@ def readBioFormatsMeta(fn): """ + # Try reimport + try: + import bioformats + except: + print("Cannot import bioformats") + + #Change system encoding to UTF 8 - reload(sys) + imp.reload(sys) sys.setdefaultencoding('UTF8') #Load and convert to utf8 @@ -1922,6 +1964,14 @@ def readBioFormats(fn,debug=True,series=0,channel='all'): #javabridge.start_vm(class_path=bioformats.JARS) + + # Try reimport + try: + import bioformats + except: + print("Cannot import bioformats") + + meta=readBioFormatsMeta(fn) #Empty list to put datasets in @@ -2004,9 +2054,9 @@ def checkProblematicStacks(reader,meta,imageIdx,debug=True): except: if debug: printWarning("Loading failed.") - print "Cannot load Image ", imageIdx,"/",meta.image_count - print "channel = ",j, "/",meta.image(imageIdx).Pixels.SizeC - print "zStack = ",k,"/",meta.image(imageIdx).Pixels.SizeZ + print("Cannot load Image ", imageIdx,"/",meta.image_count) + print("channel = ",j, "/",meta.image(imageIdx).Pixels.SizeC) + print("zStack = ",k,"/",meta.image(imageIdx).Pixels.SizeZ) problematicStacks.append(k) return list(np.unique(problematicStacks)) @@ -2041,6 +2091,14 @@ def extractBioFormats(fn,fnOut,debug=True,series=0,channel='all',enc="uint16",sc """ + + # Try reimport + try: + import bioformats + except: + print("Cannot import bioformats") + + # Read files #try: images,meta,fnsLoaded=readBioFormats(fn,debug=debug,series=series,channel=channel) @@ -2060,7 +2118,7 @@ def extractBioFormats(fn,fnOut,debug=True,series=0,channel='all',enc="uint16",sc saveImg(img,fnImg,enc=enc,scale=scale,maxVal=maxVal) if debug: - print "Saved ",fnImg + print("Saved ",fnImg) except: printError("Was not able to save images to " + fnOut) return -1 @@ -2095,8 +2153,8 @@ def runFijiMacro(macroPath,macroArgs,fijiBin=None,debug=False,batch=True): cmd=fijiBin+" -macro "+ macroPath + " '"+macroArgs +"'"+ batch*" -batch " +debug*" -debug" if debug: - print "Executing command:" - print cmd + print("Executing command:") + print(cmd) #Run try: @@ -2104,7 +2162,7 @@ def runFijiMacro(macroPath,macroArgs,fijiBin=None,debug=False,batch=True): return 0 except: printError("Something went wrong executing:" ) - print cmd + print(cmd) return -1 def getImgSmoothness(arr): diff --git a/pyfrp/modules/pyfrp_integration_module.py b/pyfrp/modules/pyfrp_integration_module.py old mode 100644 new mode 100755 diff --git a/pyfrp/modules/pyfrp_misc_module.py b/pyfrp/modules/pyfrp_misc_module.py old mode 100644 new mode 100755 index a2d4862..57b1ede --- a/pyfrp/modules/pyfrp_misc_module.py +++ b/pyfrp/modules/pyfrp_misc_module.py @@ -41,7 +41,7 @@ #=========================================================================================================================================================================== #PyFRAP modules -from pyfrp_term_module import * +from .pyfrp_term_module import * from pyfrp.modules import pyfrp_img_module #PyFRAP subclasses @@ -400,7 +400,7 @@ def vars2dict(var,loc,filt=[]): for name in var: dic[name]=loc[name] - return {name: loc[name] for name, val in var.iteritems()} + return {name: loc[name] for name, val in var.items()} def objAttr2Dict(obj,attr=[]): @@ -471,7 +471,7 @@ def findIntString(s,idxvec=[],debug=False): """ if idxvec==[]: - idxvec=range(len(s)) + idxvec=list(range(len(s))) idxs=[] found=False @@ -625,9 +625,9 @@ def findFn(fn,base,lvlsUp=3,folder=False,debug=False): os.chdir(cwd) if debug: - print "======= find_folder debugging output =======" - print "Could not find file ", fn ," . Going to return False" - print "Closest path found:", fnFound + print("======= find_folder debugging output =======") + print("Could not find file ", fn ," . Going to return False") + print("Closest path found:", fnFound) return OSError @@ -654,20 +654,20 @@ def findPreimage(key,base,lvlsUp=1,fType='tif',debug=False): folderPre=find_fn('pre',base,lvlsUp=lvlsUp,folder=True,debug=debug) if debug: - print "======= find_preimage debugging output =======" + print("======= find_preimage debugging output =======") if not folderPre: if debug: - print "Could not find prefolder with key = ", key ," . Going to return False" + print("Could not find prefolder with key = ", key ," . Going to return False") return folderPre else: files=get_sorted_folder_list(folderPre,fType) if len(files)==0: if debug: - print "Prefolder with key = ", key ," seems to be empty. Going to return False" + print("Prefolder with key = ", key ," seems to be empty. Going to return False") raise OSError("Cannot find preimage") else: - print "Found preimage = ", folderPre+"/"+files[0], " ." + print("Found preimage = ", folderPre+"/"+files[0], " .") return folderPre+"/"+files[0] def updateObj(objBlank,obj,debug=False): @@ -690,7 +690,7 @@ def updateObj(objBlank,obj,debug=False): """ if debug: - print "======update_obj: updated properties======" + print("======update_obj: updated properties======") #Going through all attributes blank object for item in vars(objBlank): @@ -699,7 +699,7 @@ def updateObj(objBlank,obj,debug=False): setattr(obj, str(item), vars(objBlank)[str(item)]) if debug: - print item, " = ", vars(self)[str(item)] + print(item, " = ", vars(self)[str(item)]) return obj @@ -734,7 +734,7 @@ def unzipLists(l): """ - l1,l2=zip(*l) + l1,l2=list(zip(*l)) return list(l1),list(l2) def assignIfVal(var,val,valCheck): @@ -1214,7 +1214,7 @@ def getPath(identifier,fnPath=None,defaultOutput=""): path=None - with open (fnPath,'rb') as f: + with open (fnPath,'r') as f: for line in f: if line.strip().startswith(identifier): ident,path=line.split('=') @@ -1271,7 +1271,7 @@ def printPaths(fnPath=None): with open(fnPath,'rb') as f: for line in f: - print line + print(line) def checkPaths(fnPath=None): @@ -1292,7 +1292,7 @@ def checkPaths(fnPath=None): for line in f: try: ident,val=line.split("=") - print ident, val.strip(), os.path.isfile(val.strip()) + print(ident, val.strip(), os.path.isfile(val.strip())) except ValueError: pass @@ -1802,4 +1802,4 @@ def listToDtype(row,dtype): rowNew=[] for r in row: rowNew.append(dtype(r)) - return rowNew \ No newline at end of file + return rowNew diff --git a/pyfrp/modules/pyfrp_openscad_module.py b/pyfrp/modules/pyfrp_openscad_module.py old mode 100644 new mode 100755 index b860414..7f8a22b --- a/pyfrp/modules/pyfrp_openscad_module.py +++ b/pyfrp/modules/pyfrp_openscad_module.py @@ -38,13 +38,13 @@ import string #PyFRAP modules -import pyfrp_plot_module -from pyfrp_term_module import * -import pyfrp_misc_module -import pyfrp_gmsh_IO_module -import pyfrp_idx_module -import pyfrp_geometry_module -import pyfrp_IO_module +from . import pyfrp_plot_module +from .pyfrp_term_module import * +from . import pyfrp_misc_module +from . import pyfrp_gmsh_IO_module +from . import pyfrp_idx_module +from . import pyfrp_geometry_module +from . import pyfrp_IO_module #Matplotlib from mpl_toolkits.mplot3d.art3d import Poly3DCollection diff --git a/pyfrp/modules/pyfrp_optimization_module.py b/pyfrp/modules/pyfrp_optimization_module.py old mode 100644 new mode 100755 index 55095fa..12636f5 --- a/pyfrp/modules/pyfrp_optimization_module.py +++ b/pyfrp/modules/pyfrp_optimization_module.py @@ -39,9 +39,9 @@ import numpy as np #PyFRAP -import pyfrp_fit_module +from . import pyfrp_fit_module -from pyfrp_term_module import * +from .pyfrp_term_module import * #=========================================================================================================================================================================== #Module Functions diff --git a/pyfrp/modules/pyfrp_plot_module.py b/pyfrp/modules/pyfrp_plot_module.py old mode 100644 new mode 100755 index 8b2f22d..d11d212 --- a/pyfrp/modules/pyfrp_plot_module.py +++ b/pyfrp/modules/pyfrp_plot_module.py @@ -49,8 +49,8 @@ import os #PyFRAP -import pyfrp_img_module -from pyfrp_term_module import * +from . import pyfrp_img_module +from .pyfrp_term_module import * from pyfrp.modules import pyfrp_idx_module #=========================================================================================================================================================================== @@ -622,7 +622,7 @@ def redraw(ax): return ax -def plotTS(xvec,yvec,label='',title='',sup='',ax=None,color=None,linewidth=1,legend=True,linestyle='-',show=True,alpha=1.,legLoc=-1): +def plotTS(xvec,yvec,label='',title='',sup='',ax=None,color=None,linewidth=1,legend=True,linestyle='-',show=True,alpha=1.,legLoc=-1,draw=True): """Plot timeseries all-in-one function. @@ -658,7 +658,7 @@ def plotTS(xvec,yvec,label='',title='',sup='',ax=None,color=None,linewidth=1,leg else: ax.set_title(title) - ax.plot(xvec,yvec,color=color,label=label,linestyle=linestyle,alpha=alpha) + ax.plot(xvec,yvec,color=color,label=label,linestyle=linestyle,alpha=alpha,linewidth=linewidth) if legend: if legLoc==-1: @@ -666,8 +666,9 @@ def plotTS(xvec,yvec,label='',title='',sup='',ax=None,color=None,linewidth=1,leg ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) else: ax.legend(loc=legLoc) - - redraw(ax) + + if draw: + redraw(ax) return ax diff --git a/pyfrp/modules/pyfrp_sim_module.py b/pyfrp/modules/pyfrp_sim_module.py old mode 100644 new mode 100755 index fe39a4d..78d6309 --- a/pyfrp/modules/pyfrp_sim_module.py +++ b/pyfrp/modules/pyfrp_sim_module.py @@ -52,11 +52,11 @@ import sys #PyFRAP Modules -import pyfrp_plot_module -import pyfrp_integration_module -import pyfrp_misc_module -from pyfrp_term_module import * -import pyfrp_idx_module +from . import pyfrp_plot_module +from . import pyfrp_integration_module +from . import pyfrp_misc_module +from .pyfrp_term_module import * +from . import pyfrp_idx_module #=========================================================================================================================================================================== #Module Functions @@ -84,7 +84,7 @@ def simulateReactDiff(simulation,signal=None,embCount=None,showProgress=True,deb simulation (pyfrp.subclasses.pyfrp_simulation.simulation): Simulation object. Keyword Args: - signal (PyQt4.QtCore.pyqtSignal): PyQT signal to send progress to GUI. + signal (PyQt5.QtCore.pyqtSignal): PyQT signal to send progress to GUI. embCount (int): Counter of counter process if multiple datasets are analyzed. debug (bool): Print final debugging messages and show debugging plots. showProgress (bool): Show simulation progress. @@ -104,9 +104,9 @@ def simulateReactDiff(simulation,signal=None,embCount=None,showProgress=True,deb #Empty list to put simulation values in vals=[] - print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" - print "Starting simulation" - print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") + print("Starting simulation") + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") startTimeTotal=time.clock() @@ -118,17 +118,17 @@ def simulateReactDiff(simulation,signal=None,embCount=None,showProgress=True,deb if simulation.mesh.mesh==None: printWarning('No mesh has been generated yet!') - a=raw_input('Do you want to generate a mesh now?[Y/N]') + a=input('Do you want to generate a mesh now?[Y/N]') if a=='Y': simulation.mesh.genMesh() - print "Mesh created in", time.clock()-startTimeMesh + print("Mesh created in", time.clock()-startTimeMesh) else: - print 'Cannot run simulation without mesh, will abort.' + print('Cannot run simulation without mesh, will abort.') return simulation timeMesh=time.clock()-startTimeMesh - print "Mesh created after", time.clock()-startTimeTotal + print("Mesh created after", time.clock()-startTimeTotal) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Initialization of PDE @@ -150,7 +150,7 @@ def simulateReactDiff(simulation,signal=None,embCount=None,showProgress=True,deb phi=applyImperfectICs(phi,simulation,simulation.embryo.geometry.getCenter(),100.,simulation.embryo.sliceHeightPx) elif simulation.ICmode==3: - phi=applyInterpolatedICs(phi,simulation,debug=False) + phi=applyInterpolatedICs(phi,simulation,debug=debug) elif simulation.ICmode==4: phi=applyIdealICs(phi,simulation,bleachedROI=simulation.bleachedROI,valOut=simulation.valOut) @@ -226,9 +226,9 @@ def simulateReactDiff(simulation,signal=None,embCount=None,showProgress=True,deb signal.emit(currPerc,embCount) - print "Step time: ", stepTime, " in %:", stepTime/(time.clock()-startTimeSim)*100 - print "Avg time: ", avgTime, " in %:", avgTime/(time.clock()-startTimeSim)*100 - print "Simulation done after", time.clock()-startTimeTotal + print("Step time: ", stepTime, " in %:", stepTime/(time.clock()-startTimeSim)*100) + print("Avg time: ", avgTime, " in %:", avgTime/(time.clock()-startTimeSim)*100) + print("Simulation done after", time.clock()-startTimeTotal) #Save to simulation object only if simulation.saveSim: @@ -251,7 +251,7 @@ def rerunReactDiff(simulation,signal=None,embCount=None,showProgress=True,debug= simulation (pyfrp.subclasses.pyfrp_simulation.simulation): Simulation object. Keyword Args: - signal (PyQt4.QtCore.pyqtSignal): PyQT signal to send progress to GUI. + signal (PyQt5.QtCore.pyqtSignal): PyQT signal to send progress to GUI. embCount (int): Counter of counter process if multiple datasets are analyzed. debug (bool): Print final debugging messages and show debugging plots. showProgress (bool): Show simulation progress. @@ -387,7 +387,7 @@ def applyRadialICs(phi,simulation,radSteps=15,debug=False): """ #Adjust center so histogram works for 'quad' - if 'quad' in simulation.embryo.analysis.process.keys(): + if 'quad' in list(simulation.embryo.analysis.process.keys()): center=[0,0] else: center=simulation.ICimg,simulation.embryo.geometry.getCenter() @@ -410,7 +410,7 @@ def applyRadialICs(phi,simulation,radSteps=15,debug=False): phi.setValue(binY[i], where=(x-center[0])**2+(y-center[1])**2 < bins[i]**2) if debug: - print "Applied concentration", binY[i], " to all nodes with radius <", bins[i] + print("Applied concentration", binY[i], " to all nodes with radius <", bins[i]) return phi @@ -447,7 +447,7 @@ def applyInterpolatedICs(phi,simulation,matchWithMaster=True,debug=False,fixNeg= center=simulation.embryo.geometry.getCenter() #Define x/y coordinates of interpolation - if 'quad' in simulation.embryo.analysis.process.keys(): + if 'quad' in list(simulation.embryo.analysis.process.keys()): #Shift everything by center to fit with the mesh xInt = np.arange(center[0]+1, center[0]+res+1, 1) yInt = np.arange(center[1]+1, center[1]+res+1, 1) @@ -474,14 +474,14 @@ def applyInterpolatedICs(phi,simulation,matchWithMaster=True,debug=False,fixNeg= indX=pyfrp_misc_module.complValsSimple(masterROI.imgIdxX,indXSqu) indY=pyfrp_misc_module.complValsSimple(masterROI.imgIdxX,indYSqu) - if 'quad' in simulation.embryo.analysis.process.keys(): + if 'quad' in list(simulation.embryo.analysis.process.keys()): img=pyfrp_img_module.unflipQuad(np.flipud(simulation.ICimg)) else: img=simulation.ICimg concRim=pyfrp_img_module.meanConc(img[indX,indY]) - print 'Approximate concRim = ', concRim + print('Approximate concRim = ', concRim) else: concRim=simulation.embryo.analysis.concRim @@ -494,19 +494,22 @@ def applyInterpolatedICs(phi,simulation,matchWithMaster=True,debug=False,fixNeg= ICimg=simulation.ICimg.copy() #Generate interpolation function - f=interp.RectBivariateSpline(xInt, yInt, ICimg.T, bbox=[None, None, None, None], kx=3, ky=3, s=0) + f=interp.RectBivariateSpline(xInt, yInt, ICimg, bbox=[None, None, None, None], kx=3, ky=3, s=0) #Set all values of solution variable to concRim phi.setValue(concRim) #Get Offset of image and check which nodes are inside image - if 'quad' in simulation.embryo.analysis.process.keys(): + if 'quad' in list(simulation.embryo.analysis.process.keys()): offset=[simulation.embryo.dataResPx/2,simulation.embryo.dataResPx/2] ins=pyfrp_idx_module.checkInsideImg(x,y,simulation.embryo.dataResPx/2,offset=offset) else: offset=[0,0] ins=pyfrp_idx_module.checkInsideImg(x,y,simulation.embryo.dataResPx,offset=offset) - + + X2, Y2 = np.meshgrid(xInt,yInt) + + #Convert into indices ind=np.arange(len(x)) ind=ind[np.where(ins)[0]] @@ -527,7 +530,9 @@ def applyInterpolatedICs(phi,simulation,matchWithMaster=True,debug=False,fixNeg= ind=np.asarray(ind) ind=ind[np.where(ins)[0]] ind=list(ind) - + + + #Apply interpolation try: phi.value[ind]=f.ev(x[ind],y[ind]) @@ -536,7 +541,7 @@ def applyInterpolatedICs(phi,simulation,matchWithMaster=True,debug=False,fixNeg= printNote("Changed index array to nparray b/c of IndexError.") ind=np.array(ind) phi.value[ind]=f.ev(x[ind],y[ind]) - + #Fix negative values if selected if fixNeg: phi=fixNegValues(phi) @@ -556,9 +561,14 @@ def fixNegValues(phi,minVal=None): """ + print(phi.value.shape) + print(sum(phi.value>=0)) if minVal==None: - minVal=min(phi.value[np.where(phi.value>=0)[0]]) - + try: + minVal=min(phi.value[np.where(phi.value>=0)[0]]) + except ValueError: + return phi + phi.value[np.where(phi.value<0)[0]]=minVal return phi diff --git a/pyfrp/modules/pyfrp_stats_module.py b/pyfrp/modules/pyfrp_stats_module.py old mode 100644 new mode 100755 index d5b99c3..6a23e3b --- a/pyfrp/modules/pyfrp_stats_module.py +++ b/pyfrp/modules/pyfrp_stats_module.py @@ -253,7 +253,7 @@ def selectDataByOverlapSubSample(d,n,k,thresh,debug=False): if len(dError[idxs].flatten())>0: for i in range(len(idxs[0])): - print "Subsamples ", idxs[0][i],idxs[1][i], " generate error ", dError[idxs[0][i],idxs[1][i]] + print("Subsamples ", idxs[0][i],idxs[1][i], " generate error ", dError[idxs[0][i],idxs[1][i]]) return len(dError[idxs].flatten())>0 @@ -611,9 +611,9 @@ def wilcoxonTest(x,y,zero_method='wilcox', correction=False,printOut=True): stat,pval=scipy.stats.wilcoxon(x, y=y, zero_method=zero_method, correction=correction) if printOut: - print "Results of Wilcoxon-Test:" - print "p-Value: ", pval - print "Wilcoxon-Statistics:", stat + print("Results of Wilcoxon-Test:") + print("p-Value: ", pval) + print("Wilcoxon-Statistics:", stat) return stat,pval @@ -641,9 +641,9 @@ def mannWhitneyUTest(x,y,printOut=True): stat,pval=scipy.stats.mannwhitneyu(x, y) if printOut: - print "Results of Mann-Whitney-U-Test:" - print "p-Value: ", pval - print "U-Statistics:", stat + print("Results of Mann-Whitney-U-Test:") + print("p-Value: ", pval) + print("U-Statistics:", stat) return stat,pval @@ -671,9 +671,9 @@ def tTestStandard(x,y,printOut=True): stat,pval=scipy.stats.ttest_ind(x, y, equal_var=True) if printOut: - print "Results of Standard t-Test:" - print "p-Value: ", pval - print "Statistics:", stat + print("Results of Standard t-Test:") + print("p-Value: ", pval) + print("Statistics:", stat) return stat,pval @@ -701,9 +701,9 @@ def tTestWelch(x,y,printOut=True): stat,pval=scipy.stats.ttest_ind(x, y, equal_var=False) if printOut: - print "Results of Welch's t-Test:" - print "p-Value: ", pval - print "Statistics:", stat + print("Results of Welch's t-Test:") + print("p-Value: ", pval) + print("Statistics:", stat) return stat,pval @@ -730,9 +730,9 @@ def shapiroTest(x,printOut=True): stat,pval=scipy.stats.sharipo(x) if printOut: - print "Results of Sharipo-Test:" - print "p-Value: ", pval - print "Statistics:", stat + print("Results of Sharipo-Test:") + print("p-Value: ", pval) + print("Statistics:", stat) return stat,pval diff --git a/pyfrp/modules/pyfrp_term_module.py b/pyfrp/modules/pyfrp_term_module.py old mode 100644 new mode 100755 index f61499f..09529a9 --- a/pyfrp/modules/pyfrp_term_module.py +++ b/pyfrp/modules/pyfrp_term_module.py @@ -33,7 +33,7 @@ #=========================================================================================================================================================================== import colorama -import PyQt4.QtGui as QtGui +import PyQt5.QtGui as QtGui import numpy as np import inspect @@ -56,7 +56,7 @@ def printWarning(txt,showCall=True,idx=2): """ - print(colorama.Fore.YELLOW + "WARNING "+showCall*("("+getFunctionCall(idx)+")")+": ") + colorama.Fore.RESET + txt + print((colorama.Fore.YELLOW + "WARNING "+showCall*("("+getFunctionCall(idx)+")")+": ") + colorama.Fore.RESET + txt) def printError(txt,showCall=True,idx=2): @@ -72,7 +72,7 @@ def printError(txt,showCall=True,idx=2): """ - print(colorama.Fore.RED + "ERROR "+showCall*("("+getFunctionCall(idx)+")")+": ") + colorama.Fore.RESET + txt + print((colorama.Fore.RED + "ERROR "+showCall*("("+getFunctionCall(idx)+")")+": ") + colorama.Fore.RESET + txt) def printNote(txt,showCall=True,idx=2): @@ -88,7 +88,7 @@ def printNote(txt,showCall=True,idx=2): """ - print(colorama.Fore.GREEN + "NOTE "+showCall*("("+getFunctionCall(idx)+")")+": ") + colorama.Fore.RESET + txt + print((colorama.Fore.GREEN + "NOTE "+showCall*("("+getFunctionCall(idx)+")")+": ") + colorama.Fore.RESET + txt) def printDict(dic,maxL=5): @@ -105,7 +105,7 @@ def printDict(dic,maxL=5): """ - for k in dic.keys(): + for k in list(dic.keys()): printAttr(k,dic[k],maxL=maxL) return True @@ -123,8 +123,8 @@ def printObjAttr(var,obj): """ - print var, " = ", vars(obj)[str(var)] - return var + print(var, " = ", vars(obj)[str(var)]) + return var def printAllObjAttr(obj,maxL=5): @@ -143,7 +143,7 @@ def printAllObjAttr(obj,maxL=5): for item in vars(obj): printAttr(item,vars(obj)[str(item)],maxL=maxL) - print + print() return True def printAttr(name,attr,maxL=5): @@ -164,14 +164,14 @@ def printAttr(name,attr,maxL=5): if isinstance(attr,(list)): if len(attr)>maxL: - print name, " = ", getListDetailsString(attr) + print(name, " = ", getListDetailsString(attr)) return True elif isinstance(attr,(np.ndarray)): if min(attr.shape)>maxL: - print name, " = ", getArrayDetailsString(attr) + print(name, " = ", getArrayDetailsString(attr)) return True - print name, " = ", attr + print(name, " = ", attr) return True @@ -233,7 +233,7 @@ def printTable(l,header,col=False): from tabulate import tabulate - print tabulate(table,headers=header) + print(tabulate(table,headers=header)) return header, table @@ -254,4 +254,4 @@ def getFunctionCall(idx=1): try: return inspect.getouterframes(frame)[idx][3] except IndexError: - return "" \ No newline at end of file + return "" diff --git a/pyfrp/modules/pyfrp_vtk_module.py b/pyfrp/modules/pyfrp_vtk_module.py old mode 100644 new mode 100755 index 6b6f4f9..59a35c1 --- a/pyfrp/modules/pyfrp_vtk_module.py +++ b/pyfrp/modules/pyfrp_vtk_module.py @@ -48,8 +48,8 @@ import os #PyFRAP -import pyfrp_img_module -from pyfrp_term_module import * +from . import pyfrp_img_module +from .pyfrp_term_module import * from pyfrp.modules import pyfrp_idx_module #=========================================================================================================================================================================== @@ -617,7 +617,7 @@ def meshToUnstructeredGrid(mesh): points.InsertNextPoint(x[i], y[i],z[i]) # Insert tetrahedrons - verts=mesh._getOrderedCellVertexIDs().T + verts=mesh._orderedCellVertexIDs.T cellArray = vtk.vtkCellArray() for j,vert in enumerate(verts): diff --git a/pyfrp/modules/pyfrp_zstack_module.py b/pyfrp/modules/pyfrp_zstack_module.py old mode 100644 new mode 100755 index c65a441..24db6fd --- a/pyfrp/modules/pyfrp_zstack_module.py +++ b/pyfrp/modules/pyfrp_zstack_module.py @@ -50,7 +50,7 @@ import sys #PyFRAP -import pyfrp_integration_module as pyfrp_integr +from . import pyfrp_integration_module as pyfrp_integr #=========================================================================================================================================================================== #Module Functions @@ -67,13 +67,21 @@ def getContours(img,kernel=(10,10)): #Open to erode small patches thresh = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) + plt.imshow(thresh) + plt.show() + #Close little holes thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE,kernel, iterations=4) + plt.imshow(thresh) + plt.show() #Find contours #contours=skimsr.find_contours(thresh,0) - thresh=thresh.astype('uint8') + #thresh=thresh.astype('uint8') + thresh=(thresh/256).astype('uint8') + plt.imshow(thresh) + plt.show() contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) areas=[] @@ -107,7 +115,7 @@ def fillEndStacks(n,debug=False): x=mpolys[i][:,1].min()+rx*(mpolys[i][:,1].max()-mpolys[i][:,1].min()) y=mpolys[i][:,0].min()+ry*(mpolys[i][:,0].max()-mpolys[i][:,0].min()) - poly=zip(list(mpolys[i][:,1]),list(mpolys[i][:,0])) + poly=list(zip(list(mpolys[i][:,1]),list(mpolys[i][:,0]))) if point_inside_polygon(x,y,poly): @@ -123,7 +131,7 @@ def fillEndStacks(n,debug=False): xvec=arange(mpolys[i][:,1].min(),mpolys[i][:,1].max(),d) yvec=arange(mpolys[i][:,0].min(),mpolys[i][:,0].max(),d) - poly=zip(list(mpolys[i][:,1]),list(mpolys[i][:,0])) + poly=list(zip(list(mpolys[i][:,1]),list(mpolys[i][:,0]))) for x in xvec: for y in yvec: @@ -144,7 +152,7 @@ def fillEndStacks(n,debug=False): if debug==1: plt.draw() - raw_input("Done filling first and last zstack, press ENTER to continue") + input("Done filling first and last zstack, press ENTER to continue") #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------- @@ -277,4 +285,4 @@ def point_inside_polygon(x,y,poly): inside = not inside p1x,p1y = p2x,p2y - return inside \ No newline at end of file + return inside diff --git a/pyfrp/subclasses/__init__.py b/pyfrp/subclasses/__init__.py old mode 100644 new mode 100755 index 4a637cd..1ade185 --- a/pyfrp/subclasses/__init__.py +++ b/pyfrp/subclasses/__init__.py @@ -15,7 +15,7 @@ if platform.system() in ["Darwin"]: import matplotlib - matplotlib.use('qt4agg') + matplotlib.use('qt5agg') #PyFRAP classes from . import pyfrp_analysis diff --git a/pyfrp/subclasses/pyfrp_ROI.py b/pyfrp/subclasses/pyfrp_ROI.py old mode 100644 new mode 100755 index b9a644c..8455aca --- a/pyfrp/subclasses/pyfrp_ROI.py +++ b/pyfrp/subclasses/pyfrp_ROI.py @@ -105,7 +105,7 @@ def __init__(self,embryo,name,Id,zmin='-inf',zmax='inf',color='b'): self.extMask=None #Number of extended pixels - self.numExt=None + self.numExt=0 # None #Result Dataseries self.dataVec=[] @@ -780,7 +780,7 @@ def showMeshIdx(self,ax=None): return ax - def showMeshIdx2D(self,ax=None): + def showMeshIdx2D(self,ax=None,transpose=True): @@ -793,8 +793,13 @@ def showMeshIdx2D(self,ax=None): #Somehow need to convert to np array since slicing does not work for fipy variables x=np.asarray(x)[self.meshIdx] y=np.asarray(y)[self.meshIdx] - - ax.scatter(x,y,c=self.color) + + if transpose: + ax.scatter(y,x,c=self.color) + + else: + ax.scatter(x,y,c=self.color) + plt.draw() return ax @@ -831,6 +836,7 @@ def computeIdxs(self,matchMesh=False,debug=False): """ + if self.embryo.getMasterROIIdx()==None: printWarning("No Master ROI has been defined yet. Will not continue compute ROI indices.") return self.getAllIdxs() @@ -844,12 +850,12 @@ def computeIdxs(self,matchMesh=False,debug=False): startIdx=time.clock() + if type(self) is not customROI: - self.computeImgIdx(debug=debug) + self.computeImgIdx(debug=debug) self.matchImgIdx(masterROI) self.computeExtIdx(debug=debug) - if self.embryo.simulation!=None: if self.embryo.simulation.mesh.mesh==None: printWarning("Mesh has not been generated, will not compute meshIdxs") @@ -869,9 +875,9 @@ def computeIdxs(self,matchMesh=False,debug=False): if self.embryo.simulation!=None: if self.embryo.simulation.mesh.mesh!=None: self.matchMeshIdx(masterROI) - + if debug: - print 'Compute Idxs: ', startIdx-time.clock() + print('Compute Idxs: ', startIdx-time.clock()) return self.getAllIdxs() @@ -916,6 +922,14 @@ def matchImgIdx(self,r): """ self.computeImgMask() + # r.computeImgMask() + + # fig,axes=plt.subplots(1,2) + # fig.show() + # axes[0].imshow(self.imgMask) + # axes[1].imshow(r.imgMask) + # plt.draw() + self.imgMask=self.imgMask*r.computeImgMask() self.imgIdxX,self.imgIdxY=pyfrp_idx_module.mask2ind(self.imgMask,self.embryo.dataResPx) return self.imgIdxX,self.imgIdxY @@ -1033,7 +1047,7 @@ def resetSimVec(self): self.setSimVec([]) return self - def plotData(self,ax=None,color=None,linewidth=1,legend=True,linestyle='-',label=None,legLoc=-1): + def plotData(self,ax=None,color=None,linewidth=1,legend=True,linestyle='-',label=None,legLoc=-1,draw=True): """Plot data vector of ROI. @@ -1059,11 +1073,11 @@ def plotData(self,ax=None,color=None,linewidth=1,legend=True,linestyle='-',label label=self.name + ' simulated' ax = pyfrp_plot_module.plotTS(self.embryo.tvecData,self.dataVec,ax=ax,linewidth=linewidth,color=color,label=self.name + ' data', - title="Data",sup=self.name+" data",linestyle=linestyle,legend=legend,legLoc=legLoc) + title="Data",sup=self.name+" data",linestyle=linestyle,legend=legend,legLoc=legLoc,draw=draw) return ax - def plotDataPinned(self,ax=None,color=None,linewidth=1,legend=True,linestyle='-',label=None,legLoc=-1): + def plotDataPinned(self,ax=None,color=None,linewidth=1,legend=True,linestyle='-',label=None,legLoc=-1,draw=True): """Plot pinned data vector of ROI. @@ -1089,7 +1103,7 @@ def plotDataPinned(self,ax=None,color=None,linewidth=1,legend=True,linestyle='-' label=self.name + ' simulated' ax = pyfrp_plot_module.plotTS(self.embryo.tvecData,self.dataVecPinned,ax=ax,linewidth=linewidth,color=color,label=self.name + ' data', - title="Data Pinned",sup=self.name+" data",linestyle=linestyle,legend=legend,legLoc=legLoc) + title="Data Pinned",sup=self.name+" data",linestyle=linestyle,legend=legend,legLoc=legLoc,draw=draw) return ax @@ -1373,7 +1387,7 @@ def getSimConc(self,phi,append=True): """ - cvs=self.embryo.simulation.mesh.mesh.getCellVolumes() + cvs=self.embryo.simulation.mesh.getCellVolumes() c=pyfrp_integration_module.getAvgConc(phi,cvs,self.meshIdx) @@ -1507,7 +1521,7 @@ def getdataVecFitted(self,fit): fit.dataVecsFitted.insert(fit.ROIsFitted.index(self),[]) return [] - def plotFit(self,fit,ax=None,color=None,linewidth=1,legend=True,title=None,linestyles=['-','-.'],show=True): + def plotFit(self,fit,ax=None,color=None,linewidth=1,legend=True,title=None,linestyles=['-','-.'],show=True,draw=True): """Plot fit for ROI. @@ -1533,10 +1547,10 @@ def plotFit(self,fit,ax=None,color=None,linewidth=1,legend=True,title=None,lines title="Fit "+fit.name ax = pyfrp_plot_module.plotTS(fit.tvecFit,self.getFittedVec(fit),ax=ax,linewidth=linewidth,color=color, - label=self.name + ' ' + fit.name,title=title,sup=self.name+" fitted",linestyle=linestyles[1],legend=legend,show=show) + label=self.name + ' ' + fit.name,title=title,sup=self.name+" fitted",linestyle=linestyles[1],legend=legend,show=show,draw=draw) ax = pyfrp_plot_module.plotTS(fit.tvecFit,self.getdataVecFitted(fit),ax=ax,linewidth=linewidth,color=color, - label=self.name + ' ' + fit.name,title=title,sup=self.name+" fitted",linestyle=linestyles[0],legend=legend,show=show) + label=self.name + ' ' + fit.name,title=title,sup=self.name+" fitted",linestyle=linestyles[0],legend=legend,show=show,draw=draw) return ax @@ -1652,8 +1666,8 @@ def refineInMeshByField(self,factor=3.,addZ=15.,findIdxs=True,debug=False,run=Tr zExtend=[zExtend[0]-addZ,zExtend[1]+addZ] if debug: - print "Adding Box Field for ROI " + self.name - print "Mesh Nodes in ROI before: ", len(self.meshIdx) + print("Adding Box Field for ROI " + self.name) + print("Mesh Nodes in ROI before: ", len(self.meshIdx)) fnOut=self.embryo.simulation.mesh.addBoxField(self.embryo.simulation.mesh.volSizePx/factor,xExtend,yExtend,zExtend,comment=self.name+" field",run=run,fnOut=fnOut) @@ -1661,7 +1675,7 @@ def refineInMeshByField(self,factor=3.,addZ=15.,findIdxs=True,debug=False,run=Tr self.computeMeshIdx(self.embryo.simulation.mesh) if debug and findIdxs: - print "Mesh Nodes in ROI after: ", len(self.meshIdx) + print("Mesh Nodes in ROI after: ", len(self.meshIdx)) return fnOut @@ -1737,40 +1751,40 @@ def adaptRefineInMeshByField(self,nNodesReq,factor=3.,addZ=15.,zIncrement=1.,fIn #Print out current status if debug: - print "Iteration ", i, ". " - print "Current parameters: addZ = ", addZ, " factor = ", factor - print "Total mesh nodes: ", nNodesAllNew - print "Mesh Nodes in ROI before refinement: " , nNodesROI, " and after ", nNodesROINew, "." + print("Iteration ", i, ". ") + print("Current parameters: addZ = ", addZ, " factor = ", factor) + print("Total mesh nodes: ", nNodesAllNew) + print("Mesh Nodes in ROI before refinement: " , nNodesROI, " and after ", nNodesROINew, ".") if ROIReq!=None: - print "Mesh Nodes in ROIReq before refinement: " , nNodesROIReq, " and after ", nNodesROIReqNew, "." + print("Mesh Nodes in ROIReq before refinement: " , nNodesROIReq, " and after ", nNodesROIReqNew, ".") #Check if nNodes requirement is met if nNodesNewnNodesMax: if debug: - print "Number of nodes exceeded maximum allowed number", nNodesMax, "." + print("Number of nodes exceeded maximum allowed number", nNodesMax, ".") if mode==0: if debug: - print "Previously tried to increase addZ. Will try old addZ, but increase factor by " ,fIncrement,". \n" + print("Previously tried to increase addZ. Will try old addZ, but increase factor by " ,fIncrement,". \n") addZ=addZ-zIncrement factor=factor+fIncrement mode=1 elif mode==1: if debug: - print "Previously tried to increase factor. Will try old factor, but increase addZ by " ,zIncrement,". \n" + print("Previously tried to increase factor. Will try old factor, but increase addZ by " ,zIncrement,". \n") addZ=addZ+zIncrement factor=factor-fIncrement mode=0 @@ -1790,9 +1804,9 @@ def printDetails(self): """Prints out all attributes of ROI object.""" - print "ROI ", self.name, " details:" + print("ROI ", self.name, " details:") printAllObjAttr(self) - print + print() def plotSimConcProfile(self,phi,ax=None,direction='x',mode='normal',nbins=20,color=None,label=None,legend=False): @@ -2396,7 +2410,7 @@ def makeReducable(self,auto=False,debug=False): self.center2Mid() if not auto: - a=raw_input("Change center of region "+ self.name + " from " + str(oldCenter) + ' to ' + str(self.getCenter()) + ' ? [Y/N]') + a=input("Change center of region "+ self.name + " from " + str(oldCenter) + ' to ' + str(self.getCenter()) + ' ? [Y/N]') if a=='N': self.setCenter(oldCenter) @@ -2891,7 +2905,7 @@ def showBoundary(self,color=None,linewidth=3,ax=None): img=np.nan*np.ones((self.embryo.dataResPx,self.embryo.dataResPx)) ax.imshow(img) - patch = ptc.Rectangle(self.offset,self.sidelength,self.sidelength,fill=False,linewidth=linewidth,color=color) + patch = ptc.Rectangle(np.flip(self.offset),self.sidelength,self.sidelength,fill=False,linewidth=linewidth,color=color) ax.add_patch(patch) return ax @@ -2907,7 +2921,7 @@ def makeReducable(self,auto=False,debug=False): self.centerOffset() if not auto: - a=raw_input("Change offset of region "+ self.name + " from " + str(oldOffset) + ' to ' + str(self.getOffset()) + ' ? [Y/N]') + a=input("Change offset of region "+ self.name + " from " + str(oldOffset) + ' to ' + str(self.getOffset()) + ' ? [Y/N]') if a=='N': self.setOffset(oldOffset) @@ -3294,7 +3308,7 @@ def makeReducable(self,atuo=False,debug=False): self.centerOffset() if not auto: - a=raw_input("Change offset of region "+ self.name + " from " + str(oldOffset) + ' to ' + str(self.getOffset()) + ' ? [Y/N]') + a=input("Change offset of region "+ self.name + " from " + str(oldOffset) + ' to ' + str(self.getOffset()) + ' ? [Y/N]') if a=='N': self.setOffset(oldOffset) @@ -3662,7 +3676,8 @@ def showBoundary(self,color=None,linewidth=3,ax=None): img=np.nan*np.ones((self.embryo.dataResPx,self.embryo.dataResPx)) ax.imshow(img) - patch = ptc.Rectangle(self.corners,closed=True,fill=False,linewidth=linewidth,color=color) + patch = ptc.Polygon(np.flip(self.corners),closed=True,fill=False,linewidth=linewidth,color=color) + #patch = ptc.Polygon(self.corners,closed=True,fill=False,linewidth=linewidth,color=color) ax.add_patch(patch) return ax @@ -3696,7 +3711,7 @@ def computeXYExtend(self): """ - cornersNP=np.array(corners) + cornersNP=np.array(self.corners) xmax=cornersNP[:,0].max() xmin=cornersNP[:,0].min() @@ -4150,4 +4165,4 @@ def genAsOpenscad(self): return openScadROI - \ No newline at end of file + diff --git a/pyfrp/subclasses/pyfrp_analysis.py b/pyfrp/subclasses/pyfrp_analysis.py old mode 100644 new mode 100755 index 9aadbc2..d34ff01 --- a/pyfrp/subclasses/pyfrp_analysis.py +++ b/pyfrp/subclasses/pyfrp_analysis.py @@ -131,7 +131,7 @@ def run(self,signal=None,embCount=None,debug=False,debugAll=False,showProgress=T data analysis. Keyword Args: - signal (PyQt4.QtCore.pyqtSignal): PyQT signal to send progress to GUI. + signal (PyQt5.QtCore.pyqtSignal): PyQT signal to send progress to GUI. embCount (int): Counter of counter process if multiple datasets are analyzed. debug (bool): Print final debugging messages and show debugging plots. debugAll (bool): Print debugging messages and show debugging plots of each step. @@ -574,7 +574,7 @@ def normOn(self): """ - return 'norm' in self.process.keys() + return 'norm' in list(self.process.keys()) def bkgdOn(self): @@ -585,7 +585,7 @@ def bkgdOn(self): """ - return 'bkgd' in self.process.keys() + return 'bkgd' in list(self.process.keys()) def flattenOn(self): @@ -596,7 +596,7 @@ def flattenOn(self): """ - return 'flatten' in self.process.keys() + return 'flatten' in list(self.process.keys()) def gaussianOn(self): @@ -607,7 +607,7 @@ def gaussianOn(self): """ - return 'gaussian' in self.process.keys() + return 'gaussian' in list(self.process.keys()) def medianOn(self): @@ -618,7 +618,7 @@ def medianOn(self): """ - return 'median' in self.process.keys() + return 'median' in list(self.process.keys()) def quadOn(self): @@ -629,7 +629,7 @@ def quadOn(self): """ - return 'quad' in self.process.keys() + return 'quad' in list(self.process.keys()) def flipBeforeProcessOn(self): @@ -640,22 +640,22 @@ def flipBeforeProcessOn(self): """ - return 'flipBeforeProcess' in self.process.keys() + return 'flipBeforeProcess' in list(self.process.keys()) def updateProcess(self): """Updates all values in process dictionary with the ones saved in attributes of analysis object.""" - if 'flatten' in self.process.keys(): + if 'flatten' in list(self.process.keys()): self.process['flatten']=self.fnFlatten - if 'norm' in self.process.keys(): + if 'norm' in list(self.process.keys()): self.process['norm']=self.fnPreimage - if 'bkgd' in self.process.keys(): + if 'bkgd' in list(self.process.keys()): self.process['bkgd']=self.fnBkgd - if 'gaussian' in self.process.keys(): + if 'gaussian' in list(self.process.keys()): self.process['gaussian']=self.gaussianSigma - if 'median' in self.process.keys(): + if 'median' in list(self.process.keys()): self.process['median']=self.medianRadius return @@ -671,7 +671,7 @@ def printAllAttr(self): """Prints out all attributes of analysis object.""" - print "Analysis of embryo ", self.embryo.name, " Details." + print("Analysis of embryo ", self.embryo.name, " Details.") printAllObjAttr(self) def parm2Process(self,b,key,val): diff --git a/pyfrp/subclasses/pyfrp_conf.py b/pyfrp/subclasses/pyfrp_conf.py old mode 100644 new mode 100755 diff --git a/pyfrp/subclasses/pyfrp_embryo.py b/pyfrp/subclasses/pyfrp_embryo.py old mode 100644 new mode 100755 index 3903f32..b279e94 --- a/pyfrp/subclasses/pyfrp_embryo.py +++ b/pyfrp/subclasses/pyfrp_embryo.py @@ -44,11 +44,11 @@ from pyfrp.modules.pyfrp_term_module import * #PyFRAP Objects -import pyfrp_geometry -import pyfrp_simulation -import pyfrp_analysis -import pyfrp_ROI -import pyfrp_fit +from . import pyfrp_geometry +from . import pyfrp_simulation +from . import pyfrp_analysis +from . import pyfrp_ROI +from . import pyfrp_fit #matplotlib import matplotlib.pyplot as plt @@ -218,8 +218,8 @@ def save(self,fn=None,copyMeshFiles=True,debug=False): if copyMeshFiles: - print "before copyMeshFiles:", fn - print "fnGeo", self.geometry.fnGeo + #print("before copyMeshFiles:", fn) + #print("fnGeo", self.geometry.fnGeo) fnGeo,fnMesh=pyfrp_IO_module.copyMeshFiles(fn,self.geometry.fnGeo,self.simulation.mesh.fnMesh,debug=debug) self.geometry.setFnGeo(fnGeo) @@ -230,7 +230,7 @@ def save(self,fn=None,copyMeshFiles=True,debug=False): pyfrp_IO_module.saveToPickle(self,fn=fn) - print "Saved "+ self.name+ " to " + fn + print("Saved "+ self.name+ " to " + fn) return fn def renameMeshFiles(self,fn=None,debug=False): @@ -496,7 +496,7 @@ def getDataResPx(self): def getDataResMu(self): - """Returns resolution of data in :math:`\um m` .""" + """Returns resolution of data in :math:`\\um m` .""" return self.dataResMu @@ -1046,7 +1046,7 @@ def listROIs(self): """Prints out all ROIs and their respective type.""" for r in self.ROIs: - print r.name , type(r) + print(r.name , type(r)) return True def genDefaultROIs(self,center,radius,rimFactor=0.66,masterROI=None,bleachedROI=None,rimROI=None,sliceHeightPx=None,clean=True): @@ -1532,7 +1532,7 @@ def computeROIIdxs(self,signal=None,debug=True): """Computes image, extended and mesh indices of all ROIs in embryo's ``ROIs`` list. Keyword Args: - signal (PyQt4.QtCore.pyqtSignal): PyQT signal to send progress to GUI. + signal (PyQt5.QtCore.pyqtSignal): PyQT signal to send progress to GUI. debug (bool): Print final debugging messages and show debugging plots. Returns: @@ -1544,7 +1544,7 @@ def computeROIIdxs(self,signal=None,debug=True): r.computeIdxs() if debug: - print r.name, time.clock()-startInit + print(r.name, time.clock()-startInit) if signal: signal.emit(int(100.*i)/float(len(self.ROIs))) @@ -1676,7 +1676,7 @@ def ROIs2Full(self): r.idxs2Full() return self.ROIs - def showAllROIBoundaries(self,ax=None,withImg=False,idx=0): + def showAllROIBoundaries(self,ax=None,withImg=False,idx=0,**kwargs): """Shows boundaries of all ROIs in ``ROIs`` list. @@ -1694,7 +1694,7 @@ def showAllROIBoundaries(self,ax=None,withImg=False,idx=0): for r in self.ROIs: if hasattr(r,'showBoundary'): - ax=r.showBoundary(ax=ax) + ax=r.showBoundary(ax=ax,**kwargs) if withImg: ax=self.showDataImg(ax=ax,idx=idx) @@ -1763,14 +1763,14 @@ def showAllROIIdxs(self,axes=None): fig,axes = pyfrp_plot_module.makeSubplot([3,len(self.ROIs)],sup=["Embryo" + self.name + " ROI Indices"],tight=True,proj=proj) for i,r in enumerate(self.ROIs): - print r.name + print(r.name) currAxes=[axes[0+i],axes[len(self.ROIs)+i],axes[2*len(self.ROIs)+i]] r.showIdxs(axes=currAxes) return axes - def plotAllData(self,ax=None,legend=True): + def plotAllData(self,ax=None,legend=True,draw=True,**kwargs): """Plots all data timeseries for all ROIs in ``ROIs`` list. @@ -1786,7 +1786,7 @@ def plotAllData(self,ax=None,legend=True): """ for r in self.ROIs: - ax=r.plotData(ax=ax,legend=legend) + ax=r.plotData(ax=ax,legend=legend,draw=draw,**kwargs) return ax @@ -1813,7 +1813,7 @@ def plotAllSim(self,ax=None,legend=True): return ax - def plotAllDataPinned(self,ax=None,legend=True): + def plotAllDataPinned(self,ax=None,legend=True,draw=True,**kwargs): """Plots all pinned data timeseries for all ROIs in ``ROIs`` list. @@ -1829,7 +1829,7 @@ def plotAllDataPinned(self,ax=None,legend=True): """ for r in self.ROIs: - ax=r.plotDataPinned(ax=ax,legend=legend) + ax=r.plotDataPinned(ax=ax,legend=legend,draw=draw,**kwargs) return ax @@ -2134,15 +2134,15 @@ def computeIdealFRAPPinVals(self,bkgdName='Bleached Square',normName='Slice',deb normValSim=normNsim normVal=normNdata - print "in switch" + print("in switch") if debug: printNote('Switched to region ' + normName + ' for computation of normalization value.' ) else: - print normBdata+bkgdBdata, normBsim+bkgdBsim + print(normBdata+bkgdBdata, normBsim+bkgdBsim) - print "not in switch" + print("not in switch") normVal=max([normBdata,normBsim]) if sepSim: normValSim=normBsim @@ -2242,7 +2242,7 @@ def getInterpolationError(self): """ for r in self.ROIs: - print r.name, r.getInterpolationError() + print(r.name, r.getInterpolationError()) def checkROIIdxs(self,debug=False): @@ -2434,9 +2434,9 @@ def compareFitsByAIC(self,ROIs=None,sigma=1,fromSSD=True,thresh=None,printOut=Tr fitNames = pyfrp_misc_module.objAttrToList(self.fits,'name') printNote("Acceptable fits under threshold "+ str(thresh) +":") for fit in acc: - print fit.name + print(fit.name) - print "Details of AIC analysis can be found in the following table:" + print("Details of AIC analysis can be found in the following table:") printTable([fitNames,AICs,deltaAICs,weights,ks,ns],["fitNames","AICs","deltaAICs","weights","k","n"],col=True) return AICs, deltaAICs,weights, acc,ks,ns @@ -2478,9 +2478,9 @@ def compareFitsByCorrAIC(self,ROIs=None,sigma=1,fromSSD=True,thresh=None,printOu fitNames = pyfrp_misc_module.objAttrToList(self.fits,'name') printNote("Acceptable fits under threshold "+ str(thresh) +":") for fit in acc: - print fit.name + print(fit.name) - print "Details of AIC analysis can be found in the following table:" + print("Details of AIC analysis can be found in the following table:") printTable([fitNames,AICs,deltaAICs,weights,ks,ns],["fitNames","AICcs","deltaAICs","weights","k","n"],col=True) return AICs, deltaAICs,weights, acc,ks,ns @@ -2533,4 +2533,4 @@ def fixFilePaths(self): #def grabDataDetails(self): - ###NOTE make a function that automatically grabs filetype and what not \ No newline at end of file + ###NOTE make a function that automatically grabs filetype and what not diff --git a/pyfrp/subclasses/pyfrp_fit.py b/pyfrp/subclasses/pyfrp_fit.py old mode 100644 new mode 100755 index 31add7a..7ed9411 --- a/pyfrp/subclasses/pyfrp_fit.py +++ b/pyfrp/subclasses/pyfrp_fit.py @@ -454,7 +454,7 @@ def runBruteInit(self,debug=False,ax=None,steps=5,x0Ds=[]): for x0D in x0Ds: if debug: - print "Trying x0(D) = ", x0D + print("Trying x0(D) = ", x0D) self.setX0D(x0D) self=pyfrp_fit_module.FRAPFitting(self,debug=debug,ax=ax) @@ -464,7 +464,7 @@ def runBruteInit(self,debug=False,ax=None,steps=5,x0Ds=[]): idxOpt=SSDs.index(min(SSDs)) if debug: - print "x0(D) yielding best result = ", x0Ds[idxOpt] + print("x0(D) yielding best result = ", x0Ds[idxOpt]) self.setX0D(x0Ds[idxOpt]) self=pyfrp_fit_module.FRAPFitting(self,debug=debug,ax=ax) @@ -544,7 +544,7 @@ def assignOptParms(self,res): return self.DOptPx, self.prodOpt, self.degrOpt, self.DOptMu - def plotFit(self,ax=None,legend=True,title=None,show=True): + def plotFit(self,ax=None,draw=True,legend=True,title=None,show=True,**kwargs): """Plots fit, showing the result for all fitted ROIs. @@ -564,7 +564,7 @@ def plotFit(self,ax=None,legend=True,title=None,show=True): """ for r in self.ROIsFitted: - ax=r.plotFit(self,ax=ax,legend=legend,title=title,show=show) + ax=r.plotFit(self,ax=ax,legend=legend,title=title,show=show,draw=draw,**kwargs) return ax @@ -1291,7 +1291,7 @@ def printRsqByROI(self): """Prints out Rsq value per ROI. """ - print "Rsq Values by ROI for fit ", self.name + print("Rsq Values by ROI for fit ", self.name) printDict(self.RsqByROI) def getNParmsFitted(self,inclEqu=True): diff --git a/pyfrp/subclasses/pyfrp_geometry.py b/pyfrp/subclasses/pyfrp_geometry.py old mode 100644 new mode 100755 index b515f51..a85976e --- a/pyfrp/subclasses/pyfrp_geometry.py +++ b/pyfrp/subclasses/pyfrp_geometry.py @@ -234,7 +234,7 @@ def centerInImg(self): oldCenter=self.getCenter() self.centerMid() - a=raw_input("Change center of geometry from " + oldCenter + ' to ' + self.getCenter() + ' ? [Y/N]') + a=input("Change center of geometry from " + oldCenter + ' to ' + self.getCenter() + ' ? [Y/N]') if a=='Y': self.updateGeoFile() if None!=self.embryo.simulation: @@ -419,9 +419,9 @@ def printDetails(self): """Prints out all details of geometry object. """ - print "Geometry of embryo ", self.embryo.name, " Details." + print("Geometry of embryo ", self.embryo.name, " Details.") printAllObjAttr(self) - print + print() def moveGeoFile(self,fn): diff --git a/pyfrp/subclasses/pyfrp_mesh.py b/pyfrp/subclasses/pyfrp_mesh.py old mode 100644 new mode 100755 index 4320a15..a17e12e --- a/pyfrp/subclasses/pyfrp_mesh.py +++ b/pyfrp/subclasses/pyfrp_mesh.py @@ -161,7 +161,7 @@ def restoreDefaults(self): self.volSizePx=20. self.fnMesh="" - def genMesh(self,fnOut=None,debug=False): + def genMesh(self,fnOut=None,debug=False,gmshBin=None): """Main mesh generation function. @@ -189,7 +189,7 @@ def genMesh(self,fnOut=None,debug=False): if self.fromFile: self.fnMesh=pyfrp_misc_module.fixPath(fnOut) - pyfrp_gmsh_module.runGmsh(self.simulation.embryo.geometry.fnGeo,fnOut=fnOut,debug=debug,volSizeMax=self.volSizePx,dim=dim) + pyfrp_gmsh_module.runGmsh(self.simulation.embryo.geometry.fnGeo,fnOut=fnOut,debug=debug,volSizeMax=self.volSizePx,dim=dim,gmshBin=gmshBin) self.importMeshFromFile(self.fnMesh) else: @@ -252,9 +252,16 @@ def importMeshFromFile(self,fn): dim=3 if dim==3: - self.mesh=fipy.GmshImporter3D(fn) + try: + self.mesh=fipy.GmshImporter3D(fn) + except AttributeError: + self.mesh=fipy.Gmsh3D(fn) elif dim==2: - self.mesh=fipy.GmshImporter2D(fn) + try: + self.mesh=fipy.GmshImporter2D(fn) + except AttributeError: + self.mesh=fipy.Gmsh2D(fn) + else: printError("Unknown dimensionality dim = "+str(dim)) self.fnMesh=fn @@ -408,13 +415,13 @@ def forceMinMeshDensityInROI(self,ROI,density,stepPercentage=0.1,debug=False,fin #Debugging output if debug: if method=='volSize': - print "Tried volSizePx ", self.getVolSizePx() + print("Tried volSizePx ", self.getVolSizePx()) elif method=='refine': - print "Refinement step, ", j + print("Refinement step, ", j) - print "Current density ", ROI.getMeshDensity(), " desired density ", density - print "Current number of nodes in ROI ", len(ROI.meshIdx) - print " Mesh now has ", np.shape(self.mesh.x)[0], "cells." + print("Current density ", ROI.getMeshDensity(), " desired density ", density) + print("Current number of nodes in ROI ", len(ROI.meshIdx)) + print(" Mesh now has ", np.shape(self.mesh.x)[0], "cells.") #Check if we reached maxCells if np.shape(self.mesh.x)[0]>maxCells: @@ -428,7 +435,7 @@ def forceMinMeshDensityInROI(self,ROI,density,stepPercentage=0.1,debug=False,fin j=j+1 if debug: - print "volSizePx = ", self.getVolSizePx(), "is sufficient." + print("volSizePx = ", self.getVolSizePx(), "is sufficient.") #Recompute idxs for all ROIs if findIdxs: @@ -450,7 +457,9 @@ def getNNodes(self): if self.mesh==None: return 0 else: - return len(self.mesh.getCellCenters()[0]) + return len(self.getCellCenters()[0]) + + def writeVTKFile(self,fn="",sub=False): @@ -703,29 +712,29 @@ def printStats(self,tetLenghts=False): x,y,z = self.getCellCenters() - print "-------------------------------------------" - print "Mesh Statistics:" - print "-------------------------------------------" - print "Mesh has ", np.shape(x)[0] , " cells" - print "Mesh has ", self.mesh._numberOfVertices, " vertices" - print "Mesh has ", self.mesh.numberOfFaces, " faces" - print "min x=", min(x), "max x=", max(x) - print "min y=", min(y), "max y=", max(y) - print "min z=", min(z), "max z=", max(z) - print "Maximum cell volume= ", max(self.mesh.getCellVolumes()) - print "Minimum cell volume= ", min(self.mesh.getCellVolumes()) + print("-------------------------------------------") + print("Mesh Statistics:") + print("-------------------------------------------") + print("Mesh has ", np.shape(x)[0] , " cells") + print("Mesh has ", self.mesh._numberOfVertices, " vertices") + print("Mesh has ", self.mesh.numberOfFaces, " faces") + print("min x=", min(x), "max x=", max(x)) + print("min y=", min(y), "max y=", max(y)) + print("min z=", min(z), "max z=", max(z)) + print("Maximum cell volume= ", max(self.getCellVolumes())) + print("Minimum cell volume= ", min(self.getCellVolumes())) - print "Maximum cell volume is", max(self.mesh.getCellVolumes()), "in cell number=", np.argmax(self.mesh.getCellVolumes()) - print "Minimum cell volume is", min(self.mesh.getCellVolumes()), "in cell number=", np.argmin(self.mesh.getCellVolumes()) - print "Average cell volume is", np.mean(self.mesh.getCellVolumes()) + print("Maximum cell volume is", max(self.getCellVolumes()), "in cell number=", np.argmax(self.getCellVolumes())) + print("Minimum cell volume is", min(self.getCellVolumes()), "in cell number=", np.argmin(self.getCellVolumes())) + print("Average cell volume is", np.mean(self.getCellVolumes())) if tetLenghts: slsVec=self.calcAllTetSidelenghts() - print "Average sidelength of tetrahedron in self.mesh:", np.mean(slsVec) - print "Maximum sidelength of tetrahedron in self.mesh:", max(slsVec) - print "Minimum sidelength of tetrahedron in self.mesh:", min(slsVec) + print("Average sidelength of tetrahedron in self.mesh:", np.mean(slsVec)) + print("Maximum sidelength of tetrahedron in self.mesh:", max(slsVec)) + print("Minimum sidelength of tetrahedron in self.mesh:", min(slsVec)) - print + print() return @@ -741,8 +750,8 @@ def calcAllTetSidelenghts(self): #Calculating sidelengths of tetrahedra slsVec=[] - for i in range(np.shape(self.mesh._getOrderedCellVertexIDs())[1]): - currVert=self.mesh._getOrderedCellVertexIDs()[:,i] + for i in range(np.shape(self.getOrderedCellVertexIDs())[1]): + currVert=self.getOrderedCellVertexIDs()[:,i] pt1=self.mesh.vertexCoords[:,currVert[0]] pt2=self.mesh.vertexCoords[:,currVert[1]] @@ -782,9 +791,9 @@ def plotDensity(self,axes=None,hist=True,bins=100,color='b'): x,y,z=self.getCellCenters() - volSortedByX,xSorted=pyfrp_misc_module.sortListsWithKey(self.mesh.getCellVolumes(),x) - volSortedByY,ySorted=pyfrp_misc_module.sortListsWithKey(self.mesh.getCellVolumes(),y) - volSortedByZ,zSorted=pyfrp_misc_module.sortListsWithKey(self.mesh.getCellVolumes(),z) + volSortedByX,xSorted=pyfrp_misc_module.sortListsWithKey(self.getCellVolumes(),x) + volSortedByY,ySorted=pyfrp_misc_module.sortListsWithKey(self.getCellVolumes(),y) + volSortedByZ,zSorted=pyfrp_misc_module.sortListsWithKey(self.getCellVolumes(),z) if axes==None: fig,axes = pyfrp_plot_module.makeSubplot([1,3],titles=["Density(x)","Density(y)","Density(z)"]) @@ -877,7 +886,7 @@ def printAllAttr(self): """Prints out all attributes of mesh object.""" - print "Mesh of embryo ", self.simulation.embryo.name, " Details." + print("Mesh of embryo ", self.simulation.embryo.name, " Details.") printAllObjAttr(self) def addBoxField(self,volSizeIn,rangeX,rangeY,rangeZ,newFile=True,fnAppendix="_box",comment="newField",run=False,fnOut=None): @@ -1097,10 +1106,47 @@ def getCellCenters(self): if self.mesh==None: return [],[],[] - if len(self.mesh.getCellCenters())==3: - return self.mesh.getCellCenters() + try: + cellCenters=self.mesh.getCellCenters() + except AttributeError: + cellCenters=self.mesh.cellCenters + + if len(cellCenters)==3: + return cellCenters else: - z=self.simulation.embryo.sliceHeightPx*np.ones((len(self.mesh.getCellCenters()[0]),)) - return self.mesh.getCellCenters()[0],self.mesh.getCellCenters()[1],z + z=self.simulation.embryo.sliceHeightPx*np.ones((len(cellCenters[0]),)) + return cellCenters[0],cellCenters[1],z + + + def getOrderedCellVertexIDs(self): + + """Returns ordered cell vertex IDs. + """ + + + + try: + ret=self.mesh._getOrderedCellVertexIDs() + except AttributeError: + ret=self.mesh._orderedCellVertexIDs + + return ret + + + def getCellVolumes(self): + + try: + cellVolumes=self.mesh.getCellVolumes() + except AttributeError: + cellVolumes=self.mesh.cellVolumes + return cellVolumes + + + + #def getCellCenters(): - \ No newline at end of file + #try: + #cellCenters=self.mesh.getCellCenters() + #except AttributeError: + #cellCenters=self.mesh.cellCenters + #return cellCenters diff --git a/pyfrp/subclasses/pyfrp_molecule.py b/pyfrp/subclasses/pyfrp_molecule.py old mode 100644 new mode 100755 index a566605..b55b589 --- a/pyfrp/subclasses/pyfrp_molecule.py +++ b/pyfrp/subclasses/pyfrp_molecule.py @@ -39,7 +39,7 @@ from pyfrp.modules import pyfrp_stats_module #PyFRAP Classes -import pyfrp_embryo +from . import pyfrp_embryo #Standard packages import os @@ -262,7 +262,7 @@ def extractEmbryos2Files(self,fn="",copyMeshFiles=True,debug=False): printError("Could not create " + fn+ ". Will not extract." ) return False - print "in mol.extract:", fn + print("in mol.extract:", fn) for embryo in self.embryos: embryo.save(fn=fn+embryo.getName()+".emb",copyMeshFiles=copyMeshFiles,debug=debug) @@ -401,7 +401,7 @@ def sumUpResults(self,sameSettings=False): same,different,notInBoth=pyfrp_misc_module.compareObjAttr(lastFit,fit) for item in self.crucialParameters: - if item in different.keys(): + if item in list(different.keys()): printError("Cannot average fits, since fits " + lastFit.name + " and " + fit.name + "do not have the same value for " + item +". However, this parameter is marked as crucial.") return False elif item in notInBoth: diff --git a/pyfrp/subclasses/pyfrp_simulation.py b/pyfrp/subclasses/pyfrp_simulation.py old mode 100644 new mode 100755 index 4b50b95..84159e2 --- a/pyfrp/subclasses/pyfrp_simulation.py +++ b/pyfrp/subclasses/pyfrp_simulation.py @@ -37,7 +37,7 @@ import scipy.interpolate as interp #PyFRAP classes -import pyfrp_mesh +from . import pyfrp_mesh #PyFRAP modules from pyfrp.modules import pyfrp_plot_module @@ -229,7 +229,7 @@ def setICMode(self,m): """ - if m not in range(5): + if m not in list(range(5)): printError("ICmode = " + m + " is not defined. Not going to change ICmode" ) return self.ICmode @@ -277,7 +277,7 @@ def run(self,signal=None,embCount=None,showProgress=True,debug=False): object to :py:func:`pyfrp.modules.pyfrp_sim_module.simulateReactDiff`. Keyword Args: - signal (PyQt4.QtCore.pyqtSignal): PyQT signal to send progress to GUI. + signal (PyQt5.QtCore.pyqtSignal): PyQT signal to send progress to GUI. embCount (int): Counter of counter process if multiple datasets are simulated. debug (bool): Print debugging messages and show debugging plots. showProgress (bool): Print out progress. @@ -398,7 +398,7 @@ def showIC(self,ax=None,roi=None,nlevels=25,vmin=None,vmax=None,typ='contour',sc """ - if self.IC!=None: + if self.IC is not None: if ax==None: if typ=='surface': @@ -461,7 +461,7 @@ def showICimg(self,ax=None,typ='contour',colorbar=True,scale=True,nlevels=25,vmi printError("Unknown plot type "+ typ) return ax - if self.ICimg!=None: + if self.ICimg is not None: if vmin==None: vmin=min(self.ICimg.flatten()) @@ -478,7 +478,7 @@ def showICimg(self,ax=None,typ='contour',colorbar=True,scale=True,nlevels=25,vmi ax=axes[0] res=self.ICimg.shape[0] - if 'quad' in self.embryo.analysis.process.keys(): + if 'quad' in list(self.embryo.analysis.process.keys()): X,Y=np.meshgrid(np.arange(res,2*res),np.arange(res,2*res)) else: X,Y=np.meshgrid(np.arange(res),np.arange(res)) @@ -521,7 +521,7 @@ def computeInterpolatedICImg(self): center=self.embryo.geometry.getCenter() #Define x/y coordinates of interpolation - if 'quad' in self.embryo.analysis.process.keys(): + if 'quad' in list(self.embryo.analysis.process.keys()): #Shift everything by center to fit with the mesh xInt = np.arange(center[0]+1, center[0]+res+1, 1) yInt = np.arange(center[1]+1, center[1]+res+1, 1) @@ -1090,7 +1090,7 @@ def getSolutionVariableSmoothness(self,vals,roi=None): if roi!=None: idxs=roi.meshIdx else: - idxs=range(len(x)) + idxs=list(range(len(x))) x=np.asarray(x)[idxs] y=np.asarray(y)[idxs] @@ -1157,7 +1157,7 @@ def rerun(self,signal=None,embCount=None,showProgress=True,debug=False): See also :py:func:`pyfrp.modules.pyfrp_sim_module.rerunReactDiff`. Keyword Args: - signal (PyQt4.QtCore.pyqtSignal): PyQT signal to send progress to GUI. + signal (PyQt5.QtCore.pyqtSignal): PyQT signal to send progress to GUI. embCount (int): Counter of counter process if multiple datasets are simulated. debug (bool): Print debugging messages and show debugging plots. showProgress (bool): Print out progress. @@ -1196,7 +1196,7 @@ def printAllAttr(self): """Prints out all attributes of embryo object.""" - print "Simulation of embryo ", self.embryo.name, " Details." + print("Simulation of embryo ", self.embryo.name, " Details.") printAllObjAttr(self) def mapOntoImgs(self,tvec=None,roi=None,fnOut="",showProgress=True,method='linear',fillVal=0.,scale=True,enc='uint16',res=None): @@ -1238,7 +1238,7 @@ def mapOntoImgs(self,tvec=None,roi=None,fnOut="",showProgress=True,method='linea fnOut=pyfrp_misc_module.slashToFn(fnOut)+self.embryo.name+"_sim_" #Output - print "Saving ", len(tvec), " images of simulation to ", fnOut + print("Saving ", len(tvec), " images of simulation to ", fnOut) #Loop all tvec and build images j=0 @@ -1261,7 +1261,7 @@ def mapOntoImgs(self,tvec=None,roi=None,fnOut="",showProgress=True,method='linea pyfrp_img_module.saveImg(img,fnOut+"t"+enum+".tif",scale=scale,enc=enc) if showProgress: - print "Saved for t=", t ," to ", fnOut+"t"+enum+".tif" + print("Saved for t=", t ," to ", fnOut+"t"+enum+".tif") return True @@ -1274,7 +1274,7 @@ def visualize(self,cut=False,app=None): add a cutter that allows to cut through the 3D simulation and display single slices, see also :py:class:`pyfrp.gui.pyfrp_gui_vtk.vtkSimVisualizerCutter`. Cutter only works for 3D simulations. - If no application is specified, will launch a new ``QtGui.QApplication``. + If no application is specified, will launch a new ``QtWidgets.QApplication``. .. note:: Simulation results must be saved in ``simulation`` object via ``saveSim=True``. @@ -1292,7 +1292,7 @@ def visualize(self,cut=False,app=None): Keyword Args: cut (bool): Visualize with cutter. - app (QtGui.QApplication): Some application. + app (QtWidgets.QApplication): Some application. """ @@ -1308,9 +1308,11 @@ def visualize(self,cut=False,app=None): # Import right module from gui submodule from pyfrp.gui import pyfrp_gui_vtk + from PyQt5 import QtGui, QtCore, QtWidgets + # Create QApplication if app==None: - app = QtGui.QApplication([]) + app = QtWidgets.QApplication([]) if cut: widget=pyfrp_gui_vtk.vtkSimVisualizerCutter(self.embryo) @@ -1318,4 +1320,4 @@ def visualize(self,cut=False,app=None): widget=pyfrp_gui_vtk.vtkSimVisualizer(self.embryo) app.exec_() - \ No newline at end of file + diff --git a/pyfrp/tests/modules/test_gmsh_IO_module.py b/pyfrp/tests/modules/test_gmsh_IO_module.py old mode 100644 new mode 100755 diff --git a/pyfrp/tests/modules/test_gmsh_geometry.py b/pyfrp/tests/modules/test_gmsh_geometry.py old mode 100644 new mode 100755 diff --git a/qt4_to_qt5.py b/qt4_to_qt5.py new file mode 100755 index 0000000..1639140 --- /dev/null +++ b/qt4_to_qt5.py @@ -0,0 +1,152 @@ +"""Script to search for PyQt4 specific strings and replace it with PyQt5 version. + +""" + +import os +import sys +import shutil +from tempfile import mkstemp + +def txtLineReplace(filePath, pattern, subst): + + """Replaces line in file that starts with ``pattern`` and substitutes it + with ``subst``. + + .. note:: Will create temporary file using ``tempfile.mkstemp()``. You should have + read/write access to whereever ``mkstemp`` is putting files. + + Args: + filePath (str): Filename. + pattern (str): Pattern to be looked for. + subst (str): String used as a replacement. + + """ + + + #Create temp file + fh, absPath = mkstemp() + newFile = open(absPath,'w') + oldFile = open(filePath) + + #Loop through file and replace line + for line in oldFile: + + if pattern in line: + newFile.write(line.replace(pattern, subst)) + else: + newFile.write(line) + + #close temp file + newFile.close() + os.close(fh) + oldFile.close() + + #Remove original file + os.remove(filePath) + + #Move new file + shutil.move(absPath, filePath) + return + +def getAllImportantFiles(fn,ftype='.py'): + + # Get all files + filesNew=[] + for root, dirs, files in os.walk(fn): + for name in files: + filesNew.append(os.path.join(root,name)) + + files=filterStrList(filesNew,ftype) + + return files + +def findAllOccurences(fn,s): + + """Finds all occurences of string s in file.""" + + lineNo=[] + fnFound=[] + lines=[] + N=0 + + try: + with open(fn,'r') as f: + + for i,line in enumerate(f): + if s in line: + lineNo.append(i) + fnFound.append(fn) + lines.append(line) + N=N+line.count(s) + except IOError: + print("Skipped file ", fn) + return fnFound,lines,lineNo,N + +def filterStrList(l,s,endswith=True): + + """Finds all entries in list that contain ``s``. """ + + lnew=[] + for x in l: + if endswith: + if x.endswith(s): + lnew.append(x) + else: + if s in x: + lnew.append(x) + + return lnew + +def replace_signal(lines,signal,val=""): + + """Replaces signal with new one.""" + + signal_str=", QtCore.SIGNAL('%s(%s)'), "%(signal,val) + + lines_new=[] + for line in lines: + if signal_str in line: + + + s,line=line.split('.connect(') + line=line.replace(signal_str,'.%s.connect('%signal) + + n_tab=s.count('\t') + line=n_tab*'\t'+line + + lines_new.append(line) + else: + lines_new.append(line) + + return lines_new + + +def read_file(fn): + + lines=[] + with open(fn,'r') as f: + for line in f: + lines.append(line) + + return lines + +def write_file(fn,lines): + + with open(fn,'w') as f: + for line in lines: + f.write(line) + + +files=getAllImportantFiles(os.getcwd()) + +for fn in files: + lines=read_file(fn) + + + lines=replace_signal(lines,'clicked') + lines=replace_signal(lines,'stateChanged',val='int') + + + write_file(fn,lines) + + diff --git a/requirements.txt b/requirements.txt old mode 100644 new mode 100755 index a4bb31f..ecd9f15 --- a/requirements.txt +++ b/requirements.txt @@ -6,11 +6,12 @@ numpy>=1.14 scipy>=0.13.3 matplotlib>=1.4.3 scikit-image>=0.11.3 +future FiPy>=3.1 -PyQt4 +PyQt5 colorama>=0.2.5 VTK>=5.8.0 numpy-stl solidpython wget -python-bioformats \ No newline at end of file +python-bioformats diff --git a/runPyFRAP.bat b/runPyFRAP.bat old mode 100644 new mode 100755 diff --git a/setup.py b/setup.py old mode 100644 new mode 100755 index 7273b74..78d56ce --- a/setup.py +++ b/setup.py @@ -190,7 +190,9 @@ def getPermDetails(self): gid=os.getgid() #Mode for files (everyone can read/write/execute. This is somewhat an overkill, but 0666 seems somehow not to work.) - mode=0777 + #mode="0777" + mode="0o777" + return uid,gid,mode @@ -662,16 +664,22 @@ def setExePath(self,fn,identifier,exePath): #Open file and enter new gmsh bin with open(fn,'rb') as fPath: - with open(fn+"_new",'wb') as fPathNew: + with open(fn+"_new",'w') as fPathNew: for line in fPath: - if line.strip().startswith(identifier): - ident,path=line.split('=') + if line.decode().strip().startswith(identifier): + ident,path=line.decode().split('=') path=path.strip() lineNew=ident+"="+fnPyfrp+exePath - fPathNew.write(lineNew+'\n') + # try: + # fPathNew.write(lineNew.decode()+'\n') + # except AttributeError: + lineNew='%s\n'%lineNew + fPathNew.write(lineNew) else: - fPathNew.write(line) - + try: + fPathNew.write(line.decode()) + except AttributeError: + fPathNew.write(line) #Rename file shutil.move(fn+'_new',fn) @@ -724,7 +732,7 @@ def changePermissions(self,filepath,uid,gid,mode): try: if not self.silent: - log.info("Changing permissions of %s to %s" %(filepath, oct(mode))) + log.info("Changing permissions of %s to %s" %(filepath, mode)) os.chmod(filepath, mode) except: if not self.silent: @@ -767,7 +775,7 @@ def makeAdditionalDataFolders(self,folder,fn,uid,gid,mode): #Check if setup.py is used to build RTD, then don't overwrite install command if os.environ.get('READTHEDOCS', None) == 'True': - print "Installing on RTD, will not overwrite install command." + print("Installing on RTD, will not overwrite install command.") setup(name='pyfrp', version=version,