├── .github └── workflows │ └── python-package.yml ├── .gitignore ├── .gitmodules ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── CONTRIBUTORS.txt ├── COPYING ├── LICENSE ├── MANIFEST.in ├── README.md ├── nd2reader ├── __init__.py ├── artificial.py ├── common.py ├── common_raw_metadata.py ├── exceptions.py ├── label_map.py ├── legacy.py ├── parser.py ├── raw_metadata.py ├── reader.py └── stitched.py ├── release.txt ├── requirements.txt ├── setup.cfg ├── setup.py ├── sphinx ├── Makefile ├── _templates │ └── layout.html ├── conf.py ├── index.rst ├── make.bat ├── nd2reader.rst └── tutorial.rst ├── test.py └── tests ├── __init__.py ├── test_artificial.py ├── test_common.py ├── test_label_map.py ├── test_legacy.py ├── test_parser.py ├── test_raw_metadata.py ├── test_reader.py └── test_version.py /.github/workflows/python-package.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | strategy: 14 | fail-fast: false 15 | matrix: 16 | python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] 17 | 18 | steps: 19 | - uses: actions/checkout@v2 20 | - name: Set up Python ${{ matrix.python-version }} 21 | uses: actions/setup-python@v2 22 | with: 23 | python-version: ${{ matrix.python-version }} 24 | - name: Install dependencies 25 | run: | 26 | python -m pip install --upgrade pip 27 | python -m pip install flake8 pytest 28 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 29 | - name: Lint with flake8 30 | run: | 31 | # stop the build if there are Python syntax errors or undefined names 32 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 33 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 34 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 35 | - name: Install as package 36 | run: | 37 | python setup.py develop 38 | - name: Test with pytest 39 | run: | 40 | pytest 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.nd2 2 | run.py 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | .idea/ 7 | *.idea/* 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | env27/ 15 | bin/ 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | 29 | # Installer logs 30 | pip-log.txt 31 | pip-delete-this-directory.txt 32 | 33 | # Unit test / coverage reports 34 | htmlcov/ 35 | .tox/ 36 | .coverage 37 | .cache 38 | nosetests.xml 39 | coverage.xml 40 | 41 | # Translations 42 | *.mo 43 | 44 | # Mr Developer 45 | .mr.developer.cfg 46 | .project 47 | .pydevproject 48 | 49 | # Rope 50 | .ropeproject 51 | 52 | # Django stuff: 53 | *.log 54 | *.pot 55 | 56 | tests/test_data/ 57 | 58 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "docs"] 2 | path = docs 3 | url = git@github.com:rbnvrw/nd2reader.git 4 | branch = gh-pages 5 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at development@lighthacking.nl. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Looking for maintainers 2 | 3 | Because I'm no longer active in this field, I'm unable to maintain this package any longer. If you'd like to help, please reach out to [me](https://github.com/rbnvrw). 4 | We can discuss your experience and I'll add you to the [OpenScienceTools](https://github.com/Open-Science-Tools) team so that you have access to the repository. 5 | 6 | # Contributing to nd2reader 7 | 8 | We welcome feature proposals and improvements to the library from anyone. If you just have an idea, you can open an [issue](https://github.com/rbnvrw/nd2reader/issues) for 9 | discussion, or get in touch with a member of [OpenScienceTools](https://github.com/Open-Science-Tools). If you already wrote some code or made changes, simply open a pull 10 | request. 11 | 12 | ## Running and Writing Tests 13 | 14 | Unit tests can be run with the command `python test.py`. The test finder will automatically locate any tests in the `tests` directory. Test classes 15 | must inherit from `unittest.TestCase` and tests will only be run if the function name starts with `test`. 16 | 17 | There are also functional tests that work with real ND2s to make sure the code actually works with a wide variety of files. We hope to someday put these into a continuous integration 18 | system so everyone can benefit, but for now, they will just be manually run by the maintainer of this library before merging in any contributions. 19 | 20 | ## Contributing Your ND2 files 21 | 22 | We always appreciate more ND2s, as they help us find corner cases. Please get in touch using any of the means listed at the top of this page if you'd like to send one in. 23 | -------------------------------------------------------------------------------- /CONTRIBUTORS.txt: -------------------------------------------------------------------------------- 1 | Author: Jim Rybarski 2 | 3 | nd2reader is based on the read_nd2 module from the SLOTH library (http://pythonhosted.org/SLOTH/_modules/sloth/read_nd2.html). 4 | Thanks to M.Kauer and B.Kauer for solving the hardest part of parsing ND2s. 5 | 6 | This fork is maintained by Ruben Verweij. -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | Copyright 2014-2016 Jim Rybarski, 2017 Ruben Verweij 2 | 3 | nd2reader is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | 8 | nd2reader is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU General Public License for more details. 12 | 13 | You should have received a copy of the GNU General Public License 14 | along with this program. If not, see . -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include MANIFEST.in 2 | include setup.py 3 | include setup.cfg 4 | include README.md 5 | include LICENSE 6 | include COPYING 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nd2reader 2 | 3 | **This package is no longer actively developed because I'm no longer working in this field and can't properly maintain it. If you'd like to help, please see the [contributing](https://github.com/rbnvrw/nd2reader/blob/master/CONTRIBUTING.md) page 4 | for more information.** 5 | 6 | [![Anaconda-Server Badge](https://anaconda.org/conda-forge/nd2reader/badges/version.svg)](https://anaconda.org/conda-forge/nd2reader) 7 | [![Anaconda-Server Badge](https://anaconda.org/conda-forge/nd2reader/badges/downloads.svg)](https://anaconda.org/conda-forge/nd2reader) 8 | [![Build status](https://github.com/rbnvrw/nd2reader/actions/workflows/python-package.yml/badge.svg)](https://github.com/rbnvrw/nd2reader/actions/workflows/python-package.yml) 9 | 10 | ### About 11 | 12 | `nd2reader` is a pure-Python package that reads images produced by NIS Elements 4.0+. It has only been definitively tested on NIS Elements 4.30.02 Build 1053. Support for older versions is being actively worked on. 13 | The reader is written in the [pims](https://github.com/soft-matter/pims) framework, enabling easy access to multidimensional files, lazy slicing, and nice display in IPython. 14 | 15 | ### Alternatives 16 | 17 | - [nd2](https://pypi.org/project/nd2/) 18 | - Open a PR if you'd like to be listed here. 19 | 20 | ### Documentation 21 | 22 | The documentation is available [here](https://open-science-tools.github.io/nd2reader/). 23 | 24 | ### Installation 25 | 26 | The package is available on PyPi. Install it using: 27 | 28 | ``` 29 | pip install nd2reader 30 | ``` 31 | 32 | If you don't already have the packages `numpy`, `pims`, `six` and `xmltodict`, they will be installed automatically if you use the `setup.py` script. 33 | Python >= 3.5 are supported. 34 | 35 | #### Installation via Conda Forge 36 | 37 | Installing `nd2reader` from the `conda-forge` channel can be achieved by adding `conda-forge` to your channels with: 38 | 39 | ``` 40 | conda config --add channels conda-forge 41 | ``` 42 | 43 | Once the `conda-forge` channel has been enabled, `nd2reader` can be installed with: 44 | 45 | ``` 46 | conda install nd2reader 47 | ``` 48 | 49 | It is possible to list all of the versions of `nd2reader` available on your platform with: 50 | 51 | ``` 52 | conda search nd2reader --channel conda-forge 53 | ``` 54 | 55 | ### ND2s 56 | 57 | `nd2reader` follows the [pims](https://github.com/soft-matter/pims) framework. To open a file and show the first frame: 58 | 59 | ```python 60 | from nd2reader import ND2Reader 61 | import matplotlib.pyplot as plt 62 | 63 | with ND2Reader('my_directory/example.nd2') as images: 64 | plt.imshow(images[0]) 65 | ``` 66 | 67 | After opening the file, all `pims` features are supported. Please refer to the [pims documentation](http://soft-matter.github.io/pims/). 68 | 69 | #### Backwards compatibility 70 | 71 | Older versions of `nd2reader` do not use the `pims` framework. To provide backwards compatibility, a legacy [Nd2](https://open-science-tools.github.io/nd2reader/nd2reader.html#module-nd2reader.legacy) class is provided. 72 | 73 | ### Contributing 74 | 75 | If you'd like to help with the development of nd2reader or just have an idea for improvement, please see the [contributing](https://github.com/rbnvrw/nd2reader/blob/master/CONTRIBUTING.md) page 76 | for more information. 77 | 78 | ### Bug Reports and Features 79 | 80 | If this fails to work exactly as expected, please open an [issue](https://github.com/rbnvrw/nd2reader/issues). 81 | If you get an unhandled exception, please paste the entire stack trace into the issue as well. 82 | 83 | ### Acknowledgments 84 | 85 | PIMS modified version by Ruben Verweij. 86 | 87 | Original version by Jim Rybarski. Support for the development of this package was partially provided by the [Finkelstein Laboratory](http://finkelsteinlab.org/). 88 | -------------------------------------------------------------------------------- /nd2reader/__init__.py: -------------------------------------------------------------------------------- 1 | from os import path 2 | from nd2reader.reader import ND2Reader 3 | from nd2reader.legacy import Nd2 4 | 5 | try: 6 | import importlib.metadata as importlib_metadata 7 | except: 8 | import importlib_metadata 9 | 10 | try: 11 | __version__ = importlib_metadata.version(__name__) 12 | except: 13 | print('Unable to read version number') 14 | -------------------------------------------------------------------------------- /nd2reader/artificial.py: -------------------------------------------------------------------------------- 1 | """Functions to create artificial nd2 data for testing purposes 2 | """ 3 | import six 4 | import numpy as np 5 | import struct 6 | from nd2reader.common import check_or_make_dir 7 | from os import path 8 | 9 | global_labels = ['image_attributes', 'image_text_info', 'image_metadata', 10 | 'image_metadata_sequence', 'image_calibration', 'x_data', 11 | 'y_data', 'z_data', 'roi_metadata', 'pfs_status', 'pfs_offset', 12 | 'guid', 'description', 'camera_exposure_time', 'camera_temp', 13 | 'acquisition_times', 'acquisition_times_2', 14 | 'acquisition_frames', 'lut_data', 'grabber_settings', 15 | 'custom_data', 'app_info', 'image_frame_0'] 16 | 17 | global_file_labels = ["ImageAttributesLV!", "ImageTextInfoLV!", 18 | "ImageMetadataLV!", "ImageMetadataSeqLV|0!", 19 | "ImageCalibrationLV|0!", "CustomData|X!", "CustomData|Y!", 20 | "CustomData|Z!", "CustomData|RoiMetadata_v1!", 21 | "CustomData|PFS_STATUS!", "CustomData|PFS_OFFSET!", 22 | "CustomData|GUIDStore!", "CustomData|CustomDescriptionV1_0!", 23 | "CustomData|Camera_ExposureTime1!", "CustomData|CameraTemp1!", 24 | "CustomData|AcqTimesCache!", "CustomData|AcqTimes2Cache!", 25 | "CustomData|AcqFramesCache!", "CustomDataVar|LUTDataV1_0!", 26 | "CustomDataVar|GrabberCameraSettingsV1_0!", 27 | "CustomDataVar|CustomDataV2_0!", "CustomDataVar|AppInfo_V1_0!", 28 | "ImageDataSeq|0!"] 29 | 30 | 31 | class ArtificialND2(object): 32 | """Artificial ND2 class (for testing purposes) 33 | """ 34 | header = 0xabeceda 35 | relative_offset = 0 36 | data_types = {'unsigned_char': 1, 37 | 'unsigned_int': 2, 38 | 'unsigned_int_2': 3, 39 | 'unsigned_long': 5, 40 | 'double': 6, 41 | 'string': 8, 42 | 'char_array': 9, 43 | 'metadata_item': 11, 44 | } 45 | 46 | def __init__(self, file, version=(3, 0), skip_blocks=None): 47 | self.version = version 48 | self.raw_text, self.locations, self.data = b'', None, None 49 | check_or_make_dir(path.dirname(file)) 50 | self._fh = open(file, 'w+b', 0) 51 | self.write_file(skip_blocks) 52 | 53 | def __enter__(self): 54 | return self 55 | 56 | def __exit__(self, exc_type, exc_value, traceback): 57 | self.close() 58 | 59 | @property 60 | def file_handle(self): 61 | """The file handle to the binary file 62 | 63 | Returns: 64 | file: the file handle 65 | 66 | """ 67 | return self._fh 68 | 69 | def close(self): 70 | """Correctly close the file handle 71 | """ 72 | if self._fh is not None: 73 | self._fh.close() 74 | 75 | def write_file(self, skip_blocks=None): 76 | if skip_blocks is None: 77 | skip_blocks = [] 78 | 79 | if 'version' not in skip_blocks: 80 | # write version header at start of the file 81 | self.write_version() 82 | 83 | if 'label_map' not in skip_blocks: 84 | # write label map + data in the center 85 | self.locations, self.data = self.write_label_map() 86 | 87 | if 'label_map_marker' not in skip_blocks: 88 | # write start position of label map at the end of the file 89 | self.write_label_map_info() 90 | 91 | # write all to file 92 | self._fh.write(self.raw_text) 93 | 94 | def write_version(self): 95 | """Write file header 96 | """ 97 | # write 16 empty bytes 98 | self.raw_text += bytearray(16) 99 | 100 | # write version info 101 | self.raw_text += self._get_version_string() 102 | 103 | def write_label_map_info(self): 104 | """Write the location of the start of the label map at the end of the file 105 | """ 106 | location = self._get_version_byte_length() 107 | self.raw_text += struct.pack("Q", location) 108 | 109 | def _get_version_string(self): 110 | return six.b('ND2 FILE SIGNATURE CHUNK NAME01!Ver%s.%s' % self.version) 111 | 112 | def _get_version_byte_length(self): 113 | return 16 + len(self._get_version_string()) 114 | 115 | def write_label_map(self): 116 | raw_text, locations, data = self.create_label_map_bytes() 117 | self.raw_text += raw_text 118 | 119 | return locations, data 120 | 121 | def create_label_map_bytes(self): 122 | """Construct a binary label map 123 | 124 | Returns: 125 | tuple: (binary data, dictionary data) 126 | 127 | """ 128 | raw_text = six.b('') 129 | labels = global_labels 130 | file_labels = global_file_labels 131 | 132 | file_data, file_data_dict = self._get_file_data(labels) 133 | 134 | locations = {} 135 | 136 | # generate random positions and lengths 137 | version_length = self._get_version_byte_length() 138 | 139 | # calculate data length 140 | label_length = np.sum([len(six.b(l)) + 16 for l in file_labels]) 141 | 142 | # write label map 143 | cur_pos = version_length + label_length 144 | for label, file_label, data in zip(labels, file_labels, file_data): 145 | raw_text += six.b(file_label) 146 | data_length = len(data) 147 | raw_text += struct.pack('QQ', cur_pos, data_length) 148 | locations[label] = (cur_pos, data_length) 149 | cur_pos += data_length 150 | 151 | # write data 152 | raw_text += six.b('').join(file_data) 153 | 154 | return raw_text, locations, file_data_dict 155 | 156 | def _pack_data_with_metadata(self, data): 157 | packed_data = self._pack_raw_data_with_metadata(data) 158 | 159 | raw_data = struct.pack("IIQ", self.header, self.relative_offset, len(packed_data)) 160 | raw_data += packed_data 161 | 162 | return raw_data 163 | 164 | def _pack_raw_data_with_metadata(self, data): 165 | raw_data = b'' 166 | 167 | if isinstance(data, dict): 168 | raw_data = self._pack_dict_with_metadata(data) 169 | elif isinstance(data, int): 170 | raw_data = struct.pack('I', data) 171 | elif isinstance(data, float): 172 | raw_data = struct.pack('d', data) 173 | elif isinstance(data, str): 174 | raw_data = self._str_to_padded_bytes(data) 175 | 176 | return raw_data 177 | 178 | def _get_data_type(self, data): 179 | if isinstance(data, dict): 180 | return self.data_types['metadata_item'] 181 | elif isinstance(data, int): 182 | return self.data_types['unsigned_int'] 183 | elif isinstance(data, str): 184 | return self.data_types['string'] 185 | else: 186 | return self.data_types['double'] 187 | 188 | @staticmethod 189 | def _str_to_padded_bytes(data): 190 | return six.b('').join([struct.pack('cx', six.b(s)) for s in data]) + struct.pack('xx') 191 | 192 | def _pack_dict_with_metadata(self, data): 193 | raw_data = b'' 194 | 195 | for data_key in data.keys(): 196 | # names have always one character extra and are padded in zero bytes??? 197 | b_data_key = self._str_to_padded_bytes(data_key) 198 | 199 | # header consists of data type and length of key name, it is represented by 2 unsigned chars 200 | raw_data += struct.pack('BB', self._get_data_type(data[data_key]), len(data_key) + 1) 201 | raw_data += b_data_key 202 | 203 | sub_data = self._pack_raw_data_with_metadata(data[data_key]) 204 | 205 | if isinstance(data[data_key], dict): 206 | # Pack: the number of keys and the length of raw data until now, sub data 207 | # and the 12 bytes that we add now 208 | raw_data += struct.pack("\d)\.(?P\d)$""", data) 39 | 40 | if match: 41 | # We haven't seen a lot of ND2s but the ones we have seen conform to this 42 | return int(match.group('major')), int(match.group('minor')) 43 | 44 | raise InvalidVersionError("The version of the ND2 you specified is not supported.") 45 | 46 | 47 | def read_chunk(fh, chunk_location): 48 | """Reads a piece of data given the location of its pointer. 49 | 50 | Args: 51 | fh: an open file handle to the ND2 52 | chunk_location (int): location to read 53 | 54 | Returns: 55 | bytes: the data at the chunk location 56 | 57 | """ 58 | if chunk_location is None or fh is None: 59 | return None 60 | fh.seek(chunk_location) 61 | # The chunk metadata is always 16 bytes long 62 | chunk_metadata = fh.read(16) 63 | header, relative_offset, data_length = struct.unpack("IIQ", chunk_metadata) 64 | if header != 0xabeceda: 65 | raise ValueError("The ND2 file seems to be corrupted.") 66 | # We start at the location of the chunk metadata, skip over the metadata, and then proceed to the 67 | # start of the actual data field, which is at some arbitrary place after the metadata. 68 | fh.seek(chunk_location + 16 + relative_offset) 69 | return fh.read(data_length) 70 | 71 | 72 | def read_array(fh, kind, chunk_location): 73 | """ 74 | 75 | Args: 76 | fh: File handle of the nd2 file 77 | kind: data type, can be one of 'double', 'int' or 'float' 78 | chunk_location: the location of the array chunk in the binary nd2 file 79 | 80 | Returns: 81 | array.array: an array of the data 82 | 83 | """ 84 | kinds = {'double': 'd', 85 | 'int': 'i', 86 | 'float': 'f'} 87 | if kind not in kinds: 88 | raise ValueError('You attempted to read an array of an unknown type.') 89 | raw_data = read_chunk(fh, chunk_location) 90 | if raw_data is None: 91 | return None 92 | return array.array(kinds[kind], raw_data) 93 | 94 | 95 | def _parse_unsigned_char(data): 96 | """ 97 | 98 | Args: 99 | data: binary data 100 | 101 | Returns: 102 | char: the data converted to unsigned char 103 | 104 | """ 105 | return struct.unpack("B", data.read(1))[0] 106 | 107 | 108 | def _parse_unsigned_int(data): 109 | """ 110 | 111 | Args: 112 | data: binary data 113 | 114 | Returns: 115 | int: the data converted to unsigned int 116 | 117 | """ 118 | return struct.unpack("I", data.read(4))[0] 119 | 120 | 121 | def _parse_unsigned_long(data): 122 | """ 123 | 124 | Args: 125 | data: binary data 126 | 127 | Returns: 128 | long: the data converted to unsigned long 129 | 130 | """ 131 | return struct.unpack("Q", data.read(8))[0] 132 | 133 | 134 | def _parse_double(data): 135 | """ 136 | 137 | Args: 138 | data: binary data 139 | 140 | Returns: 141 | double: the data converted to double 142 | 143 | """ 144 | return struct.unpack("d", data.read(8))[0] 145 | 146 | 147 | def _parse_string(data): 148 | """ 149 | 150 | Args: 151 | data: binary data 152 | 153 | Returns: 154 | string: the data converted to string 155 | 156 | """ 157 | value = data.read(2) 158 | # the string ends at the first instance of \x00\x00 159 | while not value.endswith(six.b("\x00\x00")): 160 | next_data = data.read(2) 161 | if len(next_data) == 0: 162 | break 163 | value += next_data 164 | 165 | try: 166 | decoded = value.decode("utf16")[:-1].encode("utf8") 167 | except UnicodeDecodeError: 168 | decoded = value.decode('utf8').encode("utf8") 169 | 170 | return decoded 171 | 172 | 173 | def _parse_char_array(data): 174 | """ 175 | 176 | Args: 177 | data: binary data 178 | 179 | Returns: 180 | array.array: the data converted to an array 181 | 182 | """ 183 | array_length = struct.unpack("Q", data.read(8))[0] 184 | return array.array("B", data.read(array_length)) 185 | 186 | 187 | def parse_date(text_info): 188 | """ 189 | The date and time when acquisition began. 190 | 191 | Args: 192 | text_info: the text that contains the date and time information 193 | 194 | Returns: 195 | datetime: the date and time of the acquisition 196 | 197 | """ 198 | for line in text_info.values(): 199 | line = line.decode("utf8") 200 | # ND2s seem to randomly switch between 12- and 24-hour representations. 201 | possible_formats = ["%m/%d/%Y %H:%M:%S", "%m/%d/%Y %I:%M:%S %p", "%d/%m/%Y %H:%M:%S"] 202 | for date_format in possible_formats: 203 | try: 204 | absolute_start = datetime.strptime(line, date_format) 205 | except (TypeError, ValueError): 206 | continue 207 | return absolute_start 208 | 209 | return None 210 | 211 | 212 | def _parse_metadata_item(data, cursor_position): 213 | """Reads hierarchical data, analogous to a Python dict. 214 | 215 | Args: 216 | data: the binary data that needs to be parsed 217 | cursor_position: the position in the binary nd2 file 218 | 219 | Returns: 220 | dict: a dictionary containing the metadata item 221 | 222 | """ 223 | new_count, length = struct.unpack(" 0: 48 | loops = [] 49 | for i, period in enumerate(loop_data[six.b('pPeriod')]): 50 | # exclude invalid periods 51 | if six.b('pPeriodValid') in loop_data: 52 | try: 53 | if loop_data[six.b('pPeriodValid')][i] == 1: 54 | loops.append(loop_data[six.b('pPeriod')][period]) 55 | except IndexError: 56 | continue 57 | else: 58 | # we can't be sure, append all 59 | loops.append(loop_data[six.b('pPeriod')][period]) 60 | 61 | return [loop_data] 62 | 63 | 64 | def guess_sampling_from_loops(duration, loop): 65 | """ In some cases, both keys are not saved. Then try to calculate it. 66 | 67 | Args: 68 | duration: the total duration of the loop 69 | loop: the raw loop data 70 | 71 | Returns: 72 | float: the guessed sampling interval in milliseconds 73 | 74 | """ 75 | number_of_loops = get_from_dict_if_exists('uiCount', loop) 76 | number_of_loops = number_of_loops if number_of_loops is not None and number_of_loops > 0 else 1 77 | interval = duration / number_of_loops 78 | return interval 79 | 80 | 81 | def determine_sampling_interval(duration, loop): 82 | """Determines the loop sampling interval in milliseconds 83 | 84 | Args: 85 | duration: loop duration in milliseconds 86 | loop: loop dictionary 87 | 88 | Returns: 89 | float: the sampling interval in milliseconds 90 | 91 | """ 92 | interval = get_from_dict_if_exists('dPeriod', loop) 93 | avg_interval = get_from_dict_if_exists('dAvgPeriodDiff', loop) 94 | 95 | if interval is None or interval <= 0: 96 | interval = avg_interval 97 | else: 98 | avg_interval_set = avg_interval is not None and avg_interval > 0 99 | 100 | if round(avg_interval) != round(interval) and avg_interval_set: 101 | message = ("Reported average frame interval (%.1f ms) doesn't" 102 | " match the set interval (%.1f ms). Using the average" 103 | " now.") 104 | warnings.warn(message % (avg_interval, interval), RuntimeWarning) 105 | interval = avg_interval 106 | 107 | if interval is None or interval <= 0: 108 | # In some cases, both keys are not saved. Then try to calculate it. 109 | interval = guess_sampling_from_loops(duration, loop) 110 | 111 | return interval 112 | -------------------------------------------------------------------------------- /nd2reader/exceptions.py: -------------------------------------------------------------------------------- 1 | class InvalidFileType(Exception): 2 | """Non .nd2 extension file. 3 | 4 | File does not have an extension .nd2. 5 | 6 | """ 7 | pass 8 | 9 | class InvalidVersionError(Exception): 10 | """Unknown version. 11 | 12 | We don't know how to parse the version of ND2 that we were given. 13 | 14 | """ 15 | pass 16 | 17 | class EmptyFileError(Exception): 18 | """This .nd2 file seems to be empty. 19 | 20 | Raised if no axes are found in the file. 21 | """ 22 | -------------------------------------------------------------------------------- /nd2reader/label_map.py: -------------------------------------------------------------------------------- 1 | import six 2 | import struct 3 | import re 4 | 5 | 6 | class LabelMap(object): 7 | """Contains pointers to metadata. This might only be valid for V3 files. 8 | 9 | """ 10 | 11 | def __init__(self, raw_binary_data): 12 | self._data = raw_binary_data 13 | self._image_data = {} 14 | 15 | def _get_location(self, label): 16 | try: 17 | label_location = self._data.index(label) + len(label) 18 | return self._parse_data_location(label_location) 19 | except ValueError: 20 | return None 21 | 22 | def _parse_data_location(self, label_location): 23 | location, length = struct.unpack("QQ", self._data[label_location: label_location + 16]) 24 | return location 25 | 26 | @property 27 | def image_text_info(self): 28 | """Get the location of the textual image information 29 | 30 | Returns: 31 | int: The location of the textual image information 32 | 33 | """ 34 | return self._get_location(six.b("ImageTextInfoLV!")) 35 | 36 | @property 37 | def image_metadata(self): 38 | """Get the location of the image metadata 39 | 40 | Returns: 41 | int: The location of the image metadata 42 | 43 | """ 44 | return self._get_location(six.b("ImageMetadataLV!")) 45 | 46 | @property 47 | def image_events(self): 48 | """Get the location of the image events 49 | 50 | Returns: 51 | int: The location of the image events 52 | 53 | """ 54 | return self._get_location(six.b("ImageEventsLV!")) 55 | 56 | @property 57 | def image_metadata_sequence(self): 58 | """Get the location of the image metadata sequence. There is always only one of these, even though it has a pipe 59 | followed by a zero, which is how they do indexes. 60 | 61 | Returns: 62 | int: The location of the image metadata sequence 63 | 64 | """ 65 | return self._get_location(six.b("ImageMetadataSeqLV|0!")) 66 | 67 | def get_image_data_location(self, index): 68 | """Get the location of the image data 69 | 70 | Returns: 71 | int: The location of the image data 72 | 73 | """ 74 | if not self._image_data: 75 | regex = re.compile(six.b("""ImageDataSeq\|(\d+)!""")) 76 | for match in regex.finditer(self._data): 77 | if match: 78 | location = self._parse_data_location(match.end()) 79 | self._image_data[int(match.group(1))] = location 80 | return self._image_data[index] 81 | 82 | @property 83 | def image_calibration(self): 84 | """Get the location of the image calibration 85 | 86 | Returns: 87 | int: The location of the image calibration 88 | 89 | """ 90 | return self._get_location(six.b("ImageCalibrationLV|0!")) 91 | 92 | @property 93 | def image_attributes(self): 94 | """Get the location of the image attributes 95 | 96 | Returns: 97 | int: The location of the image attributes 98 | 99 | """ 100 | return self._get_location(six.b("ImageAttributesLV!")) 101 | 102 | @property 103 | def x_data(self): 104 | """Get the location of the custom x data 105 | 106 | Returns: 107 | int: The location of the custom x data 108 | 109 | """ 110 | return self._get_location(six.b("CustomData|X!")) 111 | 112 | @property 113 | def y_data(self): 114 | """Get the location of the custom y data 115 | 116 | Returns: 117 | int: The location of the custom y data 118 | 119 | """ 120 | return self._get_location(six.b("CustomData|Y!")) 121 | 122 | @property 123 | def z_data(self): 124 | """Get the location of the custom z data 125 | 126 | Returns: 127 | int: The location of the custom z data 128 | 129 | """ 130 | return self._get_location(six.b("CustomData|Z!")) 131 | 132 | @property 133 | def roi_metadata(self): 134 | """Information about any regions of interest (ROIs) defined in the nd2 file 135 | 136 | Returns: 137 | int: The location of the regions of interest (ROIs) 138 | 139 | """ 140 | return self._get_location(six.b("CustomData|RoiMetadata_v1!")) 141 | 142 | @property 143 | def pfs_status(self): 144 | """Get the location of the perfect focus system (PFS) status 145 | 146 | Returns: 147 | int: The location of the perfect focus system (PFS) status 148 | 149 | """ 150 | return self._get_location(six.b("CustomData|PFS_STATUS!")) 151 | 152 | @property 153 | def pfs_offset(self): 154 | """Get the location of the perfect focus system (PFS) offset 155 | 156 | Returns: 157 | int: The location of the perfect focus system (PFS) offset 158 | 159 | """ 160 | return self._get_location(six.b("CustomData|PFS_OFFSET!")) 161 | 162 | @property 163 | def guid(self): 164 | """Get the location of the image guid 165 | 166 | Returns: 167 | int: The location of the image guid 168 | 169 | """ 170 | return self._get_location(six.b("CustomData|GUIDStore!")) 171 | 172 | @property 173 | def description(self): 174 | """Get the location of the image description 175 | 176 | Returns: 177 | int: The location of the image description 178 | 179 | """ 180 | return self._get_location(six.b("CustomData|CustomDescriptionV1_0!")) 181 | 182 | @property 183 | def camera_exposure_time(self): 184 | """Get the location of the camera exposure time 185 | 186 | Returns: 187 | int: The location of the camera exposure time 188 | 189 | """ 190 | return self._get_location(six.b("CustomData|Camera_ExposureTime1!")) 191 | 192 | @property 193 | def camera_temp(self): 194 | """Get the location of the camera temperature 195 | 196 | Returns: 197 | int: The location of the camera temperature 198 | 199 | """ 200 | return self._get_location(six.b("CustomData|CameraTemp1!")) 201 | 202 | @property 203 | def acquisition_times(self): 204 | """Get the location of the acquisition times, block 1 205 | 206 | Returns: 207 | int: The location of the acquisition times, block 1 208 | 209 | """ 210 | return self._get_location(six.b("CustomData|AcqTimesCache!")) 211 | 212 | @property 213 | def acquisition_times_2(self): 214 | """Get the location of the acquisition times, block 2 215 | 216 | Returns: 217 | int: The location of the acquisition times, block 2 218 | 219 | """ 220 | return self._get_location(six.b("CustomData|AcqTimes2Cache!")) 221 | 222 | @property 223 | def acquisition_frames(self): 224 | """Get the location of the acquisition frames 225 | 226 | Returns: 227 | int: The location of the acquisition frames 228 | 229 | """ 230 | return self._get_location(six.b("CustomData|AcqFramesCache!")) 231 | 232 | @property 233 | def lut_data(self): 234 | """Get the location of the LUT data 235 | 236 | Returns: 237 | int: The location of the LUT data 238 | 239 | """ 240 | return self._get_location(six.b("CustomDataVar|LUTDataV1_0!")) 241 | 242 | @property 243 | def grabber_settings(self): 244 | """Get the location of the grabber settings 245 | 246 | Returns: 247 | int: The location of the grabber settings 248 | 249 | """ 250 | return self._get_location(six.b("CustomDataVar|GrabberCameraSettingsV1_0!")) 251 | 252 | @property 253 | def custom_data(self): 254 | """Get the location of the custom user data 255 | 256 | Returns: 257 | int: The location of the custom user data 258 | 259 | """ 260 | return self._get_location(six.b("CustomDataVar|CustomDataV2_0!")) 261 | 262 | @property 263 | def app_info(self): 264 | """Get the location of the application info metadata 265 | 266 | Returns: 267 | int: The location of the application info metadata 268 | 269 | """ 270 | return self._get_location(six.b("CustomDataVar|AppInfo_V1_0!")) 271 | -------------------------------------------------------------------------------- /nd2reader/legacy.py: -------------------------------------------------------------------------------- 1 | """ 2 | Legacy class for backwards compatibility 3 | """ 4 | 5 | import warnings 6 | 7 | from nd2reader import ND2Reader 8 | 9 | 10 | class Nd2(object): 11 | """ Warning: this module is deprecated and only maintained for backwards compatibility with the non-PIMS version of 12 | nd2reader. 13 | """ 14 | 15 | def __init__(self, filename): 16 | warnings.warn( 17 | "The 'Nd2' class is deprecated, please consider using the new ND2Reader interface which uses pims.", 18 | DeprecationWarning) 19 | 20 | self.reader = ND2Reader(filename) 21 | 22 | def __repr__(self): 23 | return "\n".join(["" % self.reader.filename, 24 | "Created: %s" % (self.date if self.date is not None else "Unknown"), 25 | "Image size: %sx%s (HxW)" % (self.height, self.width), 26 | "Frames: %s" % len(self.frames), 27 | "Channels: %s" % ", ".join(["%s" % str(channel) for channel in self.channels]), 28 | "Fields of View: %s" % len(self.fields_of_view), 29 | "Z-Levels: %s" % len(self.z_levels) 30 | ]) 31 | 32 | def __enter__(self): 33 | return self 34 | 35 | def __exit__(self, exc_type, exc_val, exc_tb): 36 | if self.reader is not None: 37 | self.reader.close() 38 | 39 | def __len__(self): 40 | return len(self.reader) 41 | 42 | def __getitem__(self, item): 43 | return self.reader[item] 44 | 45 | def select(self, fields_of_view=None, channels=None, z_levels=None, start=0, stop=None): 46 | """Select images based on criteria. 47 | 48 | Args: 49 | fields_of_view: the fields of view 50 | channels: the color channels 51 | z_levels: the z levels 52 | start: the starting frame 53 | stop: the last frame 54 | 55 | Returns: 56 | ND2Reader: Sliced ND2Reader which contains the frames 57 | 58 | """ 59 | if stop is None: 60 | stop = len(self.frames) 61 | 62 | return self.reader[start:stop] 63 | 64 | def get_image(self, frame_number, field_of_view, channel_name, z_level): 65 | """Deprecated. Returns the specified image from the ND2Reader class. 66 | 67 | Args: 68 | frame_number: the frame number 69 | field_of_view: the field of view number 70 | channel_name: the name of the color channel 71 | z_level: the z level number 72 | 73 | Returns: 74 | Frame: the specified image 75 | 76 | """ 77 | return self.reader.parser.get_image_by_attributes(frame_number, field_of_view, channel_name, z_level, 78 | self.height, self.width) 79 | 80 | def close(self): 81 | """Closes the ND2Reader 82 | """ 83 | if self.reader is not None: 84 | self.reader.close() 85 | 86 | @property 87 | def height(self): 88 | """Deprecated. Fetches the height of the image. 89 | 90 | Returns: 91 | int: the pixel height of the image 92 | 93 | """ 94 | return self._get_width_or_height("height") 95 | 96 | @property 97 | def width(self): 98 | """Deprecated. Fetches the width of the image. 99 | 100 | Returns: 101 | int: the pixel width of the image 102 | 103 | """ 104 | return self._get_width_or_height("width") 105 | 106 | def _get_width_or_height(self, key): 107 | return self.reader.metadata[key] if self.reader.metadata[key] is not None else 0 108 | 109 | @property 110 | def z_levels(self): 111 | """Deprecated. Fetches the available z levels. 112 | 113 | Returns: 114 | list: z levels. 115 | 116 | """ 117 | return self.reader.metadata["z_levels"] 118 | 119 | @property 120 | def fields_of_view(self): 121 | """Deprecated. Fetches the fields of view. 122 | 123 | Returns: 124 | list: fields of view. 125 | 126 | """ 127 | return self.reader.metadata["fields_of_view"] 128 | 129 | @property 130 | def channels(self): 131 | """Deprecated. Fetches all color channels. 132 | 133 | Returns: 134 | list: the color channels. 135 | 136 | """ 137 | return self.reader.metadata["channels"] 138 | 139 | @property 140 | def frames(self): 141 | """Deprecated. Fetches all frames. 142 | 143 | Returns: 144 | list: list of frames 145 | 146 | """ 147 | return self.reader.metadata["frames"] 148 | 149 | @property 150 | def date(self): 151 | """Deprecated. Fetches the acquisition date. 152 | 153 | Returns: 154 | string: the date 155 | 156 | """ 157 | return self.reader.metadata["date"] 158 | 159 | @property 160 | def pixel_microns(self): 161 | """Deprecated. Fetches the amount of microns per pixel. 162 | 163 | Returns: 164 | float: microns per pixel 165 | 166 | """ 167 | return self.reader.metadata["pixel_microns"] 168 | -------------------------------------------------------------------------------- /nd2reader/parser.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import struct 3 | 4 | import array 5 | import six 6 | import warnings 7 | from pims.base_frames import Frame 8 | import numpy as np 9 | 10 | from nd2reader.common import get_version, read_chunk 11 | from nd2reader.label_map import LabelMap 12 | from nd2reader.raw_metadata import RawMetadata 13 | from nd2reader import stitched 14 | 15 | 16 | class Parser(object): 17 | """Parses ND2 files and creates a Metadata and driver object. 18 | 19 | """ 20 | CHUNK_HEADER = 0xabeceda 21 | CHUNK_MAP_START = six.b("ND2 FILEMAP SIGNATURE NAME 0001!") 22 | CHUNK_MAP_END = six.b("ND2 CHUNK MAP SIGNATURE 0000001!") 23 | 24 | supported_file_versions = {(3, None): True} 25 | 26 | def __init__(self, fh): 27 | self._fh = fh 28 | self._label_map = None 29 | self._raw_metadata = None 30 | self.metadata = None 31 | 32 | # First check the file version 33 | self.supported = self._check_version_supported() 34 | 35 | # Parse the metadata 36 | self._parse_metadata() 37 | 38 | def calculate_image_properties(self, index): 39 | """Calculate FOV, channels and z_levels 40 | 41 | Args: 42 | index(int): the index (which is simply the order in which the image was acquired) 43 | 44 | Returns: 45 | tuple: tuple of the field of view, the channel and the z level 46 | 47 | """ 48 | field_of_view = self._calculate_field_of_view(index) 49 | channel = self._calculate_channel(index) 50 | z_level = self._calculate_z_level(index) 51 | return field_of_view, channel, z_level 52 | 53 | def get_image(self, index): 54 | """ 55 | Creates an Image object and adds its metadata, based on the index (which is simply the order in which the image 56 | was acquired). May return None if the ND2 contains multiple channels and not all were taken in each cycle (for 57 | example, if you take bright field images every minute, and GFP images every five minutes, there will be some 58 | indexes that do not contain an image. The reason for this is complicated, but suffice it to say that we hope to 59 | eliminate this possibility in future releases. For now, you'll need to check if your image is None if you're 60 | doing anything out of the ordinary. 61 | 62 | Args: 63 | index(int): the index (which is simply the order in which the image was acquired) 64 | 65 | Returns: 66 | Frame: the image 67 | 68 | """ 69 | field_of_view, channel, z_level = self.calculate_image_properties(index) 70 | channel_offset = index % len(self.metadata["channels"]) 71 | image_group_number = int(index / len(self.metadata["channels"])) 72 | frame_number = self._calculate_frame_number(image_group_number, field_of_view, z_level) 73 | try: 74 | timestamp, image = self._get_raw_image_data(image_group_number, channel_offset, self.metadata["height"], 75 | self.metadata["width"]) 76 | except (TypeError): 77 | return Frame([], frame_no=frame_number, metadata=self._get_frame_metadata()) 78 | else: 79 | return Frame(image, frame_no=frame_number, metadata=self._get_frame_metadata()) 80 | 81 | def get_image_by_attributes(self, frame_number, field_of_view, channel, z_level, height, width): 82 | """Gets an image based on its attributes alone 83 | 84 | Args: 85 | frame_number: the frame number 86 | field_of_view: the field of view 87 | channel_name: the color channel name 88 | z_level: the z level 89 | height: the height of the image 90 | width: the width of the image 91 | 92 | Returns: 93 | Frame: the requested image 94 | 95 | """ 96 | frame_number = 0 if frame_number is None else frame_number 97 | field_of_view = 0 if field_of_view is None else field_of_view 98 | channel = 0 if channel is None else channel 99 | z_level = 0 if z_level is None else z_level 100 | 101 | image_group_number = self._calculate_image_group_number(frame_number, field_of_view, z_level) 102 | try: 103 | timestamp, raw_image_data = self._get_raw_image_data(image_group_number, channel, 104 | height, width) 105 | except (TypeError): 106 | return Frame([], frame_no=frame_number, metadata=self._get_frame_metadata()) 107 | else: 108 | return Frame(raw_image_data, frame_no=frame_number, metadata=self._get_frame_metadata()) 109 | 110 | @staticmethod 111 | def get_dtype_from_metadata(): 112 | """Determine the data type from the metadata. 113 | 114 | For now, always use float64 to prevent unexpected overflow errors when manipulating the data (calculating sums/ 115 | means/etc.) 116 | 117 | """ 118 | return np.float64 119 | 120 | def _check_version_supported(self): 121 | """Checks if the ND2 file version is supported by this reader. 122 | 123 | Returns: 124 | bool: True on supported 125 | """ 126 | major_version, minor_version = get_version(self._fh) 127 | supported = self.supported_file_versions.get( 128 | (major_version, minor_version)) or self.supported_file_versions.get((major_version, None)) 129 | 130 | if not supported: 131 | print("Warning: No parser is available for your current ND2 version (%d.%d). " % ( 132 | major_version, minor_version) + "This might lead to unexpected behaviour.") 133 | 134 | return supported 135 | 136 | def _parse_metadata(self): 137 | """Reads all metadata and instantiates the Metadata object. 138 | 139 | """ 140 | # Retrieve raw metadata from the label mapping 141 | self._label_map = self._build_label_map() 142 | self._raw_metadata = RawMetadata(self._fh, self._label_map) 143 | self.metadata = self._raw_metadata.__dict__ 144 | self.acquisition_times = self._raw_metadata.acquisition_times 145 | 146 | def _build_label_map(self): 147 | """ 148 | Every label ends with an exclamation point, however, we can't directly search for those to find all the labels 149 | as some of the bytes contain the value 33, which is the ASCII code for "!". So we iteratively find each label, 150 | grab the subsequent data (always 16 bytes long), advance to the next label and repeat. 151 | 152 | Returns: 153 | LabelMap: the computed label map 154 | 155 | """ 156 | # go 8 bytes back from file end 157 | self._fh.seek(-8, 2) 158 | chunk_map_start_location = struct.unpack("Q", self._fh.read(8))[0] 159 | self._fh.seek(chunk_map_start_location) 160 | raw_text = self._fh.read(-1) 161 | return LabelMap(raw_text) 162 | 163 | def _calculate_field_of_view(self, index): 164 | """Determines what field of view was being imaged for a given image. 165 | 166 | Args: 167 | index(int): the index (which is simply the order in which the image was acquired) 168 | 169 | Returns: 170 | int: the field of view 171 | """ 172 | images_per_cycle = len(self.metadata["z_levels"]) * len(self.metadata["channels"]) 173 | return int((index - (index % images_per_cycle)) / images_per_cycle) % len(self.metadata["fields_of_view"]) 174 | 175 | def _calculate_channel(self, index): 176 | """Determines what channel a particular image is. 177 | 178 | Args: 179 | index(int): the index (which is simply the order in which the image was acquired) 180 | 181 | Returns: 182 | string: the name of the color channel 183 | 184 | """ 185 | return self.metadata["channels"][index % len(self.metadata["channels"])] 186 | 187 | def _calculate_z_level(self, index): 188 | """Determines the plane in the z-axis a given image was taken in. 189 | 190 | In the future, this will be replaced with the actual offset in micrometers. 191 | 192 | Args: 193 | index(int): the index (which is simply the order in which the image was acquired) 194 | 195 | Returns: 196 | The z level 197 | 198 | """ 199 | return self.metadata["z_levels"][int( 200 | ((index - (index % len(self.metadata["channels"]))) / len(self.metadata["channels"])) % len( 201 | self.metadata["z_levels"]))] 202 | 203 | def _calculate_image_group_number(self, frame_number, fov, z_level): 204 | """ 205 | Images are grouped together if they share the same time index, field of view, and z-level. 206 | 207 | Args: 208 | frame_number: the time index 209 | fov: the field of view number 210 | z_level: the z level number 211 | 212 | Returns: 213 | int: the image group number 214 | 215 | """ 216 | z_length = len(self.metadata['z_levels']) 217 | z_length = z_length if z_length > 0 else 1 218 | fields_of_view = len(self.metadata["fields_of_view"]) 219 | fields_of_view = fields_of_view if fields_of_view > 0 else 1 220 | 221 | return frame_number * fields_of_view * z_length + (fov * z_length + z_level) 222 | 223 | def _calculate_frame_number(self, image_group_number, field_of_view, z_level): 224 | """ 225 | Images are in the same frame if they share the same group number and field of view and are taken sequentially. 226 | 227 | Args: 228 | image_group_number: the image group number (see _calculate_image_group_number) 229 | field_of_view: the field of view number 230 | z_level: the z level number 231 | 232 | Returns: 233 | 234 | """ 235 | return (image_group_number - (field_of_view * len(self.metadata["z_levels"]) + z_level)) / (len(self.metadata["fields_of_view"]) * len(self.metadata["z_levels"])) 236 | 237 | @property 238 | def _channel_offset(self): 239 | """ 240 | Image data is interleaved for each image set. That is, if there are four images in a set, the first image 241 | will consist of pixels 1, 5, 9, etc, the second will be pixels 2, 6, 10, and so forth. 242 | 243 | Returns: 244 | dict: the channel offset for each channel 245 | 246 | """ 247 | return {channel: n for n, channel in enumerate(self.metadata["channels"])} 248 | 249 | def _get_raw_image_data(self, image_group_number, channel_offset, height, width): 250 | """Reads the raw bytes and the timestamp of an image. 251 | 252 | Args: 253 | image_group_number: the image group number (see _calculate_image_group_number) 254 | channel_offset: the number of the color channel 255 | height: the height of the image 256 | width: the width of the image 257 | 258 | Returns: 259 | 260 | """ 261 | chunk = self._label_map.get_image_data_location(image_group_number) 262 | data = read_chunk(self._fh, chunk) 263 | 264 | # All images in the same image group share the same timestamp! So if you have complicated image data, 265 | # your timestamps may not be entirely accurate. Practically speaking though, they'll only be off by a few 266 | # seconds unless you're doing something super weird. 267 | timestamp = struct.unpack("d", data[:8])[0] 268 | image_group_data = array.array("H", data) 269 | image_data_start = 4 + channel_offset 270 | image_group_data = stitched.remove_parsed_unwanted_bytes(image_group_data, image_data_start, height, width) 271 | 272 | # The images for the various channels are interleaved within the same array. For example, the second image 273 | # of a four image group will be composed of bytes 2, 6, 10, etc. If you understand why someone would design 274 | # a data structure that way, please send the author of this library a message. 275 | number_of_true_channels = int(len(image_group_data[4:]) / (height * width)) 276 | try: 277 | image_data = np.reshape(image_group_data[image_data_start::number_of_true_channels], (height, width)) 278 | except ValueError: 279 | new_width = len(image_group_data[image_data_start::number_of_true_channels]) // height 280 | image_data = np.reshape(image_group_data[image_data_start::number_of_true_channels], (height, new_width)) 281 | 282 | # Skip images that are all zeros! This is important, since NIS Elements creates blank "gap" images if you 283 | # don't have the same number of images each cycle. We discovered this because we only took GFP images every 284 | # other cycle to reduce phototoxicity, but NIS Elements still allocated memory as if we were going to take 285 | # them every cycle. 286 | if np.any(image_data): 287 | return timestamp, image_data 288 | 289 | # If a blank "gap" image is encountered, generate an array of corresponding height and width to avoid 290 | # errors with ND2-files with missing frames. Array is filled with nan to reflect that data is missing. 291 | else: 292 | empty_frame = np.full((height, width), np.nan) 293 | warnings.warn( 294 | "ND2 file contains gap frames which are represented by np.nan-filled arrays; to convert to zeros use e.g. np.nan_to_num(array)") 295 | return timestamp, image_data 296 | 297 | def _get_frame_metadata(self): 298 | """Get the metadata for one frame 299 | 300 | Returns: 301 | dict: a dictionary containing the parsed metadata 302 | 303 | """ 304 | return self.metadata 305 | -------------------------------------------------------------------------------- /nd2reader/raw_metadata.py: -------------------------------------------------------------------------------- 1 | import re 2 | import xmltodict 3 | import six 4 | import numpy as np 5 | import warnings 6 | 7 | from nd2reader.common import read_chunk, read_array, read_metadata, parse_date, get_from_dict_if_exists 8 | from nd2reader.common_raw_metadata import parse_dimension_text_line, parse_if_not_none, parse_roi_shape, parse_roi_type, get_loops_from_data, determine_sampling_interval 9 | 10 | 11 | class RawMetadata(object): 12 | """RawMetadata class parses and stores the raw metadata that is read from the binary file in dict format. 13 | """ 14 | 15 | def __init__(self, fh, label_map): 16 | self._fh = fh 17 | self._label_map = label_map 18 | self._metadata_parsed = None 19 | 20 | @property 21 | def __dict__(self): 22 | """Returns the parsed metadata in dictionary form. 23 | 24 | Returns: 25 | dict: the parsed metadata 26 | """ 27 | return self.get_parsed_metadata() 28 | 29 | def get_parsed_metadata(self): 30 | """Returns the parsed metadata in dictionary form. 31 | 32 | Returns: 33 | dict: the parsed metadata 34 | """ 35 | 36 | if self._metadata_parsed is not None: 37 | return self._metadata_parsed 38 | 39 | frames_per_channel = self._parse_total_images_per_channel() 40 | self._metadata_parsed = { 41 | "height": parse_if_not_none(self.image_attributes, self._parse_height), 42 | "width": parse_if_not_none(self.image_attributes, self._parse_width), 43 | "date": parse_if_not_none(self.image_text_info, self._parse_date), 44 | "fields_of_view": self._parse_fields_of_view(), 45 | "frames": self._parse_frames(), 46 | "z_levels": self._parse_z_levels(), 47 | "z_coordinates": parse_if_not_none(self.z_data, self._parse_z_coordinates), 48 | "total_images_per_channel": frames_per_channel, 49 | "channels": self._parse_channels(), 50 | "pixel_microns": parse_if_not_none(self.image_calibration, self._parse_calibration) 51 | } 52 | 53 | self._set_default_if_not_empty('fields_of_view') 54 | self._set_default_if_not_empty('frames') 55 | self._metadata_parsed['num_frames'] = len(self._metadata_parsed['frames']) 56 | 57 | self._parse_roi_metadata() 58 | self._parse_experiment_metadata() 59 | self._parse_events() 60 | 61 | return self._metadata_parsed 62 | 63 | def _set_default_if_not_empty(self, entry): 64 | total_images = self._metadata_parsed['total_images_per_channel'] \ 65 | if self._metadata_parsed['total_images_per_channel'] is not None else 0 66 | 67 | if len(self._metadata_parsed[entry]) == 0 and total_images > 0: 68 | # if the file is not empty, we always have one of this entry 69 | self._metadata_parsed[entry] = [0] 70 | 71 | def _parse_width_or_height(self, key): 72 | try: 73 | length = self.image_attributes[six.b('SLxImageAttributes')][six.b(key)] 74 | except KeyError: 75 | length = None 76 | 77 | return length 78 | 79 | def _parse_height(self): 80 | return self._parse_width_or_height('uiHeight') 81 | 82 | def _parse_width(self): 83 | return self._parse_width_or_height('uiWidth') 84 | 85 | def _parse_date(self): 86 | try: 87 | return parse_date(self.image_text_info[six.b('SLxImageTextInfo')]) 88 | except KeyError: 89 | return None 90 | 91 | def _parse_calibration(self): 92 | try: 93 | return self.image_calibration.get(six.b('SLxCalibration'), {}).get(six.b('dCalibration')) 94 | except KeyError: 95 | return None 96 | 97 | def _parse_frames(self): 98 | """The number of cycles. 99 | 100 | Returns: 101 | list: list of all the frame numbers 102 | """ 103 | return self._parse_dimension(r""".*?T'?\((\d+)\).*?""") 104 | 105 | def _parse_channels(self): 106 | """These are labels created by the NIS Elements user. Typically they may a short description of the filter cube 107 | used (e.g. 'bright field', 'GFP', etc.) 108 | 109 | Returns: 110 | list: the color channels 111 | """ 112 | if self.image_metadata_sequence is None: 113 | return [] 114 | 115 | try: 116 | metadata = self.image_metadata_sequence[six.b('SLxPictureMetadata')][six.b('sPicturePlanes')] 117 | except KeyError: 118 | return [] 119 | 120 | channels = self._process_channels_metadata(metadata) 121 | 122 | return channels 123 | 124 | def _process_channels_metadata(self, metadata): 125 | validity = self._get_channel_validity_list(metadata) 126 | 127 | # Channel information is contained in dictionaries with the keys a0, a1...an where the number 128 | # indicates the order in which the channel is stored. So by sorting the dicts alphabetically 129 | # we get the correct order. 130 | channels = [] 131 | for valid, (label, chan) in zip(validity, sorted(metadata[six.b('sPlaneNew')].items())): 132 | if not valid: 133 | continue 134 | if chan[six.b('sDescription')] is not None: 135 | channels.append(chan[six.b('sDescription')].decode("utf8")) 136 | else: 137 | channels.append('Unknown') 138 | return channels 139 | 140 | def _get_channel_validity_list(self, metadata): 141 | try: 142 | validity = self.image_metadata[six.b('SLxExperiment')][six.b('ppNextLevelEx')][six.b('')][0][ 143 | six.b('ppNextLevelEx')][six.b('')][0][six.b('pItemValid')] 144 | except (KeyError, TypeError): 145 | # If none of the channels have been deleted, there is no validity list, so we just make one 146 | validity = [True for _ in metadata] 147 | return validity 148 | 149 | def _parse_fields_of_view(self): 150 | """The metadata contains information about fields of view, but it contains it even if some fields 151 | of view were cropped. We can't find anything that states which fields of view are actually 152 | in the image data, so we have to calculate it. There probably is something somewhere, since 153 | NIS Elements can figure it out, but we haven't found it yet. 154 | 155 | """ 156 | return self._parse_dimension(r""".*?XY\((\d+)\).*?""") 157 | 158 | def _parse_z_levels(self): 159 | """The different levels in the Z-plane. 160 | 161 | If they are not available from the _parse_dimension function AND there 162 | is NO 'Dimensions: ' textinfo item in the file, we return a range with 163 | the length of z_coordinates if available, otherwise an empty list. 164 | 165 | Returns: 166 | list: the z levels, just a sequence from 0 to n. 167 | """ 168 | # get the dimension text to check if we should apply the fallback or not 169 | dimension_text = self._parse_dimension_text() 170 | 171 | # this returns range(len(z_levels)) 172 | z_levels = self._parse_dimension(r""".*?Z\((\d+)\).*?""", dimension_text) 173 | 174 | if len(z_levels) > 0 or len(dimension_text) > 0: 175 | # Either we have found the z_levels (first condition) so return, or 176 | # don't fallback, because Z is apparently not in Dimensions, so 177 | # there should be no z_levels 178 | return z_levels 179 | 180 | # Not available from dimension, get from z_coordinates 181 | z_levels = parse_if_not_none(self.z_data, self._parse_z_coordinates) 182 | 183 | if z_levels is None: 184 | # No z coordinates, return empty list 185 | return [] 186 | 187 | warnings.warn("Z-levels details missing in metadata. Using Z-coordinates instead.") 188 | return range(len(z_levels)) 189 | 190 | def _parse_z_coordinates(self): 191 | """The coordinate in micron for all z planes. 192 | 193 | Returns: 194 | list: the z coordinates in micron 195 | """ 196 | return self.z_data.tolist() 197 | 198 | def _parse_dimension_text(self): 199 | """While there are metadata values that represent a lot of what we want to capture, they seem to be unreliable. 200 | Sometimes certain elements don't exist, or change their data type randomly. However, the human-readable text 201 | is always there and in the same exact format, so we just parse that instead. 202 | 203 | """ 204 | dimension_text = six.b("") 205 | if self.image_text_info is None: 206 | return dimension_text 207 | 208 | try: 209 | textinfo = self.image_text_info[six.b('SLxImageTextInfo')].values() 210 | except KeyError: 211 | return dimension_text 212 | 213 | for line in textinfo: 214 | entry = parse_dimension_text_line(line) 215 | if entry is not None: 216 | return entry 217 | 218 | return dimension_text 219 | 220 | def _parse_dimension(self, pattern, dimension_text=None): 221 | dimension_text = self._parse_dimension_text() if dimension_text is None else dimension_text 222 | if dimension_text is None: 223 | return [] 224 | 225 | if six.PY3: 226 | dimension_text = dimension_text.decode("utf8") 227 | 228 | match = re.match(pattern, dimension_text) 229 | if not match: 230 | return [] 231 | 232 | count = int(match.group(1)) 233 | return range(count) 234 | 235 | def _parse_total_images_per_channel(self): 236 | """The total number of images per channel. 237 | 238 | Warning: this may be inaccurate as it includes 'gap' images. 239 | 240 | """ 241 | if self.image_attributes is None: 242 | return 0 243 | try: 244 | total_images = self.image_attributes[six.b('SLxImageAttributes')][six.b('uiSequenceCount')] 245 | except KeyError: 246 | total_images = None 247 | 248 | return total_images 249 | 250 | def _parse_roi_metadata(self): 251 | """Parse the raw ROI metadata. 252 | 253 | """ 254 | if self.roi_metadata is None or not six.b('RoiMetadata_v1') in self.roi_metadata: 255 | return 256 | 257 | raw_roi_data = self.roi_metadata[six.b('RoiMetadata_v1')] 258 | 259 | if not six.b('m_vectGlobal_Size') in raw_roi_data: 260 | return 261 | 262 | number_of_rois = raw_roi_data[six.b('m_vectGlobal_Size')] 263 | 264 | roi_objects = [] 265 | for i in range(number_of_rois): 266 | current_roi = raw_roi_data[six.b('m_vectGlobal_%d' % i)] 267 | roi_objects.append(self._parse_roi(current_roi)) 268 | 269 | self._metadata_parsed['rois'] = roi_objects 270 | 271 | def _parse_roi(self, raw_roi_dict): 272 | """Extract the vector animation parameters from the ROI. 273 | 274 | This includes the position and size at the given timepoints. 275 | 276 | Args: 277 | raw_roi_dict: dictionary of raw roi metadata 278 | 279 | Returns: 280 | dict: the parsed ROI metadata 281 | 282 | """ 283 | number_of_timepoints = raw_roi_dict[six.b('m_vectAnimParams_Size')] 284 | 285 | roi_dict = { 286 | "timepoints": [], 287 | "positions": [], 288 | "sizes": [], 289 | "shape": parse_roi_shape(raw_roi_dict[six.b('m_sInfo')][six.b('m_uiShapeType')]), 290 | "type": parse_roi_type(raw_roi_dict[six.b('m_sInfo')][six.b('m_uiInterpType')]) 291 | } 292 | for i in range(number_of_timepoints): 293 | roi_dict = self._parse_vect_anim(roi_dict, raw_roi_dict[six.b('m_vectAnimParams_%d' % i)]) 294 | 295 | # convert to NumPy arrays 296 | roi_dict["timepoints"] = np.array(roi_dict["timepoints"], dtype=np.float64) 297 | roi_dict["positions"] = np.array(roi_dict["positions"], dtype=np.float64) 298 | roi_dict["sizes"] = np.array(roi_dict["sizes"], dtype=np.float64) 299 | 300 | return roi_dict 301 | 302 | def _parse_vect_anim(self, roi_dict, animation_dict): 303 | """ 304 | Parses a ROI vector animation object and adds it to the global list of timepoints and positions. 305 | 306 | Args: 307 | roi_dict: the raw roi dictionary 308 | animation_dict: the raw animation dictionary 309 | 310 | Returns: 311 | dict: the parsed metadata 312 | 313 | """ 314 | roi_dict["timepoints"].append(animation_dict[six.b('m_dTimeMs')]) 315 | 316 | image_width = self._metadata_parsed["width"] * self._metadata_parsed["pixel_microns"] 317 | image_height = self._metadata_parsed["height"] * self._metadata_parsed["pixel_microns"] 318 | 319 | # positions are taken from the center of the image as a fraction of the half width/height of the image 320 | position = np.array((0.5 * image_width * (1 + animation_dict[six.b('m_dCenterX')]), 321 | 0.5 * image_height * (1 + animation_dict[six.b('m_dCenterY')]), 322 | animation_dict[six.b('m_dCenterZ')])) 323 | roi_dict["positions"].append(position) 324 | 325 | size_dict = animation_dict[six.b('m_sBoxShape')] 326 | 327 | # sizes are fractions of the half width/height of the image 328 | roi_dict["sizes"].append((size_dict[six.b('m_dSizeX')] * 0.25 * image_width, 329 | size_dict[six.b('m_dSizeY')] * 0.25 * image_height, 330 | size_dict[six.b('m_dSizeZ')])) 331 | return roi_dict 332 | 333 | def _parse_experiment_metadata(self): 334 | """Parse the metadata of the ND experiment 335 | 336 | """ 337 | self._metadata_parsed['experiment'] = { 338 | 'description': 'unknown', 339 | 'loops': [] 340 | } 341 | 342 | if self.image_metadata is None or six.b('SLxExperiment') not in self.image_metadata: 343 | return 344 | 345 | raw_data = self.image_metadata[six.b('SLxExperiment')] 346 | 347 | if six.b('wsApplicationDesc') in raw_data: 348 | self._metadata_parsed['experiment']['description'] = raw_data[six.b('wsApplicationDesc')].decode('utf8') 349 | 350 | if six.b('uLoopPars') in raw_data: 351 | self._metadata_parsed['experiment']['loops'] = self._parse_loop_data(raw_data[six.b('uLoopPars')]) 352 | 353 | def _parse_loop_data(self, loop_data): 354 | """Parse the experimental loop data 355 | 356 | Args: 357 | loop_data: dictionary of experiment loops 358 | 359 | Returns: 360 | list: list of the parsed loops 361 | 362 | """ 363 | loops = get_loops_from_data(loop_data) 364 | 365 | # take into account the absolute time in ms 366 | time_offset = 0 367 | 368 | parsed_loops = [] 369 | 370 | for loop in loops: 371 | # duration of this loop 372 | duration = get_from_dict_if_exists('dDuration', loop) or 0 373 | interval = determine_sampling_interval(duration, loop) 374 | 375 | # if duration is not saved, infer it 376 | duration = self.get_duration_from_interval_and_loops(duration, interval, loop) 377 | 378 | # uiLoopType == 6 is a stimulation loop 379 | is_stimulation = get_from_dict_if_exists('uiLoopType', loop) == 6 380 | 381 | parsed_loop = { 382 | 'start': time_offset, 383 | 'duration': duration, 384 | 'stimulation': is_stimulation, 385 | 'sampling_interval': interval 386 | } 387 | 388 | parsed_loops.append(parsed_loop) 389 | 390 | # increase the time offset 391 | time_offset += duration 392 | 393 | return parsed_loops 394 | 395 | def get_duration_from_interval_and_loops(self, duration, interval, loop): 396 | """Infers the duration of the loop from the number of measurements and the interval 397 | 398 | Args: 399 | duration: loop duration in milliseconds 400 | duration: measurement interval in milliseconds 401 | loop: loop dictionary 402 | 403 | Returns: 404 | float: the loop duration in milliseconds 405 | 406 | """ 407 | if duration == 0 and interval > 0: 408 | number_of_loops = get_from_dict_if_exists('uiCount', loop) 409 | number_of_loops = number_of_loops if number_of_loops is not None and number_of_loops > 0 else 1 410 | duration = interval * number_of_loops 411 | 412 | return duration 413 | 414 | def _parse_events(self): 415 | """Extract events 416 | 417 | """ 418 | 419 | # list of event names manually extracted from an ND2 file that contains all manually 420 | # insertable events from NIS-Elements software (4.60.00 (Build 1171) Patch 02) 421 | event_names = { 422 | 1: 'Autofocus', 423 | 7: 'Command Executed', 424 | 9: 'Experiment Paused', 425 | 10: 'Experiment Resumed', 426 | 11: 'Experiment Stopped by User', 427 | 13: 'Next Phase Moved by User', 428 | 14: 'Experiment Paused for Refocusing', 429 | 16: 'External Stimulation', 430 | 33: 'User 1', 431 | 34: 'User 2', 432 | 35: 'User 3', 433 | 36: 'User 4', 434 | 37: 'User 5', 435 | 38: 'User 6', 436 | 39: 'User 7', 437 | 40: 'User 8', 438 | 44: 'No Acquisition Phase Start', 439 | 45: 'No Acquisition Phase End', 440 | 46: 'Hardware Error', 441 | 47: 'N-STORM', 442 | 48: 'Incubation Info', 443 | 49: 'Incubation Error' 444 | } 445 | 446 | self._metadata_parsed['events'] = [] 447 | 448 | events = read_metadata(read_chunk(self._fh, self._label_map.image_events), 1) 449 | 450 | if events is None or six.b('RLxExperimentRecord') not in events: 451 | return 452 | 453 | events = events[six.b('RLxExperimentRecord')][six.b('pEvents')] 454 | 455 | if len(events) == 0: 456 | return 457 | 458 | for event in events[six.b('')]: 459 | event_info = { 460 | 'index': event[six.b('I')], 461 | 'time': event[six.b('T')], 462 | 'type': event[six.b('M')], 463 | } 464 | if event_info['type'] in event_names.keys(): 465 | event_info['name'] = event_names[event_info['type']] 466 | 467 | self._metadata_parsed['events'].append(event_info) 468 | 469 | @property 470 | def image_text_info(self): 471 | """Textual image information 472 | 473 | Returns: 474 | dict: containing the textual image info 475 | 476 | """ 477 | return read_metadata(read_chunk(self._fh, self._label_map.image_text_info), 1) 478 | 479 | @property 480 | def image_metadata_sequence(self): 481 | """Image metadata of the sequence 482 | 483 | Returns: 484 | dict: containing the metadata 485 | 486 | """ 487 | return read_metadata(read_chunk(self._fh, self._label_map.image_metadata_sequence), 1) 488 | 489 | @property 490 | def image_calibration(self): 491 | """The amount of pixels per micron. 492 | 493 | Returns: 494 | dict: pixels per micron 495 | """ 496 | return read_metadata(read_chunk(self._fh, self._label_map.image_calibration), 1) 497 | 498 | @property 499 | def image_attributes(self): 500 | """Image attributes 501 | 502 | Returns: 503 | dict: containing the image attributes 504 | """ 505 | return read_metadata(read_chunk(self._fh, self._label_map.image_attributes), 1) 506 | 507 | @property 508 | def x_data(self): 509 | """X data 510 | 511 | Returns: 512 | dict: x_data 513 | """ 514 | return read_array(self._fh, 'double', self._label_map.x_data) 515 | 516 | @property 517 | def y_data(self): 518 | """Y data 519 | 520 | Returns: 521 | dict: y_data 522 | """ 523 | return read_array(self._fh, 'double', self._label_map.y_data) 524 | 525 | @property 526 | def z_data(self): 527 | """Z data 528 | 529 | Returns: 530 | dict: z_data 531 | """ 532 | try: 533 | return read_array(self._fh, 'double', self._label_map.z_data) 534 | except ValueError: 535 | # Depending on the file format/exact settings, this value is 536 | # sometimes saved as float instead of double 537 | return read_array(self._fh, 'float', self._label_map.z_data) 538 | 539 | @property 540 | def roi_metadata(self): 541 | """Contains information about the defined ROIs: shape, position and type (reference/background/stimulation). 542 | 543 | Returns: 544 | dict: ROI metadata dictionary 545 | """ 546 | return read_metadata(read_chunk(self._fh, self._label_map.roi_metadata), 1) 547 | 548 | @property 549 | def pfs_status(self): 550 | """Perfect focus system (PFS) status 551 | 552 | Returns: 553 | dict: Perfect focus system (PFS) status 554 | 555 | """ 556 | return read_array(self._fh, 'int', self._label_map.pfs_status) 557 | 558 | @property 559 | def pfs_offset(self): 560 | """Perfect focus system (PFS) offset 561 | 562 | Returns: 563 | dict: Perfect focus system (PFS) offset 564 | 565 | """ 566 | return read_array(self._fh, 'int', self._label_map.pfs_offset) 567 | 568 | @property 569 | def camera_exposure_time(self): 570 | """Exposure time information 571 | 572 | Returns: 573 | dict: Camera exposure time 574 | 575 | """ 576 | return read_array(self._fh, 'double', self._label_map.camera_exposure_time) 577 | 578 | @property 579 | def lut_data(self): 580 | """LUT information 581 | 582 | Returns: 583 | dict: LUT information 584 | 585 | """ 586 | return xmltodict.parse(read_chunk(self._fh, self._label_map.lut_data)) 587 | 588 | @property 589 | def grabber_settings(self): 590 | """Grabber settings 591 | 592 | Returns: 593 | dict: Acquisition settings 594 | 595 | """ 596 | return xmltodict.parse(read_chunk(self._fh, self._label_map.grabber_settings)) 597 | 598 | @property 599 | def custom_data(self): 600 | """Custom user data 601 | 602 | Returns: 603 | dict: custom user data 604 | 605 | """ 606 | return xmltodict.parse(read_chunk(self._fh, self._label_map.custom_data)) 607 | 608 | @property 609 | def app_info(self): 610 | """NIS elements application info 611 | 612 | Returns: 613 | dict: (Version) information of the NIS Elements application 614 | 615 | """ 616 | return xmltodict.parse(read_chunk(self._fh, self._label_map.app_info)) 617 | 618 | @property 619 | def camera_temp(self): 620 | """Camera temperature 621 | 622 | Yields: 623 | float: the temperature 624 | 625 | """ 626 | camera_temp = read_array(self._fh, 'double', self._label_map.camera_temp) 627 | if camera_temp: 628 | for temp in map(lambda x: round(x * 100.0, 2), camera_temp): 629 | yield temp 630 | 631 | @property 632 | def acquisition_times(self): 633 | """Acquisition times 634 | 635 | Yields: 636 | float: the acquisition time 637 | 638 | """ 639 | acquisition_times = read_array(self._fh, 'double', self._label_map.acquisition_times) 640 | if acquisition_times: 641 | for acquisition_time in map(lambda x: x / 1000.0, acquisition_times): 642 | yield acquisition_time 643 | 644 | @property 645 | def image_metadata(self): 646 | """Image metadata 647 | 648 | Returns: 649 | dict: Extra image metadata 650 | 651 | """ 652 | if self._label_map.image_metadata: 653 | return read_metadata(read_chunk(self._fh, self._label_map.image_metadata), 1) 654 | 655 | @property 656 | def image_events(self): 657 | """Image events 658 | 659 | Returns: 660 | dict: Image events 661 | """ 662 | if self._label_map.image_metadata: 663 | for event in self._metadata_parsed["events"]: 664 | yield event 665 | 666 | -------------------------------------------------------------------------------- /nd2reader/reader.py: -------------------------------------------------------------------------------- 1 | from pims import Frame 2 | from pims.base_frames import FramesSequenceND 3 | 4 | from nd2reader.exceptions import EmptyFileError, InvalidFileType 5 | from nd2reader.parser import Parser 6 | import numpy as np 7 | 8 | 9 | class ND2Reader(FramesSequenceND): 10 | """PIMS wrapper for the ND2 parser. 11 | This is the main class: use this to process your .nd2 files. 12 | """ 13 | 14 | _fh = None 15 | class_priority = 12 16 | 17 | def __init__(self, fh): 18 | """ 19 | Arguments: 20 | fh {str} -- absolute path to .nd2 file 21 | fh {IO} -- input buffer handler (opened with "rb" mode) 22 | """ 23 | super(ND2Reader, self).__init__() 24 | 25 | self.filename = "" 26 | 27 | if isinstance(fh, str): 28 | if not fh.endswith(".nd2"): 29 | raise InvalidFileType( 30 | ("The file %s you want to read with nd2reader" % fh) 31 | + " does not have extension .nd2." 32 | ) 33 | self.filename = fh 34 | fh = open(fh, "rb") 35 | 36 | self._fh = fh 37 | 38 | self._parser = Parser(self._fh) 39 | 40 | # Setup metadata 41 | self.metadata = self._parser.metadata 42 | 43 | # Set data type 44 | self._dtype = self._parser.get_dtype_from_metadata() 45 | 46 | # Setup the axes 47 | self._setup_axes() 48 | 49 | # Other properties 50 | self._timesteps = None 51 | 52 | @classmethod 53 | def class_exts(cls): 54 | """Let PIMS open function use this reader for opening .nd2 files 55 | 56 | """ 57 | return {"nd2"} | super(ND2Reader, cls).class_exts() 58 | 59 | def close(self): 60 | """Correctly close the file handle 61 | 62 | """ 63 | if self._fh is not None: 64 | self._fh.close() 65 | 66 | def _get_default(self, coord): 67 | try: 68 | return self.default_coords[coord] 69 | except KeyError: 70 | return 0 71 | 72 | def get_frame_2D(self, c=0, t=0, z=0, x=0, y=0, v=0): 73 | """Gets a given frame using the parser 74 | Args: 75 | x: The x-index (pims expects this) 76 | y: The y-index (pims expects this) 77 | c: The color channel number 78 | t: The frame number 79 | z: The z stack number 80 | v: The field of view index 81 | Returns: 82 | pims.Frame: The requested frame 83 | """ 84 | # This needs to be set to width/height to return an image 85 | x = self.metadata["width"] 86 | y = self.metadata["height"] 87 | 88 | return self._parser.get_image_by_attributes(t, v, c, z, y, x) 89 | 90 | @property 91 | def parser(self): 92 | """ 93 | Returns the parser object. 94 | Returns: 95 | Parser: the parser object 96 | """ 97 | return self._parser 98 | 99 | @property 100 | def pixel_type(self): 101 | """Return the pixel data type 102 | 103 | Returns: 104 | dtype: the pixel data type 105 | 106 | """ 107 | return self._dtype 108 | 109 | @property 110 | def timesteps(self): 111 | """Get the timesteps of the experiment 112 | 113 | Returns: 114 | np.ndarray: an array of times in milliseconds. 115 | 116 | """ 117 | if self._timesteps is None: 118 | return self.get_timesteps() 119 | return self._timesteps 120 | 121 | @property 122 | def events(self): 123 | """Get the events of the experiment 124 | 125 | Returns: 126 | iterator of events as dict 127 | """ 128 | 129 | return self._get_metadata_property("events") 130 | 131 | @property 132 | def frame_rate(self): 133 | """The (average) frame rate 134 | 135 | Returns: 136 | float: the (average) frame rate in frames per second 137 | """ 138 | total_duration = 0.0 139 | 140 | for loop in self.metadata["experiment"]["loops"]: 141 | total_duration += loop["duration"] 142 | 143 | if total_duration == 0: 144 | total_duration = self.timesteps[-1] 145 | 146 | if total_duration == 0: 147 | raise ValueError( 148 | "Total measurement duration could not be determined from loops" 149 | ) 150 | 151 | return self.metadata["num_frames"] / (total_duration / 1000.0) 152 | 153 | def _get_metadata_property(self, key, default=None): 154 | if self.metadata is None: 155 | return default 156 | 157 | if key not in self.metadata: 158 | return default 159 | 160 | if self.metadata[key] is None: 161 | return default 162 | 163 | return self.metadata[key] 164 | 165 | def _setup_axes(self): 166 | """Setup the xyctz axes, iterate over t axis by default 167 | 168 | """ 169 | self._init_axis_if_exists("x", self._get_metadata_property("width", default=0)) 170 | self._init_axis_if_exists("y", self._get_metadata_property("height", default=0)) 171 | self._init_axis_if_exists( 172 | "c", len(self._get_metadata_property("channels", default=[])), min_size=2 173 | ) 174 | self._init_axis_if_exists( 175 | "t", len(self._get_metadata_property("frames", default=[])) 176 | ) 177 | self._init_axis_if_exists( 178 | "z", len(self._get_metadata_property("z_levels", default=[])), min_size=2 179 | ) 180 | self._init_axis_if_exists( 181 | "v", 182 | len(self._get_metadata_property("fields_of_view", default=[])), 183 | min_size=2, 184 | ) 185 | 186 | if len(self.sizes) == 0: 187 | raise EmptyFileError("No axes were found for this .nd2 file.") 188 | 189 | # provide the default 190 | self.iter_axes = self._guess_default_iter_axis() 191 | 192 | self._register_get_frame(self.get_frame_2D, "yx") 193 | 194 | def _init_axis_if_exists(self, axis, size, min_size=1): 195 | if size >= min_size: 196 | self._init_axis(axis, size) 197 | 198 | def _guess_default_iter_axis(self): 199 | """ 200 | Guesses the default axis to iterate over based on axis sizes. 201 | Returns: 202 | the axis to iterate over 203 | """ 204 | priority = ["t", "z", "c", "v"] 205 | found_axes = [] 206 | for axis in priority: 207 | try: 208 | current_size = self.sizes[axis] 209 | except KeyError: 210 | continue 211 | 212 | if current_size > 1: 213 | return axis 214 | 215 | found_axes.append(axis) 216 | 217 | return found_axes[0] 218 | 219 | def get_timesteps(self): 220 | """Get the timesteps of the experiment 221 | 222 | Returns: 223 | np.ndarray: an array of times in milliseconds. 224 | 225 | """ 226 | if self._timesteps is not None and len(self._timesteps) > 0: 227 | return self._timesteps 228 | 229 | self._timesteps = ( 230 | np.array(list(self._parser._raw_metadata.acquisition_times), dtype=np.float64) 231 | * 1000.0 232 | ) 233 | 234 | return self._timesteps 235 | -------------------------------------------------------------------------------- /nd2reader/stitched.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import numpy as np # type: ignore 3 | 4 | 5 | def get_unwanted_bytes_ids(image_group_data, image_data_start, height, width): 6 | # Check if the byte array size conforms to the image axes size. If not, check 7 | # that the number of unexpected (unwanted) bytes is a multiple of the number of 8 | # rows (height), as the same number of unwanted bytes is expected to be 9 | # appended at the end of each row. Then, returns the indexes of the unwanted 10 | # bytes. 11 | # Skip the first 4 elements that correspond to the time stamp 12 | number_of_true_channels = int(len(image_group_data[4:]) / (height * width)) 13 | n_unwanted_bytes = (len(image_group_data[4:])) % (height * width) 14 | if not n_unwanted_bytes: 15 | return np.arange(0) 16 | assert 0 == n_unwanted_bytes % height, ( 17 | "An unexpected number of extra bytes was encountered based on the expected" 18 | + " frame size, therefore the file could not be parsed." 19 | ) 20 | return np.arange( 21 | image_data_start + width * number_of_true_channels, 22 | len(image_group_data) - n_unwanted_bytes + 1, 23 | width * number_of_true_channels, 24 | ) 25 | 26 | 27 | def remove_parsed_unwanted_bytes(image_group_data, image_data_start, height, width): 28 | # Stitched ND2 files have been reported to contain unexpected (according to 29 | # image shape) zero bytes at the end of each image data row. This hinders 30 | # proper reshaping of the data. Hence, here the unwanted zero bytes are 31 | # identified and removed. 32 | unwanted_byte_ids = get_unwanted_bytes_ids( 33 | image_group_data, image_data_start, height, width 34 | ) 35 | if 0 != len(unwanted_byte_ids): 36 | image_group_data = np.delete(np.array(image_group_data), unwanted_byte_ids) 37 | 38 | return image_group_data 39 | -------------------------------------------------------------------------------- /release.txt: -------------------------------------------------------------------------------- 1 | Update version in 'setup.py' file 2 | 3 | Rebuild sphinx documentation 4 | 5 | Commit & push both master and docs 6 | 7 | Check if travis unittests are passing 8 | 9 | Publish new release on GitHub 10 | 11 | Run `python setup.py sdist bdist_wheel` 12 | 13 | Run `twine upload dist/*` 14 | 15 | Update the version in nd2reader-feedstock to update the conda version: in recipe/meta.yaml, update version and checksum using `sha256sum` 16 | 17 | Create & merge PR in nd2reader-feedstock 18 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy>=1.20 2 | six>=1.4 3 | xmltodict>=0.9.2 4 | pims>=0.3.0 5 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description_file = README.md 3 | 4 | [bdist_wheel] 5 | universal=1 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | VERSION = '3.3.1' 4 | 5 | if __name__ == '__main__': 6 | setup( 7 | name='nd2reader', 8 | packages=['nd2reader'], 9 | install_requires=[ 10 | 'numpy>=1.14', 11 | 'six>=1.4', 12 | 'xmltodict>=0.9.2', 13 | 'pims>=0.3.0' 14 | ], 15 | python_requires=">=3.6", 16 | version=VERSION, 17 | description='A tool for reading ND2 files produced by NIS Elements', 18 | author='Ruben Verweij', 19 | author_email='ruben@kedara.nl', 20 | url='https://open-science-tools.github.io/nd2reader/', 21 | download_url='https://github.com/rbnvrw/nd2reader/tarball/%s' % VERSION, 22 | keywords=['nd2', 'nikon', 'microscopy', 'NIS Elements'], 23 | classifiers=['Development Status :: 5 - Production/Stable', 24 | 'Intended Audience :: Science/Research', 25 | 'License :: Freely Distributable', 26 | 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 27 | 'Operating System :: POSIX :: Linux', 28 | 'Programming Language :: Python :: 2.7', 29 | 'Programming Language :: Python :: 3.4', 30 | 'Topic :: Scientific/Engineering', 31 | ] 32 | ) 33 | -------------------------------------------------------------------------------- /sphinx/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXBUILD = python3 -msphinx 6 | BUILDDIR = ../docs 7 | 8 | # Internal variables. 9 | ALLSPHINXOPTS = . 10 | 11 | .PHONY: help 12 | help: 13 | @echo "Please use \`make ' where is one of" 14 | @echo " html to make standalone HTML files" 15 | 16 | .PHONY: html 17 | html: 18 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR) 19 | @echo 20 | @echo "Build finished. The HTML pages are in $(BUILDDIR)." 21 | -------------------------------------------------------------------------------- /sphinx/_templates/layout.html: -------------------------------------------------------------------------------- 1 | {% extends "!layout.html" %} 2 | -------------------------------------------------------------------------------- /sphinx/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import sphinx_bootstrap_theme 4 | from recommonmark.parser import CommonMarkParser 5 | from nd2reader import __version__ as VERSION 6 | 7 | # -- General configuration ------------------------------------------------ 8 | 9 | # If your documentation needs a minimal Sphinx version, state it here. 10 | # 11 | # needs_sphinx = '1.0' 12 | 13 | # Add any Sphinx extension module names here, as strings. They can be 14 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 15 | # ones. 16 | extensions = ['sphinx.ext.autodoc', 17 | 'sphinx.ext.todo', 18 | 'sphinx.ext.viewcode', 19 | 'sphinx.ext.napoleon'] 20 | 21 | # Add any paths that contain templates here, relative to this directory. 22 | templates_path = ['_templates'] 23 | 24 | # The suffix(es) of source filenames. 25 | # You can specify multiple suffix as a list of string: 26 | # 27 | # source_suffix = ['.rst', '.md'] 28 | 29 | source_parsers = { 30 | '.md': CommonMarkParser, 31 | } 32 | 33 | source_suffix = ['.rst', '.md'] 34 | 35 | # The master toctree document. 36 | master_doc = 'index' 37 | 38 | # General information about the project. 39 | project = 'nd2reader' 40 | copyright = '2017 - 2024, Ruben Verweij' 41 | author = 'Ruben Verweij' 42 | 43 | # The version info for the project you're documenting, acts as replacement for 44 | # |version| and |release|, also used in various other places throughout the 45 | # built documents. 46 | # 47 | # The short X.Y version. 48 | version = VERSION 49 | # The full version, including alpha/beta/rc tags. 50 | release = VERSION 51 | 52 | # The language for content autogenerated by Sphinx. Refer to documentation 53 | # for a list of supported languages. 54 | # 55 | # This is also used if you do content translation via gettext catalogs. 56 | # Usually you set "language" from the command line for these cases. 57 | language = 'en' 58 | 59 | # List of patterns, relative to source directory, that match files and 60 | # directories to ignore when looking for source files. 61 | # This patterns also effect to html_static_path and html_extra_path 62 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 63 | 64 | # The name of the Pygments (syntax highlighting) style to use. 65 | pygments_style = 'sphinx' 66 | 67 | # If true, `todo` and `todoList` produce output, else they produce nothing. 68 | todo_include_todos = True 69 | 70 | # -- Options for HTML output ---------------------------------------------- 71 | 72 | # The theme to use for HTML and HTML Help pages. See the documentation for 73 | # a list of builtin themes. 74 | # 75 | html_theme = 'bootstrap' 76 | html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() 77 | 78 | # Theme options are theme-specific and customize the look and feel of a theme 79 | # further. For a list of options available for each theme, see the 80 | # documentation. 81 | # 82 | html_theme_options = { 83 | 'navbar_links': [ 84 | 85 | ], 86 | } 87 | 88 | # Add any paths that contain custom static files (such as style sheets) here, 89 | # relative to this directory. They are copied after the builtin static files, 90 | # so a file named "default.css" will overwrite the builtin "default.css". 91 | html_static_path = [] 92 | 93 | # -- Options for HTMLHelp output ------------------------------------------ 94 | 95 | # Output file base name for HTML help builder. 96 | htmlhelp_basename = 'nd2readerdoc' 97 | 98 | # -- Options for LaTeX output --------------------------------------------- 99 | 100 | latex_elements = { 101 | # The paper size ('letterpaper' or 'a4paper'). 102 | # 103 | # 'papersize': 'letterpaper', 104 | 105 | # The font size ('10pt', '11pt' or '12pt'). 106 | # 107 | # 'pointsize': '10pt', 108 | 109 | # Additional stuff for the LaTeX preamble. 110 | # 111 | # 'preamble': '', 112 | 113 | # Latex figure (float) alignment 114 | # 115 | # 'figure_align': 'htbp', 116 | } 117 | 118 | # Grouping the document tree into LaTeX files. List of tuples 119 | # (source start file, target name, title, 120 | # author, documentclass [howto, manual, or own class]). 121 | latex_documents = [ 122 | (master_doc, 'nd2reader.tex', 'nd2reader Documentation', 123 | 'Ruben Verweij', 'manual'), 124 | ] 125 | 126 | # -- Options for manual page output --------------------------------------- 127 | 128 | # One entry per manual page. List of tuples 129 | # (source start file, name, description, authors, manual section). 130 | man_pages = [ 131 | (master_doc, 'nd2reader', 'nd2reader Documentation', 132 | [author], 1) 133 | ] 134 | 135 | # -- Options for Texinfo output ------------------------------------------- 136 | 137 | # Grouping the document tree into Texinfo files. List of tuples 138 | # (source start file, target name, title, author, 139 | # dir menu entry, description, category) 140 | texinfo_documents = [ 141 | (master_doc, 'nd2reader', 'nd2reader Documentation', 142 | author, 'nd2reader', 'One line description of project.', 143 | 'Miscellaneous'), 144 | ] 145 | 146 | # -- Options for Epub output ---------------------------------------------- 147 | 148 | # Bibliographic Dublin Core info. 149 | epub_title = project 150 | epub_author = author 151 | epub_publisher = author 152 | epub_copyright = copyright 153 | 154 | # The unique identifier of the text. This can be a ISBN number 155 | # or the project homepage. 156 | # 157 | # epub_identifier = '' 158 | 159 | # A unique identification for the text. 160 | # 161 | # epub_uid = '' 162 | 163 | # A list of files that should not be packed into the epub file. 164 | epub_exclude_files = ['search.html'] 165 | -------------------------------------------------------------------------------- /sphinx/index.rst: -------------------------------------------------------------------------------- 1 | ``nd2reader``: a pure-Python package for reading Nikon .nd2 files 2 | ================================================================= 3 | 4 | `nd2reader` is a pure-Python package that reads images produced by NIS Elements 4.0+. It has only been definitively tested on NIS Elements 4.30.02 Build 1053. Support for older versions is being actively worked on. 5 | The reader is written in the `pims `_ framework, enabling easy access to multidimensional files, lazy slicing, and nice display in IPython. To get started, see the quick start tutorial. 6 | 7 | .. toctree:: 8 | :maxdepth: 4 9 | :caption: Contents: 10 | 11 | nd2reader quick start tutorial 12 | nd2reader API reference 13 | 14 | 15 | Indices and tables 16 | ================== 17 | 18 | * :ref:`genindex` 19 | * :ref:`modindex` 20 | * :ref:`search` 21 | -------------------------------------------------------------------------------- /sphinx/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | pushd %~dp0 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=python3 -msphinx 9 | ) 10 | set BUILDDIR=../docs 11 | set ALLSPHINXOPTS= . 12 | 13 | if "%1" == "" goto help 14 | 15 | if "%1" == "help" ( 16 | :help 17 | echo.Please use `make ^` where ^ is one of 18 | echo. html to make standalone HTML files 19 | goto end 20 | ) 21 | 22 | REM Check if sphinx-build is available and fallback to Python version if any 23 | %SPHINXBUILD% 1>NUL 2>NUL 24 | if errorlevel 9009 goto sphinx_python 25 | goto sphinx_ok 26 | 27 | :sphinx_python 28 | 29 | set SPHINXBUILD=python3 -m sphinx.__init__ 30 | %SPHINXBUILD% 2> nul 31 | if errorlevel 9009 ( 32 | echo. 33 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 34 | echo.installed, then set the SPHINXBUILD environment variable to point 35 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 36 | echo.may add the Sphinx directory to PATH. 37 | echo. 38 | echo.If you don't have Sphinx installed, grab it from 39 | echo.http://sphinx-doc.org/ 40 | exit /b 1 41 | ) 42 | 43 | :sphinx_ok 44 | 45 | 46 | if "%1" == "html" ( 47 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR% 48 | if errorlevel 1 exit /b 1 49 | echo. 50 | echo.Build finished. The HTML pages are in %BUILDDIR%. 51 | goto end 52 | ) 53 | 54 | :end 55 | popd 56 | -------------------------------------------------------------------------------- /sphinx/nd2reader.rst: -------------------------------------------------------------------------------- 1 | nd2reader package 2 | ================= 3 | 4 | In general, you should only have to use the ``nd2reader.reader`` module. The rest of the submodules are for internal 5 | use only. 6 | 7 | Submodules 8 | ---------- 9 | 10 | nd2reader.reader module 11 | ----------------------- 12 | 13 | .. automodule:: nd2reader.reader 14 | :members: 15 | :undoc-members: 16 | :show-inheritance: 17 | 18 | nd2reader.parser module 19 | ----------------------- 20 | 21 | .. automodule:: nd2reader.parser 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | 26 | nd2reader.raw_metadata module 27 | ----------------------------- 28 | 29 | .. automodule:: nd2reader.raw_metadata 30 | :members: 31 | :undoc-members: 32 | :show-inheritance: 33 | 34 | nd2reader.label_map module 35 | -------------------------- 36 | 37 | .. automodule:: nd2reader.label_map 38 | :members: 39 | :undoc-members: 40 | :show-inheritance: 41 | 42 | nd2reader.common module 43 | ----------------------- 44 | 45 | .. automodule:: nd2reader.common 46 | :members: 47 | :undoc-members: 48 | :show-inheritance: 49 | 50 | nd2reader.exceptions module 51 | --------------------------- 52 | 53 | .. automodule:: nd2reader.exceptions 54 | :members: 55 | :undoc-members: 56 | :show-inheritance: 57 | 58 | nd2reader.artificial module 59 | ------------------------------- 60 | 61 | .. automodule:: nd2reader.artificial 62 | :members: 63 | :undoc-members: 64 | :show-inheritance: 65 | 66 | nd2reader.legacy module 67 | ----------------------- 68 | 69 | .. automodule:: nd2reader.legacy 70 | :members: 71 | :undoc-members: 72 | :show-inheritance: 73 | -------------------------------------------------------------------------------- /sphinx/tutorial.rst: -------------------------------------------------------------------------------- 1 | Tutorial 2 | ======== 3 | 4 | Installation 5 | ~~~~~~~~~~~~ 6 | 7 | The package is available on PyPi. Install it using: 8 | 9 | :: 10 | 11 | pip install nd2reader 12 | 13 | If you don't already have the packages ``numpy``, ``pims``, ``six`` and 14 | ``xmltodict``, they will be installed automatically if you use the 15 | ``setup.py`` script. ``nd2reader`` is an order of magnitude faster in 16 | Python 3. I recommend using it unless you have no other choice. Python 17 | 2.7 and Python >= 3.4 are supported. 18 | 19 | Installation via Conda Forge 20 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 21 | 22 | Installing ``nd2reader`` from the ``conda-forge`` channel can be 23 | achieved by adding ``conda-forge`` to your channels with: 24 | 25 | :: 26 | 27 | conda config --add channels conda-forge 28 | 29 | Once the ``conda-forge`` channel has been enabled, ``nd2reader`` can be 30 | installed with: 31 | 32 | :: 33 | 34 | conda install nd2reader 35 | 36 | It is possible to list all of the versions of ``nd2reader`` available on 37 | your platform with: 38 | 39 | :: 40 | 41 | conda search nd2reader --channel conda-forge 42 | 43 | Opening ND2s 44 | ~~~~~~~~~~~~ 45 | 46 | ``nd2reader`` follows the `pims `__ 47 | framework. To open a file and show the first frame: 48 | 49 | .. code:: python 50 | 51 | from nd2reader import ND2Reader 52 | import matplotlib.pyplot as plt 53 | 54 | with ND2Reader('my_directory/example.nd2') as images: 55 | plt.imshow(images[0]) 56 | 57 | After opening the file, all ``pims`` features are supported. Please 58 | refer to the `pims 59 | documentation `__. 60 | 61 | ND2 metadata 62 | ~~~~~~~~~~~~ 63 | 64 | The ND2 file contains various metadata, such as acquisition information, 65 | regions of interest and custom user comments. Most of this metadata is 66 | parsed and available in dictionary form. For example: 67 | 68 | .. code:: python 69 | 70 | from nd2reader import ND2Reader 71 | 72 | with ND2Reader('my_directory/example.nd2') as images: 73 | # width and height of the image 74 | print('%d x %d px' % (images.metadata['width'], images.metadata['height'])) 75 | 76 | All metadata properties are: 77 | 78 | - ``width``: the width of the image in pixels 79 | - ``height``: the height of the image in pixels 80 | - ``date``: the date the image was taken 81 | - ``fields_of_view``: the fields of view in the image 82 | - ``frames``: a list of all frame numbers 83 | - ``z_levels``: the z levels in the image 84 | - ``total_images_per_channel``: the number of images per color channel 85 | - ``channels``: the color channels 86 | - ``pixel_microns``: the amount of microns per pixel 87 | - ``rois``: the regions of interest (ROIs) defined by the user 88 | - ``experiment``: information about the nature and timings of the ND 89 | experiment 90 | 91 | Iterating over fields of view 92 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 93 | 94 | Using ``NDExperiments`` in the Nikon software, it is possible to acquire 95 | images on different ``(x, y)`` positions. This is referred to as 96 | different fields of view. Using this reader, the fields of view are on 97 | the ``v`` axis. For example: 98 | 99 | .. code:: python 100 | 101 | from nd2reader import ND2Reader 102 | 103 | with ND2Reader('my_directory/example.nd2') as images: 104 | # width and height of the image 105 | print(images.metadata) 106 | 107 | will output 108 | 109 | .. code:: python 110 | 111 | {'channels': ['BF100xoil-1x-R', 'BF+RITC'], 112 | 'date': datetime.datetime(2017, 10, 30, 14, 35, 18), 113 | 'experiment': {'description': 'ND Acquisition', 114 | 'loops': [{'duration': 0, 115 | 'sampling_interval': 0.0, 116 | 'start': 0, 117 | 'stimulation': False}]}, 118 | 'fields_of_view': [0, 1], 119 | 'frames': [0], 120 | 'height': 1895, 121 | 'num_frames': 1, 122 | 'pixel_microns': 0.09214285714285715, 123 | 'total_images_per_channel': 6, 124 | 'width': 2368, 125 | 'z_levels': [0, 1, 2]} 126 | 127 | for our example file. As you can see from the metadata, it has two 128 | fields of view. We can also look at the sizes of the axes: 129 | 130 | .. code:: python 131 | 132 | print(images.sizes) 133 | 134 | .. code:: python 135 | 136 | {'c': 2, 't': 1, 'v': 2, 'x': 2368, 'y': 1895, 'z': 3} 137 | 138 | As you can see, the fields of view are listed on the ``v`` axis. It is 139 | therefore possible to loop over them like this: 140 | 141 | .. code:: python 142 | 143 | images.iter_axes = 'v' 144 | for fov in images: 145 | print(fov) # Frame containing one field of view 146 | 147 | For more information on axis bundling and iteration, refer to the `pims 148 | documentation `__. 149 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import nose 2 | from os import path 3 | 4 | file_path = path.abspath(__file__) 5 | tests_path = path.join(path.abspath(path.dirname(file_path)), "tests") 6 | nose.main(argv=[path.abspath(__file__), "--with-coverage", "--cover-erase", "--cover-package=nd2reader", tests_path]) 7 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Open-Science-Tools/nd2reader/6d825725d0c7574409d56cdbe3680937da25b0bf/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_artificial.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from os import path 3 | import six 4 | import struct 5 | 6 | from nd2reader.artificial import ArtificialND2 7 | from nd2reader.common import get_version, parse_version, parse_date, _add_to_metadata, _parse_unsigned_char, \ 8 | _parse_unsigned_int, _parse_unsigned_long, _parse_double, check_or_make_dir 9 | from nd2reader.exceptions import InvalidVersionError 10 | 11 | 12 | class TestArtificial(unittest.TestCase): 13 | def setUp(self): 14 | dir_path = path.dirname(path.realpath(__file__)) 15 | check_or_make_dir(path.join(dir_path, 'test_data/')) 16 | self.test_file = path.join(dir_path, 'test_data/test.nd2') 17 | self.create_test_nd2() 18 | 19 | def create_test_nd2(self): 20 | with ArtificialND2(self.test_file) as artificial: 21 | self.assertIsNotNone(artificial.file_handle) 22 | artificial.close() 23 | -------------------------------------------------------------------------------- /tests/test_common.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from os import path 3 | 4 | import array 5 | import six 6 | import struct 7 | 8 | from nd2reader.artificial import ArtificialND2 9 | from nd2reader.common import get_version, parse_version, parse_date, _add_to_metadata, _parse_unsigned_char, \ 10 | _parse_unsigned_int, _parse_unsigned_long, _parse_double, check_or_make_dir, _parse_string, _parse_char_array, \ 11 | get_from_dict_if_exists, read_chunk 12 | from nd2reader.exceptions import InvalidVersionError 13 | 14 | 15 | class TestCommon(unittest.TestCase): 16 | def setUp(self): 17 | dir_path = path.dirname(path.realpath(__file__)) 18 | check_or_make_dir(path.join(dir_path, 'test_data/')) 19 | self.test_file = path.join(dir_path, 'test_data/test.nd2') 20 | 21 | def create_test_nd2(self): 22 | with ArtificialND2(self.test_file) as artificial: 23 | artificial.close() 24 | 25 | def test_parse_version_2(self): 26 | data = 'ND2 FILE SIGNATURE CHUNK NAME01!Ver2.2' 27 | actual = parse_version(data) 28 | expected = (2, 2) 29 | self.assertTupleEqual(actual, expected) 30 | 31 | def test_parse_version_3(self): 32 | data = 'ND2 FILE SIGNATURE CHUNK NAME01!Ver3.0' 33 | actual = parse_version(data) 34 | expected = (3, 0) 35 | self.assertTupleEqual(actual, expected) 36 | 37 | def test_parse_version_invalid(self): 38 | data = 'ND2 FILE SIGNATURE CHUNK NAME!Version2.2.3' 39 | self.assertRaises(InvalidVersionError, parse_version, data) 40 | 41 | def test_get_version_from_file(self): 42 | self.create_test_nd2() 43 | 44 | with open(self.test_file, 'rb') as fh: 45 | version_tuple = get_version(fh) 46 | self.assertTupleEqual(version_tuple, (3, 0)) 47 | 48 | def test_parse_date_24(self): 49 | date_format = "%m/%d/%Y %H:%M:%S" 50 | date = '02/13/2016 23:43:37' 51 | textinfo = {six.b('TextInfoItem9'): six.b(date)} 52 | result = parse_date(textinfo) 53 | self.assertEqual(result.strftime(date_format), date) 54 | 55 | def test_parse_date_12(self): 56 | date_format = "%m/%d/%Y %I:%M:%S %p" 57 | date = '02/13/2016 11:43:37 PM' 58 | textinfo = {six.b('TextInfoItem9'): six.b(date)} 59 | result = parse_date(textinfo) 60 | self.assertEqual(result.strftime(date_format), date) 61 | 62 | def test_parse_date_exception(self): 63 | date = 'i am no date' 64 | textinfo = {six.b('TextInfoItem9'): six.b(date)} 65 | result = parse_date(textinfo) 66 | self.assertIsNone(result) 67 | 68 | def test_add_to_meta_simple(self): 69 | metadata = {} 70 | _add_to_metadata(metadata, 'test', 'value') 71 | self.assertDictEqual(metadata, {'test': 'value'}) 72 | 73 | def test_add_to_meta_new_list(self): 74 | metadata = {'test': 'value1'} 75 | _add_to_metadata(metadata, 'test', 'value2') 76 | self.assertDictEqual(metadata, {'test': ['value1', 'value2']}) 77 | 78 | def test_add_to_meta_existing_list(self): 79 | metadata = {'test': ['value1', 'value2']} 80 | _add_to_metadata(metadata, 'test', 'value3') 81 | self.assertDictEqual(metadata, {'test': ['value1', 'value2', 'value3']}) 82 | 83 | @staticmethod 84 | def _prepare_bin_stream(binary_format, *value): 85 | file = six.BytesIO() 86 | data = struct.pack(binary_format, *value) 87 | file.write(data) 88 | file.seek(0) 89 | return file 90 | 91 | def test_parse_functions(self): 92 | file = self._prepare_bin_stream("B", 9) 93 | self.assertEqual(_parse_unsigned_char(file), 9) 94 | 95 | file = self._prepare_bin_stream("I", 333) 96 | self.assertEqual(_parse_unsigned_int(file), 333) 97 | 98 | file = self._prepare_bin_stream("Q", 7564332) 99 | self.assertEqual(_parse_unsigned_long(file), 7564332) 100 | 101 | file = self._prepare_bin_stream("d", 47.9) 102 | self.assertEqual(_parse_double(file), 47.9) 103 | 104 | test_string = 'colloid' 105 | file = self._prepare_bin_stream("%ds" % len(test_string), six.b(test_string)) 106 | parsed = _parse_string(file) 107 | self.assertEqual(parsed, six.b(test_string)) 108 | 109 | test_data = [1, 2, 3, 4, 5] 110 | file = self._prepare_bin_stream("Q" + ''.join(['B'] * len(test_data)), len(test_data), *test_data) 111 | parsed = _parse_char_array(file) 112 | self.assertEqual(parsed, array.array('B', test_data)) 113 | 114 | def test_get_from_dict_if_exists(self): 115 | test_dict = { 116 | six.b('existing'): 'test', 117 | 'string': 'test2' 118 | } 119 | 120 | self.assertIsNone(get_from_dict_if_exists('nowhere', test_dict)) 121 | self.assertEqual(get_from_dict_if_exists('existing', test_dict), 'test') 122 | self.assertEqual(get_from_dict_if_exists('string', test_dict, convert_key_to_binary=False), 'test2') 123 | 124 | def test_read_chunk(self): 125 | with ArtificialND2(self.test_file) as artificial: 126 | fh = artificial.file_handle 127 | chunk_location = artificial.locations['image_attributes'][0] 128 | 129 | chunk_read = read_chunk(fh, chunk_location) 130 | real_data = six.BytesIO(artificial.raw_text) 131 | 132 | real_data.seek(chunk_location) 133 | 134 | # The chunk metadata is always 16 bytes long 135 | chunk_metadata = real_data.read(16) 136 | header, relative_offset, data_length = struct.unpack("IIQ", chunk_metadata) 137 | self.assertEquals(header, 0xabeceda) 138 | 139 | # We start at the location of the chunk metadata, skip over the metadata, and then proceed to the 140 | # start of the actual data field, which is at some arbitrary place after the metadata. 141 | real_data.seek(chunk_location + 16 + relative_offset) 142 | 143 | real_chunk = real_data.read(data_length) 144 | 145 | self.assertEqual(real_chunk, chunk_read) 146 | 147 | def test_read_chunk_fail_bad_header(self): 148 | with ArtificialND2(self.test_file) as artificial: 149 | fh = artificial.file_handle 150 | chunk_location = artificial.locations['image_attributes'][0] 151 | 152 | with self.assertRaises(ValueError) as context: 153 | read_chunk(fh, chunk_location + 1) 154 | 155 | self.assertEquals(str(context.exception), "The ND2 file seems to be corrupted.") 156 | -------------------------------------------------------------------------------- /tests/test_label_map.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from nd2reader.label_map import LabelMap 3 | from nd2reader.artificial import ArtificialND2 4 | 5 | 6 | class TestLabelMap(unittest.TestCase): 7 | def setUp(self): 8 | self.nd2 = ArtificialND2('test_data/test_nd2_label_map001.nd2') 9 | self.raw_text, self.locations = self.nd2.raw_text, self.nd2.locations 10 | self.label_map = LabelMap(self.raw_text) 11 | 12 | def test_image_data_location(self): 13 | self.assertEqual(self.locations['image_frame_0'][0], self.label_map.get_image_data_location(0)) 14 | 15 | def test_image_text_info(self): 16 | self.assertEqual(self.locations['image_text_info'][0], self.label_map.image_text_info) 17 | 18 | def test_image_metadata(self): 19 | self.assertEqual(self.locations['image_metadata'][0], self.label_map.image_metadata) 20 | 21 | def test_image_attributes(self): 22 | self.assertEqual(self.locations['image_attributes'][0], self.label_map.image_attributes) 23 | 24 | def test_image_metadata_sequence(self): 25 | self.assertEqual(self.locations['image_metadata_sequence'][0], self.label_map.image_metadata_sequence) 26 | 27 | def test_image_calibration(self): 28 | self.assertEqual(self.locations['image_calibration'][0], self.label_map.image_calibration) 29 | 30 | def test_x_data(self): 31 | self.assertEqual(self.locations['x_data'][0], self.label_map.x_data) 32 | 33 | def test_y_data(self): 34 | self.assertEqual(self.locations['y_data'][0], self.label_map.y_data) 35 | 36 | def test_z_data(self): 37 | self.assertEqual(self.locations['z_data'][0], self.label_map.z_data) 38 | 39 | def test_roi_metadata(self): 40 | self.assertEqual(self.locations['roi_metadata'][0], self.label_map.roi_metadata) 41 | 42 | def test_pfs_status(self): 43 | self.assertEqual(self.locations['pfs_status'][0], self.label_map.pfs_status) 44 | 45 | def test_pfs_offset(self): 46 | self.assertEqual(self.locations['pfs_offset'][0], self.label_map.pfs_offset) 47 | 48 | def test_guid(self): 49 | self.assertEqual(self.locations['guid'][0], self.label_map.guid) 50 | 51 | def test_description(self): 52 | self.assertEqual(self.locations['description'][0], self.label_map.description) 53 | 54 | def test_camera_exposure_time(self): 55 | self.assertEqual(self.locations['camera_exposure_time'][0], self.label_map.camera_exposure_time) 56 | 57 | def test_camera_temp(self): 58 | self.assertEqual(self.locations['camera_temp'][0], self.label_map.camera_temp) 59 | 60 | def test_acquisition_times(self): 61 | self.assertEqual(self.locations['acquisition_times'][0], self.label_map.acquisition_times) 62 | 63 | def test_acquisition_times_2(self): 64 | self.assertEqual(self.locations['acquisition_times_2'][0], self.label_map.acquisition_times_2) 65 | 66 | def test_acquisition_frames(self): 67 | self.assertEqual(self.locations['acquisition_frames'][0], self.label_map.acquisition_frames) 68 | 69 | def test_lut_data(self): 70 | self.assertEqual(self.locations['lut_data'][0], self.label_map.lut_data) 71 | 72 | def test_grabber_settings(self): 73 | self.assertEqual(self.locations['grabber_settings'][0], self.label_map.grabber_settings) 74 | 75 | def test_custom_data(self): 76 | self.assertEqual(self.locations['custom_data'][0], self.label_map.custom_data) 77 | 78 | def test_app_info(self): 79 | self.assertEqual(self.locations['app_info'][0], self.label_map.app_info) 80 | -------------------------------------------------------------------------------- /tests/test_legacy.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import warnings 3 | 4 | from nd2reader.legacy import Nd2 5 | from nd2reader.reader import ND2Reader 6 | from nd2reader.artificial import ArtificialND2 7 | 8 | 9 | class TestLegacy(unittest.TestCase): 10 | def test_init(self): 11 | with ArtificialND2('test_data/legacy.nd2'): 12 | with warnings.catch_warnings(record=True) as w: 13 | # Cause all warnings to always be triggered. 14 | warnings.simplefilter("always") 15 | with Nd2('test_data/legacy.nd2') as reader: 16 | self.assertIsInstance(reader.reader, ND2Reader) 17 | self.assertTrue(issubclass(w[0].category, DeprecationWarning)) 18 | self.assertEquals(str(w[0].message), "The 'Nd2' class is deprecated, please consider using the new" + 19 | " ND2Reader interface which uses pims.") 20 | 21 | def test_misc(self): 22 | with ArtificialND2('test_data/legacy.nd2'): 23 | with Nd2('test_data/legacy.nd2') as reader: 24 | representation = "\n".join(["" % reader.reader.filename, 25 | "Created: Unknown", 26 | "Image size: %sx%s (HxW)" % (reader.height, reader.width), 27 | "Frames: %s" % len(reader.frames), 28 | "Channels: %s" % ", ".join(["%s" % str(channel) for channel 29 | in reader.channels]), 30 | "Fields of View: %s" % len(reader.fields_of_view), 31 | "Z-Levels: %s" % len(reader.z_levels) 32 | ]) 33 | self.assertEquals(representation, str(reader)) 34 | 35 | # not implemented yet 36 | self.assertEquals(reader.pixel_microns, None) 37 | 38 | self.assertEquals(len(reader), 1) 39 | -------------------------------------------------------------------------------- /tests/test_parser.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from os import path 3 | from nd2reader.artificial import ArtificialND2 4 | from nd2reader.common import check_or_make_dir 5 | from nd2reader.parser import Parser 6 | import urllib.request 7 | 8 | 9 | class TestParser(unittest.TestCase): 10 | def create_test_nd2(self): 11 | with ArtificialND2(self.test_file) as artificial: 12 | artificial.close() 13 | 14 | def setUp(self): 15 | dir_path = path.dirname(path.realpath(__file__)) 16 | check_or_make_dir(path.join(dir_path, "test_data/")) 17 | self.test_file = path.join(dir_path, "test_data/test.nd2") 18 | self.create_test_nd2() 19 | 20 | def test_can_open_test_file(self): 21 | self.create_test_nd2() 22 | 23 | with open(self.test_file, "rb") as fh: 24 | parser = Parser(fh) 25 | self.assertTrue(parser.supported) 26 | 27 | def test_get_image(self): 28 | stitched_path = "test_data/test_stitched.nd2" 29 | if not path.isfile(stitched_path): 30 | file_name, header = urllib.request.urlretrieve( 31 | "https://downloads.openmicroscopy.org/images/ND2/karl/sample_image.nd2", 32 | stitched_path, 33 | ) 34 | with open(stitched_path, "rb") as fh: 35 | parser = Parser(fh) 36 | parser.get_image(0) 37 | -------------------------------------------------------------------------------- /tests/test_raw_metadata.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import six 3 | 4 | from nd2reader.artificial import ArtificialND2 5 | from nd2reader.label_map import LabelMap 6 | from nd2reader.raw_metadata import RawMetadata 7 | from nd2reader.common_raw_metadata import parse_roi_shape, parse_roi_type, parse_dimension_text_line 8 | 9 | 10 | class TestRawMetadata(unittest.TestCase): 11 | def setUp(self): 12 | self.nd2 = ArtificialND2('test_data/test_nd2_raw_metadata001.nd2') 13 | self.raw_text, self.locations, self.file_data = self.nd2.raw_text, self.nd2.locations, self.nd2.data 14 | self.label_map = LabelMap(self.raw_text) 15 | self.metadata = RawMetadata(self.nd2.file_handle, self.label_map) 16 | 17 | def test_parse_roi_shape(self): 18 | self.assertEqual(parse_roi_shape(3), 'rectangle') 19 | self.assertEqual(parse_roi_shape(9), 'circle') 20 | self.assertIsNone(parse_roi_shape(-1)) 21 | 22 | def test_parse_roi_type(self): 23 | self.assertEqual(parse_roi_type(3), 'reference') 24 | self.assertEqual(parse_roi_type(2), 'background') 25 | self.assertEqual(parse_roi_type(4), 'stimulation') 26 | self.assertIsNone(parse_roi_type(-1)) 27 | 28 | def test_parse_dimension_text(self): 29 | line = six.b('Metadata:\r\nDimensions: T(443) x \xce\xbb(1)\r\nCamera Name: Andor Zyla VSC-01537') 30 | self.assertEqual(parse_dimension_text_line(line), six.b('Dimensions: T(443) x \xce\xbb(1)')) 31 | self.assertIsNone(parse_dimension_text_line(six.b('Dim: nothing'))) 32 | 33 | def test_parse_z_levels(self): 34 | # smokescreen test to check if the fallback to z_coordinates is working 35 | # for details, see RawMetadata._parse_z_levels() 36 | dimension_text = self.metadata._parse_dimension_text() 37 | z_levels = self.metadata._parse_dimension(r""".*?Z\((\d+)\).*?""", dimension_text) 38 | z_coords = self.metadata._parse_z_coordinates() 39 | 40 | self.assertEqual(len(dimension_text), 0) 41 | self.assertEqual(len(z_levels), 0) 42 | self.assertEqual(len(self.metadata._parse_z_levels()), len(z_coords)) 43 | 44 | def test_dict(self): 45 | self.assertTrue(type(self.metadata.__dict__) is dict) 46 | 47 | def test_parsed_metadata_has_all_keys(self): 48 | metadata = self.metadata.get_parsed_metadata() 49 | self.assertTrue(type(metadata) is dict) 50 | required_keys = ["height", "width", "date", "fields_of_view", "frames", "z_levels", "total_images_per_channel", 51 | "channels", "pixel_microns"] 52 | for required in required_keys: 53 | self.assertTrue(required in metadata) 54 | 55 | def test_cached_metadata(self): 56 | metadata_one = self.metadata.get_parsed_metadata() 57 | metadata_two = self.metadata.get_parsed_metadata() 58 | self.assertEqual(metadata_one, metadata_two) 59 | 60 | def test_pfs_status(self): 61 | self.assertEqual(self.file_data['pfs_status'], self.metadata.pfs_status[0]) 62 | 63 | def _assert_dicts_equal(self, parsed_dict, original_dict): 64 | for attribute in original_dict.keys(): 65 | parsed_key = six.b(attribute) 66 | self.assertIn(parsed_key, parsed_dict.keys()) 67 | 68 | if isinstance(parsed_dict[parsed_key], dict): 69 | self._assert_dicts_equal(parsed_dict[parsed_key], original_dict[attribute]) 70 | else: 71 | self.assertEqual(parsed_dict[parsed_key], original_dict[attribute]) 72 | 73 | def test_image_attributes(self): 74 | parsed_dict = self.metadata.image_attributes 75 | 76 | self._assert_dicts_equal(parsed_dict, self.file_data['image_attributes']) 77 | 78 | def test_color_channels(self): 79 | parsed_channels = self.metadata.get_parsed_metadata()['channels'] 80 | 81 | self.assertEquals(parsed_channels, ['TRITC']) 82 | -------------------------------------------------------------------------------- /tests/test_reader.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import numpy as np 3 | import struct 4 | 5 | from pims import Frame 6 | from nd2reader.artificial import ArtificialND2 7 | from nd2reader.exceptions import EmptyFileError, InvalidFileType 8 | from nd2reader.reader import ND2Reader 9 | from nd2reader.parser import Parser 10 | 11 | 12 | class TestReader(unittest.TestCase): 13 | def test_invalid_file_extension(self): 14 | self.assertRaises(InvalidFileType, lambda: ND2Reader('test_data/invalid_extension_file.inv')) 15 | 16 | def test_extension(self): 17 | self.assertTrue('nd2' in ND2Reader.class_exts()) 18 | 19 | def cmp_two_readers(self, r1, r2): 20 | attributes = r1.data['image_attributes']['SLxImageAttributes'] 21 | self.assertEqual(r2.metadata['width'], attributes['uiWidth']) 22 | self.assertEqual(r2.metadata['height'], attributes['uiHeight']) 23 | 24 | self.assertEqual(r2.metadata['width'], r2.sizes['x']) 25 | self.assertEqual(r2.metadata['height'], r2.sizes['y']) 26 | 27 | self.assertEqual(r2.pixel_type, np.float64) 28 | self.assertEqual(r2.iter_axes, ['t']) 29 | 30 | def test_init_and_init_axes(self): 31 | with ArtificialND2('test_data/test_nd2_reader.nd2') as artificial: 32 | with ND2Reader('test_data/test_nd2_reader.nd2') as reader: 33 | self.cmp_two_readers(artificial, reader) 34 | 35 | def test_init_from_handler(self): 36 | with ArtificialND2('test_data/test_nd2_reader.nd2') as artificial: 37 | with open('test_data/test_nd2_reader.nd2', "rb") as FH: 38 | with ND2Reader(FH) as reader: 39 | self.cmp_two_readers(artificial, reader) 40 | 41 | def test_init_empty_file(self): 42 | with ArtificialND2('test_data/empty.nd2', skip_blocks=['label_map_marker']): 43 | with self.assertRaises(EmptyFileError) as exception: 44 | with ND2Reader('test_data/empty.nd2'): 45 | pass 46 | self.assertEqual(str(exception.exception), "No axes were found for this .nd2 file.") 47 | 48 | def test_get_parser(self): 49 | with ArtificialND2('test_data/test_nd2_reader.nd2') as _: 50 | with ND2Reader('test_data/test_nd2_reader.nd2') as reader: 51 | self.assertIsInstance(reader.parser, Parser) 52 | 53 | def test_get_timesteps(self): 54 | with ArtificialND2('test_data/test_nd2_reader.nd2') as _: 55 | with ND2Reader('test_data/test_nd2_reader.nd2') as reader: 56 | timesteps = reader.timesteps 57 | self.assertEquals(len(timesteps), 0) 58 | 59 | def test_get_frame_zero(self): 60 | # Best test we can do for now: 61 | # test everything up to the actual unpacking of the frame data 62 | with ArtificialND2('test_data/test_nd2_reader.nd2') as _: 63 | with ND2Reader('test_data/test_nd2_reader.nd2') as reader: 64 | 65 | with self.assertRaises(struct.error) as exception: 66 | frame = reader[0] 67 | 68 | self.assertIn('unpack', str(exception.exception)) 69 | 70 | def test_get_frame_2D(self): 71 | # Best test we can do for now: 72 | # test everything up to the actual unpacking of the frame data 73 | with ArtificialND2('test_data/test_nd2_reader.nd2') as _: 74 | with ND2Reader('test_data/test_nd2_reader.nd2') as reader: 75 | 76 | with self.assertRaises(struct.error) as exception: 77 | frame = reader.get_frame_2D(c=0, t=0, z=0, x=0, y=0, v=0) 78 | 79 | self.assertIn('unpack', str(exception.exception)) 80 | -------------------------------------------------------------------------------- /tests/test_version.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from nd2reader import __version__ as VERSION 3 | 4 | 5 | class TestVersion(unittest.TestCase): 6 | def test_module_version_type(self): 7 | # just make sure the version number exists and is the type we expect 8 | self.assertEqual(type(VERSION), str) 9 | --------------------------------------------------------------------------------