├── .github
└── workflows
│ └── black.yml
├── .gitignore
├── .pre-commit-config.yaml
├── CITATION.cff
├── LICENSE.txt
├── README.md
├── images
├── demo.gif
└── py4DSTEM_logo.png
├── py4DGUI-keymap.html
├── pyproject.toml
└── src
└── py4D_browser
├── __init__.py
├── dialogs.py
├── empad2_reader.py
├── help_menu.py
├── logo.png
├── main_window.py
├── menu_actions.py
├── py4DGUI-keymap.png
├── runGUI.py
├── scalebar.py
├── update_views.py
└── utils.py
/.github/workflows/black.yml:
--------------------------------------------------------------------------------
1 | name: Check code style
2 |
3 | on:
4 | push:
5 | branches: [ "dev" ]
6 | pull_request:
7 | branches: [ "dev" ]
8 |
9 | jobs:
10 | lint:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v3
14 | - uses: psf/black@stable
15 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | .project
3 | .pydevproject
4 | *.swp
5 | *.ipynb_checkpoints*
6 | pyrightconfig.json
7 |
8 | # Folders #
9 | .idea/
10 | __pycache__/
11 | *.egg-info/
12 | build/
13 | dist/
14 | #py4DSTEM/sample_code/
15 | py4DSTEM/test/testdata/
16 | sample_code/data/*h5
17 | sample_code/data/*dm3
18 | py4DSTEM/test/unit_test_data/
19 | .vscode
20 | # Data Specific #
21 | #################
22 | #*.png
23 | #*.gif
24 | *.emd
25 | *.emf
26 | *.dm3
27 | *.dm4
28 | *.tiff
29 | *.tif
30 | *.jpg
31 | *.avi
32 | *.mp4
33 | *.emd
34 | *.pdf
35 | *.bin
36 | *.mat
37 | *.doc
38 | *.docx
39 | *.xlsx
40 | *.asv
41 | *.eps
42 | *.fig
43 | *.ai
44 | *.avi
45 | *.m~
46 | *.db
47 | *.eps
48 | *.asv
49 | *.svg
50 | *.emf
51 |
52 | # Compiled source #
53 | ###################
54 | *.com
55 | *.class
56 | *.dll
57 | *.exe
58 | *.o
59 | *.so
60 | *.mex*
61 |
62 | # Packages #
63 | ############
64 | # it's better to unpack these files and commit the raw source
65 | # git has its own built in compression methods
66 | *.7z
67 | *.dmg
68 | *.gz
69 | *.iso
70 | *.jar
71 | *.rar
72 | *.tar
73 | *.zip
74 |
75 | # Logs and databases #
76 | ######################
77 | *.log
78 | *.sql
79 | *.sqlite
80 |
81 | # OS generated files #
82 | ######################
83 | .DS_Store
84 | .DS_Store?
85 | ._*
86 | .Spotlight-V100
87 | .Trashes
88 | ehthumbs.db
89 | Thumbs.db
90 | Untitled.ipynb
91 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | # See https://pre-commit.com for more information
2 | # See https://pre-commit.com/hooks.html for more hooks
3 | repos:
4 | - repo: https://github.com/pre-commit/pre-commit-hooks
5 | rev: v3.2.0
6 | hooks:
7 | # - id: trailing-whitespace
8 | # - id: end-of-file-fixer
9 | # - id: check-yaml
10 | - id: check-added-large-files
11 | - repo: https://github.com/psf/black
12 | rev: 24.2.0
13 | hooks:
14 | - id: black
15 |
--------------------------------------------------------------------------------
/CITATION.cff:
--------------------------------------------------------------------------------
1 | cff-version: 1.1.0
2 | message: "If you use this software, please cite the accompanying paper."
3 | abstract: "Scanning transmission electron microscopy (STEM) allows for imaging, diffraction, and spectroscopy of materials on length scales ranging from microns to atoms. By using a high-speed, direct electron detector, it is now possible to record a full two-dimensional (2D) image of the diffracted electron beam at each probe position, typically a 2D grid of probe positions. These 4D-STEM datasets are rich in information, including signatures of the local structure, orientation, deformation, electromagnetic fields, and other sample-dependent properties. However, extracting this information requires complex analysis pipelines that include data wrangling, calibration, analysis, and visualization, all while maintaining robustness against imaging distortions and artifacts. In this paper, we present py4DSTEM, an analysis toolkit for measuring material properties from 4D-STEM datasets, written in the Python language and released with an open-source license. We describe the algorithmic steps for dataset calibration and various 4D-STEM property measurements in detail and present results from several experimental datasets. We also implement a simple and universal file format appropriate for electron microscopy data in py4DSTEM, which uses the open-source HDF5 standard. We hope this tool will benefit the research community and help improve the standards for data and computational methods in electron microscopy, and we invite the community to contribute to this ongoing project."
4 | authors:
5 | -
6 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA"
7 | family-names: Savitzky
8 | given-names: "Benjamin H."
9 | -
10 | affiliation: "Department of Materials Science and Engineering, University of California, Berkeley, CA 94720, USA"
11 | family-names: Zeltmann
12 | given-names: "Steven E. "
13 | -
14 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA"
15 | family-names: Hughes
16 | given-names: "Lauren A."
17 | -
18 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA"
19 | family-names: Brown
20 | given-names: "Hamish G."
21 | -
22 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA and Department of Materials Science and Engineering, University of California, Berkeley, CA 94720, USA"
23 | family-names: Zhao
24 | given-names: Shiteng
25 | -
26 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA and Department of Materials Science and Engineering, University of California, Berkeley, CA 94720, USA"
27 | family-names: Pelz
28 | given-names: "Philipp M."
29 | -
30 | affiliation: "Institut für Physik, Humboldt-Universität zu Berlin, Newtonstraße 15, 12489 Berlin, Germany"
31 | family-names: Pekin
32 | given-names: "Thomas C."
33 | -
34 | affiliation: "Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA"
35 | family-names: Barnard
36 | given-names: "Edward S."
37 | -
38 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA Department of Materials Science and Engineering, University of California, Berkeley, CA 94720, USA"
39 | family-names: Donohue
40 | given-names: Jennifer
41 | -
42 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA Department of Materials Science and Engineering, University of California, Berkeley, CA 94720, USA"
43 | family-names: "Rangel DaCosta"
44 | given-names: Luis
45 | -
46 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA Department of Materials Science and Engineering, University of California, Berkeley, CA 94720, USA"
47 | family-names: Kennedy
48 | given-names: Ellis
49 | -
50 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA"
51 | family-names: Xie
52 | given-names: Yujun
53 | -
54 | affiliation: "Los Alamos National Laboratory, Los Alamos, NM 87545, USA"
55 | family-names: Janish
56 | given-names: "Matthew T."
57 | -
58 | affiliation: "Los Alamos National Laboratory, Los Alamos, NM 87545, USA"
59 | family-names: Schneider
60 | given-names: "Matthew M."
61 | -
62 | affiliation: "Toyota Research Institute, Los Altos, CA 94022, USA"
63 | family-names: Herring
64 | given-names: Patrick
65 | -
66 | affiliation: "Toyota Research Institute, Los Altos, CA 94022, USA"
67 | family-names: Gopal
68 | given-names: Chirranjeevi
69 | -
70 | affiliation: "Toyota Research Institute, Los Altos, CA 94022, USA"
71 | family-names: Anapolsky
72 | given-names: Abraham
73 | -
74 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA"
75 | family-names: Dhall
76 | given-names: Rohan
77 | -
78 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA"
79 | family-names: Bustillo
80 | given-names: "Karen C."
81 | -
82 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA"
83 | family-names: Ercius
84 | given-names: Peter
85 | -
86 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA Department of Materials Science and Engineering, University of California, Berkeley, CA 94720, USA"
87 | family-names: Scott
88 | given-names: "Mary C."
89 | -
90 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA"
91 | family-names: Ciston
92 | given-names: Jim
93 | -
94 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA Department of Materials Science and Engineering, University of California, Berkeley, CA 94720, USA"
95 | family-names: Minor
96 | given-names: "Andrew M."
97 | -
98 | affiliation: "National Center for Electron Microscopy, Molecular Foundry, Lawrence Berkeley National Laboratory, 1 Cyclotron Road, Berkeley, CA 94720, USA"
99 | family-names: Ophus
100 | given-names: Colin
101 | title: "py4DSTEM: A Software Package for Four-Dimensional Scanning Transmission Electron Microscopy Data Analysis"
102 | version: 0.12.6
103 | doi: 10.1017/S1431927621000477
104 | date-released: 2021-05-21
105 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # The `py4DSTEM` GUI
3 |
4 | This repository hosts the `pyqt` based graphical 4D--STEM data browser that was originally part of **py4DSTEM** until version 0.13.11.
5 |
6 | ## Installation
7 | The GUI is available on PyPI and conda-forge:
8 |
9 | `pip install py4D-browser`
10 |
11 | `conda install -c conda-forge py4d-browser`
12 |
13 |
14 | ## Usage
15 | Run `py4DGUI` in your terminal to open the GUI. Then just drag and drop a 4D-STEM dataset into the window!
16 |
17 | ### Controls
18 | * Move the virtual detector and the real-space selector using the mouse or using the keyboard shortcuts: WASD moves the detector and IJKL moves the selector, and holding down shift moves 5 pixels at a time.
19 | * Auto scaling of both views is on by default. Press the "Autoscale" buttons in the bottom right to disable. Press either button to apply automatic scaling once, or Shift + click to lock autoscaling back on.
20 | * Different shapes of virtual detector are available in the "Detector Shape" menu, and different detector responses are available in the "Detector Response" menu.
21 | * The information in the bottom bar contains the details of the virtual detector used to generate the images, and can be entered into py4DSTEM to generate the same image.
22 | * The FFT pane can be switched between displaying the FFT of the virtual image and displaying the [exit wave power cepstrum](https://doi.org/10.1016/j.ultramic.2020.112994).
23 | * Virtual images can be exported either as the scaled and clipped displays shown in the GUI or as raw data. The exact datatype stored in the raw TIFF image depends on both the datatype of the dataset and the type of virtual image being displayed (in particular, integer datatypes are converted internally to floating point to prevent overflows when generating any synthesized virtual images).
24 | * If the [EMPAD-G2 Raw Reader](https://github.com/sezelt/empad2) is installed in the same environment, an extra menu will appear that allows the concatenated binary format data to be background subtracted and calibrated in the GUI. You can also save the calibrated data as an HDF5 file for later analysis.
25 |
26 | 
27 |
28 | The keyboard map in the Help menu was made using [this tool](https://archie-adams.github.io/keyboard-shortcut-map-maker/) and the map file is in the top level of this repo.
29 |
30 | ## About
31 |
32 | 
33 |
34 | **py4DSTEM** is an open source set of python tools for processing and analysis of four-dimensional scanning transmission electron microscopy (4D-STEM) data. Additional information:
35 |
36 | - [Our open access py4DSTEM publication in Microscopy and Microanalysis](https://doi.org/10.1017/S1431927621000477) describing this project and demonstrating a variety of applications.
37 | - [The py4DSTEM documentation pages](https://py4dstem.readthedocs.io/en/latest/index.html).
38 | - [Our open access 4D-STEM review in Microscopy and Microanalysis](https://doi.org/10.1017/S1431927619000497) describing this project and demonstrating a variety of applications.
39 |
40 |
41 | ### License
42 |
43 | GNU GPLv3
44 |
45 | **py4DSTEM** is open source software distributed under a GPLv3 license.
46 | It is free to use, alter, or build on, provided that any work derived from **py4DSTEM** is also kept free and open.
47 |
--------------------------------------------------------------------------------
/images/demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/py4dstem/py4D-browser/eb33d15d7675d749e24df67bac890914c067ac83/images/demo.gif
--------------------------------------------------------------------------------
/images/py4DSTEM_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/py4dstem/py4D-browser/eb33d15d7675d749e24df67bac890914c067ac83/images/py4DSTEM_logo.png
--------------------------------------------------------------------------------
/py4DGUI-keymap.html:
--------------------------------------------------------------------------------
1 | py4DGUI-keymap.htmlKeyboard Shortcut Map Maker
-
532 |
533 |
534 |
Keyboard Shortcuts
535 | 🚮
536 |
537 |
538 |
539 |
540 |
541 |
542 |
543 |
544 |
545 |
546 |
ESC
547 |
548 |
F1
549 |
F2
550 |
F3
551 |
F4
552 |
553 |
F5
554 |
F6
555 |
F7
556 |
F8
557 |
F9
558 |
F10
559 |
F11
560 |
F12
561 |
562 |
563 |
564 |
565 |
566 |
567 |
568 |
ESC
569 |
`
570 |
571 |
1
572 |
2
573 |
3
574 |
4
575 |
5
576 |
6
577 |
7
578 |
8
579 |
580 |
9
581 |
0
582 |
-
583 |
=
584 |
BACKSPACE
585 |
586 |
587 |
588 |
589 |
TAB
590 |
Q
591 |
WDetector Up
592 |
E
593 |
R
594 |
T
595 |
Y
596 |
U
597 |
ISelector Up
598 |
O
599 |
P
600 |
[ {
601 |
] }
602 |
\ |
603 |
604 |
605 |
606 |
CAPSLOCK
607 |
ADetector Left
608 |
SDetector Down
609 |
DDetector Right
610 |
F
611 |
G
612 |
H
613 |
JSelector Left
614 |
KSelector Down
615 |
LSelector Right
616 |
; :
617 |
' "
618 |
ENTER
619 |
620 |
621 |
622 |
SHIFTMove 5 px at once
623 |
Z
624 |
X
625 |
C
626 |
V
627 |
B
628 |
N
629 |
M
630 |
, <
631 |
. >
632 |
/ ?
633 |
SHIFT
634 |
635 |
636 |
637 |
CTRL
638 |
639 |
WIN
640 |
641 |
ALT
642 |
643 |
ALT
644 |
FN
645 |
MENU
646 |
647 |
CTRL
648 |
649 |
650 |
651 |
652 |
653 |
654 |
655 |
656 |
657 |
658 |
659 |
660 |
661 |
662 | PRTSC
663 |
INS
664 |
DEL
665 |
666 |
667 |
◁
668 |
669 |
670 |
671 |
672 | SCRLK
673 |
HOME
674 |
END
675 |
676 |
△
677 |
▽
678 |
679 |
680 |
681 |
PAUSE
682 |
683 |
PGUP
684 |
PGDN
685 |
686 |
687 |
▷
688 |
689 |
690 |
691 |
692 |
693 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools>=61.0"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [project]
6 | name = "py4D_browser"
7 | version = "1.2.1"
8 | authors = [
9 | { name="Steven Zeltmann", email="steven.zeltmann@lbl.gov" },
10 | ]
11 | description = "A 4D-STEM data browser built on py4DSTEM."
12 | readme = "README.md"
13 | requires-python = ">=3.10"
14 | classifiers = [
15 | "Programming Language :: Python :: 3",
16 | "Operating System :: OS Independent",
17 | ]
18 | dependencies = [
19 | "py4dstem >= 0.14.9",
20 | "emdfile >= 0.0.11",
21 | "h5py",
22 | "numpy >= 1.19",
23 | "matplotlib >= 3.2.2",
24 | "platformdirs",
25 | "PyQt5 >= 5.10",
26 | "pyqtgraph >= 0.11",
27 | "sigfig",
28 | ]
29 |
30 | [project.scripts]
31 | py4DGUI = "py4D_browser.runGUI:launch"
32 |
33 | [project.urls]
34 | "Homepage" = "https://github.com/py4dstem/py4D-browser"
35 | "Bug Tracker" = "https://github.com/py4dstem/py4D-browser/issues"
36 |
37 | [tool.pyright]
38 | venv = "py4dstem"
39 |
40 | [tool.setuptools]
41 | include-package-data = true
42 |
43 | [tool.setuptools.packages.find]
44 | where = ["src"]
45 |
46 | [tool.setuptools.package-data]
47 | py4D_browser = ["*.png"]
48 |
--------------------------------------------------------------------------------
/src/py4D_browser/__init__.py:
--------------------------------------------------------------------------------
1 | from py4D_browser.main_window import DataViewer
2 |
--------------------------------------------------------------------------------
/src/py4D_browser/dialogs.py:
--------------------------------------------------------------------------------
1 | from py4DSTEM import DataCube, data
2 | import pyqtgraph as pg
3 | import numpy as np
4 | from tqdm import tqdm
5 | from PyQt5.QtWidgets import QFrame, QPushButton, QApplication, QLabel
6 | from PyQt5.QtCore import pyqtSignal
7 | from PyQt5.QtCore import Qt, QObject
8 | from PyQt5.QtGui import QDoubleValidator
9 | from PyQt5.QtWidgets import (
10 | QDialog,
11 | QHBoxLayout,
12 | QVBoxLayout,
13 | QSpinBox,
14 | QLineEdit,
15 | QComboBox,
16 | QGroupBox,
17 | QGridLayout,
18 | QCheckBox,
19 | )
20 | from py4D_browser.utils import make_detector, StatusBarWriter
21 |
22 |
23 | class ResizeDialog(QDialog):
24 | def __init__(self, size, parent=None):
25 | super().__init__(parent=parent)
26 |
27 | self.new_size = size
28 | Nmax = size[0] * size[1]
29 |
30 | layout = QVBoxLayout(self)
31 |
32 | layout.addWidget(QLabel("Dataset size unknown. Please enter the shape:"))
33 |
34 | box_layout = QHBoxLayout()
35 | box_layout.addWidget(QLabel("X:"))
36 |
37 | xbox = QSpinBox()
38 | xbox.setRange(1, Nmax)
39 | xbox.setSingleStep(1)
40 | xbox.setKeyboardTracking(False)
41 | xbox.valueChanged.connect(self.x_box_changed)
42 | box_layout.addWidget(xbox)
43 |
44 | box_layout.addStretch()
45 | box_layout.addWidget(QLabel("Y:"))
46 |
47 | ybox = QSpinBox()
48 | ybox.setRange(1, Nmax)
49 | ybox.setSingleStep(1)
50 | ybox.setValue(Nmax)
51 | ybox.setKeyboardTracking(False)
52 | ybox.valueChanged.connect(self.y_box_changed)
53 | box_layout.addWidget(ybox)
54 |
55 | layout.addLayout(box_layout)
56 |
57 | button_layout = QHBoxLayout()
58 | button_layout.addStretch()
59 | done_button = QPushButton("Done")
60 | done_button.pressed.connect(self.close)
61 | button_layout.addWidget(done_button)
62 | layout.addLayout(button_layout)
63 |
64 | self.x_box = xbox
65 | self.y_box = ybox
66 | self.x_box_last = xbox.value()
67 | self.y_box_last = ybox.value()
68 | self.N = Nmax
69 |
70 | self.resize(600, 400)
71 |
72 | @classmethod
73 | def get_new_size(cls, size, parent=None):
74 | dialog = cls(size=size, parent=parent)
75 | dialog.exec_()
76 | return dialog.new_size
77 |
78 | def x_box_changed(self, new_value):
79 | if new_value == self.x_box_last:
80 | return
81 | x_new, y_new = self.get_next_rect(
82 | new_value, "down" if new_value < self.x_box_last else "up"
83 | )
84 |
85 | self.x_box_last = x_new
86 | self.y_box_last = y_new
87 |
88 | self.x_box.setValue(x_new)
89 | self.y_box.setValue(y_new)
90 |
91 | self.new_size = [x_new, y_new]
92 |
93 | def y_box_changed(self, new_value):
94 | if new_value == self.y_box_last:
95 | return
96 | y_new, x_new = self.get_next_rect(
97 | new_value, "down" if new_value < self.y_box_last else "up"
98 | )
99 |
100 | self.x_box_last = x_new
101 | self.y_box_last = y_new
102 |
103 | self.x_box.setValue(x_new)
104 | self.y_box.setValue(y_new)
105 |
106 | self.new_size = [x_new, y_new]
107 |
108 | def get_next_rect(self, current, direction):
109 | # get the next perfect rectangle
110 | iterator = (
111 | range(current, 0, -1) if direction == "down" else range(current, self.N + 1)
112 | )
113 |
114 | for i in iterator:
115 | if self.N % i == 0:
116 | return i, self.N // i
117 |
118 | raise ValueError("Factor finding failed, frustratingly.")
119 |
120 |
121 | class CalibrateDialog(QDialog):
122 | def __init__(self, datacube, parent, diffraction_selector_size=None):
123 | super().__init__(parent=parent)
124 |
125 | self.datacube = datacube
126 | self.parent = parent
127 | self.diffraction_selector_size = diffraction_selector_size
128 |
129 | layout = QVBoxLayout(self)
130 |
131 | ####### LAYOUT ########
132 |
133 | realspace_box = QGroupBox("Real Space")
134 | layout.addWidget(realspace_box)
135 | realspace_layout = QHBoxLayout()
136 | realspace_box.setLayout(realspace_layout)
137 |
138 | realspace_left_layout = QGridLayout()
139 | realspace_layout.addLayout(realspace_left_layout)
140 |
141 | realspace_left_layout.addWidget(QLabel("Pixel Size"), 0, 0, Qt.AlignRight)
142 | self.realspace_pix_box = QLineEdit()
143 | self.realspace_pix_box.setValidator(QDoubleValidator())
144 | realspace_left_layout.addWidget(self.realspace_pix_box, 0, 1)
145 |
146 | realspace_left_layout.addWidget(QLabel("Full Width"), 1, 0, Qt.AlignRight)
147 | self.realspace_fov_box = QLineEdit()
148 | realspace_left_layout.addWidget(self.realspace_fov_box, 1, 1)
149 |
150 | realspace_right_layout = QHBoxLayout()
151 | realspace_layout.addLayout(realspace_right_layout)
152 | self.realspace_unit_box = QComboBox()
153 | self.realspace_unit_box.addItems(["Å", "nm"])
154 | self.realspace_unit_box.setMinimumContentsLength(5)
155 | realspace_right_layout.addWidget(self.realspace_unit_box)
156 |
157 | diff_box = QGroupBox("Diffraction")
158 | layout.addWidget(diff_box)
159 | diff_layout = QHBoxLayout()
160 | diff_box.setLayout(diff_layout)
161 |
162 | diff_left_layout = QGridLayout()
163 | diff_layout.addLayout(diff_left_layout)
164 |
165 | diff_left_layout.addWidget(QLabel("Pixel Size"), 0, 0, Qt.AlignRight)
166 | self.diff_pix_box = QLineEdit()
167 | diff_left_layout.addWidget(self.diff_pix_box, 0, 1)
168 |
169 | diff_left_layout.addWidget(QLabel("Full Width"), 1, 0, Qt.AlignRight)
170 | self.diff_fov_box = QLineEdit()
171 | diff_left_layout.addWidget(self.diff_fov_box, 1, 1)
172 |
173 | diff_left_layout.addWidget(QLabel("Selection Radius"), 2, 0, Qt.AlignRight)
174 | self.diff_selection_box = QLineEdit()
175 | diff_left_layout.addWidget(self.diff_selection_box, 2, 1)
176 | self.diff_selection_box.setEnabled(self.diffraction_selector_size is not None)
177 |
178 | diff_right_layout = QHBoxLayout()
179 | diff_layout.addLayout(diff_right_layout)
180 | self.diff_unit_box = QComboBox()
181 | self.diff_unit_box.setMinimumContentsLength(5)
182 | self.diff_unit_box.addItems(
183 | [
184 | "mrad",
185 | "Å⁻¹",
186 | # "nm⁻¹",
187 | ]
188 | )
189 | diff_right_layout.addWidget(self.diff_unit_box)
190 |
191 | button_layout = QHBoxLayout()
192 | button_layout.addStretch()
193 | cancel_button = QPushButton("Cancel")
194 | cancel_button.pressed.connect(self.close)
195 | button_layout.addWidget(cancel_button)
196 | done_button = QPushButton("Done")
197 | done_button.pressed.connect(self.set_and_close)
198 | button_layout.addWidget(done_button)
199 | layout.addLayout(button_layout)
200 |
201 | ######### CALLBACKS ########
202 | self.realspace_pix_box.textEdited.connect(self.realspace_pix_box_changed)
203 | self.realspace_fov_box.textEdited.connect(self.realspace_fov_box_changed)
204 | self.diff_pix_box.textEdited.connect(self.diffraction_pix_box_changed)
205 | self.diff_fov_box.textEdited.connect(self.diffraction_fov_box_changed)
206 | self.diff_selection_box.textEdited.connect(
207 | self.diffraction_selection_box_changed
208 | )
209 |
210 | def realspace_pix_box_changed(self, new_text):
211 | pix_size = float(new_text)
212 |
213 | fov = pix_size * self.datacube.R_Ny
214 | self.realspace_fov_box.setText(f"{fov:g}")
215 |
216 | def realspace_fov_box_changed(self, new_text):
217 | fov = float(new_text)
218 |
219 | pix_size = fov / self.datacube.R_Ny
220 | self.realspace_pix_box.setText(f"{pix_size:g}")
221 |
222 | def diffraction_pix_box_changed(self, new_text):
223 | pix_size = float(new_text)
224 |
225 | fov = pix_size * self.datacube.Q_Ny
226 | self.diff_fov_box.setText(f"{fov:g}")
227 |
228 | if self.diffraction_selector_size:
229 | sel_size = pix_size * self.diffraction_selector_size
230 | self.diff_selection_box.setText(f"{sel_size:g}")
231 |
232 | def diffraction_fov_box_changed(self, new_text):
233 | fov = float(new_text)
234 |
235 | pix_size = fov / self.datacube.Q_Ny
236 | self.diff_pix_box.setText(f"{pix_size:g}")
237 |
238 | if self.diffraction_selector_size:
239 | sel_size = pix_size * self.diffraction_selector_size
240 | self.diff_selection_box.setText(f"{sel_size:g}")
241 |
242 | def diffraction_selection_box_changed(self, new_text):
243 | if self.diffraction_selector_size:
244 | sel_size = float(new_text)
245 |
246 | pix_size = sel_size / self.diffraction_selector_size
247 | fov = pix_size * self.datacube.Q_Nx
248 | self.diff_pix_box.setText(f"{pix_size:g}")
249 | self.diff_fov_box.setText(f"{fov:g}")
250 |
251 | sel_size = pix_size * self.diffraction_selector_size
252 | self.diff_selection_box.setText(f"{sel_size:g}")
253 |
254 | def set_and_close(self):
255 |
256 | print("Old calibration")
257 | print(self.datacube.calibration)
258 |
259 | realspace_text = self.realspace_pix_box.text()
260 | if realspace_text != "":
261 | realspace_pix = float(realspace_text)
262 | self.datacube.calibration.set_R_pixel_size(realspace_pix)
263 | self.datacube.calibration.set_R_pixel_units(
264 | self.realspace_unit_box.currentText().replace("Å", "A")
265 | )
266 |
267 | diff_text = self.diff_pix_box.text()
268 | if diff_text != "":
269 | diff_pix = float(diff_text)
270 | self.datacube.calibration.set_Q_pixel_size(diff_pix)
271 | translation = {
272 | "mrad": "mrad",
273 | "Å⁻¹": "A^-1",
274 | "nm⁻¹": "1/nm",
275 | }
276 | self.datacube.calibration.set_Q_pixel_units(
277 | translation[self.diff_unit_box.currentText()]
278 | )
279 |
280 | self.parent.update_scalebars()
281 |
282 | print("New calibration")
283 | print(self.datacube.calibration)
284 |
285 | self.close()
286 |
287 |
288 | class ManualTCBFDialog(QDialog):
289 | def __init__(self, parent):
290 | super().__init__(parent=parent)
291 |
292 | self.parent = parent
293 |
294 | layout = QVBoxLayout(self)
295 |
296 | ####### LAYOUT ########
297 |
298 | params_box = QGroupBox("Parameters")
299 | layout.addWidget(params_box)
300 |
301 | params_layout = QGridLayout()
302 | params_box.setLayout(params_layout)
303 |
304 | params_layout.addWidget(QLabel("Rotation [deg]"), 0, 0, Qt.AlignRight)
305 | self.rotation_box = QLineEdit()
306 | self.rotation_box.setValidator(QDoubleValidator())
307 | params_layout.addWidget(self.rotation_box, 0, 1)
308 |
309 | params_layout.addWidget(QLabel("Transpose x/y"), 1, 0, Qt.AlignRight)
310 | self.transpose_box = QCheckBox()
311 | params_layout.addWidget(self.transpose_box, 1, 1)
312 |
313 | params_layout.addWidget(QLabel("Max Shift [px]"), 2, 0, Qt.AlignRight)
314 | self.max_shift_box = QLineEdit()
315 | self.max_shift_box.setValidator(QDoubleValidator())
316 | params_layout.addWidget(self.max_shift_box, 2, 1)
317 |
318 | params_layout.addWidget(QLabel("Pad Images"), 3, 0, Qt.AlignRight)
319 | self.pad_checkbox = QCheckBox()
320 | params_layout.addWidget(self.pad_checkbox, 3, 1)
321 |
322 | button_layout = QHBoxLayout()
323 | button_layout.addStretch()
324 | cancel_button = QPushButton("Cancel")
325 | cancel_button.pressed.connect(self.close)
326 | button_layout.addWidget(cancel_button)
327 | done_button = QPushButton("Reconstruct")
328 | done_button.pressed.connect(self.reconstruct)
329 | button_layout.addWidget(done_button)
330 | layout.addLayout(button_layout)
331 |
332 | def reconstruct(self):
333 | datacube = self.parent.datacube
334 |
335 | # tcBF requires an area detector for generating the mask
336 | detector_shape = (
337 | self.parent.detector_shape_group.checkedAction().text().replace("&", "")
338 | )
339 | if detector_shape not in [
340 | "Rectangular",
341 | "Circle",
342 | ]:
343 | self.parent.statusBar().showMessage(
344 | "tcBF requires a selection of the BF disk"
345 | )
346 | return
347 |
348 | if detector_shape == "Rectangular":
349 | # Get slices corresponding to ROI
350 | slices, _ = self.parent.virtual_detector_roi.getArraySlice(
351 | self.parent.datacube.data[0, 0, :, :],
352 | self.parent.diffraction_space_widget.getImageItem(),
353 | )
354 | slice_y, slice_x = slices
355 |
356 | mask = np.zeros(
357 | (self.parent.datacube.Q_Nx, self.parent.datacube.Q_Ny), dtype=np.bool_
358 | )
359 | mask[slice_x, slice_y] = True
360 |
361 | elif detector_shape == "Circle":
362 | R = self.parent.virtual_detector_roi.size()[0] / 2.0
363 |
364 | x0 = self.parent.virtual_detector_roi.pos()[0] + R
365 | y0 = self.parent.virtual_detector_roi.pos()[1] + R
366 |
367 | mask = make_detector(
368 | (self.parent.datacube.Q_Nx, self.parent.datacube.Q_Ny),
369 | "circle",
370 | ((x0, y0), R),
371 | )
372 | else:
373 | raise ValueError("idk how we got here...")
374 |
375 | if self.max_shift_box.text() == "":
376 | self.parent.statusBar().showMessage("Max Shift must be specified")
377 | return
378 |
379 | rotation = np.radians(float(self.rotation_box.text() or 0.0))
380 | transpose = self.transpose_box.checkState()
381 | max_shift = float(self.max_shift_box.text())
382 |
383 | x, y = np.meshgrid(
384 | np.arange(datacube.Q_Nx), np.arange(datacube.Q_Ny), indexing="ij"
385 | )
386 |
387 | mask_comx = np.sum(mask * x) / np.sum(mask)
388 | mask_comy = np.sum(mask * y) / np.sum(mask)
389 |
390 | pix_coord_x = x - mask_comx
391 | pix_coord_y = y - mask_comy
392 |
393 | q_pix = np.hypot(pix_coord_x, pix_coord_y)
394 | # unrotated shifts in scan pixels
395 | shifts_pix_x = pix_coord_x / np.max(q_pix * mask) * max_shift
396 | shifts_pix_y = pix_coord_y / np.max(q_pix * mask) * max_shift
397 |
398 | R = np.array(
399 | [
400 | [np.cos(rotation), -np.sin(rotation)],
401 | [np.sin(rotation), np.cos(rotation)],
402 | ]
403 | )
404 | T = np.array([[0.0, 1.0], [1.0, 0.0]])
405 |
406 | if transpose:
407 | R = T @ R
408 |
409 | shifts_pix = np.stack([shifts_pix_x, shifts_pix_y], axis=2) @ R
410 | shifts_pix_x, shifts_pix_y = shifts_pix[..., 0], shifts_pix[..., 1]
411 |
412 | # generate image to accumulate reconstruction
413 | pad = self.pad_checkbox.checkState()
414 | pad_width = int(
415 | np.maximum(np.abs(shifts_pix_x).max(), np.abs(shifts_pix_y).max())
416 | )
417 |
418 | reconstruction = (
419 | np.zeros((datacube.R_Nx + 2 * pad_width, datacube.R_Ny + 2 * pad_width))
420 | if pad
421 | else np.zeros((datacube.R_Nx, datacube.R_Ny))
422 | )
423 |
424 | qx = np.fft.fftfreq(reconstruction.shape[0])
425 | qy = np.fft.fftfreq(reconstruction.shape[1])
426 |
427 | qx_operator, qy_operator = np.meshgrid(qx, qy, indexing="ij")
428 | qx_operator = qx_operator * -2.0j * np.pi
429 | qy_operator = qy_operator * -2.0j * np.pi
430 |
431 | # loop over images and shift
432 | img_indices = np.argwhere(mask)
433 | for mx, my in tqdm(
434 | img_indices,
435 | desc="Shifting images",
436 | file=StatusBarWriter(self.parent.statusBar()),
437 | mininterval=1.0,
438 | ):
439 | if mask[mx, my]:
440 | img_raw = datacube.data[:, :, mx, my]
441 |
442 | if pad:
443 | img = np.zeros_like(reconstruction) + img_raw.mean()
444 | img[
445 | pad_width : img_raw.shape[0] + pad_width,
446 | pad_width : img_raw.shape[1] + pad_width,
447 | ] = img_raw
448 | else:
449 | img = img_raw
450 |
451 | reconstruction += np.real(
452 | np.fft.ifft2(
453 | np.fft.fft2(img)
454 | * np.exp(
455 | qx_operator * shifts_pix_x[mx, my]
456 | + qy_operator * shifts_pix_y[mx, my]
457 | )
458 | )
459 | )
460 |
461 | # crop away padding so the image lines up with the original
462 | if pad:
463 | reconstruction = reconstruction[pad_width:-pad_width, pad_width:-pad_width]
464 |
465 | self.parent.set_virtual_image(reconstruction, reset=True)
466 |
--------------------------------------------------------------------------------
/src/py4D_browser/empad2_reader.py:
--------------------------------------------------------------------------------
1 | import empad2
2 | from PyQt5.QtWidgets import QFileDialog, QMessageBox, QApplication
3 | import numpy as np
4 | from py4D_browser.utils import StatusBarWriter
5 |
6 |
7 | def set_empad2_sensor(self, sensor_name):
8 | self.empad2_calibrations = empad2.load_calibration_data(sensor=sensor_name)
9 | self.statusBar().showMessage(f"{sensor_name} calibrations loaded", 5_000)
10 |
11 |
12 | def load_empad2_background(self):
13 | if self.empad2_calibrations is not None:
14 | filename = raw_file_dialog(self)
15 | self.empad2_background = empad2.load_background(
16 | filepath=filename, calibration_data=self.empad2_calibrations
17 | )
18 | self.statusBar().showMessage("Background data loaded", 5_000)
19 | else:
20 | QMessageBox.warning(
21 | self, "No calibrations loaded!", "Please select a sensor first"
22 | )
23 |
24 |
25 | def load_empad2_dataset(self):
26 | if self.empad2_calibrations is not None:
27 | dummy_data = False
28 | if self.empad2_background is None:
29 | continue_wo_bkg = QMessageBox.question(
30 | self,
31 | "Load without background?",
32 | "Background data has not been loaded. Do you want to continue loading data?",
33 | )
34 | if continue_wo_bkg == QMessageBox.No:
35 | return
36 | else:
37 | self.empad2_background = {
38 | "even": np.zeros((128, 128), dtype=np.float32),
39 | "odd": np.zeros((128, 128), dtype=np.float32),
40 | }
41 | dummy_data = True
42 |
43 | filename = raw_file_dialog(self)
44 | self.datacube = empad2.load_dataset(
45 | filename,
46 | self.empad2_background,
47 | self.empad2_calibrations,
48 | _tqdm_args={
49 | "desc": "Loading",
50 | "file": StatusBarWriter(self.statusBar()),
51 | "mininterval": 1.0,
52 | },
53 | )
54 |
55 | if dummy_data:
56 | self.empad2_background = None
57 |
58 | self.update_diffraction_space_view(reset=True)
59 | self.update_real_space_view(reset=True)
60 |
61 | self.setWindowTitle(filename)
62 |
63 | else:
64 | QMessageBox.warning(
65 | self, "No calibrations loaded!", "Please select a sensor first"
66 | )
67 |
68 |
69 | def raw_file_dialog(browser):
70 | filename = QFileDialog.getOpenFileName(
71 | browser,
72 | "Open EMPAD-G2 Data",
73 | "",
74 | "EMPAD-G2 Data (*.raw);;Any file(*)",
75 | )
76 | if filename is not None and len(filename[0]) > 0:
77 | return filename[0]
78 | else:
79 | print("File was invalid, or something?")
80 | raise ValueError("Could not read file")
81 |
--------------------------------------------------------------------------------
/src/py4D_browser/help_menu.py:
--------------------------------------------------------------------------------
1 | from PyQt5 import QtGui, QtCore
2 | from PyQt5.QtWidgets import (
3 | QWidget,
4 | QDialog,
5 | QVBoxLayout,
6 | )
7 | from pathlib import Path
8 |
9 |
10 | class KeyboardMapMenu(QDialog):
11 | def __init__(self, parent=None):
12 | super().__init__(parent=parent)
13 |
14 | self.keymap = QtGui.QPixmap(
15 | str(Path(__file__).parent.absolute() / "py4DGUI-keymap.png")
16 | ).scaledToWidth(1500)
17 | label = Label()
18 |
19 | label.setPixmap(self.keymap)
20 |
21 | layout = QVBoxLayout()
22 | layout.addWidget(label)
23 | self.setLayout(layout)
24 |
25 | self.resize(self.keymap.width(), self.keymap.height())
26 |
27 |
28 | # Widget that smoothly resizes Pixmap keeping aspect ratio
29 | class Label(QWidget):
30 | def __init__(self, parent=None):
31 | QWidget.__init__(self, parent=parent)
32 | self.p = QtGui.QPixmap()
33 |
34 | def setPixmap(self, p):
35 | self.p = p
36 | self.update()
37 |
38 | def paintEvent(self, event):
39 | if not self.p.isNull():
40 | painter = QtGui.QPainter(self)
41 | painter.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
42 | rect = self.rect()
43 | rect.setHeight(int(self.p.height() * rect.width() / self.p.width()))
44 | painter.drawPixmap(rect, self.p)
45 |
--------------------------------------------------------------------------------
/src/py4D_browser/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/py4dstem/py4D-browser/eb33d15d7675d749e24df67bac890914c067ac83/src/py4D_browser/logo.png
--------------------------------------------------------------------------------
/src/py4D_browser/main_window.py:
--------------------------------------------------------------------------------
1 | from PyQt5 import QtCore, QtGui
2 | from PyQt5.QtWidgets import (
3 | QApplication,
4 | QMainWindow,
5 | QWidget,
6 | QMenu,
7 | QAction,
8 | QHBoxLayout,
9 | QSplitter,
10 | QActionGroup,
11 | QLabel,
12 | QToolTip,
13 | QPushButton,
14 | QShortcut,
15 | )
16 |
17 | from matplotlib.backend_bases import tools
18 | import pyqtgraph as pg
19 | import numpy as np
20 |
21 | from functools import partial
22 | from pathlib import Path
23 | import importlib
24 | import os
25 | import platformdirs
26 |
27 | from py4D_browser.utils import pg_point_roi, VLine, LatchingButton
28 | from py4D_browser.scalebar import ScaleBar
29 |
30 |
31 | class DataViewer(QMainWindow):
32 | """
33 | The class is used by instantiating and then entering the main Qt loop with, e.g.:
34 | app = DataViewer(sys.argv)
35 | app.exec_()
36 | """
37 |
38 | LOG_SCALE_MIN_VALUE = 1e-6
39 |
40 | from py4D_browser.menu_actions import (
41 | load_file,
42 | load_data_arina,
43 | load_data_auto,
44 | load_data_bin,
45 | load_data_mmap,
46 | show_file_dialog,
47 | get_savefile_name,
48 | export_datacube,
49 | export_virtual_image,
50 | show_keyboard_map,
51 | show_calibration_dialog,
52 | reshape_data,
53 | update_scalebars,
54 | reconstruct_tcBF_auto,
55 | reconstruct_tcBF_manual,
56 | )
57 |
58 | from py4D_browser.update_views import (
59 | set_virtual_image,
60 | set_diffraction_image,
61 | _render_virtual_image,
62 | _render_diffraction_image,
63 | update_diffraction_space_view,
64 | update_real_space_view,
65 | update_realspace_detector,
66 | update_diffraction_detector,
67 | set_diffraction_autoscale_range,
68 | set_real_space_autoscale_range,
69 | nudge_real_space_selector,
70 | nudge_diffraction_selector,
71 | update_annulus_pos,
72 | update_annulus_radii,
73 | update_tooltip,
74 | )
75 |
76 | HAS_EMPAD2 = importlib.util.find_spec("empad2") is not None
77 | if HAS_EMPAD2:
78 | from py4D_browser.empad2_reader import (
79 | set_empad2_sensor,
80 | load_empad2_background,
81 | load_empad2_dataset,
82 | )
83 |
84 | def __init__(self, argv):
85 | super().__init__()
86 | # Define this as the QApplication object
87 | self.qtapp = QApplication.instance()
88 | if not self.qtapp:
89 | self.qtapp = QApplication(argv)
90 |
91 | self.setWindowTitle("py4DSTEM")
92 |
93 | icon = QtGui.QIcon(str(Path(__file__).parent.absolute() / "logo.png"))
94 | self.setWindowIcon(icon)
95 | self.qtapp.setWindowIcon(icon)
96 |
97 | self.setWindowTitle("py4DSTEM")
98 | self.setAcceptDrops(True)
99 |
100 | self.datacube = None
101 |
102 | # Load settings from cofig file
103 | config_path = os.path.join(
104 | platformdirs.user_config_dir("py4DGUI", "py4DSTEM"), "GUI_config.ini"
105 | )
106 | print(f"Loading configuration from {config_path}")
107 | QtCore.QCoreApplication.setOrganizationName("py4DSTEM")
108 | QtCore.QCoreApplication.setOrganizationDomain("py4DSTEM.com")
109 | QtCore.QCoreApplication.setApplicationName("py4DGUI")
110 | self.settings = QtCore.QSettings(config_path, QtCore.QSettings.Format.IniFormat)
111 |
112 | # Reset stored state if so asked:
113 | if os.environ.get("PY4DGUI_RESET"):
114 | self.settings.remove("last_state")
115 | print("Cleared saved state, using defaults...")
116 |
117 | self.setup_menus()
118 | self.setup_views()
119 |
120 | # setup listener for tooltip
121 | self.tooltip_timer = pg.ThreadsafeTimer()
122 | self.tooltip_timer.timeout.connect(self.update_tooltip)
123 | self.tooltip_timer.start(1000 // 30) # run tooltip at 30 Hz
124 | font = QtGui.QFont(self.font())
125 | font.setPointSize(10)
126 | QToolTip.setFont(font)
127 |
128 | self.resize(
129 | self.settings.value("last_state/window_size", QtCore.QSize(1000, 800)),
130 | )
131 |
132 | self.show()
133 |
134 | # If a file was passed on the command line, open it
135 | if len(argv) > 1:
136 | self.load_file(argv[1])
137 |
138 | # launch pyqtgraph's debug console if environment variable exists
139 | if os.environ.get("PY4DGUI_DEBUG"):
140 | pg.dbg()
141 |
142 | def setup_menus(self):
143 | self.menu_bar = self.menuBar()
144 |
145 | # File menu
146 | self.file_menu = QMenu("&File", self)
147 | self.menu_bar.addMenu(self.file_menu)
148 |
149 | import_label = QAction("Import", self)
150 | import_label.setDisabled(True)
151 | self.file_menu.addAction(import_label)
152 |
153 | self.load_auto_action = QAction("&Load Data...", self)
154 | self.load_auto_action.triggered.connect(self.load_data_auto)
155 | self.file_menu.addAction(self.load_auto_action)
156 | self.load_auto_action.setShortcut(QtGui.QKeySequence("Ctrl+O"))
157 |
158 | self.load_mmap_action = QAction("Load &Memory Map...", self)
159 | self.load_mmap_action.triggered.connect(self.load_data_mmap)
160 | self.file_menu.addAction(self.load_mmap_action)
161 |
162 | self.load_binned_action = QAction("Load Data &Binned...", self)
163 | self.load_binned_action.triggered.connect(self.load_data_bin)
164 | self.file_menu.addAction(self.load_binned_action)
165 |
166 | self.load_arina_action = QAction("Load &Arina Data...", self)
167 | self.load_arina_action.triggered.connect(self.load_data_arina)
168 | self.file_menu.addAction(self.load_arina_action)
169 |
170 | self.reshape_data_action = QAction("&Reshape Data...", self)
171 | self.reshape_data_action.triggered.connect(self.reshape_data)
172 | self.file_menu.addAction(self.reshape_data_action)
173 |
174 | self.file_menu.addSeparator()
175 |
176 | export_label = QAction("Export", self)
177 | export_label.setDisabled(True)
178 | self.file_menu.addAction(export_label)
179 |
180 | # Submenu to export datacube
181 | datacube_export_menu = QMenu("Export Datacube", self)
182 | self.file_menu.addMenu(datacube_export_menu)
183 | for method in ["Raw float32", "py4DSTEM HDF5", "Plain HDF5"]:
184 | menu_item = datacube_export_menu.addAction(method)
185 | menu_item.triggered.connect(partial(self.export_datacube, method))
186 | if method == "py4DSTEM HDF5":
187 | menu_item.setShortcut(QtGui.QKeySequence("Ctrl+S"))
188 |
189 | # Submenu to export virtual image
190 | vimg_export_menu = QMenu("Export Virtual Image", self)
191 | self.file_menu.addMenu(vimg_export_menu)
192 | for method in ["PNG (display)", "TIFF (display)", "TIFF (raw)"]:
193 | menu_item = vimg_export_menu.addAction(method)
194 | menu_item.triggered.connect(
195 | partial(self.export_virtual_image, method, "image")
196 | )
197 |
198 | # Submenu to export diffraction
199 | vdiff_export_menu = QMenu("Export Diffraction Pattern", self)
200 | self.file_menu.addMenu(vdiff_export_menu)
201 | for method in ["PNG (display)", "TIFF (display)", "TIFF (raw)"]:
202 | menu_item = vdiff_export_menu.addAction(method)
203 | menu_item.triggered.connect(
204 | partial(self.export_virtual_image, method, "diffraction")
205 | )
206 |
207 | # EMPAD2 menu
208 | if self.HAS_EMPAD2:
209 | self.empad2_calibrations = None
210 | self.empad2_background = None
211 |
212 | self.empad2_menu = QMenu("&EMPAD-G2", self)
213 | self.menu_bar.addMenu(self.empad2_menu)
214 |
215 | sensor_menu = self.empad2_menu.addMenu("&Sensor")
216 | calibration_action_group = QActionGroup(self)
217 | calibration_action_group.setExclusive(True)
218 | from empad2 import SENSORS
219 |
220 | for name, sensor in SENSORS.items():
221 | menu_item = sensor_menu.addAction(sensor["display-name"])
222 | calibration_action_group.addAction(menu_item)
223 | menu_item.setCheckable(True)
224 | menu_item.triggered.connect(partial(self.set_empad2_sensor, name))
225 |
226 | self.empad2_menu.addAction("Load &Background...").triggered.connect(
227 | self.load_empad2_background
228 | )
229 | self.empad2_menu.addAction("Load &Dataset...").triggered.connect(
230 | self.load_empad2_dataset
231 | )
232 |
233 | # Scaling Menu
234 | self.scaling_menu = QMenu("&Scaling", self)
235 | self.menu_bar.addMenu(self.scaling_menu)
236 |
237 | # Diffraction scaling
238 | diff_scaling_group = QActionGroup(self)
239 | diff_scaling_group.setExclusive(True)
240 | self.diff_scaling_group = diff_scaling_group
241 | diff_menu_separator = QAction("Diffraction", self)
242 | diff_menu_separator.setDisabled(True)
243 | self.scaling_menu.addAction(diff_menu_separator)
244 |
245 | diff_scale_linear_action = QAction("Linear", self)
246 | diff_scale_linear_action.setCheckable(True)
247 | diff_scale_linear_action.triggered.connect(
248 | partial(self._render_diffraction_image, True)
249 | )
250 | diff_scaling_group.addAction(diff_scale_linear_action)
251 | self.scaling_menu.addAction(diff_scale_linear_action)
252 |
253 | diff_scale_log_action = QAction("Log", self)
254 | diff_scale_log_action.setCheckable(True)
255 | diff_scale_log_action.triggered.connect(
256 | partial(self._render_diffraction_image, True)
257 | )
258 | diff_scaling_group.addAction(diff_scale_log_action)
259 | self.scaling_menu.addAction(diff_scale_log_action)
260 |
261 | diff_scale_sqrt_action = QAction("Square Root", self)
262 | diff_scale_sqrt_action.setCheckable(True)
263 | diff_scale_sqrt_action.triggered.connect(
264 | partial(self._render_diffraction_image, True)
265 | )
266 | diff_scaling_group.addAction(diff_scale_sqrt_action)
267 | diff_scale_sqrt_action.setChecked(True)
268 | self.scaling_menu.addAction(diff_scale_sqrt_action)
269 |
270 | self.scaling_menu.addSeparator()
271 |
272 | # Real space scaling
273 | vimg_scaling_group = QActionGroup(self)
274 | vimg_scaling_group.setExclusive(True)
275 | self.vimg_scaling_group = vimg_scaling_group
276 |
277 | vimg_menu_separator = QAction("Virtual Image", self)
278 | vimg_menu_separator.setDisabled(True)
279 | self.scaling_menu.addAction(vimg_menu_separator)
280 |
281 | vimg_scale_linear_action = QAction("Linear", self)
282 | self.vimg_scale_linear_action = vimg_scale_linear_action # Save this one!
283 | vimg_scale_linear_action.setCheckable(True)
284 | vimg_scale_linear_action.setChecked(True)
285 | vimg_scale_linear_action.triggered.connect(
286 | partial(self._render_virtual_image, True)
287 | )
288 | vimg_scaling_group.addAction(vimg_scale_linear_action)
289 | self.scaling_menu.addAction(vimg_scale_linear_action)
290 |
291 | vimg_scale_log_action = QAction("Log", self)
292 | vimg_scale_log_action.setCheckable(True)
293 | vimg_scale_log_action.triggered.connect(
294 | partial(self._render_virtual_image, True)
295 | )
296 | vimg_scaling_group.addAction(vimg_scale_log_action)
297 | self.scaling_menu.addAction(vimg_scale_log_action)
298 |
299 | vimg_scale_sqrt_action = QAction("Square Root", self)
300 | vimg_scale_sqrt_action.setCheckable(True)
301 | vimg_scale_sqrt_action.triggered.connect(
302 | partial(self._render_virtual_image, True)
303 | )
304 | vimg_scaling_group.addAction(vimg_scale_sqrt_action)
305 | self.scaling_menu.addAction(vimg_scale_sqrt_action)
306 |
307 | # Autorange menu
308 | self.autorange_menu = QMenu("&Autorange", self)
309 | self.menu_bar.addMenu(self.autorange_menu)
310 |
311 | diff_autoscale_separator = QAction("Diffraction", self)
312 | diff_autoscale_separator.setDisabled(True)
313 | self.autorange_menu.addAction(diff_autoscale_separator)
314 |
315 | diff_range_group = QActionGroup(self)
316 | diff_range_group.setExclusive(True)
317 |
318 | scale_range_default = self.settings.value(
319 | "last_state/diffraction_autorange", [0.1, 99.9], type=float
320 | )
321 | for scale_range in [(0, 100), (0.1, 99.9), (1, 99), (2, 98), (5, 95)]:
322 | action = QAction(f"{scale_range[0]}% – {scale_range[1]}%", self)
323 | diff_range_group.addAction(action)
324 | self.autorange_menu.addAction(action)
325 | action.setCheckable(True)
326 | action.triggered.connect(
327 | partial(self.set_diffraction_autoscale_range, scale_range)
328 | )
329 | # set default
330 | if (
331 | scale_range[0] == scale_range_default[0]
332 | and scale_range[1] == scale_range_default[1]
333 | ):
334 | action.setChecked(True)
335 | self.set_diffraction_autoscale_range(scale_range, redraw=False)
336 |
337 | self.autorange_menu.addSeparator()
338 |
339 | vimg_autoscale_separator = QAction("Virtual Image", self)
340 | vimg_autoscale_separator.setDisabled(True)
341 | self.autorange_menu.addAction(vimg_autoscale_separator)
342 |
343 | vimg_range_group = QActionGroup(self)
344 | vimg_range_group.setExclusive(True)
345 |
346 | scale_range_default = self.settings.value(
347 | "last_state/realspace_autorange", [0.1, 99.9], type=float
348 | )
349 | for scale_range in [(0, 100), (0.1, 99.9), (1, 99), (2, 98), (5, 95)]:
350 | action = QAction(f"{scale_range[0]}% – {scale_range[1]}%", self)
351 | vimg_range_group.addAction(action)
352 | self.autorange_menu.addAction(action)
353 | action.setCheckable(True)
354 | action.triggered.connect(
355 | partial(self.set_real_space_autoscale_range, scale_range)
356 | )
357 | # set default
358 | if (
359 | scale_range[0] == scale_range_default[0]
360 | and scale_range[1] == scale_range_default[1]
361 | ):
362 | action.setChecked(True)
363 | self.set_real_space_autoscale_range(scale_range, redraw=False)
364 |
365 | # Detector Response Menu
366 | self.detector_menu = QMenu("&Detector Response", self)
367 | self.menu_bar.addMenu(self.detector_menu)
368 |
369 | detector_mode_separator = QAction("Diffraction", self)
370 | detector_mode_separator.setDisabled(True)
371 | self.detector_menu.addAction(detector_mode_separator)
372 |
373 | detector_mode_group = QActionGroup(self)
374 | detector_mode_group.setExclusive(True)
375 | self.detector_mode_group = detector_mode_group
376 |
377 | detector_integrating_action = QAction("&Integrating", self)
378 | detector_integrating_action.setCheckable(True)
379 | detector_integrating_action.setChecked(True)
380 | detector_integrating_action.triggered.connect(
381 | partial(self.update_real_space_view, True)
382 | )
383 | detector_mode_group.addAction(detector_integrating_action)
384 | self.detector_menu.addAction(detector_integrating_action)
385 |
386 | detector_maximum_action = QAction("&Maximum", self)
387 | detector_maximum_action.setCheckable(True)
388 | detector_maximum_action.triggered.connect(
389 | partial(self.update_real_space_view, True)
390 | )
391 | detector_mode_group.addAction(detector_maximum_action)
392 | self.detector_menu.addAction(detector_maximum_action)
393 |
394 | detector_CoM = QAction("C&oM", self)
395 | detector_CoM.setCheckable(True)
396 | detector_CoM.triggered.connect(partial(self.update_real_space_view, True))
397 | detector_mode_group.addAction(detector_CoM)
398 | self.detector_menu.addAction(detector_CoM)
399 |
400 | detector_CoMx = QAction("CoM &X", self)
401 | detector_CoMx.setCheckable(True)
402 | detector_CoMx.triggered.connect(partial(self.update_real_space_view, True))
403 | detector_mode_group.addAction(detector_CoMx)
404 | self.detector_menu.addAction(detector_CoMx)
405 |
406 | detector_CoMy = QAction("CoM &Y", self)
407 | detector_CoMy.setCheckable(True)
408 | detector_CoMy.triggered.connect(partial(self.update_real_space_view, True))
409 | detector_mode_group.addAction(detector_CoMy)
410 | self.detector_menu.addAction(detector_CoMy)
411 |
412 | detector_iCoM = QAction("i&CoM", self)
413 | detector_iCoM.setCheckable(True)
414 | detector_iCoM.triggered.connect(partial(self.update_real_space_view, True))
415 | detector_mode_group.addAction(detector_iCoM)
416 | self.detector_menu.addAction(detector_iCoM)
417 |
418 | # Detector Response for realspace selector
419 | self.detector_menu.addSeparator()
420 | rs_detector_mode_separator = QAction("Virtual Image", self)
421 | rs_detector_mode_separator.setDisabled(True)
422 | self.detector_menu.addAction(rs_detector_mode_separator)
423 |
424 | realspace_detector_mode_group = QActionGroup(self)
425 | realspace_detector_mode_group.setExclusive(True)
426 | self.realspace_detector_mode_group = realspace_detector_mode_group
427 |
428 | detector_integrating_action = QAction("&Integrating", self)
429 | detector_integrating_action.setCheckable(True)
430 | detector_integrating_action.setChecked(True)
431 | detector_integrating_action.triggered.connect(
432 | partial(self.update_diffraction_space_view, True)
433 | )
434 | realspace_detector_mode_group.addAction(detector_integrating_action)
435 | self.detector_menu.addAction(detector_integrating_action)
436 |
437 | detector_maximum_action = QAction("&Maximum", self)
438 | detector_maximum_action.setCheckable(True)
439 | detector_maximum_action.triggered.connect(
440 | partial(self.update_diffraction_space_view, True)
441 | )
442 | realspace_detector_mode_group.addAction(detector_maximum_action)
443 | self.detector_menu.addAction(detector_maximum_action)
444 |
445 | # Detector Shape Menu
446 | self.detector_shape_menu = QMenu("Detector &Shape", self)
447 | self.menu_bar.addMenu(self.detector_shape_menu)
448 |
449 | detector_shape_group = QActionGroup(self)
450 | detector_shape_group.setExclusive(True)
451 | self.detector_shape_group = detector_shape_group
452 |
453 | diffraction_detector_separator = QAction("Diffraction", self)
454 | diffraction_detector_separator.setDisabled(True)
455 | self.detector_shape_menu.addAction(diffraction_detector_separator)
456 |
457 | detector_point_action = QAction("&Point", self)
458 | detector_point_action.setCheckable(True)
459 | detector_point_action.setChecked(True) # Default
460 | detector_point_action.triggered.connect(self.update_diffraction_detector)
461 | detector_shape_group.addAction(detector_point_action)
462 | self.detector_shape_menu.addAction(detector_point_action)
463 |
464 | detector_rectangle_action = QAction("&Rectangular", self)
465 | detector_rectangle_action.setCheckable(True)
466 | # detector_rectangle_action.setChecked(True)
467 | detector_rectangle_action.triggered.connect(self.update_diffraction_detector)
468 | detector_shape_group.addAction(detector_rectangle_action)
469 | self.detector_shape_menu.addAction(detector_rectangle_action)
470 |
471 | detector_circle_action = QAction("&Circle", self)
472 | detector_circle_action.setCheckable(True)
473 | detector_circle_action.triggered.connect(self.update_diffraction_detector)
474 | detector_shape_group.addAction(detector_circle_action)
475 | self.detector_shape_menu.addAction(detector_circle_action)
476 |
477 | detector_annulus_action = QAction("&Annulus", self)
478 | detector_annulus_action.setCheckable(True)
479 | detector_annulus_action.triggered.connect(self.update_diffraction_detector)
480 | detector_shape_group.addAction(detector_annulus_action)
481 | self.detector_shape_menu.addAction(detector_annulus_action)
482 |
483 | self.detector_shape_menu.addSeparator()
484 |
485 | diffraction_detector_separator = QAction("Virtual Image", self)
486 | diffraction_detector_separator.setDisabled(True)
487 | self.detector_shape_menu.addAction(diffraction_detector_separator)
488 |
489 | rs_detector_shape_group = QActionGroup(self)
490 | rs_detector_shape_group.setExclusive(True)
491 | self.rs_detector_shape_group = rs_detector_shape_group
492 |
493 | rs_detector_point_action = QAction("Poin&t", self)
494 | rs_detector_point_action.setCheckable(True)
495 | rs_detector_point_action.setChecked(True) # Default
496 | rs_detector_point_action.triggered.connect(self.update_realspace_detector)
497 | rs_detector_shape_group.addAction(rs_detector_point_action)
498 | self.detector_shape_menu.addAction(rs_detector_point_action)
499 |
500 | detector_rectangle_action = QAction("Rectan&gular", self)
501 | detector_rectangle_action.setCheckable(True)
502 | detector_rectangle_action.triggered.connect(self.update_realspace_detector)
503 | rs_detector_shape_group.addAction(detector_rectangle_action)
504 | self.detector_shape_menu.addAction(detector_rectangle_action)
505 |
506 | self.fft_menu = QMenu("FF&T View", self)
507 | self.menu_bar.addMenu(self.fft_menu)
508 |
509 | self.fft_source_action_group = QActionGroup(self)
510 | self.fft_source_action_group.setExclusive(True)
511 | img_fft_action = QAction("Virtual Image FFT", self)
512 | img_fft_action.setCheckable(True)
513 | img_fft_action.setChecked(True)
514 | img_fft_action.triggered.connect(partial(self.update_real_space_view, False))
515 | self.fft_menu.addAction(img_fft_action)
516 | self.fft_source_action_group.addAction(img_fft_action)
517 |
518 | img_complex_fft_action = QAction("Virtual Image FFT (complex)", self)
519 | img_complex_fft_action.setCheckable(True)
520 | self.fft_menu.addAction(img_complex_fft_action)
521 | self.fft_source_action_group.addAction(img_complex_fft_action)
522 | img_complex_fft_action.triggered.connect(
523 | partial(self.update_real_space_view, False)
524 | )
525 |
526 | img_ewpc_action = QAction("EWPC", self)
527 | img_ewpc_action.setCheckable(True)
528 | self.fft_menu.addAction(img_ewpc_action)
529 | self.fft_source_action_group.addAction(img_ewpc_action)
530 | img_ewpc_action.triggered.connect(
531 | partial(self.update_diffraction_space_view, False)
532 | )
533 |
534 | # Processing menu
535 | self.processing_menu = QMenu("&Processing", self)
536 | self.menu_bar.addMenu(self.processing_menu)
537 |
538 | calibrate_action = QAction("&Calibrate...", self)
539 | calibrate_action.triggered.connect(self.show_calibration_dialog)
540 | self.processing_menu.addAction(calibrate_action)
541 |
542 | tcBF_action_manual = QAction("tcBF (Manual)...", self)
543 | tcBF_action_manual.triggered.connect(self.reconstruct_tcBF_manual)
544 | self.processing_menu.addAction(tcBF_action_manual)
545 |
546 | tcBF_action_auto = QAction("tcBF (Automatic)", self)
547 | tcBF_action_auto.triggered.connect(self.reconstruct_tcBF_auto)
548 | self.processing_menu.addAction(tcBF_action_auto)
549 | # tcBF_action_auto.setEnabled(False)
550 |
551 | # Help menu
552 | self.help_menu = QMenu("&Help", self)
553 | self.menu_bar.addMenu(self.help_menu)
554 |
555 | self.keyboard_map_action = QAction("Show &Keyboard Map", self)
556 | self.keyboard_map_action.triggered.connect(self.show_keyboard_map)
557 | self.help_menu.addAction(self.keyboard_map_action)
558 |
559 | def setup_views(self):
560 | # Set up the diffraction space window.
561 | self.diffraction_space_widget = pg.ImageView()
562 | self.diffraction_space_widget.setImage(np.zeros((512, 512)))
563 |
564 | self.diffraction_space_widget.setMouseTracking(True)
565 |
566 | # Create virtual detector ROI selector
567 | self.update_diffraction_detector()
568 |
569 | # Scalebar
570 | self.diffraction_scale_bar = ScaleBar(pixel_size=1, units="px", width=10)
571 | self.diffraction_scale_bar.setParentItem(
572 | self.diffraction_space_widget.getView()
573 | )
574 | self.diffraction_scale_bar.anchor((1, 1), (1, 1), offset=(-40, -40))
575 |
576 | # Name and return
577 | self.diffraction_space_widget.setWindowTitle("Diffraction Space")
578 |
579 | # Set up the real space window.
580 | self.real_space_widget = pg.ImageView()
581 | self.real_space_widget.setImage(np.zeros((512, 512)))
582 |
583 | # Add point selector connected to displayed diffraction pattern
584 | self.update_realspace_detector()
585 |
586 | # Scalebar, None by default
587 | self.real_space_scale_bar = ScaleBar(pixel_size=1, units="px", width=10)
588 | self.real_space_scale_bar.setParentItem(self.real_space_widget.getView())
589 | self.real_space_scale_bar.anchor((1, 1), (1, 1), offset=(-40, -40))
590 |
591 | # Name and return
592 | self.real_space_widget.setWindowTitle("Virtual Image")
593 |
594 | self.diffraction_space_widget.setAcceptDrops(True)
595 | self.real_space_widget.setAcceptDrops(True)
596 | self.diffraction_space_widget.dragEnterEvent = self.dragEnterEvent
597 | self.real_space_widget.dragEnterEvent = self.dragEnterEvent
598 | self.diffraction_space_widget.dropEvent = self.dropEvent
599 | self.real_space_widget.dropEvent = self.dropEvent
600 |
601 | # Set up the FFT window.
602 | self.fft_widget = pg.ImageView()
603 | self.fft_widget.setImage(np.zeros((512, 512)))
604 |
605 | # FFT scale bar
606 | self.fft_scale_bar = ScaleBar(pixel_size=1, units="1/px", width=10)
607 | self.fft_scale_bar.setParentItem(self.fft_widget.getView())
608 | self.fft_scale_bar.anchor((1, 1), (1, 1), offset=(-40, -40))
609 |
610 | # Name and return
611 | self.fft_widget.setWindowTitle("FFT of Virtual Image")
612 | self.fft_widget_text = pg.TextItem("FFT", (200, 200, 200), None, (0, 1))
613 | self.fft_widget.addItem(self.fft_widget_text)
614 |
615 | self.fft_widget.setAcceptDrops(True)
616 | self.fft_widget.dragEnterEvent = self.dragEnterEvent
617 | self.fft_widget.dropEvent = self.dropEvent
618 |
619 | layout = QHBoxLayout()
620 | layout.addWidget(self.diffraction_space_widget, 1)
621 |
622 | # add a resizeable layout for the vimg and FFT
623 | rightside = QSplitter()
624 | rightside.addWidget(self.real_space_widget)
625 | rightside.addWidget(self.fft_widget)
626 | rightside.setOrientation(QtCore.Qt.Vertical)
627 | rightside.setStretchFactor(0, 2)
628 | layout.addWidget(rightside, 1)
629 |
630 | widget = QWidget()
631 | widget.setLayout(layout)
632 | self.setCentralWidget(widget)
633 |
634 | self.diffraction_space_widget.getView().setMenuEnabled(False)
635 | self.real_space_widget.getView().setMenuEnabled(False)
636 | self.fft_widget.getView().setMenuEnabled(False)
637 |
638 | # Setup Status Bar
639 | self.stats_button = QPushButton("Statistics")
640 | self.stats_menu = QMenu()
641 |
642 | self.realspace_title = QAction("Virtual Image")
643 | self.realspace_title.setDisabled(False)
644 | self.stats_menu.addAction(self.realspace_title)
645 | self.realspace_statistics_actions = [QAction("") for i in range(5)]
646 | for a in self.realspace_statistics_actions:
647 | self.stats_menu.addAction(a)
648 |
649 | self.stats_menu.addSeparator()
650 |
651 | self.diffraction_title = QAction("Diffraction")
652 | self.diffraction_title.setDisabled(False)
653 | self.stats_menu.addAction(self.diffraction_title)
654 | self.diffraction_statistics_actions = [QAction("") for i in range(5)]
655 | for a in self.diffraction_statistics_actions:
656 | self.stats_menu.addAction(a)
657 |
658 | self.stats_button.setMenu(self.stats_menu)
659 |
660 | self.cursor_value_text = QLabel("")
661 | self.diffraction_space_view_text = QLabel("Slice")
662 | self.real_space_view_text = QLabel("Scan Position")
663 |
664 | # self.statusBar().addPermanentWidget(VLine())
665 | self.statusBar().addPermanentWidget(self.cursor_value_text)
666 | self.statusBar().addPermanentWidget(VLine())
667 | self.statusBar().addPermanentWidget(self.stats_button)
668 | self.statusBar().addPermanentWidget(VLine())
669 | self.statusBar().addPermanentWidget(self.diffraction_space_view_text)
670 | self.statusBar().addPermanentWidget(VLine())
671 | self.statusBar().addPermanentWidget(self.real_space_view_text)
672 | self.statusBar().addPermanentWidget(VLine())
673 | self.diffraction_rescale_button = LatchingButton(
674 | "Autorange Diffraction",
675 | status_bar=self.statusBar(),
676 | latched=True,
677 | )
678 | self.diffraction_rescale_button.activated.connect(
679 | self.diffraction_space_widget.autoLevels
680 | )
681 | self.statusBar().addPermanentWidget(self.diffraction_rescale_button)
682 | self.realspace_rescale_button = LatchingButton(
683 | "Autorange Virtual Image",
684 | status_bar=self.statusBar(),
685 | latched=True,
686 | )
687 | self.realspace_rescale_button.activated.connect(
688 | self.real_space_widget.autoLevels
689 | )
690 | self.statusBar().addPermanentWidget(self.realspace_rescale_button)
691 |
692 | def resizeEvent(self, event):
693 | # Store window size for next run
694 | self.settings.setValue("last_state/window_size", event.size())
695 |
696 | # Handle dragging and dropping a file on the window
697 | def dragEnterEvent(self, event):
698 | if event.mimeData().hasUrls():
699 | event.accept()
700 | else:
701 | event.ignore()
702 |
703 | def dropEvent(self, event):
704 | files = [u.toLocalFile() for u in event.mimeData().urls()]
705 | if len(files) == 1:
706 | print(f"Reieving dropped file: {files[0]}")
707 | self.load_file(files[0])
708 |
709 | def keyPressEvent(self, event):
710 | key = event.key()
711 | modifier = event.modifiers()
712 |
713 | speed = 5 if modifier == QtCore.Qt.ShiftModifier else 1
714 |
715 | if key in [QtCore.Qt.Key_W, QtCore.Qt.Key_A, QtCore.Qt.Key_S, QtCore.Qt.Key_D]:
716 | self.nudge_diffraction_selector(
717 | dx=speed
718 | * (
719 | -1 if key == QtCore.Qt.Key_W else 1 if key == QtCore.Qt.Key_S else 0
720 | ),
721 | dy=speed
722 | * (
723 | -1 if key == QtCore.Qt.Key_A else 1 if key == QtCore.Qt.Key_D else 0
724 | ),
725 | )
726 | elif key in [
727 | QtCore.Qt.Key_I,
728 | QtCore.Qt.Key_J,
729 | QtCore.Qt.Key_K,
730 | QtCore.Qt.Key_L,
731 | ]:
732 | self.nudge_real_space_selector(
733 | dx=speed
734 | * (
735 | -1 if key == QtCore.Qt.Key_I else 1 if key == QtCore.Qt.Key_K else 0
736 | ),
737 | dy=speed
738 | * (
739 | -1 if key == QtCore.Qt.Key_J else 1 if key == QtCore.Qt.Key_L else 0
740 | ),
741 | )
742 |
--------------------------------------------------------------------------------
/src/py4D_browser/menu_actions.py:
--------------------------------------------------------------------------------
1 | from numbers import Real
2 | import py4DSTEM
3 | from PyQt5.QtWidgets import QFileDialog, QMessageBox
4 | import h5py
5 | import os
6 | import numpy as np
7 | import matplotlib.pyplot as plt
8 | from py4D_browser.help_menu import KeyboardMapMenu
9 | from py4D_browser.dialogs import CalibrateDialog, ResizeDialog, ManualTCBFDialog
10 | from py4D_browser.utils import make_detector
11 | from py4DSTEM.io.filereaders import read_arina
12 |
13 |
14 | def load_data_auto(self):
15 | filename = self.show_file_dialog()
16 | self.load_file(filename)
17 |
18 |
19 | def load_data_mmap(self):
20 | filename = self.show_file_dialog()
21 | self.load_file(filename, mmap=True)
22 |
23 |
24 | def load_data_bin(self):
25 | # TODO: Ask user for binning level
26 | filename = self.show_file_dialog()
27 | self.load_file(filename, mmap=False, binning=4)
28 |
29 |
30 | def load_data_arina(self):
31 | filename = self.show_file_dialog()
32 | dataset = read_arina(filename)
33 |
34 | # Warn if the data is not square
35 | if dataset.data.shape[1] == 1:
36 | self.statusBar().showMessage(f"Arina data was loaded as 3D, please reshape...")
37 |
38 | self.datacube = dataset
39 | self.diffraction_scale_bar.pixel_size = self.datacube.calibration.get_Q_pixel_size()
40 | self.diffraction_scale_bar.units = self.datacube.calibration.get_Q_pixel_units()
41 |
42 | self.real_space_scale_bar.pixel_size = self.datacube.calibration.get_R_pixel_size()
43 | self.real_space_scale_bar.units = self.datacube.calibration.get_R_pixel_units()
44 |
45 | self.fft_scale_bar.pixel_size = (
46 | 1.0 / self.datacube.calibration.get_R_pixel_size() / self.datacube.R_Ny
47 | )
48 | self.fft_scale_bar.units = f"1/{self.datacube.calibration.get_R_pixel_units()}"
49 |
50 | self.update_diffraction_space_view(reset=True)
51 | self.update_real_space_view(reset=True)
52 |
53 | self.setWindowTitle(filename)
54 |
55 |
56 | def load_file(self, filepath, mmap=False, binning=1):
57 | print(f"Loading file {filepath}")
58 | extension = os.path.splitext(filepath)[-1].lower()
59 | print(f"Type: {extension}")
60 | if extension in (".h5", ".hdf5", ".py4dstem", ".emd", ".mat"):
61 | file = h5py.File(filepath, "r")
62 | datacubes = get_ND(file)
63 | print(f"Found {len(datacubes)} 4D datasets inside the HDF5 file...")
64 | if len(datacubes) >= 1:
65 | # Read the first datacube in the HDF5 file into RAM
66 | print(f"Reading dataset at location {datacubes[0].name}")
67 | self.datacube = py4DSTEM.DataCube(
68 | datacubes[0] if mmap else datacubes[0][()]
69 | )
70 |
71 | R_size, R_units, Q_size, Q_units = find_calibrations(datacubes[0])
72 |
73 | self.datacube.calibration.set_R_pixel_size(R_size)
74 | self.datacube.calibration.set_R_pixel_units(R_units)
75 | self.datacube.calibration.set_Q_pixel_size(Q_size)
76 | self.datacube.calibration.set_Q_pixel_units(Q_units)
77 |
78 | else:
79 | # if no 4D data was found, look for 3D data
80 | datacubes = get_ND(file, N=3)
81 | print(f"Found {len(datacubes)} 3D datasets inside the HDF5 file...")
82 | if len(datacubes) >= 1:
83 | array = datacubes[0] if mmap else datacubes[0][()]
84 | new_shape = ResizeDialog.get_new_size([1, array.shape[0]], parent=self)
85 | self.datacube = py4DSTEM.DataCube(
86 | array.reshape(*new_shape, *array.shape[1:])
87 | )
88 | else:
89 | raise ValueError("No 4D (or even 3D) data detected in the H5 file!")
90 | elif extension in [".npy"]:
91 | self.datacube = py4DSTEM.DataCube(np.load(filepath))
92 | else:
93 | self.datacube = py4DSTEM.import_file(
94 | filepath,
95 | mem="MEMMAP" if mmap else "RAM",
96 | binfactor=binning,
97 | )
98 |
99 | self.update_scalebars()
100 |
101 | self.update_diffraction_space_view(reset=True)
102 | self.update_real_space_view(reset=True)
103 |
104 | self.setWindowTitle(filepath)
105 |
106 |
107 | def update_scalebars(self):
108 |
109 | realspace_translation = {
110 | "A": "Å",
111 | }
112 | reciprocal_translation = {
113 | "A^-1": "Å⁻¹",
114 | }
115 |
116 | self.diffraction_scale_bar.pixel_size = self.datacube.calibration.get_Q_pixel_size()
117 | q_units = self.datacube.calibration.get_Q_pixel_units()
118 | self.diffraction_scale_bar.units = (
119 | reciprocal_translation[q_units]
120 | if q_units in reciprocal_translation.keys()
121 | else q_units
122 | )
123 |
124 | self.real_space_scale_bar.pixel_size = self.datacube.calibration.get_R_pixel_size()
125 | r_units = self.datacube.calibration.get_R_pixel_units()
126 | self.real_space_scale_bar.units = (
127 | realspace_translation[r_units]
128 | if r_units in realspace_translation.keys()
129 | else r_units
130 | )
131 |
132 | self.fft_scale_bar.pixel_size = (
133 | 1.0 / self.datacube.calibration.get_R_pixel_size() / self.datacube.R_Ny
134 | )
135 | self.fft_scale_bar.units = f"{self.datacube.calibration.get_R_pixel_units()}⁻¹"
136 |
137 | self.diffraction_scale_bar.updateBar()
138 | self.real_space_scale_bar.updateBar()
139 | self.fft_scale_bar.updateBar()
140 |
141 |
142 | def reshape_data(self):
143 | new_shape = ResizeDialog.get_new_size(self.datacube.shape[:2], parent=self)
144 | self.datacube.data = self.datacube.data.reshape(
145 | *new_shape, *self.datacube.data.shape[2:]
146 | )
147 |
148 | print(f"Reshaping data to {new_shape}")
149 |
150 | self.update_diffraction_space_view(reset=True)
151 | self.update_real_space_view(reset=True)
152 |
153 |
154 | def export_datacube(self, save_format: str):
155 | assert save_format in [
156 | "Raw float32",
157 | "py4DSTEM HDF5",
158 | "Plain HDF5",
159 | ], f"unrecognized format {format}"
160 | assert self.datacube is not None, "No datacube!"
161 |
162 | # Display RAW format disclaimer
163 | if save_format == "Raw float32":
164 | response = QMessageBox.question(
165 | self,
166 | "Save RAW file?",
167 | (
168 | "Saving raw binary files is not recommended as such files"
169 | " encode no information about the shape, endianness, or "
170 | "ordering of the data. Saving to HDF5 is recommended. "
171 | "Do you wish to continue saving RAW data?"
172 | ),
173 | QMessageBox.Cancel,
174 | QMessageBox.Save,
175 | )
176 |
177 | if response == QMessageBox.Cancel:
178 | self.statusBar().showMessage("Cancelling due to user guilt", 5_000)
179 | return
180 |
181 | filename = self.get_savefile_name(save_format)
182 |
183 | if save_format == "Raw float32":
184 | self.datacube.data.astype(np.float32).tofile(filename)
185 |
186 | elif save_format == "py4DSTEM HDF5":
187 | py4DSTEM.save(filename, self.datacube, mode="o")
188 |
189 | elif save_format == "Plain HDF5":
190 | with h5py.File(filename, "w") as f:
191 | f["array"] = self.datacube.data
192 |
193 |
194 | def export_virtual_image(self, im_format: str, im_type: str):
195 | assert im_type in ["image", "diffraction"], f"bad image type: {im_type}"
196 |
197 | filename = self.get_savefile_name(im_format)
198 |
199 | view = (
200 | self.real_space_widget if im_type == "image" else self.diffraction_space_widget
201 | )
202 |
203 | vimg = view.image.T
204 | vmin, vmax = view.getLevels()
205 |
206 | if im_format == "PNG (display)":
207 | plt.imsave(
208 | fname=filename, arr=vimg, vmin=vmin, vmax=vmax, format="png", cmap="gray"
209 | )
210 | elif im_format == "TIFF (display)":
211 | plt.imsave(
212 | fname=filename, arr=vimg, vmin=vmin, vmax=vmax, format="tiff", cmap="gray"
213 | )
214 | elif im_format == "TIFF (raw)":
215 | from tifffile import TiffWriter
216 |
217 | vimg = (
218 | self.unscaled_realspace_image
219 | if im_type == "image"
220 | else self.unscaled_diffraction_image
221 | )
222 | with TiffWriter(filename) as tw:
223 | tw.write(vimg)
224 | else:
225 | raise RuntimeError("Nothing saved! Format not recognized")
226 |
227 |
228 | def show_keyboard_map(self):
229 | keymap = KeyboardMapMenu(parent=self)
230 | keymap.open()
231 |
232 |
233 | def reconstruct_tcBF_auto(self):
234 | # tcBF requires an area detector for generating the mask
235 | detector_shape = self.detector_shape_group.checkedAction().text().replace("&", "")
236 | if detector_shape not in [
237 | "Rectangular",
238 | "Circle",
239 | ]:
240 | self.statusBar().showMessage("tcBF requires a selection of the BF disk", 5_000)
241 | return
242 |
243 | if (
244 | self.datacube.calibration.get_R_pixel_units == "pixels"
245 | or self.datacube.calibration.get_Q_pixel_units == "pixels"
246 | ):
247 | self.statusBar().showMessage("tcBF requires caibrated data", 5_000)
248 | return
249 |
250 | if detector_shape == "Rectangular":
251 | # Get slices corresponding to ROI
252 | slices, _ = self.virtual_detector_roi.getArraySlice(
253 | self.datacube.data[0, 0, :, :], self.diffraction_space_widget.getImageItem()
254 | )
255 | slice_y, slice_x = slices
256 |
257 | mask = np.zeros((self.datacube.Q_Nx, self.datacube.Q_Ny), dtype=np.bool_)
258 | mask[slice_x, slice_y] = True
259 |
260 | elif detector_shape == "Circle":
261 | R = self.virtual_detector_roi.size()[0] / 2.0
262 |
263 | x0 = self.virtual_detector_roi.pos()[0] + R
264 | y0 = self.virtual_detector_roi.pos()[1] + R
265 |
266 | mask = make_detector(
267 | (self.datacube.Q_Nx, self.datacube.Q_Ny), "circle", ((x0, y0), R)
268 | )
269 | else:
270 | raise ValueError("idk how we got here...")
271 |
272 | # do tcBF!
273 | self.statusBar().showMessage("Reconstructing... (This may take a while)")
274 | self.app.processEvents()
275 |
276 | tcBF = py4DSTEM.process.phase.Parallax(
277 | energy=300e3,
278 | datacube=self.datacube,
279 | )
280 | tcBF.preprocess(
281 | dp_mask=mask,
282 | plot_average_bf=False,
283 | vectorized_com_calculation=False,
284 | store_initial_arrays=False,
285 | )
286 | tcBF.reconstruct(
287 | plot_aligned_bf=False,
288 | plot_convergence=False,
289 | )
290 |
291 | self.set_virtual_image(tcBF.recon_BF, reset=True)
292 |
293 |
294 | def reconstruct_tcBF_manual(self):
295 | dialog = ManualTCBFDialog(parent=self)
296 | dialog.show()
297 |
298 |
299 | def show_calibration_dialog(self):
300 | # If the selector has a size, figure that out
301 | if hasattr(self, "virtual_detector_roi") and self.virtual_detector_roi is not None:
302 | selector_size = self.virtual_detector_roi.size()[0] / 2.0
303 | else:
304 | selector_size = None
305 |
306 | dialog = CalibrateDialog(
307 | self.datacube, parent=self, diffraction_selector_size=selector_size
308 | )
309 | dialog.open()
310 |
311 |
312 | def show_file_dialog(self) -> str:
313 | filename = QFileDialog.getOpenFileName(
314 | self,
315 | "Open 4D-STEM Data",
316 | "",
317 | "4D-STEM Data (*.dm3 *.dm4 *.raw *.mib *.gtg *.h5 *.hdf5 *.emd *.py4dstem *.npy *.npz *.mat);;Any file (*)",
318 | )
319 | if filename is not None and len(filename[0]) > 0:
320 | return filename[0]
321 | else:
322 | print("File was invalid, or something?")
323 | raise ValueError("Could not read file")
324 |
325 |
326 | def get_savefile_name(self, file_format) -> str:
327 | filters = {
328 | "Raw float32": "RAW File (*.raw *.f32);;Any file (*)",
329 | "py4DSTEM HDF5": "HDF5 File (*.hdf5 *.h5 *.emd *.py4dstem);;Any file (*)",
330 | "Plain HDF5": "HDF5 File (*.hdf5 *.h5;;Any file (*)",
331 | "PNG (display)": "PNG File (*.png);;Any file (*)",
332 | "TIFF (display)": "TIFF File (*.tiff *.tif *.tff);;Any File (*)",
333 | "TIFF (raw)": "TIFF File (*.tiff *.tif *.tff);;Any File (*)",
334 | }
335 |
336 | defaults = {
337 | "Raw float32": ".raw",
338 | "py4DSTEM HDF5": ".h5",
339 | "Plain HDF5": ".h5",
340 | "PNG (display)": ".png",
341 | "TIFF (display)": ".tiff",
342 | "TIFF (raw)": ".tiff",
343 | }
344 |
345 | file_filter = filters.get(file_format, "Any file (*)")
346 |
347 | filename = QFileDialog.getSaveFileName(
348 | parent=self,
349 | caption="Select save file",
350 | directory="",
351 | filter=file_filter,
352 | )
353 |
354 | if filename is not None and len(filename[0]) > 0:
355 | fname = filename[0]
356 | print(f"Save file picked at {filename}")
357 |
358 | if os.path.splitext(fname)[1] == "":
359 | fname = fname + defaults.get(file_format, "")
360 | print(f"Added default extension to get: {fname}")
361 | return fname
362 | else:
363 | print("File was invalid, or something?")
364 | print(f"QFileDialog returned {filename}")
365 | raise ValueError("Could get save file")
366 |
367 |
368 | def get_ND(f, datacubes=None, N=4):
369 | # Traverse an h5py.File and look for Datasets with N dimensions
370 | if datacubes is None:
371 | datacubes = []
372 | for k in f.keys():
373 | if isinstance(f[k], h5py.Dataset):
374 | # we found data
375 | if len(f[k].shape) == N:
376 | datacubes.append(f[k])
377 | elif isinstance(f[k], h5py.Group):
378 | get_ND(f[k], datacubes)
379 | return datacubes
380 |
381 |
382 | def find_calibrations(dset: h5py.Dataset):
383 | # Attempt to find calibrations from an H5 file
384 | R_size, R_units, Q_size, Q_units = 1.0, "pixels", 1.0, "pixels"
385 |
386 | # Does it look like a py4DSTEM file?
387 | try:
388 | if "emd_group_type" in dset.parent.attrs:
389 | # EMD files theoretically store this in the Array,
390 | # but in practice seem to only keep the calibrations
391 | # in the Metadata object, which is separate
392 |
393 | # R_size = dset.parent["dim0"][1] - dset.parent["dim0"][0]
394 | # R_units = dset.parent["dim0"].attrs["units"]
395 |
396 | # Q_size = dset.parent["dim3"][1] - dset.parent["dim3"][0]
397 | # Q_units = dset.parent["dim3"].attrs["units"]
398 | R_size = dset.parent.parent["metadatabundle"]["calibration"][
399 | "R_pixel_size"
400 | ][()]
401 | R_units = dset.parent.parent["metadatabundle"]["calibration"][
402 | "R_pixel_units"
403 | ][()].decode()
404 |
405 | Q_size = dset.parent.parent["metadatabundle"]["calibration"][
406 | "Q_pixel_size"
407 | ][()]
408 | Q_units = dset.parent.parent["metadatabundle"]["calibration"][
409 | "Q_pixel_units"
410 | ][()].decode()
411 | except:
412 | print(
413 | "This file looked like a py4DSTEM dataset but the dim vectors appear malformed..."
414 | )
415 |
416 | # Does it look like an abTEM file?
417 | try:
418 | if "sampling" in dset.parent and "units" in dset.parent:
419 | R_size = dset.parent["sampling"][0]
420 | R_units = dset.parent["units"][0].decode().replace("Å", "A")
421 |
422 | Q_size = dset.parent["sampling"][3]
423 | Q_units = dset.parent["units"][3].decode()
424 | except:
425 | print(
426 | "This file looked like an abTEM simulation but the calibrations aren't as expected..."
427 | )
428 |
429 | return R_size, R_units, Q_size, Q_units
430 |
--------------------------------------------------------------------------------
/src/py4D_browser/py4DGUI-keymap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/py4dstem/py4D-browser/eb33d15d7675d749e24df67bac890914c067ac83/src/py4D_browser/py4DGUI-keymap.png
--------------------------------------------------------------------------------
/src/py4D_browser/runGUI.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import py4D_browser
4 | import sys
5 | from PyQt5.QtWidgets import QApplication
6 |
7 |
8 | def launch():
9 | app = QApplication(sys.argv)
10 | win = py4D_browser.DataViewer(sys.argv)
11 | win.show()
12 | sys.exit(app.exec_())
13 |
14 |
15 | if __name__ == "__main__":
16 | launch()
17 |
--------------------------------------------------------------------------------
/src/py4D_browser/scalebar.py:
--------------------------------------------------------------------------------
1 | from pyqtgraph import functions as fn
2 | from pyqtgraph import getConfigOption
3 | from pyqtgraph import Point
4 | from PyQt5 import QtCore, QtWidgets
5 | from pyqtgraph import GraphicsObject
6 | from pyqtgraph import GraphicsWidgetAnchor
7 | from pyqtgraph import TextItem
8 | import numpy as np
9 | from sigfig import round
10 |
11 | __all__ = ["ScaleBar"]
12 |
13 |
14 | class ScaleBar(GraphicsWidgetAnchor, GraphicsObject):
15 | """
16 | Displays a rectangular bar to indicate the relative scale of objects on the view.
17 | """
18 |
19 | def __init__(
20 | self,
21 | pixel_size: float,
22 | units: str,
23 | target_relaive_size=0.2,
24 | width=5,
25 | brush=None,
26 | pen=None,
27 | offset=None,
28 | nice_numbers=[1, 2, 5, 10],
29 | ):
30 | GraphicsObject.__init__(self)
31 | GraphicsWidgetAnchor.__init__(self)
32 | self.setFlag(self.GraphicsItemFlag.ItemHasNoContents)
33 | self.setAcceptedMouseButtons(QtCore.Qt.MouseButton.NoButton)
34 |
35 | if brush is None:
36 | brush = getConfigOption("foreground")
37 | self.brush = fn.mkBrush(brush)
38 | self.pen = fn.mkPen(pen)
39 | self._width = width
40 | self._target_relative_size = target_relaive_size
41 | self._nice_numbers = np.array(nice_numbers)
42 |
43 | self.pixel_size = pixel_size
44 | self.units = units
45 |
46 | if offset is None:
47 | offset = (0, 0)
48 | self.offset = offset
49 |
50 | self.bar = QtWidgets.QGraphicsRectItem()
51 | self.bar.setPen(self.pen)
52 | self.bar.setBrush(self.brush)
53 | self.bar.setParentItem(self)
54 |
55 | self.text = TextItem(text="smol", anchor=(0.5, 1))
56 | self.text.setParentItem(self)
57 |
58 | def changeParent(self):
59 | view = self.parentItem()
60 | if view is None:
61 | return
62 | view.sigRangeChanged.connect(self.updateBar)
63 | self.updateBar()
64 |
65 | def updateBar(self):
66 | view = self.parentItem()
67 |
68 | if view is None:
69 | return
70 |
71 | view_width = view.viewRect().width() * self.pixel_size
72 | target_size = view_width * self._target_relative_size
73 |
74 | exponent = np.floor(np.log10(target_size))
75 | mantissa = target_size / np.power(10, exponent)
76 |
77 | # Get the "nice" size of the scalebar
78 | nice_size = (
79 | self._nice_numbers[np.argmin(np.abs(mantissa - self._nice_numbers))]
80 | * 10**exponent
81 | )
82 |
83 | p1 = view.mapFromViewToItem(self, QtCore.QPointF(0, 0))
84 | p2 = view.mapFromViewToItem(
85 | self, QtCore.QPointF(nice_size / self.pixel_size, 0)
86 | )
87 | w = (p2 - p1).x()
88 | self.bar.setRect(QtCore.QRectF(-w, 0, w, self._width))
89 | self.text.setPos(-w / 2.0, 0)
90 | self.text.setText(f"{round(nice_size,sigfigs=1,output_type=str)} {self.units}")
91 |
92 | def boundingRect(self):
93 | return QtCore.QRectF()
94 |
95 | def setParentItem(self, p):
96 | ret = GraphicsObject.setParentItem(self, p)
97 | if self.offset is not None:
98 | offset = Point(self.offset)
99 | anchorx = 1 if offset[0] <= 0 else 0
100 | anchory = 1 if offset[1] <= 0 else 0
101 | anchor = (anchorx, anchory)
102 | self.anchor(itemPos=anchor, parentPos=anchor, offset=offset)
103 | return ret
104 |
--------------------------------------------------------------------------------
/src/py4D_browser/update_views.py:
--------------------------------------------------------------------------------
1 | import pyqtgraph as pg
2 | import numpy as np
3 | import py4DSTEM
4 | from functools import partial
5 | from PyQt5.QtWidgets import QApplication, QToolTip
6 | from PyQt5 import QtCore
7 | from PyQt5.QtGui import QCursor
8 | import os
9 |
10 | from py4D_browser.utils import (
11 | pg_point_roi,
12 | make_detector,
13 | complex_to_Lab,
14 | StatusBarWriter,
15 | )
16 |
17 |
18 | def update_real_space_view(self, reset=False):
19 | detector_shape = self.detector_shape_group.checkedAction().text().replace("&", "")
20 | assert detector_shape in [
21 | "Point",
22 | "Rectangular",
23 | "Circle",
24 | "Annulus",
25 | ], detector_shape
26 |
27 | detector_mode = self.detector_mode_group.checkedAction().text().replace("&", "")
28 | assert detector_mode in [
29 | "Integrating",
30 | "Maximum",
31 | "CoM",
32 | "CoM X",
33 | "CoM Y",
34 | "iCoM",
35 | ], detector_mode
36 |
37 | # If a CoM method is checked, ensure linear scaling
38 | scaling_mode = self.vimg_scaling_group.checkedAction().text().replace("&", "")
39 | if detector_mode == "CoM" and scaling_mode != "Linear":
40 | self.statusBar().showMessage("Warning! Setting linear scaling for CoM image")
41 | self.vimg_scale_linear_action.setChecked(True)
42 | scaling_mode = "Linear"
43 |
44 | if self.datacube is None:
45 | return
46 |
47 | # We will branch through certain combinations of detector shape and mode.
48 | # If we happen across a special case that can be handled directly, we
49 | # compute vimg. If we encounter a case that needs a more complicated
50 | # computation we compute the mask and then do the virtual image later
51 | mask = None
52 | if detector_shape == "Rectangular":
53 | # Get slices corresponding to ROI
54 | slices, transforms = self.virtual_detector_roi.getArraySlice(
55 | self.datacube.data[0, 0, :, :].T,
56 | self.diffraction_space_widget.getImageItem(),
57 | )
58 | slice_y, slice_x = slices
59 |
60 | # update the label:
61 | self.diffraction_space_view_text.setText(
62 | f"Diffraction Slice: [{slice_x.start}:{slice_x.stop},{slice_y.start}:{slice_y.stop}]"
63 | )
64 |
65 | if detector_mode == "Integrating":
66 | vimg = np.sum(self.datacube.data[:, :, slice_x, slice_y], axis=(2, 3))
67 | elif detector_mode == "Maximum":
68 | vimg = np.max(self.datacube.data[:, :, slice_x, slice_y], axis=(2, 3))
69 | else:
70 | mask = np.zeros((self.datacube.Q_Nx, self.datacube.Q_Ny), dtype=np.bool_)
71 | mask[slice_x, slice_y] = True
72 |
73 | elif detector_shape == "Circle":
74 | R = self.virtual_detector_roi.size()[0] / 2.0
75 |
76 | x0 = self.virtual_detector_roi.pos()[1] + R
77 | y0 = self.virtual_detector_roi.pos()[0] + R
78 |
79 | self.diffraction_space_view_text.setText(
80 | f"Diffraction Circle: Center ({x0:.0f},{y0:.0f}), Radius {R:.0f}"
81 | )
82 |
83 | mask = make_detector(
84 | (self.datacube.Q_Nx, self.datacube.Q_Ny), "circle", ((x0, y0), R)
85 | )
86 | elif detector_shape == "Annulus":
87 | inner_pos = self.virtual_detector_roi_inner.pos()
88 | inner_size = self.virtual_detector_roi_inner.size()
89 | R_inner = inner_size[0] / 2.0
90 | x0 = inner_pos[1] + R_inner
91 | y0 = inner_pos[0] + R_inner
92 |
93 | outer_size = self.virtual_detector_roi_outer.size()
94 | R_outer = outer_size[0] / 2.0
95 |
96 | if R_inner <= R_outer:
97 | R_inner -= 1
98 |
99 | self.diffraction_space_view_text.setText(
100 | f"Diffraction Annulus: Center ({x0:.0f},{y0:.0f}), Radii ({R_inner:.0f},{R_outer:.0f})"
101 | )
102 |
103 | mask = make_detector(
104 | (self.datacube.Q_Nx, self.datacube.Q_Ny),
105 | "annulus",
106 | ((x0, y0), (R_inner, R_outer)),
107 | )
108 | elif detector_shape == "Point":
109 | roi_state = self.virtual_detector_point.saveState()
110 | y0, x0 = roi_state["pos"]
111 | xc, yc = int(x0 + 1), int(y0 + 1)
112 |
113 | # Set the diffraction space image
114 | # Normalize coordinates
115 | xc = np.clip(xc, 0, self.datacube.Q_Nx - 1)
116 | yc = np.clip(yc, 0, self.datacube.Q_Ny - 1)
117 | vimg = self.datacube.data[:, :, xc, yc]
118 |
119 | self.diffraction_space_view_text.setText(f"Diffraction: Point [{xc},{yc}]")
120 |
121 | else:
122 | raise ValueError("Detector shape not recognized")
123 |
124 | if mask is not None:
125 | if "MASK_DEBUG" in os.environ:
126 | self.set_diffraction_image(mask.astype(np.float32), reset=reset)
127 | return
128 | mask = mask.astype(np.float32)
129 | vimg = np.zeros((self.datacube.R_Nx, self.datacube.R_Ny))
130 | iterator = py4DSTEM.tqdmnd(
131 | self.datacube.R_Nx,
132 | self.datacube.R_Ny,
133 | file=StatusBarWriter(self.statusBar()),
134 | mininterval=0.1,
135 | )
136 |
137 | if detector_mode == "Integrating":
138 | for rx, ry in iterator:
139 | vimg[rx, ry] = np.sum(self.datacube.data[rx, ry] * mask)
140 |
141 | elif detector_mode == "Maximum":
142 | for rx, ry in iterator:
143 | vimg[rx, ry] = np.max(self.datacube.data[rx, ry] * mask)
144 |
145 | elif "CoM" in detector_mode:
146 | ry_coord, rx_coord = np.meshgrid(
147 | np.arange(self.datacube.Q_Ny), np.arange(self.datacube.Q_Nx)
148 | )
149 | CoMx = np.zeros_like(vimg)
150 | CoMy = np.zeros_like(vimg)
151 | for rx, ry in iterator:
152 | ar = self.datacube.data[rx, ry] * mask
153 | tot_intens = np.sum(ar)
154 | CoMx[rx, ry] = np.sum(rx_coord * ar) / tot_intens
155 | CoMy[rx, ry] = np.sum(ry_coord * ar) / tot_intens
156 |
157 | CoMx -= np.mean(CoMx)
158 | CoMy -= np.mean(CoMy)
159 |
160 | if detector_mode == "CoM":
161 | vimg = CoMx + 1.0j * CoMy
162 | elif detector_mode == "CoM X":
163 | vimg = CoMx
164 | elif detector_mode == "CoM Y":
165 | vimg = CoMy
166 | elif detector_mode == "iCoM":
167 | dpc = py4DSTEM.process.phase.DPC(verbose=False)
168 | dpc.preprocess(
169 | force_com_measured=[CoMx, CoMy],
170 | plot_rotation=False,
171 | plot_center_of_mass="",
172 | )
173 | dpc.reconstruct(max_iter=1, step_size=1)
174 | vimg = dpc.object_phase
175 | else:
176 | raise ValueError("Mode logic gone haywire!")
177 |
178 | else:
179 | raise ValueError("Oopsie")
180 |
181 | self.set_virtual_image(vimg, reset=reset)
182 |
183 |
184 | def set_virtual_image(self, vimg, reset=False):
185 | self.unscaled_realspace_image = vimg
186 | self._render_virtual_image(reset=reset)
187 |
188 |
189 | def _render_virtual_image(self, reset=False):
190 | vimg = self.unscaled_realspace_image
191 |
192 | # for 2D images, use the scaling set by the user
193 | # for RGB (3D) images, always scale linear
194 | if np.isrealobj(vimg):
195 | scaling_mode = self.vimg_scaling_group.checkedAction().text().replace("&", "")
196 | assert scaling_mode in ["Linear", "Log", "Square Root"], scaling_mode
197 |
198 | if scaling_mode == "Linear":
199 | new_view = vimg.copy()
200 | elif scaling_mode == "Log":
201 | new_view = np.log2(np.maximum(vimg, self.LOG_SCALE_MIN_VALUE))
202 | elif scaling_mode == "Square Root":
203 | new_view = np.sqrt(np.maximum(vimg, 0))
204 | else:
205 | raise ValueError("Mode not recognized")
206 |
207 | auto_level = reset or self.realspace_rescale_button.latched
208 |
209 | self.real_space_widget.setImage(
210 | new_view.T,
211 | autoLevels=False,
212 | levels=(
213 | (
214 | np.percentile(new_view, self.real_space_autoscale_percentiles[0]),
215 | np.percentile(new_view, self.real_space_autoscale_percentiles[1]),
216 | )
217 | if auto_level
218 | else None
219 | ),
220 | autoRange=reset,
221 | )
222 | else:
223 | new_view = complex_to_Lab(vimg)
224 | self.real_space_widget.setImage(
225 | np.transpose(new_view, (1, 0, 2)), # flip x/y but keep RGB ordering
226 | autoLevels=False,
227 | levels=(0, 1),
228 | autoRange=reset,
229 | )
230 |
231 | stats_text = [
232 | f"Min:\t{vimg.min():.5g}",
233 | f"Max:\t{vimg.max():.5g}",
234 | f"Mean:\t{vimg.mean():.5g}",
235 | f"Sum:\t{vimg.sum():.5g}",
236 | f"Std:\t{np.std(vimg):.5g}",
237 | ]
238 |
239 | for t, m in zip(stats_text, self.realspace_statistics_actions):
240 | m.setText(t)
241 |
242 | # Update FFT view
243 | self.unscaled_fft_image = None
244 | vimg_2D = vimg if np.isrealobj(vimg) else np.abs(vimg)
245 | fft_window = (
246 | np.hanning(vimg_2D.shape[0])[:, None] * np.hanning(vimg_2D.shape[1])[None, :]
247 | )
248 | if self.fft_source_action_group.checkedAction().text() == "Virtual Image FFT":
249 | fft = np.abs(np.fft.fftshift(np.fft.fft2(vimg_2D * fft_window))) ** 0.5
250 | levels = (np.min(fft), np.percentile(fft, 99.9))
251 | mode_switch = self.fft_widget_text.textItem.toPlainText() != "Virtual Image FFT"
252 | self.fft_widget_text.setText("Virtual Image FFT")
253 | self.fft_widget.setImage(
254 | fft.T, autoLevels=False, levels=levels, autoRange=mode_switch
255 | )
256 | self.fft_widget.getImageItem().setRect(0, 0, fft.shape[1], fft.shape[1])
257 | if mode_switch:
258 | # Need to autorange after setRect
259 | self.fft_widget.autoRange()
260 | self.unscaled_fft_image = fft
261 | elif (
262 | self.fft_source_action_group.checkedAction().text()
263 | == "Virtual Image FFT (complex)"
264 | ):
265 | fft = np.fft.fftshift(np.fft.fft2(vimg_2D * fft_window))
266 | levels = (np.min(np.abs(fft)), np.percentile(np.abs(fft), 99.9))
267 | mode_switch = self.fft_widget_text.textItem.toPlainText() != "Virtual Image FFT"
268 | self.fft_widget_text.setText("Virtual Image FFT")
269 | fft_img = complex_to_Lab(
270 | fft.T,
271 | amin=levels[0],
272 | amax=levels[1],
273 | ab_scale=128,
274 | gamma=0.5,
275 | )
276 | self.fft_widget.setImage(
277 | fft_img,
278 | autoLevels=False,
279 | autoRange=mode_switch,
280 | levels=(0, 1),
281 | )
282 |
283 | self.fft_widget.getImageItem().setRect(0, 0, fft.shape[1], fft.shape[1])
284 | if mode_switch:
285 | # Need to autorange after setRect
286 | self.fft_widget.autoRange()
287 | self.unscaled_fft_image = fft
288 |
289 |
290 | def update_diffraction_space_view(self, reset=False):
291 | if self.datacube is None:
292 | return
293 |
294 | detector_shape = (
295 | self.rs_detector_shape_group.checkedAction().text().replace("&", "")
296 | )
297 | assert detector_shape in [
298 | "Point",
299 | "Rectangular",
300 | ], detector_shape
301 |
302 | detector_response = (
303 | self.realspace_detector_mode_group.checkedAction().text().replace("&", "")
304 | )
305 | assert detector_response in ["Integrating", "Maximum"], detector_response
306 |
307 | if detector_shape == "Point":
308 | roi_state = self.real_space_point_selector.saveState()
309 | y0, x0 = roi_state["pos"]
310 | xc, yc = int(x0 + 1), int(y0 + 1)
311 |
312 | # Set the diffraction space image
313 | # Normalize coordinates
314 | xc = np.clip(xc, 0, self.datacube.R_Nx - 1)
315 | yc = np.clip(yc, 0, self.datacube.R_Ny - 1)
316 |
317 | self.real_space_view_text.setText(f"Virtual Image: Point [{xc},{yc}]")
318 |
319 | DP = self.datacube.data[xc, yc]
320 | elif detector_shape == "Rectangular":
321 | # Get slices corresponding to ROI
322 | slices, _ = self.real_space_rect_selector.getArraySlice(
323 | np.zeros((self.datacube.Rshape)).T, self.real_space_widget.getImageItem()
324 | )
325 | slice_y, slice_x = slices
326 |
327 | # update the label:
328 | self.real_space_view_text.setText(
329 | f"Virtual Image: Slice [{slice_x.start}:{slice_x.stop},{slice_y.start}:{slice_y.stop}]"
330 | )
331 |
332 | if detector_response == "Integrating":
333 | DP = np.sum(self.datacube.data[slice_x, slice_y], axis=(0, 1))
334 | elif detector_response == "Maximum":
335 | DP = np.max(self.datacube.data[slice_x, slice_y], axis=(0, 1))
336 | else:
337 | raise ValueError("Detector response problem")
338 |
339 | else:
340 | raise ValueError("Detector shape not recognized")
341 |
342 | self.set_diffraction_image(DP, reset=reset)
343 |
344 |
345 | def set_diffraction_image(self, DP, reset=False):
346 | self.unscaled_diffraction_image = DP
347 | self._render_diffraction_image(reset=reset)
348 |
349 |
350 | def _render_diffraction_image(self, reset=False):
351 | DP = self.unscaled_diffraction_image
352 |
353 | scaling_mode = self.diff_scaling_group.checkedAction().text().replace("&", "")
354 | assert scaling_mode in ["Linear", "Log", "Square Root"]
355 |
356 | if scaling_mode == "Linear":
357 | new_view = DP.copy()
358 | elif scaling_mode == "Log":
359 | new_view = np.log2(np.maximum(DP, self.LOG_SCALE_MIN_VALUE))
360 | elif scaling_mode == "Square Root":
361 | new_view = np.sqrt(np.maximum(DP, 0))
362 | else:
363 | raise ValueError("Mode not recognized")
364 |
365 | stats_text = [
366 | f"Min:\t{DP.min():.5g}",
367 | f"Max:\t{DP.max():.5g}",
368 | f"Mean:\t{DP.mean():.5g}",
369 | f"Sum:\t{DP.sum():.5g}",
370 | f"Std:\t{np.std(DP):.5g}",
371 | ]
372 |
373 | for t, m in zip(stats_text, self.diffraction_statistics_actions):
374 | m.setText(t)
375 |
376 | auto_level = reset or self.diffraction_rescale_button.latched
377 |
378 | self.diffraction_space_widget.setImage(
379 | new_view.T,
380 | autoLevels=False,
381 | levels=(
382 | (
383 | np.percentile(new_view, self.diffraction_autoscale_percentiles[0]),
384 | np.percentile(new_view, self.diffraction_autoscale_percentiles[1]),
385 | )
386 | if auto_level
387 | else None
388 | ),
389 | autoRange=reset,
390 | )
391 |
392 | if self.fft_source_action_group.checkedAction().text() == "EWPC":
393 | log_clip = np.maximum(1e-10, np.percentile(np.maximum(DP, 0.0), 0.1))
394 | fft = np.abs(np.fft.fftshift(np.fft.fft2(np.log(np.maximum(DP, log_clip)))))
395 | levels = (np.min(fft), np.percentile(fft, 99.9))
396 | mode_switch = self.fft_widget_text.textItem.toPlainText() != "EWPC"
397 | self.fft_widget_text.setText("EWPC")
398 | self.fft_widget.setImage(
399 | fft.T, autoLevels=False, levels=levels, autoRange=mode_switch
400 | )
401 |
402 |
403 | def update_realspace_detector(self):
404 | # change the shape of the detector, then update the view
405 |
406 | detector_shape = (
407 | self.rs_detector_shape_group.checkedAction().text().replace("&", "")
408 | )
409 | assert detector_shape in ["Point", "Rectangular"], detector_shape
410 |
411 | main_pen = {"color": "g", "width": 6}
412 | handle_pen = {"color": "r", "width": 9}
413 | hover_pen = {"color": "c", "width": 6}
414 | hover_handle = {"color": "c", "width": 9}
415 |
416 | if self.datacube is None:
417 | x0, y0 = 0, 0
418 | xr, yr = 4, 4
419 | else:
420 | x, y = self.datacube.data.shape[2:]
421 | y0, x0 = x // 2, y // 2
422 | xr, yr = (np.minimum(x, y) / 10,) * 2
423 |
424 | # Remove existing detector
425 | if hasattr(self, "real_space_point_selector"):
426 | self.real_space_widget.view.scene().removeItem(self.real_space_point_selector)
427 | self.real_space_point_selector = None
428 | if hasattr(self, "real_space_rect_selector"):
429 | self.real_space_widget.view.scene().removeItem(self.real_space_rect_selector)
430 | self.real_space_rect_selector = None
431 |
432 | # Point detector
433 | if detector_shape == "Point":
434 | self.real_space_point_selector = pg_point_roi(
435 | self.real_space_widget.getView(),
436 | center=(x0 - 0.5, y0 - 0.5),
437 | pen=main_pen,
438 | hoverPen=hover_pen,
439 | )
440 | self.real_space_point_selector.sigRegionChanged.connect(
441 | partial(self.update_diffraction_space_view, False)
442 | )
443 |
444 | # Rectangular detector
445 | elif detector_shape == "Rectangular":
446 | self.real_space_rect_selector = pg.RectROI(
447 | [int(x0 - xr / 2), int(y0 - yr / 2)],
448 | [int(xr), int(yr)],
449 | pen=main_pen,
450 | handlePen=handle_pen,
451 | hoverPen=hover_pen,
452 | handleHoverPen=hover_handle,
453 | )
454 | self.real_space_widget.getView().addItem(self.real_space_rect_selector)
455 | self.real_space_rect_selector.sigRegionChangeFinished.connect(
456 | partial(self.update_diffraction_space_view, False)
457 | )
458 |
459 | else:
460 | raise ValueError("Unknown detector shape! Got: {}".format(detector_shape))
461 |
462 | self.update_diffraction_space_view(reset=True)
463 |
464 |
465 | def update_diffraction_detector(self):
466 | # change the shape of the detector, then update the view
467 |
468 | detector_shape = self.detector_shape_group.checkedAction().text().strip("&")
469 | assert detector_shape in ["Point", "Rectangular", "Circle", "Annulus"]
470 |
471 | main_pen = {"color": "g", "width": 6}
472 | handle_pen = {"color": "r", "width": 9}
473 | hover_pen = {"color": "c", "width": 6}
474 | hover_handle = {"color": "c", "width": 9}
475 |
476 | if self.datacube is None:
477 | x0, y0 = 0, 0
478 | xr, yr = 4, 4
479 | else:
480 | x, y = self.datacube.data.shape[2:]
481 | y0, x0 = x // 2, y // 2
482 | xr, yr = (np.minimum(x, y) / 10,) * 2
483 |
484 | # Remove existing detector
485 | if hasattr(self, "virtual_detector_point"):
486 | self.diffraction_space_widget.view.scene().removeItem(
487 | self.virtual_detector_point
488 | )
489 | self.virtual_detector_point = None
490 | if hasattr(self, "virtual_detector_roi"):
491 | self.diffraction_space_widget.view.scene().removeItem(self.virtual_detector_roi)
492 | self.virtual_detector_roi = None
493 | if hasattr(self, "virtual_detector_roi_inner"):
494 | self.diffraction_space_widget.view.scene().removeItem(
495 | self.virtual_detector_roi_inner
496 | )
497 | self.virtual_detector_roi_inner = None
498 | if hasattr(self, "virtual_detector_roi_outer"):
499 | self.diffraction_space_widget.view.scene().removeItem(
500 | self.virtual_detector_roi_outer
501 | )
502 | self.virtual_detector_roi_outer = None
503 |
504 | # Point detector
505 | if detector_shape == "Point":
506 | self.virtual_detector_point = pg_point_roi(
507 | self.diffraction_space_widget.getView(),
508 | center=(x0 - 0.5, y0 - 0.5),
509 | pen=main_pen,
510 | hoverPen=hover_pen,
511 | )
512 | self.virtual_detector_point.sigRegionChanged.connect(
513 | partial(self.update_real_space_view, False)
514 | )
515 |
516 | # Rectangular detector
517 | elif detector_shape == "Rectangular":
518 | self.virtual_detector_roi = pg.RectROI(
519 | [int(x0 - xr / 2), int(y0 - yr / 2)],
520 | [int(xr), int(yr)],
521 | pen=main_pen,
522 | handlePen=handle_pen,
523 | hoverPen=hover_pen,
524 | handleHoverPen=hover_handle,
525 | )
526 | self.diffraction_space_widget.getView().addItem(self.virtual_detector_roi)
527 | self.virtual_detector_roi.sigRegionChangeFinished.connect(
528 | partial(self.update_real_space_view, False)
529 | )
530 |
531 | # Circular detector
532 | elif detector_shape == "Circle":
533 | self.virtual_detector_roi = pg.CircleROI(
534 | [int(x0 - xr / 2), int(y0 - yr / 2)],
535 | [int(xr), int(yr)],
536 | pen=main_pen,
537 | handlePen=handle_pen,
538 | hoverPen=hover_pen,
539 | handleHoverPen=hover_handle,
540 | )
541 | self.diffraction_space_widget.getView().addItem(self.virtual_detector_roi)
542 | self.virtual_detector_roi.sigRegionChangeFinished.connect(
543 | partial(self.update_real_space_view, False)
544 | )
545 |
546 | # Annular dector
547 | elif detector_shape == "Annulus":
548 | # Make outer detector
549 | self.virtual_detector_roi_outer = pg.CircleROI(
550 | [int(x0 - xr), int(y0 - yr)],
551 | [int(2 * xr), int(2 * yr)],
552 | pen=main_pen,
553 | handlePen=handle_pen,
554 | hoverPen=hover_pen,
555 | handleHoverPen=hover_handle,
556 | )
557 | self.diffraction_space_widget.getView().addItem(self.virtual_detector_roi_outer)
558 |
559 | # Make inner detector
560 | self.virtual_detector_roi_inner = pg.CircleROI(
561 | [int(x0 - xr / 2), int(y0 - yr / 2)],
562 | [int(xr), int(yr)],
563 | pen=main_pen,
564 | hoverPen=hover_pen,
565 | handlePen=handle_pen,
566 | handleHoverPen=hover_handle,
567 | movable=False,
568 | )
569 | self.diffraction_space_widget.getView().addItem(self.virtual_detector_roi_inner)
570 |
571 | # Connect size/position of inner and outer detectors
572 | self.virtual_detector_roi_outer.sigRegionChanged.connect(
573 | self.update_annulus_pos
574 | )
575 | self.virtual_detector_roi_outer.sigRegionChanged.connect(
576 | self.update_annulus_radii
577 | )
578 | self.virtual_detector_roi_inner.sigRegionChanged.connect(
579 | self.update_annulus_radii
580 | )
581 |
582 | # Connect to real space view update function
583 | self.virtual_detector_roi_outer.sigRegionChangeFinished.connect(
584 | partial(self.update_real_space_view, False)
585 | )
586 | self.virtual_detector_roi_inner.sigRegionChangeFinished.connect(
587 | partial(self.update_real_space_view, False)
588 | )
589 |
590 | else:
591 | raise ValueError("Unknown detector shape! Got: {}".format(detector_shape))
592 |
593 | self.update_real_space_view(reset=True)
594 |
595 |
596 | def set_diffraction_autoscale_range(self, percentiles, redraw=True):
597 | self.diffraction_autoscale_percentiles = percentiles
598 | self.settings.setValue("last_state/diffraction_autorange", list(percentiles))
599 |
600 | if redraw:
601 | self._render_diffraction_image(reset=False)
602 |
603 |
604 | def set_real_space_autoscale_range(self, percentiles, redraw=True):
605 | self.real_space_autoscale_percentiles = percentiles
606 | self.settings.setValue("last_state/realspace_autorange", list(percentiles))
607 |
608 | if redraw:
609 | self._render_virtual_image(reset=False)
610 |
611 |
612 | def nudge_real_space_selector(self, dx, dy):
613 | if (
614 | hasattr(self, "real_space_point_selector")
615 | and self.real_space_point_selector is not None
616 | ):
617 | selector = self.real_space_point_selector
618 | elif (
619 | hasattr(self, "real_space_rect_selector")
620 | and self.real_space_rect_selector is not None
621 | ):
622 | selector = self.real_space_rect_selector
623 | else:
624 | raise RuntimeError("Can't find the real space selector!")
625 |
626 | position = selector.pos()
627 | position[0] += dy
628 | position[1] += dx
629 |
630 | selector.setPos(position)
631 |
632 |
633 | def nudge_diffraction_selector(self, dx, dy):
634 | if (
635 | hasattr(self, "virtual_detector_point")
636 | and self.virtual_detector_point is not None
637 | ):
638 | selector = self.virtual_detector_point
639 | elif (
640 | hasattr(self, "virtual_detector_roi") and self.virtual_detector_roi is not None
641 | ):
642 | selector = self.virtual_detector_roi
643 | elif (
644 | hasattr(self, "virtual_detector_roi_outer")
645 | and self.virtual_detector_roi_outer is not None
646 | ):
647 | selector = self.virtual_detector_roi_outer
648 | else:
649 | raise RuntimeError("Can't find the diffraction space selector!")
650 |
651 | position = selector.pos()
652 | position[0] += dy
653 | position[1] += dx
654 |
655 | selector.setPos(position)
656 |
657 |
658 | def update_tooltip(self):
659 | modifier_keys = QApplication.queryKeyboardModifiers()
660 |
661 | if self.datacube is not None and self.isActiveWindow():
662 | global_pos = QCursor.pos()
663 |
664 | for scene, data in [
665 | (self.diffraction_space_widget, self.unscaled_diffraction_image),
666 | (self.real_space_widget, self.unscaled_realspace_image),
667 | (self.fft_widget, self.unscaled_fft_image),
668 | ]:
669 | pos_in_scene = scene.mapFromGlobal(QCursor.pos())
670 | if scene.getView().rect().contains(pos_in_scene):
671 | pos_in_data = scene.view.mapSceneToView(pos_in_scene)
672 |
673 | y = int(np.clip(np.floor(pos_in_data.x()), 0, data.shape[1] - 1))
674 | x = int(np.clip(np.floor(pos_in_data.y()), 0, data.shape[0] - 1))
675 |
676 | if np.isrealobj(data):
677 | display_text = f"[{x},{y}]: {data[x,y]:.5g}"
678 | else:
679 | display_text = f"[{x},{y}]: |z|={np.abs(data[x,y]):.5g}, ϕ={np.degrees(np.angle(data[x,y])):.5g}°"
680 |
681 | self.cursor_value_text.setText(display_text)
682 |
683 |
684 | def update_annulus_pos(self):
685 | """
686 | Function to keep inner and outer rings of annulus aligned.
687 | """
688 | R_outer = self.virtual_detector_roi_outer.size().x() / 2
689 | R_inner = self.virtual_detector_roi_inner.size().x() / 2
690 | # Only outer annulus is draggable; when it moves, update position of inner annulus
691 | x0 = self.virtual_detector_roi_outer.pos().x() + R_outer
692 | y0 = self.virtual_detector_roi_outer.pos().y() + R_outer
693 | self.virtual_detector_roi_inner.setPos(x0 - R_inner, y0 - R_inner, update=False)
694 |
695 |
696 | def update_annulus_radii(self):
697 | R_outer = self.virtual_detector_roi_outer.size().x() / 2
698 | R_inner = self.virtual_detector_roi_inner.size().x() / 2
699 | if R_outer < R_inner:
700 | x0 = self.virtual_detector_roi_outer.pos().x() + R_outer
701 | y0 = self.virtual_detector_roi_outer.pos().y() + R_outer
702 | self.virtual_detector_roi_outer.setSize(2 * R_inner + 6, update=False)
703 | self.virtual_detector_roi_outer.setPos(
704 | x0 - R_inner - 3, y0 - R_inner - 3, update=False
705 | )
706 |
--------------------------------------------------------------------------------
/src/py4D_browser/utils.py:
--------------------------------------------------------------------------------
1 | import pyqtgraph as pg
2 | import numpy as np
3 | from PyQt5.QtWidgets import QFrame, QPushButton, QApplication, QLabel
4 | from PyQt5.QtCore import pyqtSignal
5 | from PyQt5.QtCore import Qt, QObject
6 | from PyQt5.QtWidgets import QDialog, QHBoxLayout, QVBoxLayout, QSpinBox
7 |
8 |
9 | class StatusBarWriter:
10 | def __init__(self, statusBar):
11 | self.statusBar = statusBar
12 | self.app = app = QApplication.instance()
13 |
14 | def write(self, message):
15 | self.statusBar.showMessage(message, 1_000)
16 | self.app.processEvents()
17 |
18 | def flush(self):
19 | pass
20 |
21 |
22 | class VLine(QFrame):
23 | # a simple vertical divider line
24 | def __init__(self):
25 | super(VLine, self).__init__()
26 | self.setFrameShape(self.VLine | self.Sunken)
27 |
28 |
29 | class LatchingButton(QPushButton):
30 | """
31 | Subclass of QPushButton that acts as a momentary button,
32 | unless shift is held down during the click, in which case
33 | it toggles on.
34 | Emits the "activated" signal whenever triggered, and
35 | maintains the "latched" state when latched down.
36 | """
37 |
38 | activated = pyqtSignal()
39 |
40 | def __init__(self, *args, **kwargs):
41 | self.status_bar = kwargs.pop("status_bar", None)
42 | self.latched = kwargs.pop("latched", False)
43 | super().__init__(*args, **kwargs)
44 | self.setCheckable(True)
45 | self.clicked.connect(self.on_click)
46 | if self.latched:
47 | self.setChecked(True)
48 | self.activated.emit()
49 |
50 | def on_click(self, *args):
51 | modifiers = QApplication.keyboardModifiers()
52 |
53 | if self.latched:
54 | self.setChecked(False)
55 | self.latched = False
56 | else:
57 | if modifiers == Qt.ShiftModifier:
58 | self.setChecked(True)
59 | self.latched = True
60 | self.activated.emit()
61 | else:
62 | self.setChecked(False)
63 | self.latched = False
64 | self.activated.emit()
65 | if self.status_bar is not None:
66 | self.status_bar.showMessage("Shift+click to keep on", 5_000)
67 |
68 |
69 | def pg_point_roi(view_box, center=(-0.5, -0.5), pen=(0, 9), hoverPen=None):
70 | """
71 | Point selection. Based in pyqtgraph, and returns a pyqtgraph CircleROI object.
72 | This object has a sigRegionChanged.connect() signal method to connect to other functions.
73 | """
74 | circ_roi = pg.CircleROI(center, (2, 2), movable=True, pen=pen, hoverPen=hoverPen)
75 | h = circ_roi.addTranslateHandle((0.5, 0.5))
76 | h.pen = pg.mkPen("r")
77 | h.update()
78 | view_box.addItem(circ_roi)
79 | circ_roi.removeHandle(0)
80 | return circ_roi
81 |
82 |
83 | def make_detector(shape: tuple, mode: str, geometry) -> np.ndarray:
84 | match mode, geometry:
85 | case ["point", (qx, qy)]:
86 | mask = np.zeros(shape, dtype=np.bool_)
87 | mask[qx, qy] = True
88 | case ["point", geom]:
89 | raise ValueError(
90 | f"Point detector shape must be specified as (qx,qy), not {geom}"
91 | )
92 |
93 | case [("circle" | "circular"), ((qx, qy), r)]:
94 | ix, iy = np.indices(shape)
95 | mask = np.hypot(ix - qx, iy - qy) <= r
96 | case [("circle" | "circular"), geom]:
97 | raise ValueError(
98 | f"Circular detector shape must be specified as ((qx,qy),r), not {geom}"
99 | )
100 |
101 | case [("annulus" | "annular"), ((qx, qy), (ri, ro))]:
102 | ix, iy = np.indices(shape)
103 | ir = np.hypot(ix - qx, iy - qy)
104 | mask = np.logical_and(ir >= ri, ir <= ro)
105 | case [("annulus" | "annular"), geom]:
106 | raise ValueError(
107 | f"Annular detector shape must be specified as ((qx,qy),(ri,ro)), not {geom}"
108 | )
109 |
110 | case [("rectangle" | "square" | "rectangular"), (xmin, xmax, ymin, ymax)]:
111 | mask = np.zeros(shape, dtype=np.bool_)
112 | mask[xmin:xmax, ymin:ymax] = True
113 | case [("rectangle" | "square" | "rectangular"), geom]:
114 | raise ValueError(
115 | f"Rectangular detector shape must be specified as (xmin,xmax,ymin,ymax), not {geom}"
116 | )
117 |
118 | case ["mask", mask_arr]:
119 | mask = mask_arr
120 |
121 | case unknown:
122 | raise ValueError(f"mode and geometry not understood: {unknown}")
123 |
124 | return mask
125 |
126 |
127 | def complex_to_Lab(
128 | im, amin=None, amax=None, gamma=1.0, L_scale=100, ab_scale=64, uniform_L=None
129 | ):
130 | from skimage.color import lab2rgb
131 | from matplotlib.colors import Normalize
132 | import warnings
133 |
134 | Lab = np.zeros(im.shape + (3,), dtype=np.float64)
135 | angle = np.angle(im)
136 |
137 | L = Normalize(vmin=amin, vmax=amax, clip=True)(np.abs(im)) ** gamma
138 | L = Normalize()(L)
139 |
140 | # attempt at polynomial saturation
141 | # ab_prescale = 4*L - 4*L*L
142 | ab_prescale = 0.5
143 |
144 | Lab[..., 0] = uniform_L or L * L_scale
145 | Lab[..., 1] = np.cos(angle) * ab_scale * ab_prescale
146 | Lab[..., 2] = np.sin(angle) * ab_scale * ab_prescale
147 |
148 | with warnings.catch_warnings():
149 | warnings.simplefilter("ignore")
150 | rgb = lab2rgb(Lab)
151 |
152 | return rgb
153 |
--------------------------------------------------------------------------------