spam-gui 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
spam_gui/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ # Copyright (C) 2020 SPAM Contributors
2
+ #
3
+ # This program is free software: you can redistribute it and/or modify it
4
+ # under the terms of the GNU General Public License as published by the Free
5
+ # Software Foundation, either version 3 of the License, or (at your option)
6
+ # any later version.
7
+ #
8
+ # This program is distributed in the hope that it will be useful, but WITHOUT
9
+ # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
+ # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
11
+ # more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License along with
14
+ # this program. If not, see <http://www.gnu.org/licenses/>.
15
+
16
+ """
17
+ spam-gui: graphical modules for spam, in a napari viewer.
18
+
19
+ A bar at the top of the window selects the module and shows its numbered steps;
20
+ the options of the current step are on the left, napari's layer controls and
21
+ layer list on the right (see :mod:`spam_gui.gui.window`). All modules display their
22
+ images in the same viewer.
23
+
24
+ Start it with the ``spam-gui`` command, or from napari:
25
+ ``Plugins > spam > spam-gui``.
26
+
27
+ Install: ``pip install spam-gui`` (it installs spam and napari).
28
+
29
+ Adding a module: write a subclass of :class:`spam_gui.gui.steps.StepModule`
30
+ in ``spam_gui/modules/`` and add it to ``MODULES`` in ``spam_gui/modules/__init__.py``.
31
+ """
spam_gui/app.py ADDED
@@ -0,0 +1,98 @@
1
+ # Copyright (C) 2020 SPAM Contributors
2
+ #
3
+ # This program is free software: you can redistribute it and/or modify it
4
+ # under the terms of the GNU General Public License as published by the Free
5
+ # Software Foundation, either version 3 of the License, or (at your option)
6
+ # any later version.
7
+ #
8
+ # This program is distributed in the hope that it will be useful, but WITHOUT
9
+ # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
+ # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
11
+ # more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License along with
14
+ # this program. If not, see <http://www.gnu.org/licenses/>.
15
+
16
+ """``spam-gui``: opens a napari viewer with the spam-gui panel."""
17
+
18
+ import argparse
19
+ import os
20
+ import platform
21
+
22
+
23
+ def _platformDefaults():
24
+ """
25
+ On Linux, use X11 (xcb), also in a Wayland session: under Wayland, a program cannot place its windows
26
+ (pop-ups at the centre of the window, the window kept within its screen), and napari's OpenGL drawing
27
+ may fail (it does under WSL). A Wayland choice in ``QT_QPA_PLATFORM`` is replaced; another one is kept.
28
+
29
+ With xcb, Qt draws with GLX: PyOpenGL must look for Qt's drawing context there too, while in a Wayland
30
+ session it would look for it with EGL, and fail (« Attempt to retrieve context when no valid context »).
31
+ So ``PYOPENGL_PLATFORM`` is set to ``glx``, unless the user has chosen otherwise.
32
+ """
33
+ if platform.system() != "Linux":
34
+ return
35
+ if not os.environ.get("QT_QPA_PLATFORM") or os.environ["QT_QPA_PLATFORM"].startswith("wayland"):
36
+ os.environ["QT_QPA_PLATFORM"] = "xcb"
37
+ if os.environ["QT_QPA_PLATFORM"] == "xcb":
38
+ os.environ.setdefault("PYOPENGL_PLATFORM", "glx")
39
+
40
+
41
+ def version():
42
+ """The version of spam-gui installed (from its git tag, when it was built), or « unknown »."""
43
+ from importlib.metadata import PackageNotFoundError
44
+ from importlib.metadata import version as installed
45
+
46
+ try:
47
+ return installed("spam-gui")
48
+ except PackageNotFoundError:
49
+ return "unknown"
50
+
51
+
52
+ def parser(modules):
53
+ """The command line: ``spam-gui [MODULE [its arguments]]``, a subcommand per module (its ``command``)."""
54
+ main = argparse.ArgumentParser(
55
+ prog="spam-gui",
56
+ usage="spam-gui [-h] [MODULE [its arguments]]",
57
+ description="spam-gui: graphical modules for spam, in a napari viewer. Without a module named, it opens the module used last.",
58
+ epilog="The arguments of a module: spam-gui MODULE --help (e.g., spam-gui mmr --help).",
59
+ )
60
+ main.add_argument("--version", action="version", version=f"spam-gui {version()}")
61
+ subcommands = main.add_subparsers(dest="module", title="modules", metavar="MODULE")
62
+ for cls in modules:
63
+ sub = subcommands.add_parser(cls.command, help=f"{cls.name}: {cls.description}", description=f"{cls.name}: {cls.description}")
64
+ cls.addArguments(sub)
65
+ return main
66
+
67
+
68
+ def script():
69
+ _platformDefaults() # (before napari, Qt and OpenGL are imported: with the modules)
70
+ try:
71
+ from spam_gui.modules import MODULES
72
+ except ImportError as error:
73
+ raise SystemExit(f"spam-gui cannot start: {error}")
74
+ args = parser(MODULES).parse_args()
75
+
76
+ import napari
77
+ from napari.settings import get_settings
78
+
79
+ from spam_gui import settings
80
+ from spam_gui.gui.window import installSpamWindow
81
+
82
+ commands = [cls.command for cls in MODULES]
83
+ if args.module is not None:
84
+ index = commands.index(args.module)
85
+ else: # no module named: the one used last (the first one, the very first time)
86
+ last = settings.lastModule()
87
+ index = commands.index(last) if last in commands else 0
88
+ firstTime = get_settings().application.window_size is None # no window size kept from a previous session
89
+ viewer = napari.Viewer(title="spam")
90
+ spamWindow = installSpamWindow(viewer, index)
91
+ spamWindow.fitToScreen(maximise=firstTime) # within its screen (maximised the first time, or if it does not fit)
92
+ if args.module is not None:
93
+ spamWindow.modules[index].useArguments(args)
94
+ napari.run()
95
+
96
+
97
+ if __name__ == "__main__":
98
+ script()
@@ -0,0 +1,19 @@
1
+ # Copyright (C) 2020 SPAM Contributors
2
+ #
3
+ # This program is free software: you can redistribute it and/or modify it
4
+ # under the terms of the GNU General Public License as published by the Free
5
+ # Software Foundation, either version 3 of the License, or (at your option)
6
+ # any later version.
7
+ #
8
+ # This program is distributed in the hope that it will be useful, but WITHOUT
9
+ # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
+ # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
11
+ # more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License along with
14
+ # this program. If not, see <http://www.gnu.org/licenses/>.
15
+
16
+ """
17
+ What the modules compute from the images without Qt or napari: calculations on large images by parts, volumes
18
+ computed on demand for display, reading images, Φ conversions. No image analysis: that is spam's (SPEC.md 1).
19
+ """
spam_gui/core/io.py ADDED
@@ -0,0 +1,186 @@
1
+ # Copyright (C) 2020 SPAM Contributors
2
+ #
3
+ # This program is free software: you can redistribute it and/or modify it
4
+ # under the terms of the GNU General Public License as published by the Free
5
+ # Software Foundation, either version 3 of the License, or (at your option)
6
+ # any later version.
7
+ #
8
+ # This program is distributed in the hope that it will be useful, but WITHOUT
9
+ # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
+ # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
11
+ # more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License along with
14
+ # this program. If not, see <http://www.gnu.org/licenses/>.
15
+
16
+ """
17
+ Reading 3D images (a TIFF file, or a folder of TIFF slices): their size and type, mapped from their file when it
18
+ can be, read by parts in threads, binned (``spam.DIC.binning``) a few slices at a time. No Qt, no napari.
19
+ """
20
+
21
+ import contextlib
22
+ import os
23
+ import threading
24
+
25
+ import numpy
26
+
27
+ from spam_gui.core.parts import allocate, block, runParts
28
+
29
+
30
+ def readVolume(path):
31
+ """Read a 3D image from a TIFF file, or from a folder of TIFF slices."""
32
+ import tifffile
33
+
34
+ if os.path.isdir(path):
35
+ import spam.helpers
36
+
37
+ return spam.helpers.stackToArray(path)
38
+ return tifffile.imread(path)
39
+
40
+
41
+ def _sliceFiles(folder):
42
+ """The TIFF slices of a folder, in the order of ``spam.helpers.stackToArray``."""
43
+ import glob
44
+
45
+ return sorted(glob.glob(os.path.join(folder, "*.tif*")))
46
+
47
+
48
+ def volumeInfo(path):
49
+ """(shape, dtype) of the 3D image in a TIFF file or a folder of TIFF slices, without reading its voxels."""
50
+ import tifffile
51
+
52
+ if os.path.isdir(path):
53
+ files = _sliceFiles(path)
54
+ if not files:
55
+ raise ValueError(f"no TIFF slices in {path}")
56
+ with tifffile.TiffFile(files[0]) as tif:
57
+ page = tif.pages[0]
58
+ return (len(files),) + tuple(page.shape), numpy.dtype(page.dtype)
59
+ with tifffile.TiffFile(path) as tif:
60
+ series = tif.series[0]
61
+ return tuple(series.shape), numpy.dtype(series.dtype)
62
+
63
+
64
+ BINNING_TYPES = (numpy.dtype("<u1"), numpy.dtype("<u2"), numpy.dtype("<f4")) # spam.DIC.binning gives zeros for others
65
+ READ_VOXELS = 2**23 # voxels of an image mapped from its file that are read at once, by each thread, to bin it
66
+
67
+
68
+ def mapVolume(path):
69
+ """
70
+ The 3D image of a TIFF file, mapped from the file (a read-only ``numpy.memmap``: its voxels are read
71
+ from the file when they are used, they are not loaded in memory); None if it cannot be: a folder of
72
+ slices, or a file that is compressed, tiled, or not a 3D image.
73
+ """
74
+ import tifffile
75
+
76
+ if os.path.isdir(path):
77
+ return None
78
+ try:
79
+ volume = tifffile.memmap(path, mode="r")
80
+ except Exception:
81
+ return None
82
+ if volume.ndim != 3:
83
+ return None
84
+ if isinstance(volume, numpy.memmap) and volume.flags.c_contiguous and volume.filename is not None:
85
+ volume.spamFile = (str(volume.filename), int(volume.offset)) # its boxes are read from the file (spam_gui.core.parts.block)
86
+ return volume
87
+
88
+
89
+ @contextlib.contextmanager
90
+ def _slices(path, shape):
91
+ """
92
+ A function reading slice ``z`` of the 3D image (of shape ``shape``) of a folder of TIFF slices, or of
93
+ a TIFF file with a page per slice; None for a file with another layout (it is then read whole).
94
+ """
95
+ import tifffile
96
+
97
+ if os.path.isdir(path):
98
+ files = _sliceFiles(path)
99
+ yield lambda z: tifffile.imread(files[z])
100
+ return
101
+ with tifffile.TiffFile(path) as tif:
102
+ if len(tif.pages) == shape[0] and tuple(tif.pages[0].shape) == tuple(shape[1:]):
103
+ lock = threading.Lock() # one file: its pages are read one at a time, whatever the thread
104
+
105
+ def read(z):
106
+ with lock:
107
+ return tif.pages[z].asarray()
108
+
109
+ yield read
110
+ else:
111
+ yield None
112
+
113
+
114
+ def openVolume(path, report=None, cancelled=None):
115
+ """
116
+ The 3D image of a TIFF file or of a folder of TIFF slices, at full resolution, without loading it in
117
+ memory when that can be avoided: mapped from its file if it can be (:func:`mapVolume`); otherwise read
118
+ a slice at a time, in threads, into memory if it fits there, else into a scratch file mapped in memory
119
+ (:func:`spam_gui.core.parts.allocate`). ``report`` and ``cancelled``: see :func:`spam_gui.core.parts.runParts`.
120
+ """
121
+ volume = mapVolume(path)
122
+ if volume is not None:
123
+ if report is not None:
124
+ report(1.0)
125
+ return volume
126
+ shape, dtype = volumeInfo(path)
127
+ if len(shape) != 3:
128
+ raise ValueError(f"{path} is not a 3D image (shape {shape})")
129
+ with _slices(path, shape) as read:
130
+ if read is None:
131
+ return readVolume(path)
132
+ out = allocate(shape, dtype, share=0.5)
133
+
134
+ def one(z):
135
+ out[z] = read(z)
136
+
137
+ runParts(one, range(shape[0]), report, cancelled)
138
+ return out
139
+
140
+
141
+ def readBinned(path, binning, report=None, cancelled=None):
142
+ """
143
+ The 3D image of a TIFF file or a folder of TIFF slices, binned as ``spam.DIC.binning`` bins it
144
+ (types other than uint8, uint16 and float32 in float32); not binned (``binning`` 1): see :func:`openVolume`.
145
+ The image is read and binned a few slices at a time, in threads, so that the whole image is never in
146
+ memory. ``report`` and ``cancelled``: see :func:`spam_gui.core.parts.runParts`.
147
+ """
148
+ import spam.DIC
149
+
150
+ binning = int(binning)
151
+ if binning == 1:
152
+ return openVolume(path, report, cancelled)
153
+ shape, dtype = volumeInfo(path)
154
+ work = dtype if dtype in BINNING_TYPES else numpy.dtype("<f4")
155
+ if len(shape) != 3:
156
+ raise ValueError(f"{path} is not a 3D image (shape {shape})")
157
+ first = (shape[0] % binning) // 2 # spam.DIC.binning leaves out the first voxels of what does not fit
158
+ out = numpy.empty([n // binning for n in shape], dtype=work)
159
+ volume = mapVolume(path)
160
+ if volume is not None: # mapped from its file: several slices of the result at a time
161
+ per = max(1, READ_VOXELS // (shape[1] * shape[2] * binning))
162
+
163
+ def several(k0):
164
+ k1 = min(out.shape[0], k0 + per)
165
+ chunk = block(volume, (first + k0 * binning, 0, 0), (first + k1 * binning, shape[1], shape[2]))
166
+ out[k0:k1] = spam.DIC.binning(numpy.ascontiguousarray(chunk).astype(work, copy=False), binning)
167
+
168
+ runParts(several, range(0, out.shape[0], per), report, cancelled)
169
+ return out
170
+ with _slices(path, shape) as read:
171
+ if read is None: # other layouts: read whole
172
+ return spam.DIC.binning(readVolume(path).astype(work, copy=False), binning)
173
+
174
+ def one(k):
175
+ chunk = numpy.stack([read(first + k * binning + j) for j in range(binning)]).astype(work, copy=False)
176
+ out[k] = spam.DIC.binning(chunk, binning)[0]
177
+
178
+ runParts(one, range(out.shape[0]), report, cancelled)
179
+ return out
180
+
181
+
182
+ def volumeName(path):
183
+ """Layer name for a file or folder: its base name without extension."""
184
+ base = os.path.basename(os.path.normpath(path))
185
+ root, ext = os.path.splitext(base)
186
+ return root if ext.lower() in (".tif", ".tiff") else base