├── .coveragerc ├── .github └── workflows │ ├── lazydocs.yml │ ├── release.yml │ └── test.yml ├── .gitignore ├── CITATION.cff ├── LICENSE ├── MANIFEST.in ├── README.md ├── docs ├── .pages ├── README.md └── pysnirf2.md ├── gen ├── README.md ├── data.py ├── gen.py ├── pysnirf2.jinja └── requirements.txt ├── pyproject.toml ├── requirements.txt ├── setup.py ├── snirf ├── __init__.py ├── __version__.py └── pysnirf2.py ├── snirf_specification_retrieved_26_12_24.txt └── tests ├── data ├── v120dev-sub-01_task-inclusion_nirs.snirf ├── v120dev-sub-02_task-test_nirs.snirf └── v120dev-sub-A_task-test_run-1.snirf └── test.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | source = snirf 4 | omit = 5 | */setup.py 6 | 7 | [report] 8 | exclude_lines = 9 | pragma: no cover 10 | if __name__ == .__main__.: 11 | @abstractmethod 12 | @abstractclassmethod 13 | -------------------------------------------------------------------------------- /.github/workflows/lazydocs.yml: -------------------------------------------------------------------------------- 1 | name: lazydocs 2 | on: 3 | push: 4 | branches: 5 | - main 6 | 7 | jobs: 8 | build-linux: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | max-parallel: 5 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Install Python 3 16 | uses: actions/setup-python@v1 17 | with: 18 | python-version: 3.9 19 | - name: Install dependencies 20 | run: | 21 | python -m pip install --upgrade pip 22 | pip install -r requirements.txt 23 | pip install lazydocs 24 | pip install pydocstyle 25 | - name: Generate documentation 26 | run: lazydocs --overview-file="README.md" --validate snirf docs 27 | - name: Commit 28 | run: | 29 | echo ${{ github.ref }} 30 | git add docs 31 | git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com" 32 | git config --local user.name "github-actions[bot]" 33 | git commit -m "CI: Automated docs update" -a | exit 0 34 | - name: Push 35 | uses: ad-m/github-push-action@v0.6.0 36 | with: 37 | github_token: ${{ secrets.GITHUB_TOKEN }} 38 | branch: ${{ github.ref }} 39 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Publish to PyPI 📦 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*' 7 | workflow_dispatch: 8 | 9 | permissions: 10 | contents: read 11 | id-token: write 12 | 13 | jobs: 14 | deploy: 15 | runs-on: ubuntu-20.04 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Install Python 3 19 | uses: actions/setup-python@v5 20 | with: 21 | python-version: 3.7.17 22 | - name: Install dependencies 23 | run: | 24 | python -m pip install --upgrade pip 25 | python -m pip install -r requirements.txt 26 | python -m pip install setuptools wheel twine 27 | - name: Build 28 | run: | 29 | python setup.py sdist bdist_wheel 30 | - name: Publish release distributions to PyPI 31 | uses: pypa/gh-action-pypi-publish@release/v1 32 | 33 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | concurrency: 3 | group: ${{ github.workflow }}-${{ github.event.number }}-${{ github.event.ref }} 4 | cancel-in-progress: true 5 | on: 6 | push: 7 | branches: 8 | - main 9 | paths: 10 | - snirf/** 11 | - tests/** 12 | pull_request: 13 | branches: 14 | - main 15 | jobs: 16 | build-linux: 17 | runs-on: ubuntu-latest 18 | continue-on-error: true 19 | strategy: 20 | max-parallel: 5 21 | matrix: 22 | python-version: ['3.9', '3.10', '3.11', '3.12'] 23 | defaults: 24 | run: 25 | shell: bash -el {0} 26 | steps: 27 | - uses: actions/checkout@v3 28 | - uses: actions/setup-python@v4 29 | with: 30 | python-version: ${{ matrix.python-version }} 31 | - name: Install dependencies 32 | run: | 33 | python -m pip install --upgrade pip setuptools wheel 34 | pip install -r requirements.txt pytest pytest-cov 35 | pip install --no-build-isolation -ve . 36 | - run: pytest tests/test.py 37 | - uses: codecov/codecov-action@v3 38 | if: success() 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/venv 2 | **/__pycache__ 3 | .idea 4 | *.log 5 | *.egg-info 6 | junit-results.xml 7 | tests/wd 8 | -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | # This CITATION.cff file was generated with cffinit. 2 | # Visit https://bit.ly/cffinit to generate yours today! 3 | 4 | cff-version: 1.2.0 5 | title: pysnirf2 6 | message: Cite this software 7 | type: software 8 | authors: 9 | - given-names: Stephen 10 | family-names: Tucker 11 | email: sstucker@bu.edu 12 | affiliation: Boston University Neurophotonics Center 13 | doi: https://doi.org/10.5281/zenodo.6784209 14 | date-released: 2021-12-7 15 | -------------------------------------------------------------------------------- /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 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md LICENSE -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 | pysnirf2 4 | 5 | `pip install snirf` 6 | 7 |

8 | 9 | ![testing](https://github.com/BUNPC/pysnirf2/actions/workflows/test.yml/badge.svg) 10 | ![lazydocs](https://github.com/BUNPC/pysnirf2/actions/workflows/lazydocs.yml/badge.svg) 11 | [![PyPI version](https://badge.fury.io/py/snirf.svg)](https://badge.fury.io/py/snirf) 12 | [![DOI](https://zenodo.org/badge/426339949.svg)](https://zenodo.org/badge/latestdoi/426339949) 13 | 14 | Dynamically generated Python library for reading, writing, and validating [Shared Near Infrared Spectroscopy Format (SNIRF) files](https://github.com/fNIRS/snirf). 15 | 16 | Developed and maintained by the [Boston University Neurophotonics Center](https://www.bu.edu/neurophotonics/). 17 | 18 | ## Documentation 19 | 20 | [Documentation](https://github.com/BUNPC/pysnirf2/tree/main/docs) is generated from source using [lazydocs](https://github.com/ml-tooling/lazydocs) 21 | 22 | ## Installation 23 | `pip install snirf` 24 | 25 | pysnirf2 requires Python > 3.9. 26 | 27 | # Features 28 | 29 | pysnirf2 explicitly implements all SNIRF fields so as to provide an extensible object-oriented foundation for SNIRF applications. 30 | 31 | ## Open a SNIRF file 32 | `Snirf(, )` opens a SNIRF file at `` _or creates a new one if it doesn't exist._ Use mode 'w' to create a new file, 'r' to read a file, and 'r+' to edit an existing file. 33 | ```python 34 | from snirf import Snirf 35 | snirf = Snirf(r'some\path\subj1_run01.snirf', 'r+') 36 | ``` 37 | ## Create a SNIRF file object 38 | `Snirf()` with no arguments creates a temporary file which can be written later using `save()`. 39 | ```python 40 | snirf = Snirf() 41 | ``` 42 | 43 | ## Closing a SNIRF file 44 | A `Snirf` instance wraps a file on disk. It should be closed when you're done reading from it or saving. 45 | ```python 46 | snirf.close() 47 | ``` 48 | Use a `with` statement to ensure that the file is closed when you're done with it: 49 | ```python 50 | with Snirf(r'some\path\subj1_run01.snirf', 'r+') as snirf: 51 | # Read/write 52 | snirf.save() 53 | ``` 54 | 55 | ## Copy a SNIRF file object 56 | Any `Snirf` object can be copied to a new instance in memory, after which the original can be closed. 57 | ```python 58 | snirf2 = snirf.copy() 59 | snirf.close() 60 | # snirf2 is free for manipulation 61 | ``` 62 | 63 | ## View or retrieve a file's contents 64 | ```python 65 | >>> snirf 66 | 67 | Snirf at / 68 | filename: 69 | C:\Users\you\some\path\subj1_run01.snirf 70 | formatVersion: v1.0 71 | nirs: > 72 | ``` 73 | ```python 74 | >>> snirf.nirs[0].probe 75 | 76 | Probe at /nirs1/probe 77 | correlationTimeDelayWidths: [0.] 78 | correlationTimeDelays: [0.] 79 | detectorLabels: ['D1' 'D2'] 80 | detectorPos2D: [[30. 0.] 81 | [ 0. 30.]] 82 | detectorPos3D: [[30. 0. 0.] 83 | [ 0. 30. 0.]] 84 | filename: 85 | C:\Users\you\some\path\subj1_run01.snirf 86 | frequencies: [1.] 87 | landmarkLabels: None 88 | landmarkPos2D: None 89 | landmarkPos3D: None 90 | location: /nirs/probe 91 | momentOrders: None 92 | sourceLabels: ['S1'] 93 | sourcePos2D: [[0. 0.]] 94 | sourcePos3D: [[0.] 95 | [0.] 96 | [0.]] 97 | timeDelayWidths: [0.] 98 | timeDelays: [0.] 99 | useLocalIndex: None 100 | wavelengths: [690. 830.] 101 | wavelengthsEmission: None 102 | ``` 103 | ## Edit a SNIRF file 104 | Assign a new value to a field 105 | ```python 106 | >>> snirf.nirs[0].metaDataTags.SubjectID = 'subj1' 107 | >>> snirf.nirs[0].metaDataTags.SubjectID 108 | 109 | 'subj1' 110 | ``` 111 | ```python 112 | >>> snirf.nirs[0].probe.detectorPos3D[0, :] = [90, 90, 90] 113 | >>> snirf.nirs[0].probe.detectorPos3D 114 | 115 | array([[90., 90., 90.], 116 | [ 0., 30., 0.]]) 117 | ``` 118 | > Note: assignment via slicing is not possible in `dynamic_loading` mode. 119 | ## Indexed groups 120 | Indexed groups are defined by the SNIRF file format as groups of the same type which are indexed via their name + a 1-based index, i.e. `data1`, `data2`, ... or `stim1`, `stim2`, `stim3`, ... 121 | 122 | pysnirf2 provides an iterable interface for these groups using Pythonic 0-based indexing, i.e. `data[0]`, `data[1]`, ... or `stim[0]`, `stim[1]]`, `stim[2]`, ... 123 | 124 | ```python 125 | >>> snirf.nirs[0].stim 126 | 127 | 128 | > 129 | 130 | >>> len(nirs[0].stim) 131 | 132 | 0 133 | ``` 134 | To add an indexed group, use the `appendGroup()` method of any `IndexedGroup` class. Indexed groups are created automatically. `nirs` is an indexed group. 135 | ```python 136 | >>> snirf.nirs[0].stim.appendGroup() 137 | >>> len(nirs[0].stim) 138 | 139 | 1 140 | 141 | >>> snirf.nirs[0].stim[0] 142 | 143 | StimElement at /nirs/stim2 144 | data: None 145 | dataLabels: None 146 | filename: 147 | C:\Users\you\some\path\subj1_run01.snirf 148 | name: None 149 | ``` 150 | To remove an indexed group 151 | ```python 152 | del snirf.nirs[0].stim[0] 153 | ``` 154 | ## Save a SNIRF file 155 | Overwrite the open file 156 | ```python 157 | snirf.save() 158 | ``` 159 | Save As in a new location 160 | ```python 161 | snirf.save(r'some\new\path\subj1_run01_edited.snirf') 162 | ``` 163 | The `save()` function can be called for any group or indexed group: 164 | ```python 165 | snirf.nirs[0].metaDataTags.save('subj1_run01_edited_metadata_only.snirf') 166 | ``` 167 | ## Dynamic loading mode 168 | For larger files, it may be useful to load data dynamically: data will only be loaded on access, and only changed datasets will be written on `save()`. When creating a new `Snirf` instance, set `dynamic_loading` to `True` (Default `False`). 169 | ```python 170 | snirf = Snirf(r'some\path\subj1_run01.snirf', 'r+', dynamic_loading=True) 171 | ``` 172 | > Note: in dynamic loading mode, array data cannot be modified with indices like in the example above: 173 | > ```python 174 | > >>> snirf = Snirf(TESTPATH, 'r+', dynamic_loading=True) 175 | > >>> snirf.nirs[0].probe.detectorPos3D 176 | > 177 | > array([[30., 0., 0.], 178 | > [ 0., 30., 0.]]) 179 | > 180 | > >>> snirf.nirs[0].probe.detectorPos3D[0, :] = [90, 90, 90] 181 | > >>> snirf.nirs[0].probe.detectorPos3D 182 | > 183 | > array([[30., 0., 0.], 184 | > [ 0., 30., 0.]]) 185 | > ``` 186 | > To modify an array in `dynamic_loading` mode, assign it, modify it, and assign it back to the Snirf object. 187 | > ```python 188 | > >>> detectorPos3D = snirf.nirs[0].probe.detectorPos3D 189 | > >>> detectorPos3D[0, :] = [90, 90, 90] 190 | > >>> snirf.nirs[0].probe.detectorPos3D = detectorPos3D 191 | > 192 | > array([[90., 90., 90.], 193 | > [ 0., 30., 0.]]) 194 | 195 | # Validating a SNIRF file 196 | pysnirf2 features functions for validating SNIRF files against the specification and generating detailed error reports. 197 | ## Validate a Snirf object you have created 198 | ```python 199 | result = snirf.validate() 200 | ``` 201 | ## Validate a SNIRF file on disk 202 | To validate a SNIRF file on disk 203 | ```python 204 | from snirf import validateSnirf 205 | result = validateSnirf(r'some\path\subj1_run01.snirf') 206 | assert result, 'Invalid SNIRF file!\n' + result.display() # Crash and display issues if the file is invalid. 207 | ``` 208 | ## Validation results 209 | The validation functions return a [`ValidationResult`](https://github.com/BUNPC/pysnirf2/blob/main/docs/pysnirf2.md#class-validationresult) instance which contains details about the SNIRF file. 210 | To view the validation result: 211 | ```python 212 | >>> result.display(severity=3) # Display all fatal errors 213 | 214 | 215 | /nirs1/data1/measurementList103/dataType FATAL REQUIRED_DATASET_MISSING 216 | /nirs1/data1/measurementList103/dataTypeIndex FATAL REQUIRED_DATASET_MISSING 217 | /nirs1/data1 FATAL INVALID_MEASUREMENTLIST 218 | 219 | Found 668 OK (hidden) 220 | Found 635 INFO (hidden) 221 | Found 204 WARNING (hidden) 222 | Found 3 FATAL 223 | 224 | File is INVALID 225 | ``` 226 | To look at a particular result: 227 | ```python 228 | >>> result.errors[2] 229 | 230 | 231 | location: /nirs1/data1 232 | severity: 3 FATAL 233 | name: 8 INVALID_MEASUREMENTLIST 234 | message: The number of measurementList elements does not match the second dimension of dataTimeSeries 235 | ``` 236 | The full list of validation results `result.issues` can be explored programatically. 237 | # Code generation 238 | 239 | The interface and validator are generated via metacode that downloads and parses [the latest SNIRF specification](https://raw.githubusercontent.com/fNIRS/snirf/master/snirf_specification.md). 240 | 241 | See [\gen](https://github.com/BUNPC/pysnirf2/tree/main/gen) for details. 242 | 243 | 244 | 245 | 246 | -------------------------------------------------------------------------------- /docs/.pages: -------------------------------------------------------------------------------- 1 | title: API Reference 2 | nav: 3 | - Overview: README.md 4 | - ... 5 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # API Overview 4 | 5 | ## Modules 6 | 7 | - [`pysnirf2`](./pysnirf2.md#module-pysnirf2): Module for reading, writing and validating SNIRF files. 8 | 9 | ## Classes 10 | 11 | - [`pysnirf2.Aux`](./pysnirf2.md#class-aux) 12 | - [`pysnirf2.AuxElement`](./pysnirf2.md#class-auxelement) 13 | - [`pysnirf2.Data`](./pysnirf2.md#class-data) 14 | - [`pysnirf2.DataElement`](./pysnirf2.md#class-dataelement) 15 | - [`pysnirf2.Group`](./pysnirf2.md#class-group) 16 | - [`pysnirf2.IndexedGroup`](./pysnirf2.md#class-indexedgroup) 17 | - [`pysnirf2.MeasurementList`](./pysnirf2.md#class-measurementlist): Interface for indexed group `MeasurementList`. 18 | - [`pysnirf2.MeasurementListElement`](./pysnirf2.md#class-measurementlistelement): Wrapper for an element of indexed group `MeasurementList`. 19 | - [`pysnirf2.MeasurementLists`](./pysnirf2.md#class-measurementlists) 20 | - [`pysnirf2.MetaDataTags`](./pysnirf2.md#class-metadatatags) 21 | - [`pysnirf2.Nirs`](./pysnirf2.md#class-nirs): Interface for indexed group `Nirs`. 22 | - [`pysnirf2.NirsElement`](./pysnirf2.md#class-nirselement): Wrapper for an element of indexed group `Nirs`. 23 | - [`pysnirf2.Probe`](./pysnirf2.md#class-probe) 24 | - [`pysnirf2.Snirf`](./pysnirf2.md#class-snirf) 25 | - [`pysnirf2.SnirfConfig`](./pysnirf2.md#class-snirfconfig): Structure containing Snirf-wide data and settings. 26 | - [`pysnirf2.SnirfFormatError`](./pysnirf2.md#class-snirfformaterror): Raised when SNIRF-specific error prevents file from loading or saving properly. 27 | - [`pysnirf2.Stim`](./pysnirf2.md#class-stim) 28 | - [`pysnirf2.StimElement`](./pysnirf2.md#class-stimelement) 29 | - [`pysnirf2.ValidationIssue`](./pysnirf2.md#class-validationissue): Information about the validity of a given SNIRF file location. 30 | - [`pysnirf2.ValidationResult`](./pysnirf2.md#class-validationresult): The result of Snirf file validation routines. 31 | 32 | ## Functions 33 | 34 | - [`pysnirf2.loadSnirf`](./pysnirf2.md#function-loadsnirf): Load a SNIRF file from disk. 35 | - [`pysnirf2.saveSnirf`](./pysnirf2.md#function-savesnirf): Saves a SNIRF file to disk. 36 | - [`pysnirf2.validateSnirf`](./pysnirf2.md#function-validatesnirf): Validate a SNIRF file on disk. 37 | 38 | 39 | --- 40 | 41 | _This file was automatically generated via [lazydocs](https://github.com/ml-tooling/lazydocs)._ 42 | -------------------------------------------------------------------------------- /gen/README.md: -------------------------------------------------------------------------------- 1 | # Generating pysnirf2 from the specification text 2 | 3 | A significant portion of the pysnirf2 code is generated dynamically from the [SNIRF specification document](https://raw.githubusercontent.com/fNIRS/snirf/master/snirf_specification.md) maintained in the official repository. 4 | 5 | This ensures easy maintenance of the project as the specification develops. 6 | 7 | ## Overview 8 | 9 | [gen.py](https://github.com/BUNPC/pysnirf2/blob/main/gen/gen.py) parses the spec document at the location defined as `SPEC_SRC` in [data.py](https://github.com/BUNPC/pysnirf2/blob/main/gen/data.py). 10 | 11 | [gen.py](https://github.com/BUNPC/pysnirf2/blob/main/gen/gen.py) then generates a dictionary of data which is combined with jinja2 template [pysnirf2.jinja](https://github.com/BUNPC/pysnirf2/blob/main/gen/pysnirf2.jinja) which metaprogrammatically generates the library source [pysnirf2.py](https://github.com/BUNPC/pysnirf2/blob/main/pysnirf2/pysnirf2.py). Code is inserted between the start and end delimeters as specified. [data.py](https://github.com/BUNPC/pysnirf2/blob/main/gen/data.py) should be updated and [gen.py](https://github.com/BUNPC/pysnirf2/blob/main/gen/gen.py) should be run when a new version of the SNIRF specification has been released. 12 | 13 | ## How-to 14 | 15 | 1. Ensure that [data.py](https://github.com/BUNPC/pysnirf2/blob/main/gen/data.py) contains correct data to parse the latest spec. Make sure `SPEC_SRC` and `VERSION` are up to date. 16 | 2. IMPORTANT! Back up or commit local changes to the code via git. The generation process may delete your changes. 17 | 3. Using a Python > 3.9 environment equipped with [gen/requirements.txt](https://github.com/BUNPC/pysnirf2/blob/main/gen/requirements.txt), run [gen.py](https://github.com/BUNPC/pysnirf2/blob/main/gen/gen.py) from the project root 18 | 4. Test the resulting library 19 | -------------------------------------------------------------------------------- /gen/data.py: -------------------------------------------------------------------------------- 1 | SPEC_SRC = 'https://raw.githubusercontent.com/sstucker/snirf/refs/heads/master/snirf_specification.md' 2 | SPEC_VERSION = '1.2-development' # Version of the spec linked above 3 | 4 | """ 5 | These types are fragments of the string codes used to describe the types of 6 | SNIRF datasets in the table of the specification document. 7 | 8 | i.e. if TYPELUT[] in : 9 | """ 10 | TYPELUT = { 11 | 'GROUP': '{.}', 12 | 'INDEXED_GROUP': '{i}', 13 | 'REQUIRED': '*', 14 | 'ARRAY_2D': '...]]', 15 | 'ARRAY_1D': '...]', # Parsed with if-else so these can be distinguished with a simple "in" 16 | 'INT_VALUE': '', 17 | 'FLOAT_VALUE': '', 18 | 'VARLEN_STRING': '"s"' 19 | } 20 | 21 | """ 22 | Groups with these names will be exempt from warnings and attempt to load all Datasets 23 | """ 24 | UNSPECIFIED_DATASETS_OK = ['metaDataTags'] 25 | 26 | TEMPLATE = 'gen/pysnirf2.jinja' # The name of the template file to use 27 | 28 | TEMPLATE_INSERT_BEGIN_STR = '# <<< BEGIN TEMPLATE INSERT >>>' 29 | TEMPLATE_INSERT_END_STR = '# <<< END TEMPLATE INSERT >>>' 30 | 31 | """ 32 | These strings are used to identify the beginning and end of the table 33 | and definitions sections of the spec document 34 | """ 35 | TABLE_DELIM_START = '[//]: # (SCHEMA BEGIN)' 36 | TABLE_DELIM_END = '[//]: # (SCHEMA END)' 37 | 38 | DEFINITIONS_DELIM_START = '### SNIRF data container definitions' 39 | DEFINITIONS_DELIM_END = '## Appendix' 40 | 41 | DATA_TYPE_DELIM_START = '### Supported `measurementList(k).dataType` values in `dataTimeSeries`' 42 | DATA_TYPE_DELIM_END = '### Supported `measurementList(k).dataTypeLabel` values in `dataTimeSeries`' 43 | 44 | DATA_TYPE_LABEL_TABLE_START = '### Supported `measurementList(k).dataTypeLabel` values in `dataTimeSeries`' 45 | DATA_TYPE_LABEL_TABLE_END = '### Supported `/nirs(i)/aux(j)/name` values' 46 | 47 | AUX_NAME_TABLE_START = '### Supported `/nirs(i)/aux(j)/name` values' 48 | AUX_NAME_TABLE_END = '### Examples of stimulus waveforms' 49 | 50 | # -- BIDS Probe name identifiers --------------------------------------------- 51 | 52 | BIDS_PROBE_NAMES = ['ICBM452AirSpace', 53 | 'ICBM452Warp5Space', 54 | 'IXI549Space', 55 | 'fsaverage', 56 | 'fsaverageSym', 57 | 'fsLR', 58 | 'MNIColin27', 59 | 'MNI152Lin', 60 | 'MNI152NLin2009[a-c][Sym|Asym]', 61 | 'MNI152NLin6Sym', 62 | 'MNI152NLin6ASym', 63 | 'MNI305', 64 | 'NIHPD', 65 | 'OASIS30AntsOASISAnts', 66 | 'OASIS30Atropos', 67 | 'Talairach', 68 | 'UNCInfant'] 69 | 70 | -------------------------------------------------------------------------------- /gen/gen.py: -------------------------------------------------------------------------------- 1 | from jinja2 import Environment, FileSystemLoader, select_autoescape 2 | from yapf.yapflib.yapf_api import FormatFile 3 | import requests 4 | from unidecode import unidecode 5 | from pathlib import Path 6 | from datetime import date, datetime 7 | import getpass 8 | import os 9 | import sys 10 | import re 11 | from pylint import lint 12 | 13 | """ 14 | Generates SNIRF interface and validator from the summary table of the specification 15 | hosted at SPEC_SRC. 16 | """ 17 | 18 | LIB_VERSION = '0.9.2' # Version for this script 19 | 20 | if __name__ == '__main__': 21 | 22 | cwd = os.path.abspath(os.getcwd()) 23 | if not cwd.endswith('pysnirf2'): 24 | sys.exit('The gen script must be run from the pysnirf2 project root, not ' + cwd) 25 | 26 | library_path = cwd + '/snirf/' + 'pysnirf2.py' 27 | 28 | try: 29 | from data import * 30 | except ModuleNotFoundError: 31 | from gen.data import * 32 | 33 | sys.path.append(cwd) 34 | 35 | print('-------------------------------------') 36 | print('pysnirf2 generation script v' + LIB_VERSION) 37 | print('-------------------------------------') 38 | 39 | local_spec = SPEC_SRC.split('/')[-1].split('.')[0] + '_retrieved_' + datetime.now().strftime('%d_%m_%y') + '.txt' 40 | 41 | if os.path.exists(local_spec) and input('Use local specification document ' + local_spec + '? y/n\n') == 'y': 42 | print('Loading specification from local document', local_spec, '...') 43 | with open(local_spec, 'r') as f: 44 | text = f.read() 45 | else: 46 | print('Attempting to retrieve spec from', SPEC_SRC, '...') 47 | 48 | # Retrieve the SNIRF specification from GitHub and parse it for the summary table 49 | 50 | try: 51 | spec = requests.get(SPEC_SRC) 52 | except (ConnectionError, requests.exceptions.ConnectionError): 53 | sys.exit('No internet connection and no downloaded specification document. pysnirf2 generation aborted.') 54 | 55 | if spec.text == '404: Not Found': 56 | print(spec.text) 57 | sys.exit('The Snirf specification could not be found at ' + SPEC_SRC) 58 | 59 | text = unidecode(spec.text) 60 | 61 | for file in os.listdir(): 62 | if file.startswith(SPEC_SRC.split('/')[-1].split('.')[0] + '_retrieved_') and file.endswith('.txt'): 63 | os.remove(file) 64 | 65 | with open(local_spec, 'w') as f: 66 | f.write(text) 67 | 68 | 69 | table = text.split(TABLE_DELIM_START)[1].split(TABLE_DELIM_END)[0] 70 | 71 | rows = table.split('\n') 72 | while '' in rows: 73 | rows.remove('') 74 | 75 | type_codes = [] 76 | 77 | # Parse each row of the summary table for programmatic info 78 | for row in rows[1:]: # Skip header row 79 | delim = row.split('|') 80 | 81 | if len(delim) > 1: 82 | 83 | # Number of leading spaces determines indent level, hierarchy 84 | namews = delim[1].replace('`', '').replace('.','').replace('-', '') 85 | name = namews.replace(' ', '').replace('/', '').replace('{i}', '') 86 | 87 | # Get name: format pairs for each name 88 | if len(name) > 1: # Skip the empty row 89 | type_code = delim[-2].replace(' ', '').replace('`', '') 90 | type_codes.append((type_code, name)) 91 | 92 | print('Found', len(type_codes), 'types in the table...') 93 | 94 | # Parse headings in spec for complete HDF style locations with which to build tree 95 | definitions = unidecode(text).split(DEFINITIONS_DELIM_START)[1].split(DEFINITIONS_DELIM_END)[0] 96 | definitions_lines = definitions.split('\n') 97 | 98 | # Create list of hdf5 names ("locations") by assuming each follows a '####' header character in the definitions section 99 | locations = [] 100 | descriptions = [] 101 | for i, line in enumerate(definitions_lines): 102 | line = line.replace(' ', '') 103 | if line.startswith('####'): 104 | locations.append(line.replace('`', '').replace('#', '').replace(',', '')) 105 | description_lines = [] 106 | j = i + 4 107 | while not definitions_lines[j].startswith('####'): 108 | description_lines.append(definitions_lines[j]) 109 | j += 1 110 | if j >= len(definitions_lines): 111 | break 112 | descriptions.append('\n'.join(description_lines)) 113 | 114 | # Format descriptions 115 | descriptions = [description.replace('\\', '/').replace('\t', ' ').lstrip() for description in descriptions] 116 | 117 | # Create flat list of all nodes 118 | flat = [] 119 | 120 | print('Found', len(descriptions), 'descriptions...') 121 | print('Found', len(locations), 'locations...') 122 | 123 | # Write locations to file 124 | if os.path.exists(os.path.join('gen', 'locations.txt')): 125 | os.remove(os.path.join('gen', 'locations.txt')) 126 | with open(os.path.join('gen', 'locations.txt'), 'w') as f: 127 | for location in locations: 128 | f.write(location.replace('(i)', '').replace('(j)', '').replace('(k)', '') + '\n') 129 | print('Wrote to locations.txt') 130 | 131 | errf = False 132 | for (type_code, location) in zip(type_codes, locations): 133 | if type_code[1] not in location: 134 | errf = True 135 | print('Specification format issue: location {} aligned to name/type {} from schema table'.format(location, type_code)) 136 | if errf: 137 | sys.exit('pysnirf2 generation aborted.') 138 | 139 | if len(locations) != len(type_codes) or len(locations) != len(descriptions): 140 | sys.exit('Parsed ' + str(len(type_codes[0])) + ' type codes from the summary table but ' 141 | + str(len(locations)) + ' names from the definitions and ' + str(len(descriptions)) 142 | + ' descriptions: the specification hosted at ' + SPEC_SRC +' was parsed incorrectly. Try adjusting the delimiters and then debug the parsing code (gen.py).') 143 | 144 | # Append root (flat will have 1 extra element compared to locations) 145 | flat.append({ 146 | 'name': '', 147 | 'location': '/', 148 | 'parent': None, 149 | 'type': '/', 150 | 'children': [], 151 | 'required': False 152 | }) 153 | 154 | for i, (location, description) in enumerate(zip(locations, descriptions)): 155 | type_code = type_codes[i][0] 156 | name = location.split('/')[-1].split('(')[0] # Remove (i), (j) 157 | parent = location.split('/')[-2].split('(')[0] # Remove (i), (j) 158 | print('Found', location, 'with type', type_code) 159 | if type_code is not None: 160 | required = TYPELUT['REQUIRED'] in type_code 161 | else: 162 | required = None 163 | if not any([location == node['location'] for node in flat]): 164 | flat.append({ 165 | 'name': name, 166 | 'location': location, 167 | 'description': description, 168 | 'parent': parent, 169 | 'type': type_code, 170 | 'children': [], 171 | 'required': required 172 | }) 173 | 174 | if input('Proceed? y/n\n') not in ['y', 'Y']: 175 | sys.exit('pysnirf2 generation aborted.') 176 | 177 | print('Loading BIDS-specified Probe names from gen/data.py...') 178 | for name in BIDS_PROBE_NAMES: 179 | print('Found', name) 180 | 181 | print('\nParsing specification for supported data type integer values...') 182 | data_type_table = unidecode(text).split(DATA_TYPE_DELIM_START)[1].split(DATA_TYPE_DELIM_END)[0] 183 | data_types = re.findall(r'(?<=\s)-\s(\d+)\s-', data_type_table) 184 | data_types = [int(i) for i in data_types] 185 | for i in data_types: 186 | print('Found', i) 187 | if input('Proceed? y/n\n') not in ['y', 'Y']: 188 | sys.exit('pysnirf2 generation aborted.') 189 | 190 | print('\nParsing specification for supported aux names...') 191 | aux_name_table = unidecode(text).split(AUX_NAME_TABLE_START)[1].split(AUX_NAME_TABLE_END)[0] 192 | aux_names = re.findall(r'"(.*?)"', aux_name_table) 193 | for name in aux_names: 194 | print('Found', name) 195 | if input('Proceed? y/n\n') not in ['y', 'Y']: 196 | sys.exit('pysnirf2 generation aborted.') 197 | 198 | print('\nParsing specification for supported data type labels...') 199 | data_type_label_table = unidecode(text).split(DATA_TYPE_LABEL_TABLE_START)[1].split(DATA_TYPE_LABEL_TABLE_END)[0] 200 | data_type_labels = re.findall(r'"(.*?)"', data_type_label_table) 201 | for name in data_type_labels: 202 | print('Found', name) 203 | if input('Proceed? y/n\n') not in ['y', 'Y']: 204 | sys.exit('pysnirf2 generation aborted.') 205 | 206 | # Generate data for template 207 | SNIRF = { 208 | 'VERSION': SPEC_VERSION, 209 | 'SPEC_SRC': SPEC_SRC, 210 | 'HEADER': '', 211 | 'FOOTER': '', 212 | 'ROOT': flat[0], # Snirf root '/' 213 | 'TYPES': TYPELUT, 214 | 'USER': getpass.getuser(), 215 | 'DATE': str(date.today()), 216 | 'INDEXED_GROUPS': [], 217 | 'GROUPS': [], 218 | 'UNSPECIFIED_DATASETS_OK': UNSPECIFIED_DATASETS_OK, 219 | 'BIDS_COORDINATE_SYSTEM_NAMES': BIDS_PROBE_NAMES, 220 | 'AUX_NAMES': aux_names, 221 | 'DATA_TYPES': data_types, 222 | 'DATA_TYPE_LABELS': data_type_labels 223 | } 224 | 225 | # Build list of groups and indexed groups 226 | for node in flat: 227 | if node['type'] is not None: 228 | for other_node in flat: 229 | if other_node['parent'] == node['name']: 230 | node['children'].append(other_node) 231 | if TYPELUT['GROUP'] in node['type']: 232 | SNIRF['GROUPS'].append(node) 233 | elif TYPELUT['INDEXED_GROUP'] in node['type']: 234 | SNIRF['INDEXED_GROUPS'].append(node) 235 | 236 | # %% 237 | 238 | env = Environment( 239 | loader=FileSystemLoader(searchpath='./'), 240 | autoescape=select_autoescape(), 241 | trim_blocks=True, 242 | lstrip_blocks=True, 243 | ) 244 | print('\nCreated jinja2 environment.') 245 | 246 | print('Loading template from', TEMPLATE) 247 | template = env.get_template(TEMPLATE) 248 | 249 | # Generate the complete Snirf library by inserting the template code into pysnirf2.py 250 | with open(library_path, "r") as f_in: 251 | b = f_in.read() 252 | SNIRF['HEADER'] = b.split(TEMPLATE_INSERT_BEGIN_STR)[0] + TEMPLATE_INSERT_BEGIN_STR 253 | print('Loaded header code, {} lines'.format(len(SNIRF['HEADER'].split('\n')))) 254 | SNIRF['FOOTER'] = TEMPLATE_INSERT_END_STR + b.split(TEMPLATE_INSERT_END_STR, 1)[1] 255 | print('Loaded footer code, {} lines'.format(len(SNIRF['FOOTER'].split('\n')))) 256 | 257 | if input('Proceed? LOCAL CHANGES MAY BE OVERWRITTEN OR LOST! y/n\n') not in ['y', 'Y']: 258 | sys.exit('pysnirf2 generation aborted.') 259 | try: 260 | os.remove(library_path) 261 | except FileNotFoundError: 262 | pass 263 | open(library_path, 'w') 264 | 265 | with open(library_path, "w") as f_out: 266 | f_out.write(template.render(SNIRF)) 267 | 268 | print('\nWrote script to ' + library_path + '.') 269 | 270 | with open(library_path) as generated: 271 | lines = generated.read().split('\n') 272 | print('pysnirf2.py is', len(lines), 'lines long') 273 | errors = 0 274 | for i, line in enumerate(lines): 275 | if 'TEMPLATE_ERROR' in line: 276 | errors += 1 277 | print('ERROR on line', i, '\n', line) 278 | if errors == 0: 279 | print('pysnirf2.py generated with', errors, 'errors.') 280 | 281 | if input('Format the generated code? y/n\n') in ['y', 'Y']: 282 | FormatFile(library_path, in_place=True)[:2] 283 | 284 | if input('Lint the generated code? y/n\n') in ['y', 'Y']: 285 | lint.Run(['--errors-only', library_path]) 286 | 287 | print('\npysnirf2 generation complete.') 288 | 289 | # Cleanup 290 | 291 | if os.path.exists(os.path.join('gen', 'locations.txt')): 292 | os.remove(os.path.join('gen', 'locations.txt')) 293 | -------------------------------------------------------------------------------- /gen/pysnirf2.jinja: -------------------------------------------------------------------------------- 1 | {% macro sentencecase(text) %} 2 | {{- text[0]|upper}}{{text[1:] -}} 3 | {% endmacro %} 4 | {% macro declare_members(NODE) %} 5 | {%- for CHILD in NODE.children %} 6 | {%- if TYPES.GROUP in CHILD.type %} 7 | self._{{ CHILD.name }} = _AbsentGroup # {{ CHILD.type }} 8 | {% else %} 9 | self._{{ CHILD.name }} = _AbsentDataset # {{ CHILD.type }} 10 | {% endif -%} 11 | {% endfor %} 12 | self._snirf_names = [{% for CHILD in NODE.children %}'{{ CHILD.name }}', {% endfor -%}] 13 | {% endmacro %} 14 | {% macro init_members(NODE) %} 15 | self._indexed_groups = [] 16 | {% for CHILD in NODE.children %} 17 | {% if TYPES.INDEXED_GROUP in CHILD.type %} 18 | self.{{ CHILD.name }} = {{ sentencecase(CHILD.name) }}(self, self._cfg) # Indexed group 19 | self._indexed_groups.append(self.{{ CHILD.name }}) 20 | {% elif TYPES.GROUP in CHILD.type %} 21 | if '{{ CHILD.name }}' in self._h: 22 | self._{{ CHILD.name }} = {{ sentencecase(CHILD.name) }}(self._h['{{ CHILD.name }}'].id, self._cfg) # Group 23 | else: 24 | self._{{ CHILD.name }} = {{ sentencecase(CHILD.name) }}(self.location + '/' + '{{ CHILD.name }}', self._cfg) # Anonymous group (wrapper only) 25 | {% else %} 26 | if '{{ CHILD.name }}' in self._h: 27 | if not self._cfg.dynamic_loading: 28 | {% if (TYPES.ARRAY_1D in CHILD.type) or (TYPES.ARRAY_2D in CHILD.type) %} 29 | {% if TYPES.VARLEN_STRING in CHILD.type %} 30 | self._{{ CHILD.name }} = _read_string_array(self._h['{{ CHILD.name }}']) 31 | {% elif TYPES.INT_VALUE in CHILD.type %} 32 | self._{{ CHILD.name }} = _read_int_array(self._h['{{ CHILD.name }}']) 33 | {% elif TYPES.FLOAT_VALUE in CHILD.type %} 34 | self._{{ CHILD.name }} = _read_float_array(self._h['{{ CHILD.name }}']) 35 | {% else %} 36 | self._{{ CHILD.name }} = _read_dataset(self._h['{{ CHILD.name }}']) 37 | {% endif %} 38 | {% else %} 39 | {% if TYPES.VARLEN_STRING in CHILD.type %} 40 | self._{{ CHILD.name }} = _read_string(self._h['{{ CHILD.name }}']) 41 | {% elif TYPES.INT_VALUE in CHILD.type %} 42 | self._{{ CHILD.name }} = _read_int(self._h['{{ CHILD.name }}']) 43 | {% elif TYPES.FLOAT_VALUE in CHILD.type %} 44 | self._{{ CHILD.name }} = _read_float(self._h['{{ CHILD.name }}']) 45 | {% else %} 46 | self._{{ CHILD.name }} = _read_dataset(self._h['{{ CHILD.name }}']) 47 | {% endif %} 48 | {% endif %} 49 | else: # if the dataset is found on disk but dynamic_loading=True 50 | self._{{ CHILD.name }} = _PresentDataset 51 | else: # if the dataset is not found on disk 52 | self._{{ CHILD.name }} = _AbsentDataset 53 | {% endif %} 54 | {% endfor %} 55 | {% if NODE.name in UNSPECIFIED_DATASETS_OK %} 56 | self._unspecified_names = [] 57 | # Unspecified datasets are not properties and unaffected by dynamic_loading 58 | for key in self._h.keys(): 59 | # If the name isn't specified 60 | if key not in self._snirf_names and not any([key in indexed_group for indexed_group in self._indexed_groups]): 61 | self.__dict__[key] = _read_dataset(self._h[key]) 62 | self._unspecified_names.append(key) 63 | {% endif %} 64 | {% endmacro %} 65 | {% macro gen_properties(NODE) %} 66 | {% for CHILD in NODE.children %} 67 | @property 68 | def {{ CHILD.name }}(self): 69 | """SNIRF field `{{ CHILD.name }}`. 70 | 71 | If dynamic_loading=True, the data is loaded from the SNIRF file only 72 | when accessed through the getter 73 | 74 | {{ CHILD.description | indent(8) }} 75 | """ 76 | {% if TYPES.INDEXED_GROUP in CHILD.type %} 77 | return self._{{ CHILD.name }} 78 | {% elif TYPES.GROUP in CHILD.type %} 79 | if self._{{ CHILD.name }} is _AbsentGroup: 80 | return None 81 | return self._{{ CHILD.name }} 82 | {% else %} 83 | if self._{{ CHILD.name }} is _AbsentDataset: 84 | return None 85 | if type(self._{{ CHILD.name }}) is type(_PresentDataset): 86 | {% if (TYPES.ARRAY_1D in CHILD.type) or (TYPES.ARRAY_2D in CHILD.type) %} 87 | {% if TYPES.VARLEN_STRING in CHILD.type %} 88 | return _read_string_array(self._h['{{ CHILD.name }}']) 89 | {% elif TYPES.INT_VALUE in CHILD.type %} 90 | return _read_int_array(self._h['{{ CHILD.name }}']) 91 | {% elif TYPES.FLOAT_VALUE in CHILD.type %} 92 | return _read_float_array(self._h['{{ CHILD.name }}']) 93 | {% else %} 94 | return _read_dataset(self._h['{{ CHILD.name }}']) 95 | {% endif %} 96 | {% else %} 97 | {% if TYPES.VARLEN_STRING in CHILD.type %} 98 | return _read_string(self._h['{{ CHILD.name }}']) 99 | {% elif TYPES.INT_VALUE in CHILD.type %} 100 | return _read_int(self._h['{{ CHILD.name }}']) 101 | {% elif TYPES.FLOAT_VALUE in CHILD.type %} 102 | return _read_float(self._h['{{ CHILD.name }}']) 103 | {% else %} 104 | return _read_dataset(self._h['{{ CHILD.name }}']) 105 | {% endif %} 106 | {% endif %} 107 | self._cfg.logger.info('Dynamically loaded %s/{{ CHILD.name }} from %s', self.location, self.filename) 108 | return self._{{ CHILD.name }} 109 | {% endif %} 110 | 111 | @{{ CHILD.name }}.setter 112 | def {{ CHILD.name }}(self, value): 113 | {% if TYPES.INDEXED_GROUP in CHILD.type %} 114 | self._{{ CHILD.name }} = value 115 | {% elif TYPES.GROUP in CHILD.type %} 116 | if isinstance(value, {{ sentencecase(CHILD.name) }}): 117 | self._{{ CHILD.name }} = _recursive_hdf5_copy(self._{{ CHILD.name }}, value) 118 | else: 119 | raise ValueError("Only a Group of type {{ sentencecase(CHILD.name) }} can be assigned to {{ CHILD.name }}.") 120 | {% elif TYPES.ARRAY_1D in CHILD.type or TYPES.ARRAY_2D in CHILD.type %} 121 | if value is not None and any([v is not None for v in value]): 122 | self._{{ CHILD.name }} = np.array(value) 123 | {% else %} 124 | self._{{ CHILD.name }} = value 125 | {% endif %} 126 | # self._cfg.logger.info('Assignment to %s/{{ CHILD.name }} in %s', self.location, self.filename) 127 | 128 | @{{ CHILD.name }}.deleter 129 | def {{ CHILD.name }}(self): 130 | {% if TYPES.INDEXED_GROUP in CHILD.type %} 131 | raise AttributeError('IndexedGroup ' + str(type(self._{{ CHILD.name }})) + ' cannot be deleted') 132 | {% elif TYPES.GROUP in CHILD.type %} 133 | self._{{ CHILD.name }} = _AbsentGroup 134 | {% else %} 135 | self._{{ CHILD.name }} = _AbsentDataset 136 | {% endif %} 137 | self._cfg.logger.info('Deleted %s/{{ CHILD.name }} from %s', self.location, self.filename) 138 | 139 | {% endfor %} 140 | {% endmacro %} 141 | {% macro gen_writer(NODE) %} 142 | def _save(self, *args): 143 | if len(args) > 0 and type(args[0]) is h5py.File: 144 | file = args[0] 145 | if self.location not in file: 146 | file.create_group(self.location) 147 | # self._cfg.logger.info('Created Group at %s in %s', self.location, file) 148 | else: 149 | if self.location not in file: 150 | # Assign the wrapper to the new HDF5 Group on disk 151 | self._h = file.create_group(self.location) 152 | # self._cfg.logger.info('Created Group at %s in %s', self.location, file) 153 | if self._h != {}: 154 | file = self._h.file 155 | else: 156 | raise ValueError('Cannot save an anonymous ' + self.__class__.__name__ + ' instance without a filename') 157 | {% for CHILD in NODE.children %} 158 | name = self.location + '/{{ CHILD.name }}' 159 | {% if TYPES.INDEXED_GROUP in CHILD.type %} 160 | self.{{ CHILD.name }}._save(*args) 161 | {% elif TYPES.GROUP in CHILD.type %} 162 | if self._{{ CHILD.name }} is _AbsentGroup or self._{{ CHILD.name }}.is_empty(): 163 | if name in file: 164 | del file[name] 165 | self._cfg.logger.info('Deleted Group %s/{{ CHILD.name }} from %s', self.location, file) 166 | else: 167 | self.{{ CHILD.name }}._save(*args) 168 | {% else %} 169 | if not self._{{ CHILD.name }} is _AbsentDataset: 170 | data = self.{{ CHILD.name }} # Use loader function via getter 171 | if name in file: 172 | del file[name] 173 | {% if TYPES.ARRAY_2D in CHILD.type %} 174 | {% if TYPES.VARLEN_STRING in CHILD.type %} 175 | _create_dataset_string_array(file, name, data, ndim=2) 176 | {% elif TYPES.INT_VALUE in CHILD.type %} 177 | _create_dataset_int_array(file, name, data, ndim=2) 178 | {% elif TYPES.FLOAT_VALUE in CHILD.type %} 179 | _create_dataset_float_array(file, name, data, ndim=2) 180 | {% else %} 181 | _create_dataset(file, name, data) 182 | {% endif %} 183 | {% elif TYPES.ARRAY_1D in CHILD.type %} 184 | {% if TYPES.VARLEN_STRING in CHILD.type %} 185 | _create_dataset_string_array(file, name, data, ndim=1) 186 | {% elif TYPES.INT_VALUE in CHILD.type %} 187 | _create_dataset_int_array(file, name, data, ndim=1) 188 | {% elif TYPES.FLOAT_VALUE in CHILD.type %} 189 | _create_dataset_float_array(file, name, data, ndim=1) 190 | {% else %} 191 | _create_dataset(file, name, data) 192 | {% endif %} 193 | {% else %} 194 | {% if TYPES.VARLEN_STRING in CHILD.type %} 195 | _create_dataset_string(file, name, data) 196 | {% elif TYPES.INT_VALUE in CHILD.type %} 197 | _create_dataset_int(file, name, data) 198 | {% elif TYPES.FLOAT_VALUE in CHILD.type %} 199 | _create_dataset_float(file, name, data) 200 | {% else %} 201 | _create_dataset(file, name, data) 202 | {% endif %} 203 | {% endif %} 204 | # self._cfg.logger.info('Creating Dataset %s in %s', name, file) 205 | else: 206 | if name in file: 207 | del file[name] 208 | self._cfg.logger.info('Deleted Dataset %s from %s', name, file) 209 | {% endif %} 210 | {% endfor %} 211 | {% if NODE.name in UNSPECIFIED_DATASETS_OK %} 212 | for unspecified_name in self._unspecified_names: 213 | name = self.location + '/' + unspecified_name 214 | if name in file: 215 | del file[name] 216 | self._cfg.logger.info('Deleted Dataset %s from %s', name, file) 217 | try: 218 | data = getattr(self, unspecified_name) 219 | except AttributeError: # Dataset was deleted 220 | continue 221 | _create_dataset(file, name, data) 222 | 223 | {% endif %} 224 | {% endmacro %} 225 | {% macro gen_validator(NODE) %} 226 | def _validate(self, result: ValidationResult): 227 | # Validate unwritten datasets after writing them to this tempfile 228 | with h5py.File(str(uuid.uuid4()), 'w', driver='core', backing_store=False) as tmp: 229 | {% for CHILD in NODE.children %} 230 | name = self.location + '/{{ CHILD.name }}' 231 | {% if TYPES.INDEXED_GROUP in CHILD.type %} 232 | {% if TYPES.REQUIRED in CHILD.type %} 233 | if len(self._{{ CHILD.name }}) == 0: 234 | result._add(name, 'REQUIRED_INDEXED_GROUP_EMPTY') 235 | {% else %} 236 | if len(self._{{ CHILD.name }}) == 0: 237 | result._add(name, 'OPTIONAL_INDEXED_GROUP_EMPTY') 238 | {% endif %} 239 | else: 240 | self.{{ CHILD.name }}._validate(result) 241 | {% elif TYPES.GROUP in CHILD.type %} 242 | # If Group is not present in file and empty in the wrapper, it is missing 243 | if self._{{ CHILD.name }} is _AbsentGroup or ('{{ CHILD.name }}' not in self._h and self._{{ CHILD.name }}.is_empty()): 244 | {% if TYPES.REQUIRED in CHILD.type %} 245 | result._add(name, 'REQUIRED_GROUP_MISSING') 246 | {% else %} 247 | result._add(name, 'OPTIONAL_GROUP_MISSING') 248 | {% endif %} 249 | else: 250 | self._{{ CHILD.name }}._validate(result) 251 | {% else %} 252 | if self._{{ CHILD.name }} is _AbsentDataset: 253 | {% if TYPES.REQUIRED in CHILD.type %} 254 | result._add(name, 'REQUIRED_DATASET_MISSING') 255 | {% else %} 256 | result._add(name, 'OPTIONAL_DATASET_MISSING') 257 | {% endif %} 258 | else: 259 | try: 260 | if type(self._{{ CHILD.name }}) is type(_PresentDataset) or '{{ CHILD.name }}' in self._h: 261 | dataset = self._h['{{ CHILD.name }}'] 262 | else: 263 | {% if TYPES.ARRAY_2D in CHILD.type %} 264 | {% if TYPES.VARLEN_STRING in CHILD.type %} 265 | dataset = _create_dataset_string_array(tmp, '{{ CHILD.name }}', self._{{ CHILD.name }}) 266 | result._add(name, _validate_string_array(dataset, ndims=[2])) 267 | {% elif TYPES.INT_VALUE in CHILD.type %} 268 | dataset = _create_dataset_int_array(tmp, '{{ CHILD.name }}', self._{{ CHILD.name }}) 269 | result._add(name, _validate_int_array(dataset, ndims=[2])) 270 | {% elif TYPES.FLOAT_VALUE in CHILD.type %} 271 | dataset = _create_dataset_float_array(tmp, '{{ CHILD.name }}', self._{{ CHILD.name }}) 272 | result._add(name, _validate_float_array(dataset, ndims=[2])) 273 | {% else %} 274 | ### TEMPLATE ERROR: NO VALIDATOR FUNCTION MATCHING {{ CHILD.name }} 275 | {% endif %} 276 | {% elif TYPES.ARRAY_1D in CHILD.type %} 277 | {% if TYPES.VARLEN_STRING in CHILD.type %} 278 | dataset = _create_dataset_string_array(tmp, '{{ CHILD.name }}', self._{{ CHILD.name }}) 279 | result._add(name, _validate_string_array(dataset, ndims=[1])) 280 | {% elif TYPES.INT_VALUE in CHILD.type %} 281 | dataset = _create_dataset_int_array(tmp, '{{ CHILD.name }}', self._{{ CHILD.name }}) 282 | result._add(name, _validate_int_array(dataset, ndims=[1])) 283 | {% elif TYPES.FLOAT_VALUE in CHILD.type %} 284 | dataset = _create_dataset_float_array(tmp, '{{ CHILD.name }}', self._{{ CHILD.name }}) 285 | result._add(name, _validate_float_array(dataset, ndims=[1])) 286 | {% else %} 287 | ### TEMPLATE ERROR: NO VALIDATOR FUNCTION MATCHING {{ CHILD.name }} 288 | {% endif %} 289 | {% else %} 290 | {% if TYPES.VARLEN_STRING in CHILD.type %} 291 | dataset = _create_dataset_string(tmp, '{{ CHILD.name }}', self._{{ CHILD.name }}) 292 | result._add(name, _validate_string(dataset)) 293 | {% elif TYPES.INT_VALUE in CHILD.type %} 294 | dataset = _create_dataset_int(tmp, '{{ CHILD.name }}', self._{{ CHILD.name }}) 295 | {% if 'Index' in CHILD.name %} 296 | err_code = _validate_int(dataset) 297 | if _read_int(dataset) < 0 and err_code == 'OK': 298 | result._add(name, 'NEGATIVE_INDEX') 299 | elif _read_int(dataset) == 0 and err_code == 'OK': 300 | result._add(name, 'INDEX_OF_ZERO') 301 | else: 302 | result._add(name, err_code) 303 | {% else %} 304 | result._add(name, _validate_int(dataset)) 305 | {% endif %} 306 | {% elif TYPES.FLOAT_VALUE in CHILD.type %} 307 | dataset = _create_dataset_float(tmp, '{{ CHILD.name }}', self._{{ CHILD.name }}) 308 | result._add(name, _validate_float(dataset)) 309 | {% else %} 310 | ### TEMPLATE ERROR: NO VALIDATOR FUNCTION MATCHING {{ CHILD.name }} 311 | {% endif %} 312 | {% endif %} 313 | except ValueError: # If the _create_dataset function can't convert the data 314 | result._add(name, 'INVALID_DATASET_TYPE') 315 | {% endif %} 316 | {% endfor %} 317 | {% if not NODE.name in UNSPECIFIED_DATASETS_OK %} 318 | for key in self._h.keys(): 319 | if not any([key.startswith(name) for name in self._snirf_names]): 320 | if type(self._h[key]) is h5py.Group: 321 | result._add(self.location + '/' + key, 'UNRECOGNIZED_GROUP') 322 | elif type(self._h[key]) is h5py.Dataset: 323 | result._add(self.location + '/' + key, 'UNRECOGNIZED_DATASET') 324 | {% endif %} 325 | {% endmacro %} 326 | {{ HEADER }} 327 | 328 | # generated by {{ USER }} on {{ DATE }} 329 | # version {{ VERSION }} SNIRF specification parsed from {{ SPEC_SRC }} 330 | 331 | 332 | {% for GROUP in GROUPS %} 333 | class {{ sentencecase(GROUP.name) -}}(Group): 334 | """Wrapper for Group of type `{{ GROUP.name }}`. 335 | 336 | {{ GROUP.description | indent }} 337 | """ 338 | def __init__(self, var, cfg: SnirfConfig): 339 | super().__init__(var, cfg) 340 | {{ declare_members(GROUP) | indent }} 341 | {{ init_members(GROUP) | indent }} 342 | {{ gen_properties(GROUP) }} 343 | {{ gen_writer(GROUP) }} 344 | {{ gen_validator(GROUP) }} 345 | 346 | 347 | {% endfor %} 348 | {% for INDEXED_GROUP in INDEXED_GROUPS %} 349 | class {{ sentencecase(INDEXED_GROUP.name) -}}Element(Group): 350 | """Wrapper for an element of indexed group `{{ sentencecase(INDEXED_GROUP.name) }}`.""" 351 | def __init__(self, gid: h5py.h5g.GroupID, cfg: SnirfConfig): 352 | super().__init__(gid, cfg) 353 | {{ declare_members(INDEXED_GROUP) | indent }} 354 | {{ init_members(INDEXED_GROUP) | indent }} 355 | {{ gen_properties(INDEXED_GROUP) }} 356 | {{ gen_writer(INDEXED_GROUP) }} 357 | {{ gen_validator(INDEXED_GROUP) }} 358 | 359 | class {{ sentencecase(INDEXED_GROUP.name) -}}(IndexedGroup): 360 | """Interface for indexed group `{{ sentencecase(INDEXED_GROUP.name) }}`. 361 | 362 | Can be indexed like a list to retrieve `{{ sentencecase(INDEXED_GROUP.name) }}` elements. 363 | 364 | To add or remove an element from the list, use the `appendGroup` method and the `del` operator, respectively. 365 | 366 | {{ INDEXED_GROUP.description | indent }} 367 | """ 368 | _name: str = '{{ INDEXED_GROUP.name }}' 369 | _element: Group = {{ sentencecase(INDEXED_GROUP.name) -}}Element 370 | 371 | def __init__(self, h: h5py.File, cfg: SnirfConfig): 372 | super().__init__(h, cfg) 373 | 374 | 375 | {% endfor %} 376 | class Snirf(Group): 377 | 378 | _name = '/' 379 | 380 | # overload 381 | def __init__(self, *args, dynamic_loading: bool = False, enable_logging: bool = False): 382 | self._cfg = SnirfConfig() 383 | self._cfg.dynamic_loading = dynamic_loading 384 | self._cfg.fmode = '' 385 | self._f = None # handle for filelikes and temporary files 386 | if len(args) > 0: 387 | path = args[0] 388 | if enable_logging: 389 | self._cfg.logger = _create_logger(path, path.split('.')[0] + '.log') 390 | else: 391 | self._cfg.logger = _create_logger('', None) # Do not log to file 392 | if len(args) > 1: 393 | assert type(args[1]) is str, 'Positional argument 2 must be "r"/"w" mode' 394 | if args[1] == 'r': 395 | self._cfg.fmode = 'r' 396 | elif args[1] == 'r+': 397 | self._cfg.fmode = 'r+' 398 | elif args[1] == 'w': 399 | self._cfg.fmode = 'w' 400 | else: 401 | raise ValueError("Invalid mode: '{}'. Only 'r', 'r+' and 'w' are supported.".format(args[1])) 402 | else: 403 | warn('Use `Snirf(, )` to open SNIRF file from path. Path-only construction is deprecated.', DeprecationWarning) 404 | # fmode is '' 405 | if type(path) is str: 406 | if not path.endswith('.snirf'): 407 | path.replace('.', '') 408 | path = path + '.snirf' 409 | if os.path.exists(path): 410 | self._cfg.logger.info('Loading from file %s', path) 411 | if self._cfg.fmode == '': 412 | self._cfg.fmode = 'r+' 413 | self._h = h5py.File(path, self._cfg.fmode) 414 | else: 415 | self._cfg.logger.info('Creating new file at %s', path) 416 | if self._cfg.fmode == '': 417 | self._cfg.fmode = 'w' 418 | self._h = h5py.File(path, self._cfg.fmode) 419 | elif _isfilelike(args[0]): 420 | self._cfg.logger.info('Loading from filelike object') 421 | if self._cfg.fmode == '': 422 | self._cfg.fmode = 'r' 423 | self._f = args[0] 424 | self._h = h5py.File(self._f, 'r', backing_store=False) 425 | else: 426 | raise TypeError(str(path) + ' is not a valid filename') 427 | else: 428 | path = None 429 | if enable_logging: 430 | self._cfg.logger = _logger 431 | self._cfg.logger.info('Created Snirf object based on tempfile') 432 | else: 433 | self._cfg.logger = _create_logger('', None) # Do not log to file 434 | self._cfg.fmode = 'w' 435 | self._h = h5py.File(str(uuid.uuid4()), 'w', driver='core', backing_store=False) 436 | {{ declare_members(ROOT) | indent }} 437 | {{ init_members(ROOT) | indent }} 438 | {{ gen_properties(ROOT) }} 439 | {{ gen_writer(ROOT) }} 440 | {{ gen_validator(ROOT) }} 441 | 442 | _RECOGNIZED_COORDINATE_SYSTEM_NAMES = [{% for NAME in BIDS_COORDINATE_SYSTEM_NAMES %}'{{ NAME }}', {% endfor -%}] 443 | 444 | _RECOGNIZED_AUX_NAMES = [{% for NAME in AUX_NAMES %}'{{ NAME }}', {% endfor -%}] 445 | 446 | _RECOGNIZED_DATA_TYPES = [{% for VALUE in DATA_TYPES %}{{ VALUE }}, {% endfor -%}] 447 | 448 | _RECOGNIZED_DATA_TYPE_LABELS = [{% for NAME in DATA_TYPE_LABELS %}'{{ NAME }}', {% endfor -%}] 449 | 450 | {{ FOOTER }} -------------------------------------------------------------------------------- /gen/requirements.txt: -------------------------------------------------------------------------------- 1 | Jinja2==3.0.3 2 | MarkupSafe==2.0.1 3 | Unidecode==1.3.2 4 | certifi==2021.10.8 5 | charset-normalizer==2.0.7 6 | yapf==0.32.0 7 | idna==3.3 8 | pathlib==1.0.1 9 | requests==2.26.0 10 | urllib3==1.26.7 11 | pylint==2.14.4 -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=42", 4 | "wheel" 5 | ] 6 | build-backend = "setuptools.build_meta" 7 | 8 | [tool.pytest.ini_options] 9 | addopts = """-ra --cov-report= --tb=short \ 10 | --junit-xml=junit-results.xml \ 11 | --color=yes --capture=sys""" 12 | junit_family = "xunit2" 13 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | h5py 2 | numpy>=2.0.0 3 | setuptools 4 | pip 5 | termcolor 6 | colorama 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Based on https://github.com/kennethreitz/setup.py 4 | # To upload to PyPI 5 | # >>> setup.py upload 6 | 7 | import io 8 | import os 9 | from pathlib import Path 10 | import sys 11 | from shutil import rmtree 12 | 13 | from setuptools import find_packages, setup, Command 14 | 15 | # Do not "import snirf" here because that requires h5py to be installed 16 | with open(Path(__file__).parent / "snirf" / "__version__.py") as f: 17 | VERSION = f.readline().split("=")[1].strip().strip('()') 18 | VERSION = ".".join(VERSION.replace(' ', '').replace(',', '.').split(',')) 19 | 20 | NAME = 'snirf' 21 | 22 | about = {} 23 | about['__version__'] = VERSION 24 | 25 | here = os.path.abspath(os.path.dirname(__file__)) 26 | 27 | try: 28 | with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f: 29 | long_description = '\n' + f.read() 30 | except FileNotFoundError: 31 | long_description = '' 32 | 33 | 34 | class UploadCommand(Command): 35 | """Support setup.py upload.""" 36 | 37 | description = 'Build and publish the package.' 38 | user_options = [] 39 | 40 | @staticmethod 41 | def status(s): 42 | """Prints things in bold.""" 43 | print('\033[1m{0}\033[0m'.format(s)) 44 | 45 | def initialize_options(self): 46 | pass 47 | 48 | def finalize_options(self): 49 | pass 50 | 51 | def run(self): 52 | try: 53 | self.status('Removing previous builds…') 54 | rmtree(os.path.join(here, 'dist')) 55 | except OSError: 56 | pass 57 | 58 | self.status('Building Source and Wheel (universal) distribution…') 59 | os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) 60 | 61 | self.status('Uploading the package to PyPI via Twine…') 62 | os.system('twine upload dist/*') 63 | 64 | self.status('Pushing git tags…') 65 | os.system('git tag v{0}'.format(about['__version__'])) 66 | os.system('git push --tags') 67 | 68 | sys.exit() 69 | 70 | 71 | setup( 72 | name=NAME, 73 | version=about['__version__'], 74 | description='Interface and validator for SNIRF files', 75 | long_description=long_description, 76 | long_description_content_type='text/markdown', 77 | author_email='sstucker@bu.edu', 78 | python_requires='>=3.9.0', 79 | install_requires=[ 80 | 'h5py>=3.1.0', 81 | 'numpy>2.0.0', 82 | 'setuptools', 83 | 'pip', 84 | 'termcolor', 85 | 'colorama', 86 | ], 87 | url='https://github.com/BUNPC/pysnirf2', 88 | packages=find_packages(exclude=('tests', 'gen')), 89 | include_package_data=True, 90 | license='GPLv3', 91 | classifiers=[ 92 | 'License :: OSI Approved :: MIT License', 93 | 'Programming Language :: Python', 94 | 'Programming Language :: Python :: 3', 95 | 'Programming Language :: Python :: 3.6', 96 | 'Programming Language :: Python :: Implementation :: CPython', 97 | 'Programming Language :: Python :: Implementation :: PyPy' 98 | ], 99 | # $ setup.py publish support. 100 | cmdclass={ 101 | 'upload': UploadCommand, 102 | }, 103 | ) 104 | -------------------------------------------------------------------------------- /snirf/__init__.py: -------------------------------------------------------------------------------- 1 | from .pysnirf2 import * 2 | from .__version__ import __version__ as __version__ -------------------------------------------------------------------------------- /snirf/__version__.py: -------------------------------------------------------------------------------- 1 | __VERSION__ = (0, 8, 0) 2 | __version__ = '.'.join(map(str, __VERSION__)) 3 | -------------------------------------------------------------------------------- /snirf_specification_retrieved_26_12_24.txt: -------------------------------------------------------------------------------- 1 | Shared Near Infrared Spectroscopy Format (SNIRF) Specification 2 | ============================================================== 3 | 4 | * **Document Version**: v1.1 5 | * **License**: This document is in the public domain. 6 | 7 | ## Table of Content 8 | 9 | - [Introduction](#introduction) 10 | - [Data format](#data-format) 11 | - [SNIRF file specification](#snirf-file-specification) 12 | * [SNIRF data format summary](#snirf-data-format-summary) 13 | * [SNIRF data container definitions](#snirf-data-container-definitions) 14 | * [formatVersion](#formatversion) 15 | * [nirs](#nirsi) 16 | * [metaDataTags](#nirsimetadatatags) 17 | * [data](#nirsidataj) 18 | * [data.dataTimeSeries](#nirsidatajdatatimeseries) 19 | * [data.dataOffset](#nirsidatajdataoffset) 20 | * [data.time](#nirsidatajtime) 21 | * [data.measurementList](#nirsidatajmeasurementlistk) 22 | * [data.measurementList.sourceIndex](#nirsidatajmeasurementlistksourceindex) 23 | * [data.measurementList.detectorIndex](#nirsidatajmeasurementlistkdetectorindex) 24 | * [data.measurementList.wavelengthIndex](#nirsidatajmeasurementlistkwavelengthindex) 25 | * [data.measurementList.wavelengthActual](#nirsidatajmeasurementlistkwavelengthactual) 26 | * [data.measurementList.wavelengthEmissionActual](#nirsidatajmeasurementlistkwavelengthemissionactual) 27 | * [data.measurementList.dataType](#nirsidatajmeasurementlistkdatatype) 28 | * [data.measurementList.dataUnit](#nirsidatajmeasurementlistkdataunit) 29 | * [data.measurementList.dataTypeLabel](#nirsidatajmeasurementlistkdatatypelabel) 30 | * [data.measurementList.dataTypeIndex](#nirsidatajmeasurementlistkdatatypeindex) 31 | * [data.measurementList.sourcePower](#nirsidatajmeasurementlistksourcepower) 32 | * [data.measurementList.detectorGain](#nirsidatajmeasurementlistkdetectorgain) 33 | * [data.measurementLists](#nirsidatajmeasurementlists) 34 | * [data.measurementLists.sourceIndex](#nirsidatajmeasurementlistssourceindex) 35 | * [data.measurementLists.detectorIndex](#nirsidatajmeasurementlistsdetectorindex) 36 | * [data.measurementLists.wavelengthIndex](#nirsidatajmeasurementlistswavelengthindex) 37 | * [data.measurementLists.wavelengthActual](#nirsidatajmeasurementlistswavelengthactual) 38 | * [data.measurementLists.wavelengthEmissionActual](#nirsidatajmeasurementlistswavelengthemissionactual) 39 | * [data.measurementLists.dataType](#nirsidatajmeasurementlistsdatatype) 40 | * [data.measurementLists.dataUnit](#nirsidatajmeasurementlistsdataunit) 41 | * [data.measurementLists.dataTypeLabel](#nirsidatajmeasurementlistsdatatypelabel) 42 | * [data.measurementLists.dataTypeIndex](#nirsidatajmeasurementlistsdatatypeindex) 43 | * [data.measurementLists.sourcePower](#nirsidatajmeasurementlistssourcepower) 44 | * [data.measurementLists.detectorGain](#nirsidatajmeasurementlistsdetectorgain) 45 | * [stim](#nirsistimj) 46 | * [stim.name](#nirsistimjname) 47 | * [stim.data](#nirsistimjdata) 48 | * [stim.dataLabels](#nirsistimjdatalabels) 49 | * [probe](#nirsiprobe) 50 | * [probe.wavelengths](#nirsiprobewavelengths) 51 | * [probe.wavelengthsEmission](#nirsiprobewavelengthsemission) 52 | * [probe.sourcePos2D](#nirsiprobesourcepos2d) 53 | * [probe.sourcePos3D](#nirsiprobesourcepos3d) 54 | * [probe.detectorPos2D](#nirsiprobedetectorpos2d) 55 | * [probe.detectorPos3D](#nirsiprobedetectorpos3d) 56 | * [probe.frequencies](#nirsiprobefrequencies) 57 | * [probe.timeDelays](#nirsiprobetimedelays) 58 | * [probe.timeDelayWidths](#nirsiprobetimedelaywidths) 59 | * [probe.momentOrders](#nirsiprobemomentorders) 60 | * [probe.correlationTimeDelays](#nirsiprobecorrelationtimedelays) 61 | * [probe.correlationTimeDelayWidths](#nirsiprobecorrelationtimedelaywidths) 62 | * [probe.sourceLabels](#nirsiprobesourcelabels) 63 | * [probe.detectorLabels](#nirsiprobedetectorlabels) 64 | * [probe.landmarkPos2D](#nirsiprobelandmarkpos2d) 65 | * [probe.landmarkPos3D](#nirsiprobelandmarkpos3d) 66 | * [probe.landmarkLabels](#nirsiprobelandmarklabelsj) 67 | * [probe.CoordinateSystem](#nirsiprobecoordinatesystem) 68 | * [probe.CoordinateSystemDescription](#nirsiprobecoordinatesystemdescription) 69 | * [aux](#nirsiauxj) 70 | * [aux.name](#nirsiauxjname) 71 | * [aux.dataTimeSeries](#nirsiauxjdatatimeseries) 72 | * [aux.dataUnit](#nirsiauxjdataunit) 73 | * [aux.time](#nirsiauxjtime) 74 | * [aux.timeOffset](#nirsiauxjtimeoffset) 75 | - [Appendix](#appendix) 76 | - [Acknowledgement](#acknowledgement) 77 | 78 | 79 | ## Introduction 80 | 81 | The file format specification uses the extension `.snirf`. These are HDF5 82 | format files, renamed with the `.snirf` extension. For a program to be 83 | "SNIRF-compliant", it must be able to read and write the SNIRF file. 84 | 85 | The development of the SNIRF specification is conducted in an open manner using the GitHub 86 | platform. To contribute or provide feedback visit [https://github.com/fNIRS/snirf](https://github.com/fNIRS/snirf). 87 | 88 | ## Data format 89 | 90 | The HDF5 specifications are defined by the HDF5 group and found at 91 | https://www.hdfgroup.org. It is expected that HDF5 future versions will remain 92 | backwards compatibility in the foreseeable future. 93 | 94 | The HDF5 format defines "groups" (`H5G` class) and "datasets" (`H5D` class) 95 | that are the two primary data organization and storage classes used in the 96 | SNIRF specification. 97 | 98 | The structure of each data file has a minimum of required elements noted below. 99 | 100 | For each element in the data structure, one of the 4 types is assigned, 101 | including 102 | 103 | - `group`: a structure containing sub-fields (defined in the `H5G` object 104 | class). Arrays of groups, also known as the indexed-groups, are denoted 105 | with numbers at the end (e.g. `/nirs/data1`, `/nirs/data2`) starting with 106 | index 1. Array indices should be contiguous with no skipped values 107 | (an empty group with no sub-member is permitted). 108 | - `string`: a variable-length, null-terminated sequence of characters, i.e. `H5T_C_S1` 109 | with size set to `H5T_VARIABLE`. At this time HDF5 does not have a UTF16 native type, 110 | so `H5T_NATIVE_B16` will need to be converted to/from unicode-16 within the read/write code). 111 | 112 | > Strings MUST be stored in null-terminated 'variable-length' format to be considered valid. Fixed-length strings and variable-length strings are loaded differently by HDF5 interface implementations.* 113 | - `integer`: the native integer types `H5T_NATIVE_INT` `H5T` datatype (alias of 114 | `H5T_STD_I32BE` or `H5T_STD_I32LE`). Use of 64-bit `long` string types such as `H5T_STD_I64LE` is *not recommended*, although most HDF5 interface implementations will not have issues converting between the two implicitly. 115 | - `numeric`: one of the native double or floating-point types; 116 | `H5T_NATIVE_DOUBLE` or `H5T_NATIVE_FLOAT` in `H5T` (alias of 117 | `H5T_IEEE_F64BE`,`H5T_IEEE_F64LE`, i.e. "double", or `H5T_IEEE_F32BE`, 118 | `H5T_IEEE_F32LE`, i.e. "float") 119 | 120 | Datasets which are not arrays must be saved in [scalar dataspaces](http://davis.lbl.gov/Manuals/HDF5-1.8.7/UG/UG_frame12Dataspaces.html). It is NOT VALID to save Datasets which are not specified as arrays in simple dataspaces with 1 dimension and with size 1. HDF5 interface implementations distinguish between these two formats and exhibit different behavior depending on the format of the file. 121 | 122 | Valid arrays MUST: 123 | 124 | * Contain elements of a correct type as described above. 125 | * Occupy a [simple dataspace](http://davis.lbl.gov/Manuals/HDF5-1.8.7/UG/UG_frame12Dataspaces.html). 126 | * Have exactly the number of dimensions specified. A SNIRF field specified by this document as a `numeric 1-D array` must occupy a dataspace with `rank` of 1. 127 | 128 | > For code samples in various programming languages which demonstrate the writing of SNIRF-specified formats, see the [Appendix](#code-samples). 129 | 130 | ## SNIRF file specification 131 | 132 | The SNIRF data format must have the initial `H5G` group type `/nirs` at the 133 | initial file location. 134 | 135 | All indices (source, detector, wavelength, datatype etc) start at 1. 136 | 137 | All SNIRF data elements are associated with a unique HDF5 location path in the 138 | form of `/root/parent/.../name`. All paths must use `/nirs` or `/nirs#` (indexed group array). 139 | Note that the root `/nirs` can be either indexed or a non-indexed single entry. 140 | 141 | If a data element is an HDF5 group and contains multiple sub-groups, it is referred 142 | to as an **indexed group**. Each element of the sub-group is uniquely identified 143 | by appending a string-formatted index (starting from 1, with no preceding zeros) 144 | in the name, for example, `/.../name1` denotes the first sub-group of data element 145 | `name`, and `/.../name2` denotes the 2nd element, and so on. 146 | 147 | In the below sections, we use the notations `"(i)"` `"(j)"` or `"(k)"` inside the 148 | HDF5 location paths to denote the indices of sub-elements when multiplicity presents. 149 | 150 | 151 | ### SNIRF data format summary 152 | 153 | Note that this table serves as machine-readable schema for the SNIRF format. Its format may not be altered. 154 | 155 | [//]: # (SCHEMA BEGIN) 156 | 157 | | SNIRF-formatted NIRS data structure | Meaning of the data | Type | 158 | |---------------------------------------|----------------------------------------------|----------------| 159 | | `/formatVersion` | * SNIRF format version | `"s"` * | 160 | | `/nirs{i}` | * Root-group for 1 or more NIRS datasets | `{i}` * | 161 | | `metaDataTags` | * Root-group for metadata headers | `{.}` * | 162 | | `SubjectID` | * Subject identifier | `"s"` * | 163 | | `MeasurementDate` | * Date of the measurement | `"s"` * | 164 | | `MeasurementTime` | * Time of the measurement | `"s"` * | 165 | | `LengthUnit` | * Length unit (case sensitive) | `"s"` * | 166 | | `TimeUnit` | * Time unit (case sensitive) | `"s"` * | 167 | | `FrequencyUnit` | * Frequency unit (case sensitive) | `"s"` * | 168 | | ... | * Additional user-defined metadata entries | | 169 | | `data{i}` | * Root-group for 1 or more data blocks | `{i}` * | 170 | | `dataTimeSeries` | * Time-varying signals from all channels | `[[,...]]`* | 171 | | `time` | * Time (in `TimeUnit` defined in metaDataTag)| `[,...]` * | 172 | | `offset` | * Absolute offset for all channels | `[,...]` * | 173 | | `measurementList{i}` | * Per-channel source-detector information | `{i}` * | 174 | | `sourceIndex` | * Source index for a given channel | `` * | 175 | | `detectorIndex` | * Detector index for a given channel | `` * | 176 | | `wavelengthIndex` | * Wavelength index for a given channel | `` * | 177 | | `wavelengthActual` | * Actual wavelength for a given channel | `` | 178 | | `wavelengthEmissionActual` | * Actual emission wavelength for a channel | `` | 179 | | `dataType` | * Data type for a given channel | `` * | 180 | | `dataUnit` | * SI unit for a given channel | `"s"` | 181 | | `dataTypeLabel` | * Data type name for a given channel | `"s"` | 182 | | `dataTypeIndex` | * Data type index for a given channel | `` * | 183 | | `sourcePower` | * Source power for a given channel | `` | 184 | | `detectorGain` | * Detector gain for a given channel | `` | 185 | | `measurementLists` | * source-detector information | `{.}` * | 186 | | `sourceIndex` | * Source index for each channel | `[,...]`* | 187 | | `detectorIndex` | * Detector index for each channel | `[,...]`* | 188 | | `wavelengthIndex` | * Wavelength index for each channel | `[,...]`* | 189 | | `wavelengthActual` | * Actual wavelength for each channel | `[,...]` | 190 | | `wavelengthEmissionActual` | * Actual emission wavelength for each channel| `[,...]` | 191 | | `dataType` | * Data type for each channel | `[,...]`* | 192 | | `dataUnit` | * SI unit for each channel | `["s",...]` | 193 | | `dataTypeLabel` | * Data type name for each channel | `["s",...]` | 194 | | `dataTypeIndex` | * Data type index for each channel | `[,...]`* | 195 | | `sourcePower` | * Source power for each channel | `[,...]` | 196 | | `detectorGain` | * Detector gain for each channel | `[,...]` | 197 | | `stim{i}` | * Root-group for stimulus measurements | `{i}` | 198 | | `name` | * Name of the stimulus data | `"s"` + | 199 | | `data` | * Data stream of the stimulus channel | `[[,...]]` +| 200 | | `dataLabels` | * Names of additional columns of stim data | `["s",...]` | 201 | | `probe` | * Root group for NIRS probe information | `{.}` * | 202 | | `wavelengths` | * List of wavelengths (in nm) | `[,...]` * | 203 | | `wavelengthsEmission` | * List of emission wavelengths (in nm) | `[,...]` | 204 | | `sourcePos2D` | * Source 2-D positions in `LengthUnit` | `[[,...]]`*1| 205 | | `sourcePos3D` | * Source 3-D positions in `LengthUnit` | `[[,...]]`*1| 206 | | `detectorPos2D` | * Detector 2-D positions in `LengthUnit` | `[[,...]]`*2| 207 | | `detectorPos3D` | * Detector 3-D positions in `LengthUnit` | `[[,...]]`*2| 208 | | `frequencies` | * Modulation frequency list | `[,...]` | 209 | | `timeDelays` | * Time delays for gated time-domain data | `[,...]` | 210 | | `timeDelayWidths` | * Time delay width for gated time-domain data| `[,...]` | 211 | | `momentOrders` | * Moment orders of the moment TD data | `[,...]` | 212 | | `correlationTimeDelays` | * Time delays for DCS measurements | `[,...]` | 213 | | `correlationTimeDelayWidths` | * Time delay width for DCS measurements | `[,...]` | 214 | | `sourceLabels` | * String arrays specifying source names | `[["s",...]]` | 215 | | `detectorLabels` | * String arrays specifying detector names | `["s",...]` | 216 | | `landmarkPos2D` | * Anatomical landmark 2-D positions | `[[,...]]` | 217 | | `landmarkPos3D` | * Anatomical landmark 3-D positions | `[[,...]]` | 218 | | `landmarkLabels` | * String arrays specifying landmark names | `["s",...]` | 219 | | `coordinateSystem` | * Coordinate system used in probe description| `"s"` | 220 | | `coordinateSystemDescription` | * Description of coordinate system | `"s"` | 221 | | `aux{i}` | * Root-group for auxiliary measurements | `{i}` | 222 | | `name` | * Name of the auxiliary channel | `"s"` + | 223 | | `dataTimeSeries` | * Data acquired from the auxiliary channel | `[[,...]]` +| 224 | | `dataUnit` | * SI unit of the auxiliary channel | `"s"` | 225 | | `time` | * Time (in `TimeUnit`) for auxiliary data | `[,...]` + | 226 | | `timeOffset` | * Time offset of auxiliary channel data | `[,...]` | 227 | 228 | [//]: # (SCHEMA END) 229 | 230 | In the above schema table, the used notations are explained below: 231 | * `{.}` represents a simple HDF5 group 232 | * `{i}` represents an HDF5 group with one or multiple sub-groups (i.e. an indexed-group) 233 | * `` represents an integer value 234 | * `` represents a numeric value 235 | * `"s"` represents a string of arbitrary length 236 | * `[...]` represents a 1-D vector (dataset), can be empty 237 | * `[[...]]` represents a 2-D array (dataset), can be empty 238 | * `...` (optional) additional elements similar to the previous element 239 | * `*` in the last column indicates a required subfield 240 | * `*n` in the last column indicates that at least one of the subfields in the subgroup identified by `n` is required 241 | * `+` in the last column indicates a required subfield if the optional parent object is included 242 | 243 | ### SNIRF data container definitions 244 | 245 | #### /formatVersion 246 | * **Presence**: required 247 | * **Type**: string 248 | * **Location**: `/formatVersion` 249 | 250 | This is a string that specifies the version of the file format. This document 251 | describes format version "1.0" 252 | 253 | #### /nirs(i) 254 | * **Presence**: required 255 | * **Type**: indexed group 256 | * **Location**: `/nirs(i)` 257 | 258 | This group stores one set of NIRS data. This can be extended by adding the count 259 | number (e.g. `/nirs1`, `/nirs2`,...) to the group name. This is intended to 260 | allow the storage of 1 or more complete NIRS datasets inside a single SNIRF 261 | document. For example, a two-subject hyperscanning can be stored using the notation 262 | * `/nirs1` = first subject's data 263 | * `/nirs2` = second subject's data 264 | The use of a non-indexed (e.g. `/nirs`) entry is allowed when only one entry 265 | is present and is assumed to be entry 1. 266 | 267 | 268 | #### /nirs(i)/metaDataTags 269 | * **Presence**: required 270 | * **Type**: group 271 | * **Location**: `/nirs(i)/metaDataTags` 272 | 273 | The `metaDataTags` group contains the metadata associated with the measurements. 274 | Each metadata record is represented as a dataset under this group - with the name of 275 | the record, i.e. the key, as the dataset's name, and the value of the record as the 276 | actual data stored in the dataset. Each metadata record can potentially have different 277 | data types. Sub-groups should not be used to organize metadata records: a member of the `metaDataTags` Group must be a Dataset. 278 | 279 | The below five metadata records are minimally required in a SNIRF file 280 | 281 | #### /nirs(i)/metaDataTags/SubjectID 282 | * **Presence**: required as part of `metaDataTags` 283 | * **Type**: string 284 | * **Location**: `/nirs(i)/metaDataTags/SubjectID` 285 | 286 | This record stores the string-valued ID of the study subject or experiment. 287 | 288 | #### /nirs(i)/metaDataTags/MeasurementDate 289 | * **Presence**: required as part of `metaDataTags` 290 | * **Type**: string 291 | * **Location**: `/nirs(i)/metaDataTags/MeasurementDate` 292 | 293 | This record stores the date of the measurement as a string. The format of the date 294 | string must either be `"unknown"`, or follow the ISO 8601 date string format `YYYY-MM-DD`, where 295 | - `YYYY` is the 4-digit year 296 | - `MM` is the 2-digit month (padding zero if a single digit) 297 | - `DD` is the 2-digit date (padding zero if a single digit) 298 | 299 | #### /nirs(i)/metaDataTags/MeasurementTime 300 | * **Presence**: required as part of `metaDataTags` 301 | * **Type**: string 302 | * **Location**: `/nirs(i)/metaDataTags/MeasurementTime` 303 | 304 | This record stores the time of the measurement as a string. The format of the time 305 | string must either be `"unknown"` or follow the ISO 8601 time string format `hh:mm:ss.sTZD`, where 306 | - `hh` is the 2-digit hour 307 | - `mm` is the 2-digit minute 308 | - `ss` is the 2-digit second 309 | - `.s` is 1 or more digit representing a decimal fraction of a second (optional) 310 | - `TZD` is the time zone designator (`Z` or `+hh:mm` or `-hh:mm`) 311 | 312 | #### /nirs(i)/metaDataTags/LengthUnit 313 | * **Presence**: required as part of `metaDataTags` 314 | * **Type**: string 315 | * **Location**: `/nirs(i)/metaDataTags/LengthUnit` 316 | 317 | This record stores the **case-sensitive** SI length unit used in this 318 | measurement. Sample length units include "mm", "cm", and "m". A value of 319 | "um" is the same as "mm", i.e. micrometer. 320 | 321 | #### /nirs(i)/metaDataTags/TimeUnit 322 | * **Presence**: required as part of `metaDataTags` 323 | * **Type**: string 324 | * **Location**: `/nirs(i)/metaDataTags/TimeUnit` 325 | 326 | This record stores the **case-sensitive** SI time unit used in this 327 | measurement. Sample time units include "s", and "ms". A value of "us" 328 | is the same as "ms", i.e. microsecond. 329 | 330 | #### /nirs(i)/metaDataTags/FrequencyUnit 331 | * **Presence**: required as part of `metaDataTags` 332 | * **Type**: string 333 | * **Location**: `/nirs(i)/metaDataTags/FrequencyUnit` 334 | 335 | This record stores the **case-sensitive** SI frequency unit used in 336 | this measurement. Sample frequency units "Hz", "MHz" and "GHz". Please 337 | note that "mHz" is milli-Hz while "MHz" denotes "mega-Hz" according to 338 | SI unit system. 339 | 340 | We do not limit the total number of metadata records in the `metaDataTags`. Users 341 | can add additional customized metadata records; no duplicated metadata record names 342 | are allowed. 343 | 344 | Additional metadata record samples can be found in the below table. 345 | 346 | | Metadata Key Name | Metadata value | 347 | |-------------------|----------------| 348 | |ManufacturerName | "Company Name" | 349 | |Model | "Model Name" | 350 | |SubjectName | "LastName, FirstName" | 351 | |DateOfBirth | "YYYY-MM-DD" | 352 | |AcquisitionStartTime | "1569465620" | 353 | |StudyID | "Infant Brain Development" | 354 | |StudyDescription | "In this study, we measure ...." | 355 | |AccessionNumber | "##########################" | 356 | |InstanceNumber | 2 | 357 | |CalibrationFileName | "phantomcal_121015.snirf" | 358 | |UnixTime | "1569465667" | 359 | 360 | The metadata records `"StudyID"` and `"AccessionNumber"` are unique strings that 361 | can be used to link the current dataset to a particular study and a particular 362 | procedure, respectively. The `"StudyID"` tag is similar to the DICOM tag "Study 363 | ID" (0020,0010) and `"AccessionNumber"` is similar to the DICOM tag "Accession 364 | Number"(0008,0050), as defined in the DICOM standard (ISO 12052). 365 | 366 | The metadata record `"InstanceNumber"` is defined similarly to the DICOM tag 367 | "Instance Number" (0020,0013), and can be used as the sequence number to group 368 | multiple datasets into a larger dataset - for example, concatenating streamed 369 | data segments during a long measurement session. 370 | 371 | The metadata record `"UnixTime"` defines the Unix Epoch Time, i.e. the total elapse 372 | time in seconds since 1970-01-01T00:00:00Z (UTC) minus the leap seconds. 373 | 374 | #### /nirs(i)/data(j) 375 | * **Presence**: required 376 | * **Type**: indexed group 377 | * **Location**: `/nirs(i)/data(j)` 378 | 379 | This group stores one block of NIRS data. This can be extended adding the 380 | count number (e.g. `data1`, `data2`,...) to the group name. This is intended to 381 | allow the storage of 1 or more blocks of NIRS data from within the same `/nirs` 382 | entry 383 | * `/nirs/data1` = data block 1 384 | * `/nirs/data2` = data block 2 385 | 386 | 387 | #### /nirs(i)/data(j)/dataTimeSeries 388 | * **Presence**: required 389 | * **Type**: numeric 2-D array 390 | * **Location**: `/nirs(i)/data(j)/dataTimeSeries` 391 | 392 | This is the actual raw or processed data variable. This variable has dimensions 393 | of ` x `. Columns in 394 | `dataTimeSeries` are mapped to the measurement list (`measurementList` variable 395 | described below). 396 | 397 | `dataTimeSeries` can be compressed using the HDF5 filter (using the built-in 398 | [`deflate`](https://portal.hdfgroup.org/display/HDF5/H5P_SET_DEFLATE) 399 | filter or [3rd party filters such as `305-LZO` or `307-bzip2`](https://portal.hdfgroup.org/display/support/Registered+Filter+Plugins) 400 | 401 | Chunked data is allowed to support real-time streaming of data in this array. 402 | 403 | 404 | #### /nirs(i)/data(j)/dataOffset 405 | * **Presence**: optional 406 | * **Type**: numeric 1-D array 407 | * **Location**: `/nirs(i)/data(j)/dataOffset` 408 | 409 | This stores an optional offset value per channel, which, when added to 410 | `/nirs(i)/data(j)/dataTimeSeries`, results in absolute data values. 411 | 412 | The length of this array is equal to the as represented 413 | by the second dimension in the `dataTimeSeries`. 414 | 415 | 416 | #### /nirs(i)/data(j)/time 417 | * **Presence**: required 418 | * **Type**: numeric 1-D array 419 | * **Location**: `/nirs(i)/data(j)/time` 420 | 421 | The `time` variable. This provides the acquisition time of the measurement 422 | relative to the time origin. This will usually be a straight line with slope 423 | equal to the acquisition frequency, but does not need to be equal spacing. For 424 | the special case of equal sample spacing an array of length `<2>` is allowed 425 | where the first entry is the start time and the 426 | second entry is the sample time spacing in `TimeUnit` specified in the 427 | `metaDataTags`. The default time unit is in second ("s"). For example, 428 | a time spacing of 0.2 (s) indicates a sampling rate of 5 Hz. 429 | 430 | * **Option 1** - The size of this variable is `` and 431 | corresponds to the sample time of every data point 432 | * **Option 2**- The size of this variable is `<2>` and corresponds to the start 433 | time and sample spacing. 434 | 435 | Chunked data is allowed to support real-time streaming of data in this array. 436 | 437 | #### /nirs(i)/data(j)/measurementList(k) 438 | * **Presence**: required if `measurementLists` is not present 439 | * **Type**: indexed group 440 | * **Location**: `/nirs(i)/data(j)/measurementList(k)` 441 | 442 | The measurement list. This variable serves to map the data array onto the probe 443 | geometry (sources and detectors), data type, and wavelength. This variable is 444 | an array structure that has the size `` that 445 | describes the corresponding column in the data matrix. For example, the 446 | `measurementList3` describes the third column of the data matrix (i.e. 447 | `dataTimeSeries(:,3)`). 448 | 449 | Each element of the array is a structure which describes the measurement 450 | conditions for this data with the following fields: 451 | 452 | 453 | #### /nirs(i)/data(j)/measurementList(k)/sourceIndex 454 | * **Presence**: required 455 | * **Type**: integer 456 | * **Location**: `/nirs(i)/data(j)/measurementList(k)/sourceIndex` 457 | 458 | Index of the source. 459 | 460 | #### /nirs(i)/data(j)/measurementList(k)/detectorIndex 461 | * **Presence**: required 462 | * **Type**: integer 463 | * **Location**: `/nirs(i)/data(j)/measurementList(k)/detectorIndex` 464 | 465 | Index of the detector. 466 | 467 | #### /nirs(i)/data(j)/measurementList(k)/wavelengthIndex 468 | * **Presence**: required 469 | * **Type**: integer 470 | * **Location**: `/nirs(i)/data(j)/measurementList(k)/wavelengthIndex` 471 | 472 | Index of the "nominal" wavelength (in `probe.wavelengths`). 473 | 474 | #### /nirs(i)/data(j)/measurementList(k)/wavelengthActual 475 | * **Presence**: optional 476 | * **Type**: numeric 477 | * **Location**: `/nirs(i)/data(j)/measurementList(k)/wavelengthActual` 478 | 479 | Actual (measured) wavelength in nm, if available, for the source in a given channel. 480 | 481 | #### /nirs(i)/data(j)/measurementList(k)/wavelengthEmissionActual 482 | * **Presence**: optional 483 | * **Type**: numeric 484 | * **Location**: `/nirs(i)/data(j)/measurementList(k)/wavelengthEmissionActual` 485 | 486 | Actual (measured) emission wavelength in nm, if available, for the source in a given channel. 487 | 488 | #### /nirs(i)/data(j)/measurementList(k)/dataType 489 | * **Presence**: required 490 | * **Type**: integer 491 | * **Location**: `/nirs(i)/data(j)/measurementList(k)/dataType` 492 | 493 | Data-type identifier. See Appendix for list possible values. 494 | 495 | #### /nirs(i)/data(j)/measurementList(k)/dataUnit 496 | * **Presence**: optional 497 | * **Type**: string 498 | * **Location**: `/nirs(i)/data(j)/measurementList(k)/dataUnit` 499 | 500 | International System of Units (SI units) identifier for the given channel. Encoding should follow the [CMIXF-12 standard](https://people.csail.mit.edu/jaffer/MIXF/CMIXF-12), avoiding special unicode symbols like U+03BC (m) or U+00B5 (u) and using '/' rather than 'per' for units such as `V/us`. The recommended export format is in unscaled units such as V, s, Mole. 501 | 502 | #### /nirs(i)/data(j)/measurementList(k)/dataTypeLabel 503 | * **Presence**: optional 504 | * **Type**: string 505 | * **Location**: `/nirs(i)/data(j)/measurementList(k)/dataTypeLabel` 506 | 507 | Data-type label. Only required if dataType is "processed" (`99999`). See Appendix 508 | for list of possible values. 509 | 510 | #### /nirs(i)/data(j)/measurementList(k)/dataTypeIndex 511 | * **Presence**: required 512 | * **Type**: integer 513 | * **Location**: `/nirs(i)/data(j)/measurementList(k)/dataTypeIndex` 514 | 515 | Data-type specific parameter index. The data type index specifies additional data type specific parameters that are further elaborated by other fields in the probe structure, as detailed below. Note that where multiple parameters are required, the same index must be used into each (examples include data types such as Time Domain and Diffuse Correlation Spectroscopy). One use of this parameter is as a stimulus condition index when `measurementList(k).dataType = 99999` (i.e, `processed` and `measurementList(k).dataTypeLabel = 'HRF ...'` . 516 | 517 | #### /nirs(i)/data(j)/measurementList(k)/sourcePower 518 | * **Presence**: optional 519 | * **Type**: numeric 520 | * **Location**: `/nirs(i)/data(j)/measurementList(k)/sourcePower` 521 | 522 | The units are not defined, unless the user takes the option of using a `metaDataTag` as described below. 523 | 524 | #### /nirs(i)/data(j)/measurementList(k)/detectorGain 525 | * **Presence**: optional 526 | * **Type**: numeric 527 | * **Location**: `/nirs(i)/data(j)/measurementList(k)/detectorGain` 528 | 529 | Detector gain 530 | 531 | For example, if `measurementList5` is a structure with `sourceIndex=2`, 532 | `detectorIndex=3`, `wavelengthIndex=1`, `dataType=1`, `dataTypeIndex=1` would 533 | imply that the data in the 5th column of the `dataTimeSeries` variable was 534 | measured with source #2 and detector #3 at wavelength #1. Wavelengths (in 535 | nanometers) are described in the `probe.wavelengths` variable (described 536 | later). The data type in this case is 1, implying that it was a continuous wave 537 | measurement. The complete list of currently supported data types is found in 538 | the Appendix. The data type index specifies additional data type specific 539 | parameters that are further elaborated by other fields in the `probe` 540 | structure, as detailed below. Note that the Time Domain and Diffuse Correlation 541 | Spectroscopy data types have two additional parameters and so the data type 542 | index must be a vector with 2 elements that index the additional parameters. 543 | 544 | `sourcePower` provides the option for information about the source power for 545 | that channel to be saved along with the data. The units are not defined, unless 546 | the user takes the option of using a `metaDataTag` described below to define, 547 | for instance, `sourcePowerUnit`. `detectorGain` provides the option for 548 | information about the detector gain for that channel to be saved along with the 549 | data. 550 | 551 | Note: The source indices generally refer to the optode naming (probe 552 | positions) and not necessarily the physical laser numbers on the instrument. 553 | The same is true for the detector indices. Each source optode would generally, 554 | but not necessarily, have 2 or more wavelengths (hence lasers) plugged into it 555 | in order to calculate deoxy- and oxy-hemoglobin concentrations. The data from 556 | these two wavelengths will be indexed by the same source, detector, and data 557 | type values, but have different wavelength indices. Using the same source index 558 | for lasers at the same location but with different wavelengths simplifies the 559 | bookkeeping for converting intensity measurements into concentration changes. 560 | As described below, optional variables `probe.sourceLabels` and 561 | `probe.detectorLabels` are provided for indicating the instrument specific 562 | label for sources and detectors. 563 | 564 | #### /nirs(i)/data(j)/measurementLists 565 | * **Presence**: required if measurementList is not present 566 | * **Type**: group 567 | * **Location**: `/nirs(i)/data(j)/measurementLists` 568 | 569 | The group for measurement list variables which map the data array onto the probe geometry (sources and detectors), data type, and wavelength. This group's datasets are arrays with size ``, with each position describing the corresponding column in the data matrix. (i.e. the values at `measurementLists/sourceIndex(3)` and `measurementLists/detectorIndex(3)` correspond to `dataTimeSeries(:,3)`). 570 | 571 | This group is required only if the indexed-group format `/nirs(i)/data(j)/measurementList(k)` is not used to encode the measurement list. `measurementLists` is an alternative that may offer better performance for larger probes. 572 | 573 | The arrays of `measurementLists` are: 574 | 575 | #### /nirs(i)/data(j)/measurementLists/sourceIndex 576 | * **Presence**: required if measurementLists is present 577 | * **Type**: integer 1-D array 578 | * **Location**: `/nirs(i)/data(j)/measurementLists/sourceIndex` 579 | 580 | Source indices for each channel. A 1-D array with length equal to the size of the second dimension of `/nirs(i)/data(j)/dataTimeSeries`. 581 | 582 | #### /nirs(i)/data(j)/measurementLists/detectorIndex 583 | * **Presence**: required if measurementLists is present 584 | * **Type**: integer 1-D array 585 | * **Location**: `/nirs(i)/data(j)/measurementLists/detectorIndex` 586 | 587 | Detector indices for each channel. A 1-D array with length equal to the size of the second dimension of `/nirs(i)/data(j)/dataTimeSeries`. 588 | 589 | #### /nirs(i)/data(j)/measurementLists/wavelengthIndex 590 | * **Presence**: required if measurementLists is present 591 | * **Type**: integer 1-D array 592 | * **Location**: `/nirs(i)/data(j)/measurementLists/wavelengthIndex` 593 | 594 | Index of the "nominal" wavelength (in `probe.wavelengths`) for each channel. A 1-D array with length equal to the size of the second dimension of `/nirs(i)/data(j)/dataTimeSeries`. 595 | 596 | #### /nirs(i)/data(j)/measurementLists/wavelengthActual 597 | * **Presence**: optional 598 | * **Type**: numeric 1-D array 599 | * **Location**: `/nirs(i)/data(j)/measurementLists/wavelengthActual` 600 | 601 | Actual (measured) wavelength in nm, if available, for the source in each channel. A 1-D array with length equal to the size of the second dimension of `/nirs(i)/data(j)/dataTimeSeries`. 602 | 603 | #### /nirs(i)/data(j)/measurementLists/wavelengthEmissionActual 604 | * **Presence**: optional 605 | * **Type**: numeric 1-D array 606 | * **Location**: `/nirs(i)/data(j)/measurementLists/wavelengthEmissionActual` 607 | 608 | Actual (measured) emission wavelength in nm, if available, for the source in each channel. A 1-D array with length equal to the size of the second dimension of `/nirs(i)/data(j)/dataTimeSeries`. 609 | 610 | #### /nirs(i)/data(j)/measurementLists/dataType 611 | * **Presence**: required if measurementLists is present 612 | * **Type**: integer 1-D array 613 | * **Location**: `/nirs(i)/data(j)/measurementLists/dataType` 614 | 615 | A 1-D array with length equal to the size of the second dimension of `/nirs(i)/data(j)/dataTimeSeries`. See Appendix for list of possible values. 616 | 617 | #### /nirs(i)/data(j)/measurementLists/dataUnit 618 | * **Presence**: optional 619 | * **Type**: string 1-D array 620 | * **Location**: `/nirs(i)/data(j)/measurementLists/dataUnit` 621 | 622 | International System of Units (SI units) identifier for each channel. A 1-D array with length equal to the size of the second dimension of `/nirs(i)/data(j)/dataTimeSeries`. 623 | 624 | #### /nirs(i)/data(j)/measurementLists/dataTypeLabel 625 | * **Presence**: optional 626 | * **Type**: string 1-D array 627 | * **Location**: `/nirs(i)/data(j)/measurementLists/dataTypeLabel` 628 | 629 | Data-type label. A 1-D array with length equal to the size of the second dimension of `/nirs(i)/data(j)/dataTimeSeries`. 630 | 631 | #### /nirs(i)/data(j)/measurementLists/dataTypeIndex 632 | * **Presence**: required if measurementLists is present 633 | * **Type**: integer 1-D array 634 | * **Location**: `/nirs(i)/data(j)/measurementLists/dataTypeIndex` 635 | 636 | Data-type specific parameter indices. A 1-D array with length equal to the size of the second dimension of `/nirs(i)/data(j)/dataTimeSeries`. Note that the Time Domain and Diffuse Correlation Spectroscopy data types have two additional parameters and so `dataTimeIndex` must be a 2-D array with 2 columns that index the additional parameters. 637 | 638 | #### /nirs(i)/data(j)/measurementLists/sourcePower 639 | * **Presence**: optional 640 | * **Type**: numeric 1-D array 641 | * **Location**: `/nirs(i)/data(j)/measurementLists/sourcePower` 642 | 643 | A 1-D array with length equal to the size of the second dimension of `/nirs(i)/data(j)/dataTimeSeries`. Units are optionally defined in `metaDataTags`. 644 | 645 | #### /nirs(i)/data(j)/measurementLists/detectorGain 646 | * **Presence**: optional 647 | * **Type**: numeric 1-D array 648 | * **Location**: `/nirs(i)/data(j)/measurementLists/detectorGain` 649 | 650 | A 1-D array with length equal to the size of the second dimension of `/nirs(i)/data(j)/dataTimeSeries`. Units are optionally defined in `metaDataTags`. 651 | 652 | #### /nirs(i)/stim(j) 653 | * **Presence**: optional 654 | * **Type**: indexed group 655 | * **Location**: `/nirs(i)/stim(j)` 656 | 657 | This is an array describing any stimulus conditions. Each element of the array 658 | has the following required fields. 659 | 660 | 661 | #### /nirs(i)/stim(j)/name 662 | * **Presence**: required as part of `stim(i)` 663 | * **Type**: string 664 | * **Location**: `/nirs(i)/stim(j)/name` 665 | 666 | This is a string describing the jth stimulus condition. 667 | 668 | 669 | #### /nirs(i)/stim(j)/data 670 | * **Presence**: required as part of `stim(i)` 671 | * **Type**: numeric 2-D array 672 | * **Location**: `/nirs(i)/stim(j)/data` 673 | * **Allowed attribute**: `names` 674 | 675 | This is a numeric 2-D array with at least 3 columns, specifying the stimulus 676 | time course for the jth condition. Each row corresponds to a 677 | specific stimulus trial. The first three columns indicate `[starttime duration value]`. 678 | The starttime, in seconds, is the time relative to the time origin when the 679 | stimulus takes on a value; the duration is the time in seconds that the stimulus 680 | value continues, and value is the stimulus amplitude. The number of rows is 681 | not constrained. (see examples in the appendix). 682 | 683 | Additional columns can be used to store user-specified data associated with 684 | each stimulus trial. An optional record `/nirs(i)/stim(j)/dataLabels` can be 685 | used to annotate the meanings of each data column. 686 | 687 | #### /nirs(i)/stim(j)/dataLabels 688 | * **Presence**: optional 689 | * **Type**: string 1-D array 690 | * **Location**: `/nirs(i)/stim(j)/dataLabels(k)` 691 | 692 | This is a string array providing annotations for each data column in 693 | `/nirs(i)/stim(j)/data`. Each element of the array must be a string; 694 | the total length of this array must be the same as the column number 695 | of `/nirs(i)/stim(j)/data`, including the first 3 required columns. 696 | 697 | #### /nirs(i)/probe 698 | * **Presence**: required 699 | * **Type**: group 700 | * **Location**: `/nirs(i)/probe ` 701 | 702 | This is a structured variable that describes the probe (source-detector) 703 | geometry. This variable has a number of required fields. 704 | 705 | #### /nirs(i)/probe/wavelengths 706 | * **Presence**: required 707 | * **Type**: numeric 1-D array 708 | * **Location**: `/nirs(i)/probe/wavelengths` 709 | 710 | This field describes the "nominal" wavelengths used (in `nm` unit). This is indexed by the 711 | `wavelengthIndex` of the measurementList variable. For example, `probe.wavelengths` = [690, 712 | 780, 830]; implies that the measurements were taken at three wavelengths (690 nm, 713 | 780 nm, and 830 nm). The wavelength index of 714 | `measurementList(k).wavelengthIndex` variable refers to this field. 715 | `measurementList(k).wavelengthIndex` = 2 means the kth measurement 716 | was at 780 nm. 717 | 718 | Please note that this field stores the "nominal" wavelengths. If the precise 719 | (measured) wavelengths differ from the nominal wavelengths, one can store those 720 | in the `measurementList.wavelengthActual` field in a per-channel fashion. 721 | 722 | The number of wavelengths is not limited (except that at least two are needed 723 | to calculate the two forms of hemoglobin). Each source-detector pair would 724 | generally have measurements at all wavelengths. 725 | 726 | This field must present, but can be empty, for example, in the case that the stored 727 | data are processed data (`dataType=99999`, see Appendix). 728 | 729 | 730 | #### /nirs(i)/probe/wavelengthsEmission 731 | * **Presence**: optional 732 | * **Type**: numeric 1-D array 733 | * **Location**: `/nirs(i)/probe/wavelengthsEmission` 734 | 735 | This field is required only for fluorescence data types, and describes the 736 | "nominal" emission wavelengths used (in `nm` unit). The indexing of this variable is the same 737 | wavelength index in measurementList used for `probe.wavelengths` such that the 738 | excitation wavelength is paired with this emission wavelength for a given measurement. 739 | 740 | Please note that this field stores the "nominal" emission wavelengths. If the precise 741 | (measured) emission wavelengths differ from the nominal ones, one can store those 742 | in the `measurementList.wavelengthEmissionActual` field in a per-channel fashion. 743 | 744 | 745 | #### /nirs(i)/probe/sourcePos2D 746 | * **Presence**: at least one of `sourcePos2D` or `sourcePos3D` is required 747 | * **Type**: numeric 2-D array 748 | * **Location**: `/nirs(i)/probe/sourcePos2D` 749 | 750 | This field describes the position (in `LengthUnit` units) of each source 751 | optode. The positions are coordinates in a flattened 2D probe layout. 752 | This field has size ` x 2`. For example, 753 | `probe.sourcePos2D(1,:) = [1.4 1]`, and `LengthUnit='cm'` places source 754 | number 1 at x=1.4 cm and y=1 cm. 755 | 756 | 757 | #### /nirs(i)/probe/sourcePos3D 758 | * **Presence**: at least one of `sourcePos2D` or `sourcePos3D` is required 759 | * **Type**: numeric 2-D array 760 | * **Location**: `/nirs(i)/probe/sourcePos3D` 761 | 762 | This field describes the position (in `LengthUnit` units) of each source 763 | optode in 3D. This field has size ` x 3`. 764 | 765 | 766 | #### /nirs(i)/probe/detectorPos2D 767 | * **Presence**: at least one of `detectorPos2D` or `detectorPos3D` is required 768 | * **Type**: numeric 2-D array 769 | * **Location**: `/nirs(i)/probe/detectorPos2D` 770 | 771 | Same as `probe.sourcePos2D`, but describing the detector positions in a 772 | flattened 2D probe layout. 773 | 774 | 775 | #### /nirs(i)/probe/detectorPos3D 776 | * **Presence**: at least one of `detectorPos2D` or `detectorPos3D` is required 777 | * **Type**: numeric 2-D array 778 | * **Location**: `/nirs(i)/probe/detectorPos3D` 779 | 780 | This field describes the position (in `LengthUnit` units) of each detector 781 | optode in 3D, defined similarly to `sourcePos3D`. 782 | 783 | 784 | #### /nirs(i)/probe/frequencies 785 | * **Presence**: optional 786 | * **Type**: numeric 1-D array 787 | * **Location**: `/nirs(i)/probe/frequencies` 788 | 789 | This field describes the frequencies used (in `FrequencyUnit` units) for 790 | frequency domain measurements. This field is only required for frequency 791 | domain data types, and is indexed by `measurementList(k).dataTypeIndex`. 792 | 793 | 794 | #### /nirs(i)/probe/timeDelays 795 | * **Presence**: optional 796 | * **Type**: numeric 1-D array 797 | * **Location**: `/nirs(i)/probe/timeDelays` 798 | 799 | This field describes the time delays (in `TimeUnit` units) used for gated time domain measurements. 800 | This field is only required for gated time domain data types, and is indexed by 801 | `measurementList(k).dataTypeIndex`. The indexing of this field is paired with 802 | the indexing of `probe.timeDelayWidths`. 803 | 804 | 805 | #### /nirs(i)/probe/timeDelayWidths 806 | * **Presence**: optional 807 | * **Type**: numeric 1-D array 808 | * **Location**: `/nirs(i)/probe/timeDelayWidths` 809 | 810 | This field describes the time delay widths (in `TimeUnit` units) used for gated time domain 811 | measurements. This field is only required for gated time domain data types, and 812 | is indexed by `measurementList(k).dataTypeIndex`. The indexing of this field 813 | is paired with the indexing of `probe.timeDelays`. 814 | 815 | 816 | #### /nirs(i)/probe/momentOrders 817 | * **Presence**: optional 818 | * **Type**: numeric 1-D array 819 | * **Location**: `/nirs(i)/probe/momentOrders` 820 | 821 | This field describes the moment orders of the temporal point spread function (TPSF) or the distribution of time-of-flight (DTOF) 822 | for moment time domain measurements. This field is only required for moment time domain data types, and is indexed by `measurementList(k).dataTypeIndex`. 823 | Note that the numeric value in this array is the exponent in the integral used for calculating the moments. For detailed/specific definitions of moments, see [Wabnitz et al, 2020](https://doi.org/10.1364/BOE.396585); for general definitions of moments see [here](https://en.wikipedia.org/wiki/Moment_(mathematics) ). 824 | 825 | In brief, given a TPSF or DTOF N(t) (photon counts vs. photon arrival time at the detector): \ 826 | momentOrder = 0: total counts: `N_total = \intergral N(t)dt` \ 827 | momentOrder = 1: mean time of flight: `m = = (1/N_total) \integral t N(t) dt` \ 828 | momentOrder = 2: variance/second central moment: `V = (1/N_total) \integral (t - )^2 N(t) dt` \ 829 | Please note that all moments (for orders >=1) are expected to be normalized by the total counts (i.e. n=0); Additionally all moments (for orders >= 2) are expected to be centralized. 830 | 831 | 832 | #### /nirs(i)/probe/correlationTimeDelays 833 | * **Presence**: optional 834 | * **Type**: numeric 1-D array 835 | * **Location**: `/nirs(i)/probe/correlationTimeDelays` 836 | 837 | This field describes the time delays (in `TimeUnit` units) used for diffuse correlation spectroscopy 838 | measurements. This field is only required for diffuse correlation spectroscopy 839 | data types, and is indexed by `measurementList(k).dataTypeIndex`. The indexing 840 | of this field is paired with the indexing of `probe.correlationTimeDelayWidths`. 841 | 842 | 843 | #### /nirs(i)/probe/correlationTimeDelayWidths 844 | * **Presence**: optional 845 | * **Type**: numeric 1-D array 846 | * **Location**: `/nirs(i)/probe/correlationTimeDelayWidth` 847 | 848 | This field describes the time delay widths (in `TimeUnit` units) used for diffuse correlation 849 | spectroscopy measurements. This field is only required for gated time domain 850 | data types, and is indexed by `measurementList(k).dataTypeIndex`. The indexing 851 | of this field is paired with the indexing of `probe.correlationTimeDelays`. 852 | 853 | 854 | #### /nirs(i)/probe/sourceLabels 855 | * **Presence**: optional 856 | * **Type**: string 2-D array 857 | * **Location**: `/nirs(i)/probe/sourceLabels(j)` 858 | 859 | This is a string array providing user friendly or instrument specific labels 860 | for each source. Each element of the array must be a unique string among both 861 | `probe.sourceLabels` and `probe.detectorLabels`.This can be of size `x 1` or ` x `. This is indexed by `measurementList(k).sourceIndex` and 864 | `measurementList(k).wavelengthIndex`. 865 | 866 | 867 | #### /nirs(i)/probe/detectorLabels 868 | * **Presence**: optional 869 | * **Type**: string 1-D array 870 | * **Location**: `/nirs(i)/probe/detectorLabels(j)` 871 | 872 | This is a string array providing user friendly or instrument specific labels 873 | for each detector. Each element of the array must be a unique string among both 874 | `probe.sourceLabels` and `probe.detectorLabels`. This is indexed by 875 | `measurementList(k).detectorIndex`. 876 | 877 | 878 | #### /nirs(i)/probe/landmarkPos2D 879 | * **Presence**: optional 880 | * **Type**: numeric 2-D array 881 | * **Location**: `/nirs(i)/probe/landmarkPos2D` 882 | 883 | This is a 2-D array storing the neurological landmark positions projected 884 | along the 2-D (flattened) probe plane in order to map optical data from the 885 | flattened optode positions to brain anatomy. This array should contain a minimum 886 | of 2 columns, representing the x and y coordinates (in `LengthUnit` units) 887 | of the 2-D projected landmark positions. If a 3rd column presents, it stores 888 | the index to the labels of the given landmark. Label names are stored in the 889 | `probe.landmarkLabels` subfield. An label index of 0 refers to an undefined landmark. 890 | 891 | 892 | #### /nirs(i)/probe/landmarkPos3D 893 | * **Presence**: optional 894 | * **Type**: numeric 2-D array 895 | * **Location**: `/nirs(i)/probe/landmarkPos3D` 896 | 897 | This is a 2-D array storing the neurological landmark positions measurement 898 | from 3-D digitization and tracking systems to facilitate the registration and 899 | mapping of optical data to brain anatomy. This array should contain a minimum 900 | of 3 columns, representing the x, y and z coordinates (in `LengthUnit` units) 901 | of the digitized landmark positions. If a 4th column presents, it stores the 902 | index to the labels of the given landmark. Label names are stored in the 903 | `probe.landmarkLabels` subfield. An label index of 0 refers to an undefined landmark. 904 | 905 | 906 | #### /nirs(i)/probe/landmarkLabels(j) 907 | * **Presence**: optional 908 | * **Type**: string 1-D array 909 | * **Location**: `/nirs(i)/probe/landmarkLabels(j)` 910 | 911 | This string array stores the names of the landmarks. The first string denotes 912 | the name of the landmarks with an index of 1 in the 4th column of 913 | `probe.landmark`, and so on. One can adopt the commonly used 10-20 landmark 914 | names, such as "Nasion", "Inion", "Cz" etc, or use user-defined landmark 915 | labels. The landmark label can also use the unique source and detector labels 916 | defined in `probe.sourceLabels` and `probe.detectorLabels`, respectively, to 917 | associate the given landmark to a specific source or detector. All strings are 918 | ASCII encoded char arrays. 919 | 920 | 921 | #### /nirs(i)/probe/coordinateSystem 922 | * **Presence**: optional 923 | * **Type**: string 924 | * **Location**: `/nirs(i)/probe/coordinateSystem` 925 | 926 | Defines the coordinate system for sensor positions. 927 | The string must be one of the coordinate systems listed in the 928 | [BIDS specification (Appendix VII)](https://bids-specification.readthedocs.io/en/stable/99-appendices/08-coordinate-systems.html#standard-template-identifiers) 929 | such as "MNI152NLin2009bAsym", "CapTrak" or "Other". 930 | If the value "Other" is specified, then a defition of the coordinate 931 | system must be provided in `/nirs(i)/probe/coordinateSystemDescription`. 932 | See the [FieldTrip toolbox web page](https://www.fieldtriptoolbox.org/faq/coordsys/) 933 | for detailed descriptions of different coordinate systems. 934 | 935 | 936 | #### /nirs(i)/probe/coordinateSystemDescription 937 | * **Presence**: optional 938 | * **Type**: string 939 | * **Location**: `/nirs(i)/probe/coordinateSystemDescription` 940 | 941 | Free-form text description of the coordinate system. 942 | May also include a link to a documentation page or 943 | paper describing the system in greater detail. 944 | This field is required if the `coordinateSystem` field is set to "Other". 945 | 946 | 947 | #### /nirs(i)/aux(j) 948 | * **Presence**: optional 949 | * **Type**: indexed group 950 | * **Location**: `/nirs(i)/aux(j)` 951 | 952 | This optional array specifies any recorded auxiliary data. Each element of 953 | `aux` has the following required fields: 954 | 955 | #### /nirs(i)/aux(j)/name 956 | * **Presence**: optional; required if `aux` is used 957 | * **Type**: string 958 | * **Location**: `/nirs(i)/aux(j)/name` 959 | 960 | This is string describing the jth auxiliary data timecourse. While auxiliary data can be given any title, standard names for commonly used auxiliary channels (i.e. accelerometer data) are specified in the appendix. 961 | 962 | #### /nirs(i)/aux(j)/dataTimeSeries 963 | * **Presence**: optional; required if `aux` is used 964 | * **Type**: numeric 2-D array 965 | * **Location**: `/nirs(i)/aux(j)/dataTimeSeries` 966 | 967 | This is the aux data variable. This variable has dimensions of ` x `. If multiple channels of related data are generated by a system, they may be encoded in the multiple columns of the time series (i.e. complex numbers). For example, a system containing more than one accelerometer may output this data as a set of `ACCEL_X`/`ACCEL_Y`/`ACCEL_Z` auxiliary time series, where each has the dimension of ` x `. Note that it is NOT recommended to encode the various accelerometer dimensions as multiple channels of the same `aux` Group: instead follow the `"ACCEL_X"`, `"ACCEL_Y"`, `"ACCEL_Z"` naming conventions described in the appendix. Chunked data is allowed to support real-time data streaming. 969 | 970 | #### /nirs(i)/aux(j)/dataUnit 971 | * **Presence**: optional 972 | * **Type**: string 973 | * **Location**: `/nirs(i)/aux(j)/dataUnit` 974 | 975 | International System of Units (SI units) identifier for the given channel. Encoding should follow the [CMIXF-12 standard](https://people.csail.mit.edu/jaffer/MIXF/CMIXF-12), avoiding special unicode symbols like U+03BC (m) or U+00B5 (u) and using '/' rather than 'per' for units such as `V/us`. The recommended export format is in unscaled units such as V, s, Mole. 976 | 977 | #### /nirs(i)/aux(j)/time 978 | * **Presence**: optional; required if `aux` is used 979 | * **Type**: numeric 1-D array 980 | * **Location**: `/nirs(i)/aux(j)/time` 981 | 982 | The time variable. This provides the acquisition time (in `TimeUnit` units) 983 | of the aux measurement relative to the time origin. This will usually be 984 | a straight line with slope equal to the acquisition frequency, but does 985 | not need to be equal spacing. The size of this variable is 986 | `` or `<2>` similar to definition of the 987 | `/nirs(i)/data(j)/time` field. 988 | 989 | Chunked data is allowed to support real-time data streaming 990 | 991 | #### /nirs(i)/aux(j)/timeOffset 992 | * **Presence**: optional 993 | * **Type**: numeric 994 | * **Location**: `/nirs(i)/aux(j)/timeOffset` 995 | 996 | This variable specifies the offset of the file time origin relative to absolute 997 | (clock) time in `TimeUnit` units. 998 | 999 | 1000 | ## Appendix 1001 | 1002 | ### Supported `measurementList(k).dataType` values in `dataTimeSeries` 1003 | 1004 | + 001-100: Raw - Continuous Wave (CW) 1005 | - 001 - Amplitude 1006 | - 051 - Fluorescence Amplitude 1007 | 1008 | + 101-200: Raw - Frequency Domain (FD) 1009 | - 101 - AC Amplitude 1010 | - 102 - Phase 1011 | - 151 - Fluorescence Amplitude 1012 | - 152 - Fluorescence Phase 1013 | 1014 | + 201-300: Raw - Time Domain - Gated (TD Gated) 1015 | - 201 - Amplitude 1016 | - 251 - Fluorescence Amplitude 1017 | + 301-400: Raw - Time domain - Moments (TD Moments) 1018 | - 301 - Amplitude 1019 | - 351 - Fluorescence Amplitude 1020 | + 401-500: Raw - Diffuse Correlation Spectroscopy (DCS): 1021 | - 401 - g2 1022 | - 410 - BFi 1023 | + 99999: Processed 1024 | 1025 | 1026 | ### Supported `measurementList(k).dataTypeLabel` values in `dataTimeSeries` 1027 | 1028 | | Tag Name | Meanings | 1029 | |-----------|------------------------------------------------------------------| 1030 | |"dOD" | Change in optical density | 1031 | |"dMean" | Change in mean time-of-flight | 1032 | |"dVar" | Change in variance (2nd central moment) | 1033 | |"dSkew" | Change in skewness (3rd central moment) | 1034 | |"mua" | Absorption coefficient | 1035 | |"musp" | Scattering coefficient | 1036 | |"HbO" | Oxygenated hemoglobin (oxyhemoglobin) concentration | 1037 | |"HbR" | Deoxygenated hemoglobin (deoxyhemoglobin) concentration | 1038 | |"HbT" | Total hemoglobin concentration | 1039 | |"H2O" | Water content | 1040 | |"Lipid" | Lipid concentration | 1041 | |"StO2" | Tissue oxygen saturation | 1042 | |"BFi" | Blood flow index | 1043 | |"HRF dOD" | Hemodynamic response function for change in optical density | 1044 | |"HRF dMean"| HRF for change in mean time-of-flight | 1045 | |"HRF dVar" | HRF for change in variance (2nd central moment) | 1046 | |"HRF dSkew"| HRF for change in skewness (3rd central moment) | 1047 | |"HRF HbO" | Hemodynamic response function for oxyhemoglobin concentration | 1048 | |"HRF HbR" | Hemodynamic response function for deoxyhemoglobin concentration | 1049 | |"HRF HbT" | Hemodynamic response function for total hemoglobin concentration | 1050 | |"HRF BFi" | Hemodynamic response function for blood flow index | 1051 | 1052 | 1053 | ### Supported `/nirs(i)/aux(j)/name` values 1054 | 1055 | | Tag Name | Meanings | 1056 | |-----------|------------------------------------------------------------------| 1057 | |"ACCEL_X" | Accelerometer data, first axis of orientation | 1058 | |"ACCEL_Y" | Accelerometer data, second axis of orientation | 1059 | |"ACCEL_Z" | Accelerometer data, third axis of orientation | 1060 | |"GYRO_X" | Gyrometer data, first axis of orientation | 1061 | |"GYRO_Y" | Gyrometer data, second axis of orientation | 1062 | |"GYRO_Z" | Gyrometer data, third axis of orientation | 1063 | |"MAGN_X" | Magnetometer data, first axis of orientation | 1064 | |"MAGN_Y" | Magnetometer data, second axis of orientation | 1065 | |"MAGN_Z" | Magnetometer data, third axis of orientation | 1066 | 1067 | 1068 | ### Examples of stimulus waveforms 1069 | 1070 | Assume there are 10 time points, starting at zero, spaced 0.1s apart. If we 1071 | assume a stimulus to be a 0.2 second off, 0.2 second on repeating block, it 1072 | would be specified as follows: 1073 | ``` 1074 | [0.2 0.2 1.0] 1075 | [0.6 0.2 1.0] 1076 | ``` 1077 | 1078 | ### Code samples 1079 | 1080 | The following code demonstrates how to use the Python `h5py` and `numpy` libraries and the MATLAB `H5ML.hdf5lib2` "low-level" interface to write specified SNIRF datatypes to disk as HDF5 Datasets of the proper format. 1081 | 1082 | #### String `"s"` 1083 | 1084 | **MATLAB** 1085 | ```matlab 1086 | fid = H5F.open(, 'H5F_ACC_RDWR', 'H5P_DEFAULT') 1087 | sid = H5S.create('H5S_SCALAR') 1088 | tid = H5T.copy('H5T_C_S1'); 1089 | H5T.set_size(tid, 'H5T_VARIABLE'); 1090 | did = H5D.create(fid, , tid, sid, 'H5P_DEFAULT') 1091 | H5D.write(did, tid, 'H5S_ALL', 'H5S_ALL', 'H5P_DEFAULT', ) 1092 | ``` 1093 | **Python** 1094 | ```python 1095 | file = h5py.File(, 'r+') 1096 | varlen_str_dtype = h5py.string_dtype(encoding='ascii', length=None) 1097 | file.create_dataset(, dtype=varlen_str_dtype, data=) 1098 | ``` 1099 | 1100 | #### numeric `` 1101 | 1102 | **MATLAB** 1103 | ```matlab 1104 | fid = H5F.open(, 'H5F_ACC_RDWR', 'H5P_DEFAULT') 1105 | tid = H5T.copy('H5T_NATIVE_DOUBLE') 1106 | sid = H5S.create('H5S_SCALAR') 1107 | H5D.create(fid, , tid, sid, 'H5P_DEFAULT') 1108 | h5write(, , ) 1109 | ``` 1110 | **Python** 1111 | ```python 1112 | file = h5py.File(, 'r+') 1113 | file.create_dataset(, dtype='f8', data=) 1114 | ``` 1115 | 1116 | #### integer `` 1117 | **MATLAB** 1118 | ```matlab 1119 | fid = H5F.open(, 'H5F_ACC_RDWR', 'H5P_DEFAULT') 1120 | tid = H5T.copy('H5T_NATIVE_INT') 1121 | sid = H5S.create('H5S_SCALAR') 1122 | H5D.create(fid, , tid, sid, 'H5P_DEFAULT') 1123 | h5write(, , ) 1124 | ``` 1125 | **Python** 1126 | ```python 1127 | file = h5py.File(, 'r+') 1128 | file.create_dataset(, dtype='i4', data=) 1129 | ``` 1130 | 1131 | #### string array `["s",...]` 1132 | **MATLAB** 1133 | ```matlab 1134 | fid = H5F.open(, 'H5F_ACC_RDWR', 'H5P_DEFAULT') 1135 | 1136 | str_arr = {'Hello', 'World', 'foo', 'bar'} % values to write, a cell array of strings of any length 1137 | 1138 | sid = H5S.create_simple(1, numel(str_arr), H5ML.get_constant_value('H5S_UNLIMITED')); 1139 | 1140 | tid = H5T.copy('H5T_C_S1'); 1141 | H5T.set_size(tid, 'H5T_VARIABLE'); 1142 | 1143 | pid = H5P.create('H5P_DATASET_CREATE'); 1144 | H5P.set_chunk(pid, 2); 1145 | 1146 | did = H5D.create(fid, , tid, sid, pid) 1147 | 1148 | H5D.write(did, tid, 'H5S_ALL', 'H5S_ALL', 'H5P_DEFAULT', str_arr) 1149 | ``` 1150 | **Python** 1151 | ```python 1152 | array = numpy.array().astype('O') # A list of strings must be converted to a NumPy list with dtype 'O' 1153 | file = h5py.File(, 'r+') 1154 | varlen_str_dtype = h5py.string_dtype(encoding='ascii', length=None) 1155 | file.create_dataset(, dtype=varlen_str_dtype, data=array) 1156 | ``` 1157 | #### numeric array `[,...]` or `[[,...]]` 1158 | **MATLAB** 1159 | > Note: Because MATLAB has no notion of arrays with fewer than 2 dimensions, using `size(data)` as the 3rd argument of 1160 | `h5create` will erroneously save arrays with 1 dimension as a row or column vector of 2 dimensions. In the 1D case, use `length(data)` as the 3rd argument of `h5create`. 1161 | ```matlab 1162 | data = 1163 | h5create(, , length(data) / size(data), 'Datatype', 'double') 1164 | h5write(, , data) 1165 | ``` 1166 | **Python** 1167 | ```python 1168 | array = numpy.array().astype(numpy.float64) # A list or nested list of values should be converted to a NumPy array 1169 | file = h5py.File(, 'r+') 1170 | file.create_dataset(, dtype='f8', data=array) 1171 | ``` 1172 | 1173 | #### integer array `[,...]` or `[[,...]]` 1174 | 1175 | **MATLAB** 1176 | > Note: Because MATLAB has no notion of arrays with fewer than 2 dimensions, using `size(data)` as the 3rd argument of 1177 | `h5create` will erroneously save arrays with 1 dimension as a row or column vector of 2 dimensions. In the 1D case, use `length(data)` as the 3rd argument of `h5create`. 1178 | ```matlab 1179 | data = 1180 | h5create(, , length(data) / size(data), 'Datatype', 'int32') 1181 | h5write(, , data) 1182 | ``` 1183 | **Python** 1184 | ```python 1185 | array = numpy.array().astype(int) # A list or nested list of values should be converted to a NumPy array 1186 | file = h5py.File(, 'r+') 1187 | file.create_dataset(, dtype='i4', data=array) 1188 | ``` 1189 | 1190 | ## Acknowledgement 1191 | 1192 | This document was originally drafted by Blaise Frederic (bbfrederick at 1193 | mclean.harvard.edu) and David Boas (dboas at bu.edu). 1194 | 1195 | Other significant contributors to this specification include: 1196 | - Theodore Huppert (huppert1 at pitt.edu) 1197 | - Jay Dubb (jdubb at bu.edu) 1198 | - Qianqian Fang (q.fang at neu.edu) 1199 | 1200 | The following individuals representing academic, industrial, software, and 1201 | hardware interests are also contributing to and supporting the adoption of this 1202 | specification: 1203 | 1204 | ### Software 1205 | - Ata Akin, Acibadem University 1206 | - Hasan Ayaz, Drexel University 1207 | - Joe Culver, University of Washington, neuroDOT 1208 | - Hamid Deghani, University of Birmingham, NIRFAST 1209 | - Adam Eggebrecht, University of Washington, neuroDOT 1210 | - Christophe Grova, McGill University, NIRSTORM 1211 | - Felipe Orihuela-Espina, Instituto Nacional de Astrofisica, Optica y Electronica, ICNNA 1212 | - Luca Pollonini, Houston Methodist, Phoebe 1213 | - Sungho Tak, Korea Basic Science Institute, NIRS-SPM 1214 | - Alessandro Torricelli, Politecnico di Milano 1215 | - Stanislaw Wojtkiewicz, University of Birmingham, NIRFAST 1216 | - Robert Luke, Macquarie University, MNE-NIRS 1217 | - Stephen Tucker, Boston University 1218 | - Michael Luhrs, Maastricht University, Brain Innovation B.V., Satori 1219 | - Robert Oostenveld, Radboud University, FieldTrip 1220 | 1221 | ### Hardware 1222 | - Hirokazu Asaka, Hitachi 1223 | - Rob Cooper, Gower Labs Inc 1224 | - Mathieu Coursolle, Rogue Research 1225 | - Rueben Hill, Gower Labs Inc 1226 | - Jorn Horschig, Artinis Medical Systems B.V. 1227 | - Takumi Inakazu, Hitachi 1228 | - Lamija Pasalic, NIRx 1229 | - Davood Tashayyod, fNIR Devices and Biopac Inc 1230 | - Hanseok Yun, OBELAB Inc 1231 | - Zahra M. Aghajan, Kernel 1232 | -------------------------------------------------------------------------------- /tests/data/v120dev-sub-01_task-inclusion_nirs.snirf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BUNPC/pysnirf2/636971477a249eed26c1d80e9d7791e53c1aa42f/tests/data/v120dev-sub-01_task-inclusion_nirs.snirf -------------------------------------------------------------------------------- /tests/data/v120dev-sub-02_task-test_nirs.snirf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BUNPC/pysnirf2/636971477a249eed26c1d80e9d7791e53c1aa42f/tests/data/v120dev-sub-02_task-test_nirs.snirf -------------------------------------------------------------------------------- /tests/data/v120dev-sub-A_task-test_run-1.snirf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BUNPC/pysnirf2/636971477a249eed26c1d80e9d7791e53c1aa42f/tests/data/v120dev-sub-A_task-test_run-1.snirf -------------------------------------------------------------------------------- /tests/test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import h5py 3 | import os 4 | import sys 5 | import time 6 | from numbers import Number 7 | from collections import deque 8 | from collections.abc import Set, Mapping 9 | import numpy as np 10 | import shutil 11 | try: 12 | import snirf 13 | from snirf import Snirf, validateSnirf, loadSnirf, saveSnirf 14 | except ImportError: 15 | sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) 16 | import snirf 17 | from snirf import Snirf, validateSnirf, loadSnirf, saveSnirf 18 | 19 | VERBOSE = True # Additional print statements in each test 20 | 21 | # Need to run from the repository root 22 | snirf_directory = os.path.join('tests', 'data') # Sample data source 23 | working_directory = os.path.join('tests', 'wd') # Working directory for testing 24 | 25 | if not os.path.isdir(working_directory): 26 | os.mkdir(working_directory) 27 | 28 | if len(os.listdir(snirf_directory)) == 0: 29 | sys.exit('Failed to find test data in '+ snirf_directory) 30 | 31 | ZERO_DEPTH_BASES = (str, bytes, Number, range, bytearray) 32 | def getsize(obj_0): 33 | """ 34 | Recursively calculate size of object & members in bytes. 35 | the work of Aaron Hall https://stackoverflow.com/a/30316760 36 | """ 37 | _seen_ids = set() 38 | def inner(obj): 39 | obj_id = id(obj) 40 | if obj_id in _seen_ids: 41 | return 0 42 | _seen_ids.add(obj_id) 43 | size = sys.getsizeof(obj) 44 | if isinstance(obj, ZERO_DEPTH_BASES): 45 | pass # bypass remaining control flow and return 46 | elif isinstance(obj, (tuple, list, Set, deque)): 47 | size += sum(inner(i) for i in obj) 48 | elif isinstance(obj, Mapping) or hasattr(obj, 'items'): 49 | if getattr(obj, 'items') is not None: 50 | size += sum(inner(k) + inner(v) for k, v in getattr(obj, 'items')()) 51 | # Check for custom object instances - may subclass above too 52 | if hasattr(obj, '__dict__'): 53 | size += inner(vars(obj)) 54 | if hasattr(obj, '__slots__'): # can have __slots__ with __dict__ 55 | size += sum(inner(getattr(obj, s)) for s in obj.__slots__ if hasattr(obj, s)) 56 | return size 57 | return inner(obj_0) 58 | 59 | 60 | def compare_snirf(snirf_path_1, snirf_path_2, enforce_length=True): 61 | ''' 62 | Returns a struct pairing the Dataset names appearing in each SNIRF file with 63 | the result of comparing these values after a cast to numpy array. If None, 64 | the Dataset appears in only one of the two SNIRF files. 65 | ''' 66 | f1 = h5py.File(snirf_path_1, 'r') 67 | f2 = h5py.File(snirf_path_2, 'r') 68 | loc_f1 = get_all_dataset_locations(f1) 69 | loc_f2 = get_all_dataset_locations(f2) 70 | 71 | if VERBOSE: 72 | print('Loaded', f1, 'and', f2, 'for comparison') 73 | 74 | results = {} 75 | 76 | locations = list(set(loc_f1 + loc_f2)) 77 | for location in locations: 78 | if not (location in loc_f1 and location in loc_f2): 79 | results[location] = None 80 | else: 81 | arr1 = np.array(f1[location]) 82 | arr2 = np.array(f2[location]) 83 | if not enforce_length: 84 | if arr1.size == 1 or len(arr1) == 1: 85 | try: 86 | arr1 = arr1[0] 87 | except IndexError: 88 | arr1 = arr1[()] 89 | if arr2.size == 1 or len(arr2) == 1: 90 | try: 91 | arr2 = arr2[0] 92 | except IndexError: 93 | arr2 = arr2[()] 94 | eq = arr1 == arr2 95 | if not (type(eq) is np.bool_ or type(eq) is bool): 96 | eq = eq.all() 97 | if VERBOSE and not eq: 98 | print(type(arr1), arr1, '!=', type(arr2), arr2) 99 | results[location] = bool(eq) 100 | f1.close() 101 | f2.close() 102 | return results 103 | 104 | 105 | def get_all_dataset_locations(h): 106 | ''' 107 | Recursively create list of all relative names of the Datasets in an HDF5 108 | group or file 109 | ''' 110 | locations = [] 111 | for key in h.keys(): 112 | if type(h[key]) is h5py.Dataset: 113 | locations.append(h[key].name) 114 | else: 115 | locations += get_all_dataset_locations(h[key]) 116 | return locations 117 | 118 | 119 | def dataset_equal_test(test, fname1, fname2): 120 | """ 121 | Asserts that the HDF files at fname1 and fname2 have the same datasets 122 | """ 123 | result = compare_snirf(fname1, fname2) 124 | false_keys = [] 125 | none_keys = [] 126 | for key in result.keys(): 127 | if result[key] is None: 128 | none_keys.append(key) 129 | elif result[key] is False: 130 | false_keys.append(key) 131 | elif result[key] is True: 132 | pass 133 | else: 134 | raise ValueError('test_loading_saving failed. Invalid comparison between ', fname1 + ' and ' + fname2 + 'resulted in value' + str(result[key])) 135 | if len(none_keys) > 0 and VERBOSE: 136 | print('The following keys were not found in both SNIRF files:') 137 | print(none_keys) 138 | if len(false_keys) > 0 and VERBOSE: 139 | print('The following keys were not equivalent:') 140 | print(false_keys) 141 | missing = np.array([('metaDataTags' in key or 'stim0' in key or 'measurementList0' in key or 'data0' in key or 'aux0' in key or 'nirs0' in key) for key in none_keys]).astype(bool) 142 | test.assertTrue(missing.all(), msg=fname1 + ' and ' + fname2 + 'not equal: specified datasets are missing from the copied file: ' + str(none_keys)) 143 | test.assertFalse(len(false_keys) > 0, msg=fname1 + ' and ' + fname2 + 'are not equal: datasets were incorrectly copied: ' + str(false_keys)) 144 | 145 | 146 | def _print_keys(group): 147 | for key in group.keys(): 148 | print(key) 149 | 150 | 151 | # -- Tests -------------------------------------------------------------------- 152 | 153 | class PySnirf2_Test(unittest.TestCase): 154 | 155 | def test_validate_datatypes(self): 156 | """ 157 | Test validation methods for dataType and dataType labels 158 | """ 159 | for i, mode in enumerate([False, True]): 160 | for file in self._test_files: 161 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 162 | if len(s.nirs[0].data) == 1 and len(s.nirs[0].data[0].measurementList) > 1: 163 | s.nirs[0].data[0].measurementList[0].dataType = -100 164 | if VERBOSE: 165 | s.validate().display(severity=3) 166 | self.assertTrue('UNRECOGNIZED_DATA_TYPE' in [err.name for err in s.validate().errors], msg='Failed to raise dataType error') 167 | s.nirs[0].data[0].measurementList[0].dataType = 99999 168 | s.nirs[0].data[0].measurementList[0].dataTypeLabel = 'bar' 169 | if VERBOSE: 170 | s.validate().display(severity=3) 171 | self.assertTrue('UNRECOGNIZED_DATA_TYPE_LABEL' in [err.name for err in s.validate().errors], msg='Failed to raise dataTypeLabel error') 172 | s.measurementList_to_measurementLists() 173 | if VERBOSE: 174 | s.validate().display(severity=3) 175 | self.assertTrue('UNRECOGNIZED_DATA_TYPE_LABEL' in [err.name for err in s.validate().errors], msg='Failed to raise dataTypeLabel error after converting to measurementLists') 176 | s.nirs[0].data[0].measurementLists.dataType[-1] = -100 177 | self.assertTrue('UNRECOGNIZED_DATA_TYPE' in [err.name for err in s.validate().errors], msg='Failed to raise dataType error after converting to measurementLists') 178 | 179 | def test_validate_measurementList_dimensions(self): 180 | """ 181 | Test validation that measurementList dimensions are consistent with dataTimeSeries 182 | """ 183 | for i, mode in enumerate([False, True]): 184 | for file in self._test_files: 185 | # Test measurementList(s) length validation 186 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 187 | if len(s.nirs[0].data) == 1 and len(s.nirs[0].data[0].measurementList) > 1: 188 | self.assertTrue(s.validate(), msg="Failed to validate SNIRF object") 189 | s.nirs[0].data[0].measurementList.appendGroup() 190 | if VERBOSE: 191 | s.validate().display(severity=3) 192 | self.assertTrue('INVALID_MEASUREMENTLIST' in [err.name for err in s.validate().errors], msg='Failed to raise measurementList length error') 193 | new_path = file.split('.')[0] + '_invalid_ml.snirf' 194 | s.save(new_path) 195 | self.assertTrue('INVALID_MEASUREMENTLIST' in [err.name for err in validateSnirf(new_path).errors], msg='Failed to raise measurementList length error') 196 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 197 | if len(s.nirs[0].data) >= 1 and len(s.nirs[0].data[0].measurementList) > 0: 198 | s.measurementList_to_measurementLists() 199 | wli = s.nirs[0].data[0].measurementLists.wavelengthIndex 200 | s.nirs[0].data[0].measurementLists.wavelengthIndex = np.concatenate([wli, [0]]) 201 | self.assertTrue('INVALID_MEASUREMENTLISTS' in [err.name for err in s.validate().errors], msg='Failed to raise measurementList length error') 202 | # Test measurementList(s) value validation 203 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 204 | if len(s.nirs[0].data) >= 1 and len(s.nirs[0].data[0].measurementList) > 0: 205 | s.nirs[0].data[0].measurementList[0].wavelengthIndex = 999_999_999_999 # Unreasonable values 206 | s.nirs[0].data[0].measurementList[0].sourceIndex = -1 207 | s.nirs[0].data[0].measurementList[0].detectorIndex = 999_999_999_999 208 | if VERBOSE: 209 | s.validate().display(severity=3) 210 | errs = [err.name for err in s.validate().errors] 211 | self.assertTrue('INVALID_WAVELENGTH_INDEX' in errs, msg='Failed to raise wavelengthIndex error') 212 | self.assertTrue('INVALID_SOURCE_INDEX' in errs, msg='Failed to raise sourceIndex error') 213 | self.assertTrue('INVALID_DETECTOR_INDEX' in errs, msg='Failed to raise detectorIndex error') 214 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 215 | if len(s.nirs[0].data) >= 1 and len(s.nirs[0].data[0].measurementList) > 0: 216 | s.measurementList_to_measurementLists() 217 | s.nirs[0].data[0].measurementLists.wavelengthIndex[0] = 999_999_999_999 218 | s.nirs[0].data[0].measurementLists.sourceIndex[0] = -1 219 | s.nirs[0].data[0].measurementLists.detectorIndex[0] = 999_999_999_999 220 | if VERBOSE: 221 | s.validate().display(severity=3) 222 | errs = [err.name for err in s.validate().errors] 223 | self.assertTrue('INVALID_WAVELENGTH_INDEX' in errs, msg='Failed to raise wavelengthIndex error') 224 | self.assertTrue('INVALID_SOURCE_INDEX' in errs, msg='Failed to raise sourceIndex error') 225 | self.assertTrue('INVALID_DETECTOR_INDEX' in errs, msg='Failed to raise detectorIndex error') 226 | 227 | 228 | def test_validate_measurementList_conversion(self): 229 | """ 230 | Validate that measurementList can be converted to measurementLists and back 231 | 232 | Also tests that Groups can be deleted from files on disk 233 | """ 234 | for i, mode in enumerate([False, True]): 235 | for file in self._test_files: 236 | with Snirf(file, dynamic_loading=mode) as s: 237 | if len(s.nirs[0].data) >= 1 and len(s.nirs[0].data[0].measurementList) > 0: # Subset of test data? 238 | if VERBOSE: 239 | print('Converting measurementList', file, 'to measurementLists') 240 | s.nirs[0].data[0].measurementList_to_measurementLists() 241 | del s.nirs[0].data[0].measurementList[:] 242 | new_path = file.split('.')[0] + '_converted_to_measurementLists.snirf' 243 | if VERBOSE: 244 | s.validate().display(severity=3) 245 | self.assertTrue(s.validate(), msg="Failed to validate SNIRF object after conversion to measurementLists") 246 | if VERBOSE: 247 | print('Writing file to', new_path) 248 | s.save(new_path) 249 | self.assertTrue(validateSnirf(new_path), msg="Failed to validate file on disk after conversion to measurementLists") 250 | with Snirf(new_path, dynamic_loading=mode) as s: 251 | if VERBOSE: 252 | print('Converting measurementLists in', new_path, 'back to measurementList') 253 | s.nirs[0].data[0].measurementLists_to_measurementList() 254 | del s.nirs[0].data[0].measurementLists 255 | self.assertTrue(s.validate(), msg="Failed to validate file after conversion back to measurementList") 256 | s.save() 257 | print('Checking to see if conversion is reversible...') 258 | dataset_equal_test(self, file, new_path) 259 | 260 | def test_multidimensional_aux(self): 261 | """ 262 | Test to ensure the validator permits multidimensional aux 263 | 264 | """ 265 | for i, mode in enumerate([False, True]): 266 | for file in self._test_files: 267 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 268 | s.nirs[0].aux.appendGroup() 269 | s.nirs[0].aux[-1].name = 'My2DAux' 270 | s.nirs[0].aux[-1].time = np.linspace(0, 10, 100) 271 | s.nirs[0].aux[-1].dataTimeSeries = np.random.random([100, 2]) 272 | if VERBOSE: 273 | print("Created new aux channel:", s.nirs[0].aux[-1]) 274 | s.save() 275 | if VERBOSE: 276 | s.validate().display() 277 | self.assertTrue(s.validate(), msg="Incorrectly invalidated multidimensional aux signal") 278 | self.assertTrue(validateSnirf(file), msg="Incorrectly invalidated multidimensional aux signal in file on disk") 279 | 280 | def test_assignment(self): 281 | """ 282 | Assign a Group and IndexedGroup element from one Snirf object to another. Validate that Datasets, 283 | misc metaDataTags and collections are copied successfully. 284 | 285 | """ 286 | for i, mode in enumerate([False, True]): 287 | s2_paths = [] 288 | start = time.time() 289 | for file in self._test_files: 290 | if VERBOSE: 291 | print('Loading', file, 'with dynamic_loading=' + str(mode)) 292 | # Reassignment of same probe 293 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 294 | if len(s.nirs[0].data[0].measurementList) < 1: 295 | continue # skip cases without measurementList 296 | same_probe = s.nirs[0].probe 297 | self.assertTrue(isinstance(same_probe, snirf.Probe), msg="Could not assign Probe reference") 298 | same_probe.sourcePos3D = np.random.random([31, 3]) 299 | try: 300 | s.nirs[0].probe = "foo" 301 | except Exception as e: 302 | self.assertTrue(type(e) is ValueError, msg="Faulty assignment to ProbeClass did not raise ValueError") 303 | s.nirs[0].probe = same_probe 304 | # Assignment of new probe and measurement list element 305 | new_path = file.split('.')[0] + '_2.snirf' 306 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 307 | s.save(new_path) 308 | for mode2 in [False, True]: 309 | print('Loading', new_path, 'with dynamic_loading=' + str(mode2)) 310 | with Snirf(new_path, 'r+', dynamic_loading=mode2) as s2: 311 | # Group 312 | new_srcpos3 = np.random.random([31, 3]) 313 | s2.nirs[0].probe.sourcePos3D = new_srcpos3 314 | if VERBOSE: 315 | print('Assigning probe from', new_path, 'to', file) 316 | s.nirs[0].probe = s2.nirs[0].probe 317 | s_location = str(s.nirs[0].probe._h.file.filename) 318 | self.assertTrue(s_location == file, msg='Probe assignment unsuccessful, HDF5 file is ' + s_location + ', not ' + file) 319 | self.assertTrue(np.all(s.nirs[0].probe.sourcePos3D == s2.nirs[0].probe.sourcePos3D), msg='Probe assignment unsuccessful: data not copied.') 320 | # Indexed Group element 321 | new_dataTypeLabel = str(int(np.random.random() * 10**5))[0:6] # Random phony dataTypeLabel 322 | s2.nirs[0].data[0].measurementList[0].dataTypeLabel = new_dataTypeLabel 323 | if VERBOSE: 324 | print('Assigning measurementList[0] from', new_path, 'to', file) 325 | s.nirs[0].data[0].measurementList[0] = s2.nirs[0].data[0].measurementList[0] 326 | s_location = str(s.nirs[0].data[0].measurementList[0]._h.file.filename) 327 | self.assertTrue(s_location == file, msg='measurementList[0] assignment unsuccessful, HDF5 file is ' + s_location + ', not ' + file) 328 | self.assertTrue(s.nirs[0].data[0].measurementList[0].dataTypeLabel == s2.nirs[0].data[0].measurementList[0].dataTypeLabel, msg='measurementList[0] assignment unsuccessful: data not copied.') 329 | # Assigning group and checking subgroups 330 | new_dataTypeLabel = str(int(np.random.random() * 10**5))[0:6] # Random phony dataTypeLabel 331 | new_path = file.split('.')[0] + '_3.snirf' 332 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 333 | s.save(new_path) 334 | for mode2 in [False, True]: 335 | print('Loading', new_path, 'with dynamic_loading=' + str(mode2)) 336 | with Snirf(new_path, 'r+', dynamic_loading=mode2) as s2: 337 | # Edit measurementList, Assign Nirs Group element 338 | s2.nirs[0].data[0].measurementList[0].dataTypeLabel = new_dataTypeLabel 339 | # Remove a channel of data 340 | del s2.nirs[0].data[0].measurementList[-1] 341 | ch_count_old = np.shape(s2.nirs[0].data[0].dataTimeSeries)[1] 342 | s2.nirs[0].data[0].dataTimeSeries = s2.nirs[0].data[0].dataTimeSeries[:, 0:-1] 343 | ch_count_new = np.shape(s2.nirs[0].data[0].dataTimeSeries)[1] 344 | # Add new metaDataTag 345 | s2.nirs[0].metaDataTags.add('foo', 'bar') 346 | if VERBOSE: 347 | print("Assigned new dataTypeLabel to first measurementList element") 348 | print("Reduced channel count from", ch_count_old, "to", ch_count_new) 349 | print('Assigning nirs[0] from', new_path, 'to', file) 350 | s.nirs[0] = s2.nirs[0] 351 | new_new_path = new_path.split('.')[0] + '_resaved.snirf' 352 | s.save(new_new_path) 353 | # s_location = str(s.nirs[0].data[0].measurementList[0].filename) 354 | # self.assertTrue(str(s.nirs[0].filename) == file, msg='nirs[0] assignment unsuccessful, HDF5 file for nirs element is ' + s_location + ', not ' + file) 355 | # self.assertTrue(s_location == file, msg='measurementList[0] assignment unsuccessful, HDF5 file for measurementList element is ' + s_location + ', not ' + file) 356 | self.assertTrue(len(s.nirs[0].data[0].measurementList) == len(s2.nirs[0].data[0].measurementList), msg='Assignment unsuccessful, IndexedGroup not successfully copied on assignment. Edited file had ' + str(len(s.nirs[0].data[0].measurementList)) + ' channels') 357 | self.assertTrue(s.nirs[0].data[0].measurementList[0].dataTypeLabel == s2.nirs[0].data[0].measurementList[0].dataTypeLabel, msg='Assignment unsuccessful: data not copied.') 358 | self.assertTrue(s.nirs[0].metaDataTags.foo == 'bar', msg='Assignment unsuccessful, failed to set the unspecified metaDataTag \'foo\'') 359 | # Resaved 360 | with Snirf(new_new_path, 'r+', dynamic_loading=mode) as s: 361 | with Snirf(new_path, 'r+', dynamic_loading=mode2) as s2: 362 | self.assertTrue(len(s.nirs[0].data[0].measurementList) == len(s2.nirs[0].data[0].measurementList) - 1, msg='Assignment unsuccessful after saving, IndexedGroup not successfully copied on assignment. Edited file had ' + str(len(s.nirs[0].data[0].measurementList)) + ' channels') 363 | self.assertTrue(s.nirs[0].data[0].measurementList[0].dataTypeLabel == new_dataTypeLabel, msg='Assignment unsuccessful after saving: data not copied.') 364 | self.assertTrue(s.nirs[0].metaDataTags.foo == 'bar', msg='Assignment unsuccessful after saving, failed to set the unspecified metaDataTag \'foo\'') 365 | 366 | 367 | def test_copying(self): 368 | """ 369 | Loads all files in filenames using Snirf in both dynamic and static mode, 370 | saves copies to new files, compares the results using h5py and a naive cast. 371 | If returns True, all specified datasets are equivalent in the copied files. 372 | """ 373 | for i, mode in enumerate([False, True]): 374 | s2_paths = [] 375 | for file in self._test_files: 376 | new_path = file.split('.')[0] + '_copied.snirf' 377 | if VERBOSE: 378 | print('Loading', file, 'with dynamic_loading=' + str(mode)) 379 | print('Making a copy of', file) 380 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 381 | s2 = s.copy() 382 | s.save() # Save it, otherwise differences in IndexedGroup naming will raise issues with comparison 383 | s2.save(new_path) 384 | s2_paths.append(new_path) 385 | for (fname1, fname2) in zip(self._test_files, s2_paths): 386 | if VERBOSE: 387 | print('Testing equality between', fname1, 'and', fname2) 388 | dataset_equal_test(self, fname1, fname2) 389 | 390 | 391 | def test_loading_saving_functions(self): 392 | """Test basic saving and loading interfaces `saveSnirf` and `loadSnirf`.""" 393 | s1_paths = [] 394 | s2_paths = [] 395 | start = time.time() 396 | for file in self._test_files: 397 | s1 = loadSnirf(file) 398 | s1_paths.append(file) 399 | saveSnirf(file, s1) # Otherwise, nirs/nirs1 inconsistencies will cause test to fail 400 | new_path = file.split('.')[0] + '_unedited.snirf' 401 | saveSnirf(new_path, s1) 402 | s2_paths.append(new_path) 403 | s1.close() 404 | for (fname1, fname2) in zip(s1_paths, s2_paths): 405 | dataset_equal_test(self, fname1, fname2) 406 | 407 | 408 | def test_disabled_logging(self): 409 | """Validate that no logs are created when logging is disabled.""" 410 | for file in self._test_files: 411 | if VERBOSE: 412 | print('Loading', file) 413 | logfile = file.replace('.snirf', '.log') 414 | with Snirf(file, 'r', enable_logging=False) as s: 415 | self.assertFalse(os.path.exists(logfile), msg='{} created even though enable_logging=False'.format(logfile)) 416 | 417 | 418 | def test_enabled_logging(self): 419 | """Test log file creation.""" 420 | for file in self._test_files: 421 | if VERBOSE: 422 | print('Loading', file) 423 | logfile = file.replace('.snirf', '.log') 424 | with Snirf(file, 'r', enable_logging=True) as s: 425 | self.assertTrue(os.path.exists(logfile), msg='{} was not created with enable_logging=True'.format(logfile)) 426 | if VERBOSE: 427 | print(logfile, 'contents:') 428 | print('---------------------------------------------') 429 | with open(logfile, 'r') as f: 430 | [print(line) for line in f.readlines()] 431 | print('---------------------------------------------') 432 | 433 | 434 | def test_unknown_coordsys_name(self): 435 | """Test that the validator warns about unknown coordinate system names if no description is present.""" 436 | for i, mode in enumerate([False, True]): 437 | for file in self._test_files: 438 | if VERBOSE: 439 | print('Loading', file, 'with dynamic_loading=' + str(mode)) 440 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 441 | if VERBOSE: 442 | print("Adding unrecognized coordinate system") 443 | s.nirs[0].probe.coordinateSystem = 'MNIFoo27' 444 | result = s.validate() 445 | if VERBOSE: 446 | result.display(severity=2) 447 | self.assertTrue('UNRECOGNIZED_COORDINATE_SYSTEM' in [issue.name for issue in result.warnings], msg='Failed to raise warning about unknown coordinate system') 448 | newname = file.split('.')[0] + '_coordinate_system_added' 449 | s.save(newname) 450 | if VERBOSE: 451 | print('Loading', newname, 'with dynamic_loading=' + str(mode)) 452 | with Snirf(newname, 'r+', dynamic_loading=mode) as s: 453 | result = s.validate() 454 | if VERBOSE: 455 | result.display(severity=2) 456 | self.assertTrue('UNRECOGNIZED_COORDINATE_SYSTEM' in [issue.name for issue in result.warnings], msg='Failed to raise warning about unknown coordinate system in file saved to disk') 457 | self.assertTrue(s.validate(), msg='File was incorrectly invalidated') 458 | 459 | 460 | def test_known_coordsys_name(self): 461 | """Test that the validator does NOT warn about known coordinate system names.""" 462 | for i, mode in enumerate([False, True]): 463 | for file in self._test_files: 464 | if VERBOSE: 465 | print('Loading', file, 'with dynamic_loading=' + str(mode)) 466 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 467 | if VERBOSE: 468 | print("Adding recognized coordinate system") 469 | s.nirs[0].probe.coordinateSystem = 'MNIColin27' 470 | result = s.validate() 471 | if VERBOSE: 472 | result.display(severity=2) 473 | self.assertFalse('UNRECOGNIZED_COORDINATE_SYSTEM' in [issue.name for issue in result.warnings], msg='Failed to recognize known coordinate system') 474 | newname = file.split('.')[0] + '_unknown_coordinate_system_added' 475 | s.save(newname) 476 | if VERBOSE: 477 | print('Loading', newname, 'with dynamic_loading=' + str(mode)) 478 | with Snirf(newname, 'r+', dynamic_loading=mode) as s: 479 | result = s.validate() 480 | if VERBOSE: 481 | result.display(severity=2) 482 | self.assertFalse('UNRECOGNIZED_COORDINATE_SYSTEM' in [issue.name for issue in result.warnings], msg='Failed to recognize known coordinate system in file saved to disk') 483 | self.assertTrue(s.validate(), msg='File was incorrectly invalidated') 484 | 485 | 486 | def test_unspecified_metadatatags(self): 487 | """Test that misc metaDataTags can be added, removed, saved and loaded.""" 488 | for i, mode in enumerate([False, True]): 489 | for file in self._test_files: 490 | if VERBOSE: 491 | print('Loading', file, 'with dynamic_loading=' + str(mode)) 492 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 493 | if VERBOSE: 494 | print("Adding metaDataTags 'foo', 'bar', and 'array_of_strings'") 495 | s.save() # Otherwise, nirs/nirs1 inconsistencies will cause test to fail 496 | s.nirs[0].metaDataTags.add('foo', 'Hello') 497 | s.nirs[0].metaDataTags.add('Bar', 'World') 498 | s.nirs[0].metaDataTags.add('_array_of_strings', ['foo', 'bar']) 499 | self.assertTrue(s.validate(), msg='adding the unspecified metaDataTags resulted in an INVALID file') 500 | self.assertTrue(s.nirs[0].metaDataTags.foo == 'Hello', msg='Failed to set the unspecified metadatatags') 501 | self.assertTrue(s.nirs[0].metaDataTags.Bar == 'World', msg='Failed to set the unspecified metadatatags') 502 | self.assertTrue(s.nirs[0].metaDataTags._array_of_strings[0] == 'foo', msg='Failed to set the unspecified metadatatags') 503 | newname = file.split('.')[0] + '_unspecified_tags' 504 | s.save(newname) 505 | if VERBOSE: 506 | print('Loading', newname, 'with dynamic_loading=' + str(mode)) 507 | with Snirf(newname, 'r+', dynamic_loading=mode) as s: 508 | self.assertTrue(s.nirs[0].metaDataTags.foo == 'Hello', msg='Failed to save the unspecified metadatatags to disk') 509 | self.assertTrue(s.nirs[0].metaDataTags.Bar == 'World', msg='Failed to save the unspecified metadatatags to disk') 510 | self.assertTrue(s.nirs[0].metaDataTags._array_of_strings[0] == 'foo', msg='Failed to save the unspecified metadatatags to disk') 511 | s.nirs[0].metaDataTags.remove('foo') 512 | s.nirs[0].metaDataTags.remove('Bar') 513 | s.nirs[0].metaDataTags.remove('_array_of_strings') 514 | s.save() 515 | dataset_equal_test(self, file, newname + '.snirf') 516 | 517 | 518 | def test_validator_required_probe_dataset_missing(self): 519 | """Test that the validator invalidates an a missing required dataset.""" 520 | for i, mode in enumerate([False, True]): 521 | for file in self._test_files: 522 | if VERBOSE: 523 | print('Loading', file, 'with dynamic_loading=' + str(mode)) 524 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 525 | probloc = s.nirs[0].probe.location 526 | # Otherwise probloc will not find issue 527 | if len(s.nirs) == 1: 528 | probloc = probloc.replace('nirs1', 'nirs') 529 | s.save() 530 | del s.nirs[0].probe.sourcePos2D 531 | del s.nirs[0].probe.detectorPos2D 532 | if VERBOSE: 533 | print('Deleted source and detector 2D positions from probe:') 534 | print(s.nirs[0].probe) 535 | result = s.validate() 536 | if VERBOSE: 537 | result.display(severity=3) 538 | self.assertFalse(result[probloc + '/sourcePos2D'].name == 'REQUIRED_DATASET_MISSING', msg='REQUIRED_DATASET_MISSING not expected') 539 | self.assertFalse(result[probloc + '/detectorPos2D'].name == 'REQUIRED_DATASET_MISSING', msg='REQUIRED_DATASET_MISSING not expected') 540 | self.assertTrue(result[probloc + '/sourcePos2D'].name == 'OPTIONAL_DATASET_MISSING', msg='OPTIONAL_DATASET_MISSING expected') 541 | self.assertTrue(result[probloc + '/detectorPos2D'].name == 'OPTIONAL_DATASET_MISSING', msg='OPTIONAL_DATASET_MISSING expected') 542 | newname = file.split('.')[0] + '_optional_pos_missing' 543 | newname2 = file.split('.')[0] + '_required_pos_missing' 544 | s.save(newname) 545 | del s.nirs[0].probe.sourcePos3D 546 | del s.nirs[0].probe.detectorPos3D 547 | s.save(newname2) 548 | result = validateSnirf(newname) 549 | if VERBOSE: 550 | result.display(severity=3) 551 | self.assertFalse(result[probloc + '/sourcePos2D'].name == 'REQUIRED_DATASET_MISSING', msg='REQUIRED_DATASET_MISSING not expected') 552 | self.assertFalse(result[probloc + '/detectorPos2D'].name == 'REQUIRED_DATASET_MISSING', msg='REQUIRED_DATASET_MISSING not expected') 553 | self.assertTrue(result[probloc + '/sourcePos2D'].name == 'OPTIONAL_DATASET_MISSING', msg='OPTIONAL_DATASET_MISSING expected') 554 | self.assertTrue(result[probloc + '/detectorPos2D'].name == 'OPTIONAL_DATASET_MISSING', msg='OPTIONAL_DATASET_MISSING expected') 555 | result = validateSnirf(newname2) 556 | if VERBOSE: 557 | print('Deleted source and detector 2D and 3D positions from probe:') 558 | result.display(severity=3) 559 | self.assertTrue(result[probloc + '/sourcePos2D'].name == 'REQUIRED_DATASET_MISSING', msg='REQUIRED_DATASET_MISSING expected') 560 | self.assertTrue(result[probloc + '/detectorPos2D'].name == 'REQUIRED_DATASET_MISSING', msg='REQUIRED_DATASET_MISSING expected') 561 | self.assertTrue(result[probloc + '/sourcePos3D'].name == 'REQUIRED_DATASET_MISSING', msg='REQUIRED_DATASET_MISSING expected') 562 | self.assertTrue(result[probloc + '/detectorPos3D'].name == 'REQUIRED_DATASET_MISSING', msg='REQUIRED_DATASET_MISSING expected') 563 | 564 | 565 | def test_validator_required_group_missing(self): 566 | """Test that the validator invalidates an a missing required Group.""" 567 | for i, mode in enumerate([False, True]): 568 | for file in self._test_files: 569 | if VERBOSE: 570 | print('Loading', file, 'with dynamic_loading=' + str(mode)) 571 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 572 | del s.nirs[0].probe 573 | if VERBOSE: 574 | print('Performing local validation on probeless', s) 575 | result = s.validate() 576 | if VERBOSE: 577 | result.display(severity=3) 578 | self.assertFalse(result, msg='The Snirf object was incorrectly validated') 579 | self.assertTrue('REQUIRED_GROUP_MISSING' in [issue.name for issue in result.errors], msg='REQUIRED_GROUP_MISSING not found') 580 | newname = file.split('.')[0] + '_required_group_missing' 581 | s.save(newname) 582 | 583 | if VERBOSE: 584 | print('Performing file validation on probeless', newname + '.snirf') 585 | result = validateSnirf(newname) 586 | if VERBOSE: 587 | result.display(severity=3) 588 | self.assertFalse(result, msg='The file was incorrectly validated') 589 | self.assertTrue('REQUIRED_GROUP_MISSING' in [issue.name for issue in result.errors], msg='REQUIRED_GROUP_MISSING not found') 590 | 591 | 592 | def test_validator_required_dataset_missing(self): 593 | """Test that the validator invalidates an a missing required dataset.""" 594 | for i, mode in enumerate([False, True]): 595 | for file in self._test_files[0:1]: 596 | if VERBOSE: 597 | print('Loading', file + '.snirf', 'with dynamic_loading=' + str(mode)) 598 | with Snirf(file, 'r+', dynamic_loading=mode) as s: 599 | del s.formatVersion 600 | if VERBOSE: 601 | print('Performing local validation on formatVersionless', s) 602 | result = s.validate() 603 | if VERBOSE: 604 | result.display(severity=3) 605 | self.assertFalse(result, msg='The Snirf object was incorrectly validated') 606 | self.assertTrue('REQUIRED_DATASET_MISSING' in [issue.name for issue in result.errors], msg='REQUIRED_DATASET_MISSING not found') 607 | newname = file.split('.')[0] + '_required_dataset_missing' 608 | s.save(newname) 609 | 610 | if VERBOSE: 611 | print('Performing file validation on formatVersionless', newname + '.snirf') 612 | result = validateSnirf(newname) 613 | if VERBOSE: 614 | result.display(severity=3) 615 | self.assertFalse(result, msg='The file was incorrectly validated') 616 | self.assertTrue('REQUIRED_DATASET_MISSING' in [issue.name for issue in result.errors], msg='REQUIRED_DATASET_MISSING not found') 617 | 618 | 619 | def test_validator_required_indexed_group_empty(self): 620 | """Test that the validator invalidates an empty indexed group.""" 621 | for i, mode in enumerate([False, True]): 622 | for file in self._test_files[0:1]: 623 | if VERBOSE: 624 | print('Loading', file + '.snirf', 'with dynamic_loading=' + str(mode)) 625 | s = Snirf(file, 'r+', dynamic_loading=mode) 626 | while len(s.nirs[0].data) > 0: 627 | del s.nirs[0].data[0] 628 | if VERBOSE: 629 | print('Performing local validation on dataless', s) 630 | result = s.validate() 631 | if VERBOSE: 632 | result.display(severity=3) 633 | self.assertFalse(result, msg='The Snirf object was incorrectly validated') 634 | self.assertTrue('REQUIRED_INDEXED_GROUP_EMPTY' in [issue.name for issue in result.errors], msg='REQUIRED_INDEXED_GROUP_EMPTY not found') 635 | newname = file.split('.')[0] + '_required_ig_empty' 636 | s.save(newname) 637 | s.close() 638 | if VERBOSE: 639 | print('Performing file validation on dataless', newname + '.snirf') 640 | result = validateSnirf(newname) 641 | if VERBOSE: 642 | result.display(severity=3) 643 | self.assertFalse(result, msg='The file was incorrectly validated') 644 | self.assertTrue('REQUIRED_INDEXED_GROUP_EMPTY' in [issue.name for issue in result.errors], msg='REQUIRED_INDEXED_GROUP_EMPTY not found') 645 | 646 | 647 | def test_validator_invalid_measurement_list(self): 648 | """Test that the validator catches a measurementList which mismatches the dataTimeSeries in length.""" 649 | for i, mode in enumerate([False, True]): 650 | for file in self._test_files[0:1]: 651 | if VERBOSE: 652 | print('Loading', file + '.snirf', 'with dynamic_loading=' + str(mode)) 653 | s = Snirf(file, 'r+', dynamic_loading=mode) 654 | if len(s.nirs[0].data[0].measurementList) < 1: 655 | s.close() 656 | continue # skip cases without measurementList 657 | s.nirs[0].data[0].measurementList.appendGroup() # Add extra ml 658 | if VERBOSE: 659 | print('Performing local validation on invalid ml', s) 660 | result = s.validate() 661 | if VERBOSE: 662 | result.display(severity=3) 663 | self.assertFalse(result, msg='The Snirf object was incorrectly validated') 664 | self.assertTrue('INVALID_MEASUREMENTLIST' in [issue.name for issue in result.errors], msg='INVALID_MEASUREMENTLIST not found') 665 | newname = file.split('.')[0] + '_invalid_ml' 666 | s.save(newname) 667 | s.close() 668 | if VERBOSE: 669 | print('Performing file validation on invalid ml', newname + '.snirf') 670 | result = validateSnirf(newname) 671 | if VERBOSE: 672 | result.display(severity=3) 673 | self.assertFalse(result, msg='The file was incorrectly validated') 674 | self.assertTrue('INVALID_MEASUREMENTLIST' in [issue.name for issue in result.errors], msg='INVALID_MEASUREMENTLIST not found') 675 | 676 | 677 | def test_edit_probe_group(self): 678 | """ 679 | Edit some probe Group. Confirm they can be saved using save methods on 680 | the Snirf object and just the Group save method. 681 | """ 682 | for i, mode in enumerate([False, True]): 683 | for file in self._test_files: 684 | if VERBOSE: 685 | print('Loading', file + '.snirf', 'with dynamic_loading=' + str(mode)) 686 | s = Snirf(file, 'r+', dynamic_loading=mode) 687 | 688 | group_save_file = file.split('.')[0] + '_edited_group_save.snirf' 689 | if VERBOSE: 690 | print('Creating working copy for Group-level save', group_save_file) 691 | s.save(group_save_file) 692 | 693 | desired_probe_sourcelabels = ['S1_A', 'S2_A', 'S3_A', 'S4_A', 694 | 'S5_A', 'S6_A', 'S7_A', 'S8_A', 695 | 'S9_A', 'S10_A', 'S11_A', 'S12_A', 696 | 'S13_A', 'S14_A', 'S15_A'] 697 | desired_probe_sourcepos3d = np.random.random([31, 3]) 698 | 699 | s.nirs[0].probe.sourceLabels = desired_probe_sourcelabels 700 | s.nirs[0].probe.sourcePos3D = desired_probe_sourcepos3d 701 | 702 | snirf_save_file = file.split('.')[0] + '_edited_snirf_save.snirf' 703 | print('Saving edited file to', snirf_save_file) 704 | s.save(snirf_save_file) 705 | 706 | print('Saving edited Probe group to', group_save_file) 707 | s.nirs[0].probe.save(group_save_file) 708 | 709 | s.close() 710 | 711 | for edited_filename in [snirf_save_file, group_save_file]: 712 | 713 | print('Loading', edited_filename, 'for comparison with dynamic_loading=' + str(mode)) 714 | s2 = Snirf(edited_filename, 'r+', dynamic_loading=mode) 715 | 716 | self.assertTrue((s2.nirs[0].probe.sourceLabels == desired_probe_sourcelabels).all(), msg='Failed to edit sourceLabels properly in ' + edited_filename) 717 | self.assertTrue((s2.nirs[0].probe.sourcePos3D == desired_probe_sourcepos3d).all(), msg='Failed to edit sourceLabels properly in ' + edited_filename) 718 | 719 | s2.close() 720 | 721 | 722 | def test_add_remove_stim(self): 723 | """ 724 | Use the interface to add and remove stim groups. Verify in memory and then in a reloaded file. 725 | """ 726 | for i, mode in enumerate([False, True]): 727 | for file in self._test_files: 728 | file = self._test_files[0].split('.')[0] 729 | if VERBOSE: 730 | print('Loading', file + '.snirf', 'with dynamic_loading=' + str(mode)) 731 | s = Snirf(file, 'r+', dynamic_loading=mode) 732 | nstim = len(s.nirs[0].stim) 733 | s.nirs[0].stim.appendGroup() 734 | if VERBOSE: 735 | print('Adding stim to', file + '.stim') 736 | self.assertTrue(len(s.nirs[0].stim) == nstim + 1, msg='IndexedGroup.appendGroup() failed') 737 | s.nirs[0].stim[-1].data = [[0, 10, 1], [5, 10, 1]] 738 | s.nirs[0].stim[-1].dataLabels = ['Onset', 'Duration', 'Amplitude'] 739 | s.nirs[0].stim[-1].name = 'newCondition' 740 | newfile = file + '_added_stim_' + str(i) 741 | if VERBOSE: 742 | print('Save As edited file to', newfile + '.stim') 743 | s.save(newfile) 744 | s.close() 745 | s2 = Snirf(newfile, 'r+', dynamic_loading=mode) 746 | self.assertTrue(len(s2.nirs[0].stim) == nstim + 1, msg='The new stim Group was not Saved As to ' + newfile + '.snirf') 747 | if VERBOSE: 748 | print('Adding another stim group to', newfile + '.snirf and reloading it') 749 | s2.nirs[0].stim.appendGroup() 750 | s2.nirs[0].stim[-1].data = [[0, 10, 1], [5, 10, 1]] 751 | s2.nirs[0].stim[-1].dataLabels = ['Onset', 'Duration', 'Amplitude'] 752 | s2.nirs[0].stim[-1].name = 'newCondition2' 753 | s2.save() 754 | s2.close() 755 | s3 = Snirf(newfile, 'r+', dynamic_loading=mode) 756 | self.assertTrue(len(s3.nirs[0].stim) == nstim + 2, msg='The new stim Group was not Saved to ' + newfile + '.snirf') 757 | if VERBOSE: 758 | print('Removing all but one stim Group from', newfile + '.snirf and reloading it') 759 | name_to_keep = s3.nirs[0].stim[0].name 760 | while s3.nirs[0].stim[-1].name != name_to_keep: 761 | if VERBOSE: 762 | print('Deleting stim Group with name:', s3.nirs[0].stim[-1].name) 763 | del s3.nirs[0].stim[-1] 764 | s3.close() 765 | s4 = Snirf(newfile, 'r+', dynamic_loading=mode) 766 | self.assertTrue(s4.nirs[0].stim[0].name == name_to_keep, msg='Failed to remove desired stim Groups from ' + newfile + '.snirf') 767 | s4.close() 768 | 769 | 770 | def test_loading_saving(self): 771 | """ 772 | Loads all files in filenames using Snirf in both dynamic and static mode, 773 | saves them to a new file, compares the results using h5py and a naive cast. 774 | If returns True, all specified datasets are equivalent in the resaved files. 775 | """ 776 | for i, mode in enumerate([False, True]): 777 | s1_paths = [] 778 | s2_paths = [] 779 | start = time.time() 780 | for file in self._test_files: 781 | snirf = Snirf(file, 'r+', dynamic_loading=mode) 782 | s1_paths.append(file) 783 | snirf.save() # Otherwise, nirs/nirs1 will cause dataset_equal_test to fail 784 | new_path = file.split('.')[0] + '_unedited.snirf' 785 | snirf.save(new_path) 786 | s2_paths.append(new_path) 787 | snirf.close() 788 | if VERBOSE: 789 | print('Read and rewrote', len(self._test_files), 'SNIRF files in', 790 | str(time.time() - start)[0:6], 'seconds with dynamic_loading =', mode) 791 | 792 | for (fname1, fname2) in zip(s1_paths, s2_paths): 793 | dataset_equal_test(self, fname1, fname2) 794 | 795 | def test_dynamic(self): 796 | """ 797 | Confirm that dynamically loaded files have smaller memory footprints 798 | and faster load-times than non dynamically loaded files 799 | """ 800 | times = [-1, -1] 801 | sizes = [-1, -1] 802 | for i, mode in enumerate([False, True]): 803 | s = [] 804 | start = time.time() 805 | for file in self._test_files: 806 | s.append(Snirf(file, 'r+', dynamic_loading=mode)) 807 | times[i] = time.time() - start 808 | sizes[i] = getsize(s) 809 | for snirf in s: 810 | snirf.close() 811 | if VERBOSE: 812 | print('Loaded', len(self._test_files), 'SNIRF files of total size', sizes[i], 813 | 'in', str(times[i])[0:6], 'seconds with dynamic_loading =', mode) 814 | assert times[1] < times[0], 'Dynamically-loaded files not loaded faster' 815 | if sys.version_info >= (3, 11): 816 | raise unittest.SkipTest("Python 3.11 optimizations") 817 | 818 | assert sizes[1] < sizes[0], 'Dynamically-loaded files not smaller in memory' 819 | 820 | 821 | def setUp(self): 822 | if VERBOSE: 823 | print('Copying all test files to', working_directory) 824 | for file in os.listdir(snirf_directory): 825 | shutil.copy(os.path.join(snirf_directory, file), os.path.join(working_directory, file)) 826 | time.sleep(0.5) # Sleep while executing copy operation 827 | 828 | self._test_files = [os.path.join(working_directory, file) for file in os.listdir(working_directory)] 829 | if len(self._test_files) == 0: 830 | sys.exit('Failed to set up test data working directory at '+ working_directory) 831 | 832 | 833 | def tearDown(self): 834 | if VERBOSE: 835 | print('Deleting all files in', working_directory) 836 | for file in os.listdir(working_directory): 837 | os.remove(os.path.join(working_directory, file)) 838 | if VERBOSE: 839 | print('Deleted', os.path.join(working_directory, file)) 840 | 841 | # -- Set up test working-directory -------------------------------------------- 842 | 843 | if __name__ == '__main__': 844 | result = unittest.main() 845 | --------------------------------------------------------------------------------