particle-pack-tools 0.0.7__tar.gz

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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: particle-pack-tools
3
+ Version: 0.0.7
4
+ Summary: A toolkit for processing and visualizing particle pack data.
5
+ Author-email: Bogong Wang <bogongwang.dev@outlook.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/bogongwang/particle-pack-tools
8
+ Project-URL: Repository, https://github.com/bogongwang/particle-pack-tools
9
+ Keywords: particle pack,tools,visualization,data processing,particle pack
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.11
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: xarray>=2025.1
16
+ Requires-Dist: dask>=2025.1
17
+ Requires-Dist: netCDF4>=1.7.2
18
+ Requires-Dist: scikit-image>=0.25.0
19
+ Requires-Dist: scipy>=1.15.0
20
+ Requires-Dist: numpy>=1.25.0
21
+ Requires-Dist: numba>=0.60.0
22
+ Requires-Dist: matplotlib>=3.10.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=7.0; extra == "dev"
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest>=7.0; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # Particle Pack Tools
30
+
31
+ ## Installation
32
+ To install the package, run:
33
+ ```
34
+ pip install particle-pack-tools
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ ### Dataset I/O
40
+ Load particle pack datasets using:
41
+ ```
42
+ from pptools.io import load_nc, load_nc_arr
43
+ ```
44
+
45
+ ### Dataset Preprocessing
46
+ Preprocess particle pack datasets with:
47
+ ```
48
+ from pptools.preprocess import crop_3d
49
+ # ...additional preprocessing functions...
50
+ ```
51
+
52
+ ### Dataset Visualization
53
+ Visualize particle pack datasets using the `Visualizer` class:
54
+ ```
55
+ from pptools.visualize import Visualizer
56
+
57
+ # Initialize the visualizer
58
+ vis = Visualizer()
59
+
60
+ # Plot a tomogram
61
+ vis.plot_tomo(tomo_img)
62
+ vis.show()
63
+
64
+ # Plot a multi-label mask
65
+ vis.plot_mask(mask_img)
66
+ vis.show()
67
+ ```
68
+
69
+ ---
70
+
71
+ Feel free to report any issues or share suggestions to help improve this toolkit.
@@ -0,0 +1,43 @@
1
+ # Particle Pack Tools
2
+
3
+ ## Installation
4
+ To install the package, run:
5
+ ```
6
+ pip install particle-pack-tools
7
+ ```
8
+
9
+ ## Usage
10
+
11
+ ### Dataset I/O
12
+ Load particle pack datasets using:
13
+ ```
14
+ from pptools.io import load_nc, load_nc_arr
15
+ ```
16
+
17
+ ### Dataset Preprocessing
18
+ Preprocess particle pack datasets with:
19
+ ```
20
+ from pptools.preprocess import crop_3d
21
+ # ...additional preprocessing functions...
22
+ ```
23
+
24
+ ### Dataset Visualization
25
+ Visualize particle pack datasets using the `Visualizer` class:
26
+ ```
27
+ from pptools.visualize import Visualizer
28
+
29
+ # Initialize the visualizer
30
+ vis = Visualizer()
31
+
32
+ # Plot a tomogram
33
+ vis.plot_tomo(tomo_img)
34
+ vis.show()
35
+
36
+ # Plot a multi-label mask
37
+ vis.plot_mask(mask_img)
38
+ vis.show()
39
+ ```
40
+
41
+ ---
42
+
43
+ Feel free to report any issues or share suggestions to help improve this toolkit.
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: particle-pack-tools
3
+ Version: 0.0.7
4
+ Summary: A toolkit for processing and visualizing particle pack data.
5
+ Author-email: Bogong Wang <bogongwang.dev@outlook.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/bogongwang/particle-pack-tools
8
+ Project-URL: Repository, https://github.com/bogongwang/particle-pack-tools
9
+ Keywords: particle pack,tools,visualization,data processing,particle pack
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.11
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: xarray>=2025.1
16
+ Requires-Dist: dask>=2025.1
17
+ Requires-Dist: netCDF4>=1.7.2
18
+ Requires-Dist: scikit-image>=0.25.0
19
+ Requires-Dist: scipy>=1.15.0
20
+ Requires-Dist: numpy>=1.25.0
21
+ Requires-Dist: numba>=0.60.0
22
+ Requires-Dist: matplotlib>=3.10.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=7.0; extra == "dev"
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest>=7.0; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # Particle Pack Tools
30
+
31
+ ## Installation
32
+ To install the package, run:
33
+ ```
34
+ pip install particle-pack-tools
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ ### Dataset I/O
40
+ Load particle pack datasets using:
41
+ ```
42
+ from pptools.io import load_nc, load_nc_arr
43
+ ```
44
+
45
+ ### Dataset Preprocessing
46
+ Preprocess particle pack datasets with:
47
+ ```
48
+ from pptools.preprocess import crop_3d
49
+ # ...additional preprocessing functions...
50
+ ```
51
+
52
+ ### Dataset Visualization
53
+ Visualize particle pack datasets using the `Visualizer` class:
54
+ ```
55
+ from pptools.visualize import Visualizer
56
+
57
+ # Initialize the visualizer
58
+ vis = Visualizer()
59
+
60
+ # Plot a tomogram
61
+ vis.plot_tomo(tomo_img)
62
+ vis.show()
63
+
64
+ # Plot a multi-label mask
65
+ vis.plot_mask(mask_img)
66
+ vis.show()
67
+ ```
68
+
69
+ ---
70
+
71
+ Feel free to report any issues or share suggestions to help improve this toolkit.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ particle_pack_tools.egg-info/PKG-INFO
5
+ particle_pack_tools.egg-info/SOURCES.txt
6
+ particle_pack_tools.egg-info/dependency_links.txt
7
+ particle_pack_tools.egg-info/requires.txt
8
+ particle_pack_tools.egg-info/top_level.txt
9
+ pptools/__init__.py
10
+ pptools/io.py
11
+ pptools/preprocess.py
12
+ pptools/visualize.py
@@ -0,0 +1,14 @@
1
+ xarray>=2025.1
2
+ dask>=2025.1
3
+ netCDF4>=1.7.2
4
+ scikit-image>=0.25.0
5
+ scipy>=1.15.0
6
+ numpy>=1.25.0
7
+ numba>=0.60.0
8
+ matplotlib>=3.10.0
9
+
10
+ [dev]
11
+ pytest>=7.0
12
+
13
+ [test]
14
+ pytest>=7.0
@@ -0,0 +1,7 @@
1
+ """
2
+ Package for processing and visualizing particle pack data.
3
+ """
4
+ __all__ = ["io", "preprocess", "visualize"]
5
+ __version__ = "0.0.1"
6
+ __author__ = "Bogong Wang"
7
+ __email__ = "bogongwang.dev@outlook.com"
@@ -0,0 +1,480 @@
1
+ import os
2
+ from typing import Tuple, Optional
3
+ import warnings
4
+
5
+ import numpy as np
6
+ import xarray as xr
7
+ import dask.array as da
8
+ from netCDF4 import Dataset
9
+
10
+ def load_nc(path: str, varname: Optional[str] = None) -> xr.Dataset:
11
+ """
12
+ Load netCDF files into an xarray Dataset, attempting to interpret data based on a priority list
13
+ or a specific variable name.
14
+
15
+ Args:
16
+ path: Path to a netCDF file or list of paths. Wildcards supported.
17
+ varname: Specific variable to load. If None, attempts to load ["tomo", "labels", "distance_map", "segmented"] in order.
18
+ The concat_dim is derived as f"{varname}_zdim".
19
+
20
+ Returns:
21
+ xarray.Dataset: The loaded dataset.
22
+ """
23
+ LOAD_ORDER = ["tomo", "labels", "distance_map", "segmented"]
24
+ candidates = [varname] if varname else LOAD_ORDER
25
+ errors = {}
26
+
27
+ for var in candidates:
28
+ try:
29
+ return xr.open_mfdataset(
30
+ path,
31
+ concat_dim=f"{var}_zdim",
32
+ data_vars="minimal",
33
+ combine="nested",
34
+ combine_attrs="drop_conflicts",
35
+ coords="minimal",
36
+ compat="override",
37
+ )
38
+ except Exception as e:
39
+ errors[f'varname={var}'] = str(e)
40
+
41
+ raise RuntimeError(f"Failed to load netCDF. Tried: {candidates}. Errors: {errors}. Try specifying 'varname' explicitly.")
42
+
43
+ def load_nc_arr(path: str, varname: Optional[str] = None) -> da.Array:
44
+ """
45
+ Load netCDF files and return the specific data array as a Dask array.
46
+
47
+ Args:
48
+ path: Path to a netCDF file or list of paths.
49
+ varname: Specific variable to load. If None, follows standard priority order.
50
+
51
+ Returns:
52
+ dask.array.Array: The raw data array of the loaded variable.
53
+ """
54
+ LOAD_ORDER = ["tomo", "labels", "distance_map", "segmented"]
55
+ candidates = [varname] if varname else LOAD_ORDER
56
+ ds = load_nc(path, varname)
57
+
58
+ # If auto-detected, find which variable from the priority list exists in the dataset.
59
+ for var in candidates:
60
+ if var in ds:
61
+ return ds[var].data
62
+
63
+ raise RuntimeError(f"Dataset loaded, but could not locate any of {candidates} in variables: {list(ds.data_vars)}")
64
+
65
+ class NCWriter:
66
+ """
67
+ NCWriter is a utility class for creating, writing to, and managing NetCDF files.
68
+
69
+ This class provides methods to:
70
+ - Create a new NetCDF file with specified label dimensions and attributes.
71
+ - Open an existing NetCDF label file for modification.
72
+ - Write 2D slices into a 3D label dataset efficiently.
73
+ - Support context manager protocol for safe usage with 'with' statements.
74
+ - Finalize and close the NetCDF file, ensuring data integrity.
75
+
76
+ Usage:
77
+ with NCWriter("output_labels.nc") as nw:
78
+ nw.create_labels_nc(shape=(10, 128, 128), attrs={"description": "Segmentation labels"})
79
+ for z in range(10):
80
+ nw.write(z, label_slice[z])
81
+ # File is automatically closed at the end of the with block.
82
+
83
+ Key Features:
84
+ - Efficient partial writing of large label volumes.
85
+ - Optional attribute storage.
86
+ - Automatic resource management via context manager.
87
+ """
88
+ def __init__(
89
+ self,
90
+ path: str,
91
+ ):
92
+ """
93
+ Initialize a NCWriter instance for a given NetCDF file path.
94
+
95
+ Args:
96
+ path (str): Path to the NetCDF file to create or open. If the file exists, it is opened for writing; otherwise, a new file can be created with `create_labels_nc`.
97
+ """
98
+ self.path = path
99
+ self._dataset= None
100
+ self._nc_arr = None
101
+ self._shape = None
102
+ self._varname = None
103
+
104
+ def __enter__(self):
105
+ """
106
+ Enter the context manager, returning this NCWriter instance.
107
+ Enables use with 'with' statements for automatic cleanup.
108
+ """
109
+ return self
110
+
111
+ def __exit__(self, exc_type, exc_value, traceback):
112
+ """
113
+ Exit the context manager, automatically closing the NetCDF file and releasing resources.
114
+ """
115
+ self.close()
116
+
117
+ def open(self, varname="labels"):
118
+ """
119
+ Open an existing NetCDF file for writing.
120
+
121
+ Args:
122
+ varname (str, optional): Name of the variable to write to (default: 'labels').
123
+
124
+ Behaviour:
125
+ Opens the specified NetCDF file in read/write mode and initializes internal arrays.
126
+ """
127
+ self._varname = varname
128
+ self._open_nc()
129
+
130
+ def create_nc(
131
+ self,
132
+ shape: Tuple[int, int, int],
133
+ varname: str = "labels",
134
+ attrs: dict = None,
135
+ complevel: int = 2,
136
+ overwrite: bool = False,
137
+ ):
138
+ """
139
+ Create a new NetCDF file with specified shape and attributes.
140
+
141
+ Args:
142
+ shape (tuple): A tuple of (z, y, x) specifying the dimensions of the label volume.
143
+ attrs (dict, optional): Attributes to store in the NetCDF file's global attributes.
144
+ complevel (int, optional): Compression level for zlib compression (default: 2).
145
+ overwrite (bool, optional): If True, overwrite an existing file at the path; otherwise, raises an error if file exists.
146
+
147
+ Behaviour:
148
+ Creates a NetCDF file with dimensions ('labels_zdim', 'labels_ydim', 'labels_xdim') and a variable 'labels'.
149
+ Applies optional compression and stores provided attributes.
150
+ Opens the file for subsequent writing.
151
+ """
152
+ if self._dataset:
153
+ if overwrite:
154
+ self.close()
155
+ os.remove(self.path)
156
+ print(f"Existing nc file at {self.path} was overwritten.")
157
+ else:
158
+ raise FileExistsError(f"File {self.path} already exists (overwrite is disabled).")
159
+ self._varname = varname
160
+ dimensions = (f'{self._varname}_zdim', f'{self._varname}_ydim', f'{self._varname}_xdim')
161
+ ds = Dataset(self.path, 'w')
162
+ ds.createDimension(dimensions[0], shape[0])
163
+ ds.createDimension(dimensions[1], shape[1])
164
+ ds.createDimension(dimensions[2], shape[2])
165
+ ds.createVariable(
166
+ varname=self._varname,
167
+ datatype=np.int32,
168
+ dimensions=dimensions,
169
+ zlib=True,
170
+ complevel=complevel,
171
+ shuffle=False,
172
+ chunksizes=(1, shape[1], shape[2]),
173
+ fill_value=-1
174
+ )
175
+ if attrs:
176
+ for key, val in attrs.items():
177
+ setattr(ds, key, val)
178
+ ds.close()
179
+ self._open_nc()
180
+
181
+ def write(self, idx: int, data: np.ndarray, sync: bool = True):
182
+ """
183
+ Write a 2D data slice into the 3D label dataset at the specified index.
184
+
185
+ Args:
186
+ idx (int): Index along the z-dimension where the data slice will be written.
187
+ data (np.ndarray): 2D numpy array of shape (y, x) to write into the dataset.
188
+ sync (bool, optional): If True (default), flush changes to disk immediately. Always flushes on the last slice.
189
+
190
+ Behaviour:
191
+ Overwrites the specified z-slice in the NetCDF variable 'labels' with the provided data.
192
+ """
193
+ assert data.shape == self._shape[1:], f"Data shape {data.shape} does not match expected shape {self._shape[1:]}"
194
+ self._nc_arr[idx] = data
195
+ # Flush on request or on last slice
196
+ if sync or (idx == self._shape[0] - 1):
197
+ self.sync()
198
+
199
+ def write_block(
200
+ self,
201
+ data: np.ndarray,
202
+ offset: Tuple[int] = (0, 0, 0),
203
+ sync: bool = True
204
+ ):
205
+ """
206
+ Write a 3D data block into the label dataset starting at the specified index.
207
+
208
+ Args:
209
+ data (np.ndarray): 3D numpy array of shape (z, y, x) to write into the dataset.
210
+ offset (tuple): A tuple of (z_start, y_start, x_start) specifying where to write the data block.
211
+ sync (bool, optional): If True (default), flush changes to disk immediately after writing.
212
+
213
+ Behaviour:
214
+ Overwrites a sub-volume in the NetCDF variable 'labels' with the provided data block.
215
+ """
216
+ z_start, y_start, x_start = offset
217
+ z_end = z_start + data.shape[0]
218
+ y_end = y_start + data.shape[1]
219
+ x_end = x_start + data.shape[2]
220
+ data_mask = data > 0
221
+ if np.any(data_mask):
222
+ write_target = self._nc_arr[z_start:z_end, y_start:y_end, x_start:x_end]
223
+ # netCDF4 returns a copy for slices, so mutate then assign back explicitly
224
+ write_target[data_mask] = data[data_mask]
225
+ self._nc_arr[z_start:z_end, y_start:y_end, x_start:x_end] = write_target
226
+ if sync:
227
+ self.sync()
228
+
229
+ def replace(self, idx: int, src: int, dst: int):
230
+ """
231
+ Replace all occurrences of a label value within a 2D slice of the dataset.
232
+
233
+ Args:
234
+ idx (int): Index along the z-dimension specifying which slice to modify.
235
+ src (int): Source label value to be replaced.
236
+ dst (int): Destination label value to replace the source with.
237
+
238
+ Behaviour:
239
+ Scans the specified z-slice in the NetCDF variable 'labels' and replaces
240
+ all pixels with value `src` by `dst`. The modification is performed in-place.
241
+ """
242
+ self._nc_arr[idx] = xr.where(self._nc_arr[idx] == src, dst, self._nc_arr[idx])
243
+
244
+ def sync(self):
245
+ """
246
+ Flush any pending changes in the dataset to disk.
247
+
248
+ Behaviour:
249
+ Ensures that all modifications made to the NetCDF variable 'labels'
250
+ are written to disk, keeping the on-disk data consistent with memory.
251
+ Useful after multiple write or correct operations.
252
+ """
253
+ self._dataset.sync()
254
+
255
+ def close(self):
256
+ """
257
+ Finalize and close the NetCDF label file.
258
+
259
+ Ensures all data is flushed to disk and resources are released. Safe to call multiple times.
260
+ """
261
+ if self._dataset:
262
+ self._dataset.sync()
263
+ self._dataset.close()
264
+ self._dataset = None
265
+ self._nc_arr = None
266
+
267
+ def _open_nc(self):
268
+ """
269
+ Open an existing NetCDF file in read/write mode and initialize internal arrays.
270
+
271
+ This method is called automatically when opening an existing file or after creating a new one,
272
+ setting up the internal dataset and reference to the 'labels' variable for writing.
273
+ """
274
+ if not self._dataset:
275
+ self._dataset = Dataset(self.path, 'r+')
276
+ self._nc_arr = self._dataset[self._varname]
277
+ self._shape = self._nc_arr.shape
278
+
279
+ class MaskWriter:
280
+ """
281
+ MaskWriter is a utility class for creating, writing to, and managing NetCDF label (mask) files.
282
+
283
+ This class provides methods to:
284
+ - Create a new NetCDF file with specified label dimensions and attributes.
285
+ - Open an existing NetCDF label file for modification.
286
+ - Write 2D slices into a 3D label dataset efficiently.
287
+ - Support context manager protocol for safe usage with 'with' statements.
288
+ - Finalize and close the NetCDF file, ensuring data integrity.
289
+
290
+ Usage:
291
+ with MaskWriter("output_labels.nc") as mw:
292
+ mw.create_labels_nc(shape=(10, 128, 128), attrs={"description": "Segmentation labels"})
293
+ for z in range(10):
294
+ mw.write(z, label_slice[z])
295
+ # File is automatically closed at the end of the with block.
296
+
297
+ Key Features:
298
+ - Efficient partial writing of large label volumes.
299
+ - Optional attribute storage.
300
+ - Automatic resource management via context manager.
301
+ """
302
+ def __init__(
303
+ self,
304
+ path: str,
305
+ ):
306
+ """
307
+ Initialize a MaskWriter instance for a given NetCDF file path.
308
+
309
+ Args:
310
+ path (str): Path to the NetCDF file to create or open. If the file exists, it is opened for writing; otherwise, a new file can be created with `create_labels_nc`.
311
+ """
312
+ warnings.warn(
313
+ "MaskWriter is deprecated and will be removed by 0.0.10 versions. Please use NCWriter instead.",
314
+ DeprecationWarning
315
+ )
316
+ self.path = path
317
+ self._dataset= None
318
+ self._labels_arr = None
319
+ self._shape = None
320
+ if os.path.exists(path):
321
+ self._open_labels_nc()
322
+
323
+ def __enter__(self):
324
+ """
325
+ Enter the context manager, returning this MaskWriter instance.
326
+ Enables use with 'with' statements for automatic cleanup.
327
+ """
328
+ return self
329
+
330
+ def __exit__(self, exc_type, exc_value, traceback):
331
+ """
332
+ Exit the context manager, automatically closing the NetCDF file and releasing resources.
333
+ """
334
+ self.close()
335
+
336
+ def create_labels_nc(
337
+ self,
338
+ shape: Tuple[int, int, int],
339
+ attrs: dict = None,
340
+ complevel: int = 2,
341
+ overwrite: bool = False,
342
+ ):
343
+ """
344
+ Create a new NetCDF file for labels with specified shape and attributes.
345
+
346
+ Args:
347
+ shape (tuple): A tuple of (z, y, x) specifying the dimensions of the label volume.
348
+ attrs (dict, optional): Attributes to store in the NetCDF file's global attributes.
349
+ complevel (int, optional): Compression level for zlib compression (default: 2).
350
+ overwrite (bool, optional): If True, overwrite an existing file at the path; otherwise, raises an error if file exists.
351
+
352
+ Behaviour:
353
+ Creates a NetCDF file with dimensions ('labels_zdim', 'labels_ydim', 'labels_xdim') and a variable 'labels'.
354
+ Applies optional compression and stores provided attributes.
355
+ Opens the file for subsequent writing.
356
+ """
357
+ if self._dataset:
358
+ if overwrite:
359
+ self.close()
360
+ os.remove(self.path)
361
+ print(f"Existing nc file at {self.path} was overwritten.")
362
+ else:
363
+ raise FileExistsError(f"File {self.path} already exists (overwrite is disabled).")
364
+ ds = Dataset(self.path, 'w')
365
+ ds.createDimension('labels_zdim', shape[0])
366
+ ds.createDimension('labels_ydim', shape[1])
367
+ ds.createDimension('labels_xdim', shape[2])
368
+ ds.createVariable(
369
+ varname="labels",
370
+ datatype=np.int32,
371
+ dimensions=('labels_zdim', 'labels_ydim', 'labels_xdim'),
372
+ zlib=True,
373
+ complevel=complevel,
374
+ shuffle=False,
375
+ chunksizes=(1, shape[1], shape[2]),
376
+ fill_value=-1
377
+ )
378
+ if attrs:
379
+ for key, val in attrs.items():
380
+ setattr(ds, key, val)
381
+ ds.close()
382
+ self._open_labels_nc()
383
+
384
+ def write(self, idx: int, data: np.ndarray, sync: bool = True):
385
+ """
386
+ Write a 2D data slice into the 3D label dataset at the specified index.
387
+
388
+ Args:
389
+ idx (int): Index along the z-dimension where the data slice will be written.
390
+ data (np.ndarray): 2D numpy array of shape (y, x) to write into the dataset.
391
+ sync (bool, optional): If True (default), flush changes to disk immediately. Always flushes on the last slice.
392
+
393
+ Behaviour:
394
+ Overwrites the specified z-slice in the NetCDF variable 'labels' with the provided data.
395
+ """
396
+ assert data.shape == self._shape[1:], f"Data shape {data.shape} does not match expected shape {self._shape[1:]}"
397
+ self._labels_arr[idx] = data
398
+ # Flush on request or on last slice
399
+ if sync or (idx == self._shape[0] - 1):
400
+ self.sync()
401
+
402
+ def write_block(
403
+ self,
404
+ data: np.ndarray,
405
+ offset: Tuple[int] = (0, 0, 0),
406
+ sync: bool = True
407
+ ):
408
+ """
409
+ Write a 3D data block into the label dataset starting at the specified index.
410
+
411
+ Args:
412
+ start_idx (tuple): A tuple of (z_start, y_start, x_start) specifying where to write the data block.
413
+ data (np.ndarray): 3D numpy array of shape (z, y, x) to write into the dataset.
414
+ sync (bool, optional): If True (default), flush changes to disk immediately after writing.
415
+
416
+ Behaviour:
417
+ Overwrites a sub-volume in the NetCDF variable 'labels' with the provided data block.
418
+ """
419
+ z_start, y_start, x_start = offset
420
+ z_end = z_start + data.shape[0]
421
+ y_end = y_start + data.shape[1]
422
+ x_end = x_start + data.shape[2]
423
+ data_mask = data > 0
424
+ if np.any(data_mask):
425
+ write_target = self._labels_arr[z_start:z_end, y_start:y_end, x_start:x_end]
426
+ # netCDF4 returns a copy for slices, so mutate then assign back explicitly
427
+ write_target[data_mask] = data[data_mask]
428
+ self._labels_arr[z_start:z_end, y_start:y_end, x_start:x_end] = write_target
429
+ if sync:
430
+ self.sync()
431
+
432
+ def replace(self, idx: int, src: int, dst: int):
433
+ """
434
+ Replace all occurrences of a label value within a 2D slice of the dataset.
435
+
436
+ Args:
437
+ idx (int): Index along the z-dimension specifying which slice to modify.
438
+ src (int): Source label value to be replaced.
439
+ dst (int): Destination label value to replace the source with.
440
+
441
+ Behaviour:
442
+ Scans the specified z-slice in the NetCDF variable 'labels' and replaces
443
+ all pixels with value `src` by `dst`. The modification is performed in-place.
444
+ """
445
+ self._labels_arr[idx] = xr.where(self._labels_arr[idx] == src, dst, self._labels_arr[idx])
446
+
447
+ def sync(self):
448
+ """
449
+ Flush any pending changes in the dataset to disk.
450
+
451
+ Behaviour:
452
+ Ensures that all modifications made to the NetCDF variable 'labels'
453
+ are written to disk, keeping the on-disk data consistent with memory.
454
+ Useful after multiple write or correct operations.
455
+ """
456
+ self._dataset.sync()
457
+
458
+ def close(self):
459
+ """
460
+ Finalize and close the NetCDF label file.
461
+
462
+ Ensures all data is flushed to disk and resources are released. Safe to call multiple times.
463
+ """
464
+ if self._dataset:
465
+ self._dataset.sync()
466
+ self._dataset.close()
467
+ self._dataset = None
468
+ self._labels_arr = None
469
+
470
+ def _open_labels_nc(self):
471
+ """
472
+ Open an existing NetCDF label file in read/write mode and initialize internal arrays.
473
+
474
+ This method is called automatically when opening an existing file or after creating a new one,
475
+ setting up the internal dataset and reference to the 'labels' variable for writing.
476
+ """
477
+ if not self._dataset:
478
+ self._dataset = Dataset(self.path, 'r+')
479
+ self._labels_arr = self._dataset['labels']
480
+ self._shape = self._labels_arr.shape
@@ -0,0 +1,82 @@
1
+ import numpy as np
2
+ import dask.array as da
3
+ from skimage.util import view_as_blocks
4
+ from numba import njit
5
+
6
+ @njit
7
+ def _get_bboxes_helper(_mask, _max_label, _offset):
8
+ """
9
+ Compute bounding boxes for labelled regions in a 3D mask array.
10
+
11
+ :param ndarray _mask: 3D array where each voxel is labelled with an integer.
12
+ :param int _max_label: Maximum number of labels.
13
+ :param list _offset: Offset to adjust the bounding box coordinates.
14
+ :return: Array of bounding boxes with shape (1, _max_label, 6), each as [x_min, y_min, z_min, x_max, y_max, z_max].
15
+ :rtype: ndarray
16
+ """
17
+ bboxes = np.full((1, _max_label, 6), 32767, dtype=np.int16)
18
+ bboxes[..., 3:] = -1
19
+ for x in range(_mask.shape[0]):
20
+ for y in range(_mask.shape[1]):
21
+ for z in range(_mask.shape[2]):
22
+ label = _mask[x, y, z]
23
+ if label < _max_label: # 0 is background
24
+ x_min, y_min, z_min, x_max, y_max, z_max = bboxes[0, label]
25
+ real_x = x + _offset[0]
26
+ real_y = y + _offset[1]
27
+ real_z = z + _offset[2]
28
+ bboxes[0, label, 0] = min(x_min, real_x)
29
+ bboxes[0, label, 1] = min(y_min, real_y)
30
+ bboxes[0, label, 2] = min(z_min, real_z)
31
+ bboxes[0, label, 3] = max(x_max, real_x)
32
+ bboxes[0, label, 4] = max(y_max, real_y)
33
+ bboxes[0, label, 5] = max(z_max, real_z)
34
+ return bboxes
35
+
36
+ def get_bboxes_helper(mask, max_label, block_info=None):
37
+ """
38
+ Compute bounding boxes for a 3D mask using Dask block metadata.
39
+
40
+ :param ndarray mask: 3D array where each voxel is labelled with an integer.
41
+ :param int max_label: Maximum label number.
42
+ :param dict block_info: Dask block information to compute offsets.
43
+ :return: Array of bounding boxes for the provided mask block.
44
+ :rtype: ndarray
45
+ """
46
+ offset = [loc[0] for loc in block_info[0]['array-location']]
47
+ return _get_bboxes_helper(mask, _max_label=max_label, _offset=offset)
48
+
49
+ def get_bboxes(arr, max_label=10_000):
50
+ """
51
+ Aggregate bounding boxes from a Dask array across all blocks.
52
+
53
+ :param ndarray arr: 3D array with labelled regions.
54
+ :return: Aggregated array of bounding boxes, each as [x_min, y_min, z_min, x_max, y_max, z_max].
55
+ :rtype: ndarray
56
+ """
57
+ blocked_res = da.map_blocks(get_bboxes_helper, arr, max_label=max_label, chunks=(1, max_label, 6), dtype=np.int16).compute()
58
+ res_reshaped = view_as_blocks(blocked_res, block_shape=(1, max_label, 6)).reshape(-1, max_label, 6)
59
+ res_arr = np.empty((max_label, 6), dtype=np.int16)
60
+ res_arr[:, :3] = np.min(res_reshaped[:, :, :3], axis=0)
61
+ res_arr[:, 3:] = np.max(res_reshaped[:, :, 3:], axis=0)
62
+ return res_arr
63
+
64
+ def crop_3d(arr, loc, padding=0):
65
+ """
66
+ Crop a 3D array to the specified bounding box with optional padding.
67
+
68
+ :param ndarray arr: 3D array to crop.
69
+ :param tuple loc: Bounding box coordinates as (z_min, x_min, y_min, z_max, x_max, y_max).
70
+ :param int padding: Number of voxels to pad around the bounding box.
71
+ :return: Cropped 3D array.
72
+ :rtype: ndarray
73
+ """
74
+ if padding == 0:
75
+ return arr[loc[0]:loc[3] + 1, loc[1]:loc[4] + 1, loc[2]:loc[5] + 1]
76
+ z_min = max(loc[0] - padding, 0)
77
+ x_min = max(loc[1] - padding, 0)
78
+ y_min = max(loc[2] - padding, 0)
79
+ z_max = min(loc[3] + padding, arr.shape[0] - 1)
80
+ x_max = min(loc[4] + padding, arr.shape[1] - 1)
81
+ y_max = min(loc[5] + padding, arr.shape[2] - 1)
82
+ return arr[z_min:z_max + 1, x_min:x_max + 1, y_min:y_max + 1]
@@ -0,0 +1,244 @@
1
+ import numpy as np
2
+
3
+ import matplotlib as mpl
4
+ import matplotlib.pyplot as plt
5
+ from matplotlib import colormaps
6
+ from matplotlib.colors import ListedColormap
7
+ import matplotlib.colors as mcolors
8
+ from matplotlib.widgets import Slider
9
+ from skimage.transform import resize
10
+
11
+ class Visualizer:
12
+ @staticmethod
13
+ def create_mask_cmap(n, cmap='gist_rainbow', seed: int = None):
14
+ """
15
+ Create a custom color map that plots n colors, while leaving the background black
16
+ """
17
+ original_cmap = colormaps[cmap]
18
+ colors = np.linspace(0, 1, n - 1)
19
+ if seed is not None:
20
+ np.random.seed(seed)
21
+ np.random.shuffle(colors)
22
+ cmap_colors = original_cmap(colors)
23
+ black = np.array([[0, 0, 0, 1]])
24
+ cmap_colors = np.concatenate((black, cmap_colors))
25
+ return ListedColormap(cmap_colors)
26
+
27
+ def __init__(self, cmap='gist_rainbow', n_colors=32768, seed=42, latex=False):
28
+ if latex:
29
+ text_color = 'black'
30
+ plt.style.use('default')
31
+ plt.rcParams['text.color'] = text_color
32
+ plt.rcParams['axes.labelcolor'] = text_color
33
+ plt.rcParams['xtick.color'] = text_color
34
+ plt.rcParams['ytick.color'] = text_color
35
+ plt.rcParams['axes.edgecolor'] = text_color
36
+ plt.rcParams['font.family'] = 'Computer Modern'
37
+ plt.rcParams['mathtext.fontset'] = 'cm'
38
+ plt.rcParams['text.usetex'] = True
39
+ plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
40
+ else:
41
+ mpl.rcParams.update(mpl.rcParamsDefault)
42
+ self.tomo_cmap = 'gray'
43
+ self.mask_cmap = Visualizer.create_mask_cmap(n_colors, cmap=cmap, seed=seed)
44
+ self.mask_cmap_norm = mcolors.Normalize(vmin=0, vmax=n_colors)
45
+ self.sliders = []
46
+
47
+ def plot_tomo(self, tomo, alpha=1, show_ticks=False, ax=None):
48
+ """
49
+ Plot a tomogram.
50
+
51
+ Parameters:
52
+ - tomo: The tomogram to be plotted.
53
+ - alpha: The transparency level of the image.
54
+ - show_ticks: Whether to show the xy ticks.
55
+ - ax: The axis to plot on. If None, use the current axis.
56
+ """
57
+ if ax is None:
58
+ if not show_ticks:
59
+ plt.gca().set_axis_off()
60
+ plt.imshow(tomo, alpha=alpha, cmap=self.tomo_cmap, interpolation='none')
61
+ else:
62
+ if not show_ticks:
63
+ plt.gca().set_axis_off()
64
+ return ax.imshow(tomo, alpha=alpha, cmap=self.tomo_cmap, interpolation='none', rasterized=True)
65
+
66
+ def plot_mask(self, mask, max_mask_val=None, alpha=1, show_ticks=False, ax=None):
67
+ """
68
+ Plot a mask image.
69
+
70
+ Parameters:
71
+ - mask: The mask data to be plotted.
72
+ - alpha: The transparency level of the image.
73
+ - show_ticks: Whether to show the xy ticks.
74
+ - ax: The axis to plot on. If None, use the current axis.
75
+ """
76
+ if max_mask_val is not None:
77
+ mask = mask.copy()
78
+ mask[mask > max_mask_val] = 0
79
+ if ax is None:
80
+ if not show_ticks:
81
+ plt.gca().set_axis_off()
82
+ plt.imshow(mask, alpha=alpha, cmap=self.mask_cmap, norm=self.mask_cmap_norm, interpolation='none', rasterized=True)
83
+ else:
84
+ if not show_ticks:
85
+ plt.gca().set_axis_off()
86
+ return ax.imshow(mask, alpha=alpha, cmap=self.mask_cmap, norm=self.mask_cmap_norm, interpolation='none', rasterized=True)
87
+
88
+
89
+ def compare_tomo_mask(self, tomo, mask, figsize=(10, 5), show_ticks=False, stacked=True):
90
+ """
91
+ Compare a tomogram with a mask.
92
+ The mask will be plotted on top of the tomogram.
93
+
94
+ Parameters:
95
+ - tomo: The tomography data to be plotted.
96
+ - mask: The mask data to be plotted.
97
+ - figsize: The size of the figure.
98
+ - show_ticks: Whether to show the xy ticks.
99
+ - stacked: Whether to stack the images on top of each other or displayed in a row.
100
+ """
101
+ if stacked:
102
+ fig, ax = plt.subplots(figsize=figsize)
103
+ self.plot_tomo(tomo, show_ticks=show_ticks, ax=ax)
104
+ top_im = self.plot_mask(mask, show_ticks=show_ticks, ax=ax)
105
+ slider_ax = plt.axes([0.2, 0, 0.6, 0.04])
106
+ slider = Slider(slider_ax, '', 0, 1, valinit=0.5)
107
+ def _update(val):
108
+ top_im.set_alpha(slider.val)
109
+ fig.canvas.draw_idle()
110
+ slider.on_changed(_update)
111
+ else:
112
+ fig, ax = plt.subplots(1, 2, figsize=figsize)
113
+ self.plot_tomo(tomo, ax=ax[0], show_ticks=show_ticks)
114
+ self.plot_mask(mask, ax=ax[1], show_ticks=show_ticks)
115
+ self.show()
116
+
117
+ def compare_masks(self, *masks, figsize=(10, 5), show_ticks=False, stacked=True):
118
+ """
119
+ Compare multiple masks.
120
+ The masks can be stacked on top of each other with sliders to adjust transparency, or displayed side by side.
121
+
122
+ Parameters:
123
+ - masks: The masks to be compared. At least two masks are required.
124
+ - figsize: The size of the figure.
125
+ - show_ticks: Whether to show the xy ticks.
126
+ - stacked: Whether to stack the images on top of each other or display them side by side.
127
+ """
128
+ if len(masks) < 2:
129
+ raise ValueError("At least two masks are required.")
130
+ if stacked:
131
+ n_sliders = len(masks) - 1
132
+ slider_height = 0.04
133
+ gap = 0.01
134
+ total_slider_height = n_sliders * (slider_height + gap)
135
+ fig, ax = plt.subplots(1, 1, figsize=figsize)
136
+ fig.subplots_adjust(bottom=total_slider_height + 0.05)
137
+ # Plot the base mask.
138
+ self.plot_mask(masks[0], ax=ax, show_ticks=show_ticks)
139
+ for i, mask in enumerate(masks[1:]):
140
+ im = self.plot_mask(mask, ax=ax, show_ticks=show_ticks)
141
+ slider_ax = fig.add_axes([0.2, 0.05 + (n_sliders - i - 1)*(slider_height + gap), 0.6, slider_height])
142
+ slider = Slider(slider_ax, f'mask {i+1}', 0, 1, valinit=0.5)
143
+ def update(val, im=im):
144
+ im.set_alpha(val)
145
+ fig.canvas.draw_idle()
146
+ slider.on_changed(update)
147
+ self.sliders.append(slider)
148
+ self.show()
149
+ else:
150
+ n_axes = len(masks)
151
+ fig, axes = plt.subplots(1, n_axes, figsize=figsize)
152
+ for ax, mask in zip(axes, masks):
153
+ self.plot_mask(mask, ax=ax, show_ticks=show_ticks)
154
+ self.show()
155
+
156
+ def compare_tomo_mask_pred(self, tomo, mask, pred):
157
+ fig, ax = plt.subplots(1, 3, figsize=(15, 5))
158
+ self.plot_tomo(tomo, ax=ax[0])
159
+ self.plot_mask(mask, ax=ax[1])
160
+ self.plot_mask(pred, ax=ax[2])
161
+ plt.show()
162
+
163
+ def plot_tomo_stack(self, tomo_stack, figsize=(10, 10), downscale=False):
164
+ """
165
+ Visualise a tomogram stack with a slider.
166
+
167
+ Note: Using Dask array directly as input can significantly slow down
168
+ drawing performance. It is recommended to load the Dask array in advance
169
+ before using this function.
170
+
171
+ Parameters:
172
+ - tomo_stack: 3D numpy array of slices.
173
+ - figsize : Figure size.
174
+ - downscale : If True, each slice is downscaled to 300*300.
175
+ """
176
+ n_slices = tomo_stack.shape[0]
177
+ fig, ax = plt.subplots(figsize=figsize)
178
+ plt.subplots_adjust(bottom=0.25)
179
+ if downscale:
180
+ slice0 = resize(np.array(tomo_stack[0]), (300, 300), mode='reflect', anti_aliasing=True)
181
+ else:
182
+ slice0 = np.array(tomo_stack[0])
183
+ im = self.plot_tomo(slice0, show_ticks=False, ax=ax)
184
+ ax.set_title("Slice 0")
185
+ slider_ax = fig.add_axes([0.2, 0, 0.6, 0.03])
186
+ slider = Slider(slider_ax, 'Slice', 0, n_slices - 1, valinit=0, valfmt='%d', valstep=1)
187
+ def update(val):
188
+ idx = int(slider.val)
189
+ if downscale:
190
+ slice_img = resize(np.array(tomo_stack[idx]), (300, 300), mode='reflect', anti_aliasing=True)
191
+ else:
192
+ slice_img = np.array(tomo_stack[idx])
193
+ im.set_data(slice_img)
194
+ ax.set_title(f"Slice {idx}")
195
+ fig.canvas.draw_idle()
196
+ del slice_img
197
+ slider.on_changed(update)
198
+ self.sliders.append(slider)
199
+ self.show()
200
+
201
+ def plot_mask_stack(self, mask_stack, figsize=(10, 10), downscale=False):
202
+ """
203
+ Visualise a mask stack with a slider.
204
+
205
+ Note: Using Dask array directly as input can significantly slow down
206
+ drawing performance. It is recommended to load the Dask array in advance
207
+ before using this function.
208
+
209
+ Parameters:
210
+ - tomo_stack: 3D numpy array of slices.
211
+ - figsize : Figure size.
212
+ - downscale : If True, each slice is downscaled to 300*300.
213
+ """
214
+ n_slices = mask_stack.shape[0]
215
+ fig, ax = plt.subplots(figsize=figsize)
216
+ plt.subplots_adjust(bottom=0.25)
217
+ if downscale:
218
+ slice0 = np.array(mask_stack[0]).astype(np.float32)
219
+ slice0 = resize(slice0, (300, 300), mode='reflect', anti_aliasing=False)
220
+ else:
221
+ slice0 = mask_stack[0]
222
+ im = self.plot_mask(slice0, show_ticks=False, ax=ax)
223
+ ax.set_title("Slice 0")
224
+ slider_ax = fig.add_axes([0.2, 0, 0.6, 0.03])
225
+ slider = Slider(slider_ax, 'Slice', 0, n_slices - 1, valinit=0, valfmt='%d', valstep=1)
226
+ def update(val):
227
+ idx = int(slider.val)
228
+ if downscale:
229
+ slice_img = np.array(mask_stack[idx]).astype(np.float32)
230
+ slice_img = resize(slice_img, (300, 300), mode='reflect', anti_aliasing=False)
231
+ else:
232
+ slice_img = mask_stack[idx]
233
+ im.set_data(slice_img)
234
+ ax.set_title(f"Slice {idx}")
235
+ fig.canvas.draw_idle()
236
+ slider.on_changed(update)
237
+ self.sliders.append(slider)
238
+ self.show()
239
+
240
+ def figsize(self, figsize=(10, 10)):
241
+ plt.figure(figsize=figsize)
242
+
243
+ def show(self):
244
+ plt.show()
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "particle-pack-tools"
7
+ version = "0.0.7"
8
+ authors = [
9
+ { name = "Bogong Wang", email = "bogongwang.dev@outlook.com" }
10
+ ]
11
+ description = "A toolkit for processing and visualizing particle pack data."
12
+ readme = "README.md"
13
+ requires-python = ">=3.11"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ ]
18
+ license = "Apache-2.0"
19
+ license-files = ["LICENSE"]
20
+ keywords = ["particle pack", "tools", "visualization", "data processing", "particle pack"]
21
+
22
+ dependencies = [
23
+ "xarray>=2025.1",
24
+ "dask>=2025.1",
25
+ "netCDF4>=1.7.2",
26
+ "scikit-image>=0.25.0",
27
+ "scipy>=1.15.0",
28
+ "numpy>=1.25.0",
29
+ "numba>=0.60.0",
30
+ "matplotlib>=3.10.0"
31
+ ]
32
+
33
+ [project.optional-dependencies]
34
+ dev = ["pytest>=7.0"]
35
+ test = ["pytest>=7.0"]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/bogongwang/particle-pack-tools"
39
+ Repository = "https://github.com/bogongwang/particle-pack-tools"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+