├── .gitignore ├── LICENSE-DeepSlice ├── MANIFEST.in ├── README.md ├── constructor ├── environment.yml └── src ├── 0. Register And Save State.ipynb ├── 1. Open State.ipynb ├── 2. Register To BrainGlobe Atlas.ipynb ├── 3. Open State and Use Transforms.ipynb ├── 4. Register QuPath Project.ipynb ├── Playground - Adding a python registration method.ipynb └── abba_python ├── Abba.py ├── __init__.py ├── abba_private ├── AbbaAtlas.py ├── AbbaMap.py ├── AbbaOntology.py ├── DeepSliceProcessor.py └── __init__.py ├── deepslice ├── DeepSlice.py ├── LICENSE ├── README.md ├── __init__.py └── utilities │ ├── QuickNII_functions.py │ ├── __init__.py │ ├── neuron_tools.py │ ├── plane_alignment.py │ ├── plane_alignment_rat.py │ └── render_tools.py ├── itk ├── __init__.py └── abba_itk.py ├── run-abba-local-fiji.py ├── run-abba.py └── scijava_python_command ├── __init__.py ├── command.py ├── jupyter_ui.py └── magic.py /.gitignore: -------------------------------------------------------------------------------- 1 | /images/ 2 | /src/images/ 3 | /.idea/ 4 | /dist/ 5 | *.iml 6 | .ipynb_checkpoints/ 7 | /src/abba_python/deepslice/NN_weights/ 8 | /src/temp/ 9 | *.log 10 | *.json 11 | /notebooks/.ipynb_checkpoints/ 12 | __pycache__/ 13 | /constructor/abba_python/ 14 | /constructor/abba-pack-win.tar.gz 15 | /constructor/*.exe 16 | /temp/ 17 | /src/temp/ 18 | /constructor/win/elastix-5.0.1-win64/ 19 | /constructor/win/Fiji.app/ 20 | /constructor/Fiji.app/ 21 | /notebooks/images/ 22 | /notebooks/temp/ 23 | -------------------------------------------------------------------------------- /LICENSE-DeepSlice: -------------------------------------------------------------------------------- 1 | DeepSlice source code © [2022] Macquarie University patent pending in Australia, and contact Macquarie University for other countries. Macquarie University 2 | grants users a non-exclusive, non-transferable, non-sublicenseable licence to copy, reproduce and adapt DeepSlice only for use for non-commercial research 3 | purposes and not for other purposes without Macquarie University's prior written consent. DeepSlice is made available on the basis that it is released as a test 4 | version, 'as is', and should only be used for coronal images of the adult mouse brain, and may contain errors or produce results that are incorrect. DeepSlice 5 | or its derivatives should not be used or released for commercial use and cannot at present be reliably used to analyse brain images from species other than the 6 | mouse. Users agree that if they adapt DeepSlice, and make those adaptations available for others to use, they will release the adapted source code to GitHub on 7 | the same terms as this licence 8 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | 2 | include src/abba_python/deepslice/*.h5 3 | include src/abba_python/deepslice/*.hdf5 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # This repository is now replaced by [https://github.com/BIOP/abba_python](https://github.com/BIOP/abba_python) 2 | 3 | 4 | # [ABBA](https://biop.github.io/ijp-imagetoatlas/)-Python 5 | 6 | This repository demoes how to use [ABBA](https://biop.github.io/ijp-imagetoatlas/) with python by using [PyImageJ](https://github.com/imagej/pyimagej) and [JPype](https://github.com/jpype-project/jpype). 7 | 8 | For the documentation, please check the relevant sections within [https://biop.github.io/ijp-imagetoatlas/](https://biop.github.io/ijp-imagetoatlas/). 9 | 10 | # [DeepSlice](https://github.com/PolarBean/DeepSlice) 11 | 12 | If you want to register mouse brain sections to the Allen Brain Atlas, ABBA-Python also includes [DeepSlice](https://github.com/PolarBean/DeepSlice), a powerful deep learning tool which can be used for automatic registration of coronal sections of mouse brains. 13 | 14 | DeepSlice is completely independent from ABBA and has been developped by [Harry Carey](https://twitter.com/harrycarey2) and colleagues. Please check [its license](https://github.com/PolarBean/DeepSlice/blob/master/LICENSE) and cite [its preprint](https://www.biorxiv.org/content/10.1101/2022.04.28.489953v1?) if you are using it. 15 | 16 | ### DEEPSLICE IS INDEPENDENT FROM ABBA AND WAS NOT WRITTEN BY THE BIOP 17 | 18 | But because of my lack of skills in dependency management in python, copying the code is the only way I found to make it run with ABBA. 19 | -------------------------------------------------------------------------------- /constructor/LICENCE.txt: -------------------------------------------------------------------------------- 1 | This installer packages the following core software components: 2 | 3 | - Aligning Big Brains and Atlases (ABBA) components (https://github.com/BIOP/ijp-imagetoatlas) | BSD-3 4 | - ImageJ/Fiji (https://imagej.net/) | see sub-components 5 | - DeepSlice (https://github.com/PolarBean/DeepSlice) and dependencies | GPL-v3 6 | - PyImageJ (https://github.com/imagej/pyimagej) and dependencies | Apache-2 7 | 8 | ------------------ Aligning Big Brains and Atlases 9 | 10 | (c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, BioImaging And Optics Platform (BIOP), 2023 11 | 12 | Licensed under the BSD-3-Clause License: 13 | Redistribution and use in source and binary forms, with or without modification, are permitted provided 14 | that the following conditions are met: 15 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 16 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer 17 | in the documentation and/or other materials provided with the distribution. 18 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products 19 | derived from this software without specific prior written permission. 20 | 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 22 | BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 23 | IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 24 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 25 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 26 | STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 27 | ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | 29 | 30 | ------------------ ImageJ 31 | 32 | see https://imagej.net/licensing/ 33 | 34 | ------------------ PyImageJ 35 | 36 | Copyright (C) 2013 - 2020 Board of Regents of the University of 37 | Wisconsin-Madison. 38 | 39 | Licensed under the Apache License, Version 2.0 (the "License"); 40 | you may not use this file except in compliance with the License. 41 | You may obtain a copy of the License at 42 | 43 | http://www.apache.org/licenses/LICENSE-2.0 44 | 45 | Unless required by applicable law or agreed to in writing, software 46 | distributed under the License is distributed on an "AS IS" BASIS, 47 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 48 | See the License for the specific language governing permissions and 49 | limitations under the License. 50 | 51 | ------------------ DeepSlice 52 | 53 | GNU GENERAL PUBLIC LICENSE 54 | Version 3, 29 June 2007 55 | 56 | Copyright (C) 2007 Free Software Foundation, Inc. 57 | Everyone is permitted to copy and distribute verbatim copies 58 | of this license document, but changing it is not allowed. 59 | 60 | Preamble 61 | 62 | The GNU General Public License is a free, copyleft license for 63 | software and other kinds of works. 64 | 65 | The licenses for most software and other practical works are designed 66 | to take away your freedom to share and change the works. By contrast, 67 | the GNU General Public License is intended to guarantee your freedom to 68 | share and change all versions of a program--to make sure it remains free 69 | software for all its users. We, the Free Software Foundation, use the 70 | GNU General Public License for most of our software; it applies also to 71 | any other work released this way by its authors. You can apply it to 72 | your programs, too. 73 | 74 | When we speak of free software, we are referring to freedom, not 75 | price. Our General Public Licenses are designed to make sure that you 76 | have the freedom to distribute copies of free software (and charge for 77 | them if you wish), that you receive source code or can get it if you 78 | want it, that you can change the software or use pieces of it in new 79 | free programs, and that you know you can do these things. 80 | 81 | To protect your rights, we need to prevent others from denying you 82 | these rights or asking you to surrender the rights. Therefore, you have 83 | certain responsibilities if you distribute copies of the software, or if 84 | you modify it: responsibilities to respect the freedom of others. 85 | 86 | For example, if you distribute copies of such a program, whether 87 | gratis or for a fee, you must pass on to the recipients the same 88 | freedoms that you received. You must make sure that they, too, receive 89 | or can get the source code. And you must show them these terms so they 90 | know their rights. 91 | 92 | Developers that use the GNU GPL protect your rights with two steps: 93 | (1) assert copyright on the software, and (2) offer you this License 94 | giving you legal permission to copy, distribute and/or modify it. 95 | 96 | For the developers' and authors' protection, the GPL clearly explains 97 | that there is no warranty for this free software. For both users' and 98 | authors' sake, the GPL requires that modified versions be marked as 99 | changed, so that their problems will not be attributed erroneously to 100 | authors of previous versions. 101 | 102 | Some devices are designed to deny users access to install or run 103 | modified versions of the software inside them, although the manufacturer 104 | can do so. This is fundamentally incompatible with the aim of 105 | protecting users' freedom to change the software. The systematic 106 | pattern of such abuse occurs in the area of products for individuals to 107 | use, which is precisely where it is most unacceptable. Therefore, we 108 | have designed this version of the GPL to prohibit the practice for those 109 | products. If such problems arise substantially in other domains, we 110 | stand ready to extend this provision to those domains in future versions 111 | of the GPL, as needed to protect the freedom of users. 112 | 113 | Finally, every program is threatened constantly by software patents. 114 | States should not allow patents to restrict development and use of 115 | software on general-purpose computers, but in those that do, we wish to 116 | avoid the special danger that patents applied to a free program could 117 | make it effectively proprietary. To prevent this, the GPL assures that 118 | patents cannot be used to render the program non-free. 119 | 120 | The precise terms and conditions for copying, distribution and 121 | modification follow. 122 | 123 | TERMS AND CONDITIONS 124 | 125 | 0. Definitions. 126 | 127 | "This License" refers to version 3 of the GNU General Public License. 128 | 129 | "Copyright" also means copyright-like laws that apply to other kinds of 130 | works, such as semiconductor masks. 131 | 132 | "The Program" refers to any copyrightable work licensed under this 133 | License. Each licensee is addressed as "you". "Licensees" and 134 | "recipients" may be individuals or organizations. 135 | 136 | To "modify" a work means to copy from or adapt all or part of the work 137 | in a fashion requiring copyright permission, other than the making of an 138 | exact copy. The resulting work is called a "modified version" of the 139 | earlier work or a work "based on" the earlier work. 140 | 141 | A "covered work" means either the unmodified Program or a work based 142 | on the Program. 143 | 144 | To "propagate" a work means to do anything with it that, without 145 | permission, would make you directly or secondarily liable for 146 | infringement under applicable copyright law, except executing it on a 147 | computer or modifying a private copy. Propagation includes copying, 148 | distribution (with or without modification), making available to the 149 | public, and in some countries other activities as well. 150 | 151 | To "convey" a work means any kind of propagation that enables other 152 | parties to make or receive copies. Mere interaction with a user through 153 | a computer network, with no transfer of a copy, is not conveying. 154 | 155 | An interactive user interface displays "Appropriate Legal Notices" 156 | to the extent that it includes a convenient and prominently visible 157 | feature that (1) displays an appropriate copyright notice, and (2) 158 | tells the user that there is no warranty for the work (except to the 159 | extent that warranties are provided), that licensees may convey the 160 | work under this License, and how to view a copy of this License. If 161 | the interface presents a list of user commands or options, such as a 162 | menu, a prominent item in the list meets this criterion. 163 | 164 | 1. Source Code. 165 | 166 | The "source code" for a work means the preferred form of the work 167 | for making modifications to it. "Object code" means any non-source 168 | form of a work. 169 | 170 | A "Standard Interface" means an interface that either is an official 171 | standard defined by a recognized standards body, or, in the case of 172 | interfaces specified for a particular programming language, one that 173 | is widely used among developers working in that language. 174 | 175 | The "System Libraries" of an executable work include anything, other 176 | than the work as a whole, that (a) is included in the normal form of 177 | packaging a Major Component, but which is not part of that Major 178 | Component, and (b) serves only to enable use of the work with that 179 | Major Component, or to implement a Standard Interface for which an 180 | implementation is available to the public in source code form. A 181 | "Major Component", in this context, means a major essential component 182 | (kernel, window system, and so on) of the specific operating system 183 | (if any) on which the executable work runs, or a compiler used to 184 | produce the work, or an object code interpreter used to run it. 185 | 186 | The "Corresponding Source" for a work in object code form means all 187 | the source code needed to generate, install, and (for an executable 188 | work) run the object code and to modify the work, including scripts to 189 | control those activities. However, it does not include the work's 190 | System Libraries, or general-purpose tools or generally available free 191 | programs which are used unmodified in performing those activities but 192 | which are not part of the work. For example, Corresponding Source 193 | includes interface definition files associated with source files for 194 | the work, and the source code for shared libraries and dynamically 195 | linked subprograms that the work is specifically designed to require, 196 | such as by intimate data communication or control flow between those 197 | subprograms and other parts of the work. 198 | 199 | The Corresponding Source need not include anything that users 200 | can regenerate automatically from other parts of the Corresponding 201 | Source. 202 | 203 | The Corresponding Source for a work in source code form is that 204 | same work. 205 | 206 | 2. Basic Permissions. 207 | 208 | All rights granted under this License are granted for the term of 209 | copyright on the Program, and are irrevocable provided the stated 210 | conditions are met. This License explicitly affirms your unlimited 211 | permission to run the unmodified Program. The output from running a 212 | covered work is covered by this License only if the output, given its 213 | content, constitutes a covered work. This License acknowledges your 214 | rights of fair use or other equivalent, as provided by copyright law. 215 | 216 | You may make, run and propagate covered works that you do not 217 | convey, without conditions so long as your license otherwise remains 218 | in force. You may convey covered works to others for the sole purpose 219 | of having them make modifications exclusively for you, or provide you 220 | with facilities for running those works, provided that you comply with 221 | the terms of this License in conveying all material for which you do 222 | not control copyright. Those thus making or running the covered works 223 | for you must do so exclusively on your behalf, under your direction 224 | and control, on terms that prohibit them from making any copies of 225 | your copyrighted material outside their relationship with you. 226 | 227 | Conveying under any other circumstances is permitted solely under 228 | the conditions stated below. Sublicensing is not allowed; section 10 229 | makes it unnecessary. 230 | 231 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 232 | 233 | No covered work shall be deemed part of an effective technological 234 | measure under any applicable law fulfilling obligations under article 235 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 236 | similar laws prohibiting or restricting circumvention of such 237 | measures. 238 | 239 | When you convey a covered work, you waive any legal power to forbid 240 | circumvention of technological measures to the extent such circumvention 241 | is effected by exercising rights under this License with respect to 242 | the covered work, and you disclaim any intention to limit operation or 243 | modification of the work as a means of enforcing, against the work's 244 | users, your or third parties' legal rights to forbid circumvention of 245 | technological measures. 246 | 247 | 4. Conveying Verbatim Copies. 248 | 249 | You may convey verbatim copies of the Program's source code as you 250 | receive it, in any medium, provided that you conspicuously and 251 | appropriately publish on each copy an appropriate copyright notice; 252 | keep intact all notices stating that this License and any 253 | non-permissive terms added in accord with section 7 apply to the code; 254 | keep intact all notices of the absence of any warranty; and give all 255 | recipients a copy of this License along with the Program. 256 | 257 | You may charge any price or no price for each copy that you convey, 258 | and you may offer support or warranty protection for a fee. 259 | 260 | 5. Conveying Modified Source Versions. 261 | 262 | You may convey a work based on the Program, or the modifications to 263 | produce it from the Program, in the form of source code under the 264 | terms of section 4, provided that you also meet all of these conditions: 265 | 266 | a) The work must carry prominent notices stating that you modified 267 | it, and giving a relevant date. 268 | 269 | b) The work must carry prominent notices stating that it is 270 | released under this License and any conditions added under section 271 | 7. This requirement modifies the requirement in section 4 to 272 | "keep intact all notices". 273 | 274 | c) You must license the entire work, as a whole, under this 275 | License to anyone who comes into possession of a copy. This 276 | License will therefore apply, along with any applicable section 7 277 | additional terms, to the whole of the work, and all its parts, 278 | regardless of how they are packaged. This License gives no 279 | permission to license the work in any other way, but it does not 280 | invalidate such permission if you have separately received it. 281 | 282 | d) If the work has interactive user interfaces, each must display 283 | Appropriate Legal Notices; however, if the Program has interactive 284 | interfaces that do not display Appropriate Legal Notices, your 285 | work need not make them do so. 286 | 287 | A compilation of a covered work with other separate and independent 288 | works, which are not by their nature extensions of the covered work, 289 | and which are not combined with it such as to form a larger program, 290 | in or on a volume of a storage or distribution medium, is called an 291 | "aggregate" if the compilation and its resulting copyright are not 292 | used to limit the access or legal rights of the compilation's users 293 | beyond what the individual works permit. Inclusion of a covered work 294 | in an aggregate does not cause this License to apply to the other 295 | parts of the aggregate. 296 | 297 | 6. Conveying Non-Source Forms. 298 | 299 | You may convey a covered work in object code form under the terms 300 | of sections 4 and 5, provided that you also convey the 301 | machine-readable Corresponding Source under the terms of this License, 302 | in one of these ways: 303 | 304 | a) Convey the object code in, or embodied in, a physical product 305 | (including a physical distribution medium), accompanied by the 306 | Corresponding Source fixed on a durable physical medium 307 | customarily used for software interchange. 308 | 309 | b) Convey the object code in, or embodied in, a physical product 310 | (including a physical distribution medium), accompanied by a 311 | written offer, valid for at least three years and valid for as 312 | long as you offer spare parts or customer support for that product 313 | model, to give anyone who possesses the object code either (1) a 314 | copy of the Corresponding Source for all the software in the 315 | product that is covered by this License, on a durable physical 316 | medium customarily used for software interchange, for a price no 317 | more than your reasonable cost of physically performing this 318 | conveying of source, or (2) access to copy the 319 | Corresponding Source from a network server at no charge. 320 | 321 | c) Convey individual copies of the object code with a copy of the 322 | written offer to provide the Corresponding Source. This 323 | alternative is allowed only occasionally and noncommercially, and 324 | only if you received the object code with such an offer, in accord 325 | with subsection 6b. 326 | 327 | d) Convey the object code by offering access from a designated 328 | place (gratis or for a charge), and offer equivalent access to the 329 | Corresponding Source in the same way through the same place at no 330 | further charge. You need not require recipients to copy the 331 | Corresponding Source along with the object code. If the place to 332 | copy the object code is a network server, the Corresponding Source 333 | may be on a different server (operated by you or a third party) 334 | that supports equivalent copying facilities, provided you maintain 335 | clear directions next to the object code saying where to find the 336 | Corresponding Source. Regardless of what server hosts the 337 | Corresponding Source, you remain obligated to ensure that it is 338 | available for as long as needed to satisfy these requirements. 339 | 340 | e) Convey the object code using peer-to-peer transmission, provided 341 | you inform other peers where the object code and Corresponding 342 | Source of the work are being offered to the general public at no 343 | charge under subsection 6d. 344 | 345 | A separable portion of the object code, whose source code is excluded 346 | from the Corresponding Source as a System Library, need not be 347 | included in conveying the object code work. 348 | 349 | A "User Product" is either (1) a "consumer product", which means any 350 | tangible personal property which is normally used for personal, family, 351 | or household purposes, or (2) anything designed or sold for incorporation 352 | into a dwelling. In determining whether a product is a consumer product, 353 | doubtful cases shall be resolved in favor of coverage. For a particular 354 | product received by a particular user, "normally used" refers to a 355 | typical or common use of that class of product, regardless of the status 356 | of the particular user or of the way in which the particular user 357 | actually uses, or expects or is expected to use, the product. A product 358 | is a consumer product regardless of whether the product has substantial 359 | commercial, industrial or non-consumer uses, unless such uses represent 360 | the only significant mode of use of the product. 361 | 362 | "Installation Information" for a User Product means any methods, 363 | procedures, authorization keys, or other information required to install 364 | and execute modified versions of a covered work in that User Product from 365 | a modified version of its Corresponding Source. The information must 366 | suffice to ensure that the continued functioning of the modified object 367 | code is in no case prevented or interfered with solely because 368 | modification has been made. 369 | 370 | If you convey an object code work under this section in, or with, or 371 | specifically for use in, a User Product, and the conveying occurs as 372 | part of a transaction in which the right of possession and use of the 373 | User Product is transferred to the recipient in perpetuity or for a 374 | fixed term (regardless of how the transaction is characterized), the 375 | Corresponding Source conveyed under this section must be accompanied 376 | by the Installation Information. But this requirement does not apply 377 | if neither you nor any third party retains the ability to install 378 | modified object code on the User Product (for example, the work has 379 | been installed in ROM). 380 | 381 | The requirement to provide Installation Information does not include a 382 | requirement to continue to provide support service, warranty, or updates 383 | for a work that has been modified or installed by the recipient, or for 384 | the User Product in which it has been modified or installed. Access to a 385 | network may be denied when the modification itself materially and 386 | adversely affects the operation of the network or violates the rules and 387 | protocols for communication across the network. 388 | 389 | Corresponding Source conveyed, and Installation Information provided, 390 | in accord with this section must be in a format that is publicly 391 | documented (and with an implementation available to the public in 392 | source code form), and must require no special password or key for 393 | unpacking, reading or copying. 394 | 395 | 7. Additional Terms. 396 | 397 | "Additional permissions" are terms that supplement the terms of this 398 | License by making exceptions from one or more of its conditions. 399 | Additional permissions that are applicable to the entire Program shall 400 | be treated as though they were included in this License, to the extent 401 | that they are valid under applicable law. If additional permissions 402 | apply only to part of the Program, that part may be used separately 403 | under those permissions, but the entire Program remains governed by 404 | this License without regard to the additional permissions. 405 | 406 | When you convey a copy of a covered work, you may at your option 407 | remove any additional permissions from that copy, or from any part of 408 | it. (Additional permissions may be written to require their own 409 | removal in certain cases when you modify the work.) You may place 410 | additional permissions on material, added by you to a covered work, 411 | for which you have or can give appropriate copyright permission. 412 | 413 | Notwithstanding any other provision of this License, for material you 414 | add to a covered work, you may (if authorized by the copyright holders of 415 | that material) supplement the terms of this License with terms: 416 | 417 | a) Disclaiming warranty or limiting liability differently from the 418 | terms of sections 15 and 16 of this License; or 419 | 420 | b) Requiring preservation of specified reasonable legal notices or 421 | author attributions in that material or in the Appropriate Legal 422 | Notices displayed by works containing it; or 423 | 424 | c) Prohibiting misrepresentation of the origin of that material, or 425 | requiring that modified versions of such material be marked in 426 | reasonable ways as different from the original version; or 427 | 428 | d) Limiting the use for publicity purposes of names of licensors or 429 | authors of the material; or 430 | 431 | e) Declining to grant rights under trademark law for use of some 432 | trade names, trademarks, or service marks; or 433 | 434 | f) Requiring indemnification of licensors and authors of that 435 | material by anyone who conveys the material (or modified versions of 436 | it) with contractual assumptions of liability to the recipient, for 437 | any liability that these contractual assumptions directly impose on 438 | those licensors and authors. 439 | 440 | All other non-permissive additional terms are considered "further 441 | restrictions" within the meaning of section 10. If the Program as you 442 | received it, or any part of it, contains a notice stating that it is 443 | governed by this License along with a term that is a further 444 | restriction, you may remove that term. If a license document contains 445 | a further restriction but permits relicensing or conveying under this 446 | License, you may add to a covered work material governed by the terms 447 | of that license document, provided that the further restriction does 448 | not survive such relicensing or conveying. 449 | 450 | If you add terms to a covered work in accord with this section, you 451 | must place, in the relevant source files, a statement of the 452 | additional terms that apply to those files, or a notice indicating 453 | where to find the applicable terms. 454 | 455 | Additional terms, permissive or non-permissive, may be stated in the 456 | form of a separately written license, or stated as exceptions; 457 | the above requirements apply either way. 458 | 459 | 8. Termination. 460 | 461 | You may not propagate or modify a covered work except as expressly 462 | provided under this License. Any attempt otherwise to propagate or 463 | modify it is void, and will automatically terminate your rights under 464 | this License (including any patent licenses granted under the third 465 | paragraph of section 11). 466 | 467 | However, if you cease all violation of this License, then your 468 | license from a particular copyright holder is reinstated (a) 469 | provisionally, unless and until the copyright holder explicitly and 470 | finally terminates your license, and (b) permanently, if the copyright 471 | holder fails to notify you of the violation by some reasonable means 472 | prior to 60 days after the cessation. 473 | 474 | Moreover, your license from a particular copyright holder is 475 | reinstated permanently if the copyright holder notifies you of the 476 | violation by some reasonable means, this is the first time you have 477 | received notice of violation of this License (for any work) from that 478 | copyright holder, and you cure the violation prior to 30 days after 479 | your receipt of the notice. 480 | 481 | Termination of your rights under this section does not terminate the 482 | licenses of parties who have received copies or rights from you under 483 | this License. If your rights have been terminated and not permanently 484 | reinstated, you do not qualify to receive new licenses for the same 485 | material under section 10. 486 | 487 | 9. Acceptance Not Required for Having Copies. 488 | 489 | You are not required to accept this License in order to receive or 490 | run a copy of the Program. Ancillary propagation of a covered work 491 | occurring solely as a consequence of using peer-to-peer transmission 492 | to receive a copy likewise does not require acceptance. However, 493 | nothing other than this License grants you permission to propagate or 494 | modify any covered work. These actions infringe copyright if you do 495 | not accept this License. Therefore, by modifying or propagating a 496 | covered work, you indicate your acceptance of this License to do so. 497 | 498 | 10. Automatic Licensing of Downstream Recipients. 499 | 500 | Each time you convey a covered work, the recipient automatically 501 | receives a license from the original licensors, to run, modify and 502 | propagate that work, subject to this License. You are not responsible 503 | for enforcing compliance by third parties with this License. 504 | 505 | An "entity transaction" is a transaction transferring control of an 506 | organization, or substantially all assets of one, or subdividing an 507 | organization, or merging organizations. If propagation of a covered 508 | work results from an entity transaction, each party to that 509 | transaction who receives a copy of the work also receives whatever 510 | licenses to the work the party's predecessor in interest had or could 511 | give under the previous paragraph, plus a right to possession of the 512 | Corresponding Source of the work from the predecessor in interest, if 513 | the predecessor has it or can get it with reasonable efforts. 514 | 515 | You may not impose any further restrictions on the exercise of the 516 | rights granted or affirmed under this License. For example, you may 517 | not impose a license fee, royalty, or other charge for exercise of 518 | rights granted under this License, and you may not initiate litigation 519 | (including a cross-claim or counterclaim in a lawsuit) alleging that 520 | any patent claim is infringed by making, using, selling, offering for 521 | sale, or importing the Program or any portion of it. 522 | 523 | 11. Patents. 524 | 525 | A "contributor" is a copyright holder who authorizes use under this 526 | License of the Program or a work on which the Program is based. The 527 | work thus licensed is called the contributor's "contributor version". 528 | 529 | A contributor's "essential patent claims" are all patent claims 530 | owned or controlled by the contributor, whether already acquired or 531 | hereafter acquired, that would be infringed by some manner, permitted 532 | by this License, of making, using, or selling its contributor version, 533 | but do not include claims that would be infringed only as a 534 | consequence of further modification of the contributor version. For 535 | purposes of this definition, "control" includes the right to grant 536 | patent sublicenses in a manner consistent with the requirements of 537 | this License. 538 | 539 | Each contributor grants you a non-exclusive, worldwide, royalty-free 540 | patent license under the contributor's essential patent claims, to 541 | make, use, sell, offer for sale, import and otherwise run, modify and 542 | propagate the contents of its contributor version. 543 | 544 | In the following three paragraphs, a "patent license" is any express 545 | agreement or commitment, however denominated, not to enforce a patent 546 | (such as an express permission to practice a patent or covenant not to 547 | sue for patent infringement). To "grant" such a patent license to a 548 | party means to make such an agreement or commitment not to enforce a 549 | patent against the party. 550 | 551 | If you convey a covered work, knowingly relying on a patent license, 552 | and the Corresponding Source of the work is not available for anyone 553 | to copy, free of charge and under the terms of this License, through a 554 | publicly available network server or other readily accessible means, 555 | then you must either (1) cause the Corresponding Source to be so 556 | available, or (2) arrange to deprive yourself of the benefit of the 557 | patent license for this particular work, or (3) arrange, in a manner 558 | consistent with the requirements of this License, to extend the patent 559 | license to downstream recipients. "Knowingly relying" means you have 560 | actual knowledge that, but for the patent license, your conveying the 561 | covered work in a country, or your recipient's use of the covered work 562 | in a country, would infringe one or more identifiable patents in that 563 | country that you have reason to believe are valid. 564 | 565 | If, pursuant to or in connection with a single transaction or 566 | arrangement, you convey, or propagate by procuring conveyance of, a 567 | covered work, and grant a patent license to some of the parties 568 | receiving the covered work authorizing them to use, propagate, modify 569 | or convey a specific copy of the covered work, then the patent license 570 | you grant is automatically extended to all recipients of the covered 571 | work and works based on it. 572 | 573 | A patent license is "discriminatory" if it does not include within 574 | the scope of its coverage, prohibits the exercise of, or is 575 | conditioned on the non-exercise of one or more of the rights that are 576 | specifically granted under this License. You may not convey a covered 577 | work if you are a party to an arrangement with a third party that is 578 | in the business of distributing software, under which you make payment 579 | to the third party based on the extent of your activity of conveying 580 | the work, and under which the third party grants, to any of the 581 | parties who would receive the covered work from you, a discriminatory 582 | patent license (a) in connection with copies of the covered work 583 | conveyed by you (or copies made from those copies), or (b) primarily 584 | for and in connection with specific products or compilations that 585 | contain the covered work, unless you entered into that arrangement, 586 | or that patent license was granted, prior to 28 March 2007. 587 | 588 | Nothing in this License shall be construed as excluding or limiting 589 | any implied license or other defenses to infringement that may 590 | otherwise be available to you under applicable patent law. 591 | 592 | 12. No Surrender of Others' Freedom. 593 | 594 | If conditions are imposed on you (whether by court order, agreement or 595 | otherwise) that contradict the conditions of this License, they do not 596 | excuse you from the conditions of this License. If you cannot convey a 597 | covered work so as to satisfy simultaneously your obligations under this 598 | License and any other pertinent obligations, then as a consequence you may 599 | not convey it at all. For example, if you agree to terms that obligate you 600 | to collect a royalty for further conveying from those to whom you convey 601 | the Program, the only way you could satisfy both those terms and this 602 | License would be to refrain entirely from conveying the Program. 603 | 604 | 13. Use with the GNU Affero General Public License. 605 | 606 | Notwithstanding any other provision of this License, you have 607 | permission to link or combine any covered work with a work licensed 608 | under version 3 of the GNU Affero General Public License into a single 609 | combined work, and to convey the resulting work. The terms of this 610 | License will continue to apply to the part which is the covered work, 611 | but the special requirements of the GNU Affero General Public License, 612 | section 13, concerning interaction through a network will apply to the 613 | combination as such. 614 | 615 | 14. Revised Versions of this License. 616 | 617 | The Free Software Foundation may publish revised and/or new versions of 618 | the GNU General Public License from time to time. Such new versions will 619 | be similar in spirit to the present version, but may differ in detail to 620 | address new problems or concerns. 621 | 622 | Each version is given a distinguishing version number. If the 623 | Program specifies that a certain numbered version of the GNU General 624 | Public License "or any later version" applies to it, you have the 625 | option of following the terms and conditions either of that numbered 626 | version or of any later version published by the Free Software 627 | Foundation. If the Program does not specify a version number of the 628 | GNU General Public License, you may choose any version ever published 629 | by the Free Software Foundation. 630 | 631 | If the Program specifies that a proxy can decide which future 632 | versions of the GNU General Public License can be used, that proxy's 633 | public statement of acceptance of a version permanently authorizes you 634 | to choose that version for the Program. 635 | 636 | Later license versions may give you additional or different 637 | permissions. However, no additional obligations are imposed on any 638 | author or copyright holder as a result of your choosing to follow a 639 | later version. 640 | 641 | 15. Disclaimer of Warranty. 642 | 643 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 644 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 645 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 646 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 647 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 648 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 649 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 650 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 651 | 652 | 16. Limitation of Liability. 653 | 654 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 655 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 656 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 657 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 658 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 659 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 660 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 661 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 662 | SUCH DAMAGES. 663 | 664 | 17. Interpretation of Sections 15 and 16. 665 | 666 | If the disclaimer of warranty and limitation of liability provided 667 | above cannot be given local legal effect according to their terms, 668 | reviewing courts shall apply local law that most closely approximates 669 | an absolute waiver of all civil liability in connection with the 670 | Program, unless a warranty or assumption of liability accompanies a 671 | copy of the Program in return for a fee. 672 | 673 | END OF TERMS AND CONDITIONS 674 | 675 | How to Apply These Terms to Your New Programs 676 | 677 | If you develop a new program, and you want it to be of the greatest 678 | possible use to the public, the best way to achieve this is to make it 679 | free software which everyone can redistribute and change under these terms. 680 | 681 | To do so, attach the following notices to the program. It is safest 682 | to attach them to the start of each source file to most effectively 683 | state the exclusion of warranty; and each file should have at least 684 | the "copyright" line and a pointer to where the full notice is found. 685 | 686 | 687 | Copyright (C) 688 | 689 | This program is free software: you can redistribute it and/or modify 690 | it under the terms of the GNU General Public License as published by 691 | the Free Software Foundation, either version 3 of the License, or 692 | (at your option) any later version. 693 | 694 | This program is distributed in the hope that it will be useful, 695 | but WITHOUT ANY WARRANTY; without even the implied warranty of 696 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 697 | GNU General Public License for more details. 698 | 699 | You should have received a copy of the GNU General Public License 700 | along with this program. If not, see . 701 | 702 | Also add information on how to contact you by electronic and paper mail. 703 | 704 | If the program does terminal interaction, make it output a short 705 | notice like this when it starts in an interactive mode: 706 | 707 | Copyright (C) 708 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 709 | This is free software, and you are welcome to redistribute it 710 | under certain conditions; type `show c' for details. 711 | 712 | The hypothetical commands `show w' and `show c' should show the appropriate 713 | parts of the General Public License. Of course, your program's commands 714 | might be different; for a GUI interface, you would use an "about box". 715 | 716 | You should also get your employer (if you work as a programmer) or school, 717 | if any, to sign a "copyright disclaimer" for the program, if necessary. 718 | For more information on this, and how to apply and follow the GNU GPL, see 719 | . 720 | 721 | The GNU General Public License does not permit incorporating your program 722 | into proprietary programs. If your program is a subroutine library, you 723 | may consider it more useful to permit linking proprietary applications with 724 | the library. If this is what you want to do, use the GNU Lesser General 725 | Public License instead of this License. But first, please read 726 | . 727 | -------------------------------------------------------------------------------- /constructor/README.md: -------------------------------------------------------------------------------- 1 | # MAKING AN INSTALLER 2 | 3 | This folder contains some files which can be used to create an installer for ABBA by using https://github.com/conda/constructor 4 | 5 | The yaml file contains the dependencies required to make the installer, but that's not all. Each OS has it own requirements. 6 | 7 | Normally you won't need to use the content of this folder. It's just there for the main dev (Nico) that has to make releases from times to time. But if you're sufficiently knowledgable in python, you won't need the installer and will just run ABBA from source and by using the env yaml file in the parent directory. 8 | 9 | ## All OS 10 | 11 | This folder: 12 | 13 | - needs to contains an up-to-date `Fiji.app` folder, but without Java (take it from https://imagej.net/software/fiji/downloads, choose no JRE) 14 | - then, in this Fiji, put ABBA, for instance by installing it from intellij and specifying the Fiji directory and maven build it. 15 | 16 | 17 | ## Windows 18 | 19 | The win folder should also contain the elastix executable. Version 5.0.1: `win\elastix-5.0.1-win64` 20 | 21 | Then run `prepare_win.bat` which copies the abba-python code in the same folder (that's because I do not know how to tar properly from another folder) and zips everything into a abba-pack-win.tar.gz file which will be included in the installer. 22 | 23 | Then create a conda env, install conda constructor in it, and run `constructor .` once your current directory is there. After a few minutes, an executable file should be created. That's the installer! 24 | 25 | It is big because it contains a pretty big conda environment, some models, java, and an almost complete Fiji. 26 | 27 | ## Mac 28 | 29 | see https://github.com/NicoKiaru/ABBA-Python/issues/16 30 | 31 | ## Linux 32 | 33 | see https://github.com/NicoKiaru/ABBA-Python/issues/17 -------------------------------------------------------------------------------- /constructor/construct.yaml: -------------------------------------------------------------------------------- 1 | name: ABBA-Python 2 | version: 0.5.2 3 | 4 | channels: 5 | - conda-forge 6 | - defaults 7 | 8 | specs: 9 | - python=3.7.12 10 | - mkl 11 | - numpy=1.21.6 12 | - pandas=1.3.5 13 | - pip=22.2.2 14 | - protobuf=4.21.7 15 | - scikit-image=0.17.2 16 | - scikit-learn=0.23.2 17 | - scipy=1.6.0 18 | - tensorflow=1.14.0 # modif 1: other wise the predictions from DeepSlice are bad with nan values everywhere 19 | - tqdm=4.56.0 20 | - pyimagej=1.2.1 21 | - xarray=0.20.2 22 | - h5py=2.10.0 # modif 2: seems required for deepslice, otherwise a keras decode utf8 error is raiser 23 | - bg-atlasapi=1.0.2 24 | - openssl=1.1.1q # modif 3: dll not loaded error with netcdf4 on windows 25 | - openjdk=8 # 8 or 11 should work, but java 11 has issues with xml 26 | - netcdf4=1.5.7 27 | - conda 28 | - console_shortcut # [win] 29 | - menuinst # [win] 30 | 31 | register_python: false 32 | initialize_conda: false 33 | 34 | company: BIOP-EPFL 35 | 36 | extra_files: 37 | - abba-pack-win.tar.gz # [win] 38 | 39 | welcome_image: img/logo128x128.png # [win] 40 | header_image: img/logo.png # [win] 41 | icon_image: img/logo128x128.png # [win] 42 | 43 | post_install: post_install_unix.sh # [unix] 44 | post_install: post_install_win.bat # [win] 45 | 46 | # TODO : pre_uninstall to remove extra shortcuts in windows -------------------------------------------------------------------------------- /constructor/img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NicoKiaru/ABBA-Python/1626654aaf370cd2619896195c7f88aeb7d16a7c/constructor/img/logo.png -------------------------------------------------------------------------------- /constructor/img/logo128x128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NicoKiaru/ABBA-Python/1626654aaf370cd2619896195c7f88aeb7d16a7c/constructor/img/logo128x128.png -------------------------------------------------------------------------------- /constructor/img/logo256x256.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NicoKiaru/ABBA-Python/1626654aaf370cd2619896195c7f88aeb7d16a7c/constructor/img/logo256x256.ico -------------------------------------------------------------------------------- /constructor/img/logo256x256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NicoKiaru/ABBA-Python/1626654aaf370cd2619896195c7f88aeb7d16a7c/constructor/img/logo256x256.png -------------------------------------------------------------------------------- /constructor/post_install_unix.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | tar -xzvf "$PREFIX/abba-code.tar.gz" 4 | -------------------------------------------------------------------------------- /constructor/post_install_win.bat: -------------------------------------------------------------------------------- 1 | REM untar the code to the install folder 2 | REM tar -cvzf abba-code.tar.gz abba-code img 3 | tar -xzvf "%PREFIX%\abba-pack-win.tar.gz" -C "%PREFIX%" 4 | 5 | set shortcutPath='%userprofile%\Desktop\ABBA.lnk' 6 | set shortcutTarget='%PREFIX%\win\run-abba.bat' 7 | set shortcutIcon='%PREFIX%\img\logo256x256.ico' 8 | 9 | 10 | REM '%PREFIX%\img\logo256x256.ico' 11 | 12 | @echo off 13 | REM set /p "id=Shortcut path: " 14 | 15 | echo %shortcutPath% 16 | 17 | @echo off 18 | REM set /p "id=Shortcut target: " 19 | 20 | echo %shortcutTarget% 21 | 22 | @echo off 23 | REM set /p "id=Installing shortcut: " 24 | 25 | %SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe "$s=(New-Object -COM WScript.Shell).CreateShortcut("%shortcutPath%");$s.IconLocation="%shortcutIcon%";$s.TargetPath="%shortcutTarget%";$s.Save()" 26 | 27 | REM add shortcut to C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs 28 | 29 | set shortcutProgramsPath='%userprofile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\ABBA.lnk' 30 | 31 | %SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe "$s=(New-Object -COM WScript.Shell).CreateShortcut("%shortcutProgramsPath%");$s.IconLocation="%shortcutIcon%";$s.TargetPath="%shortcutTarget%";$s.Save()" 32 | 33 | echo ABBA shortcuts installed 34 | 35 | @echo off 36 | REM set /p "id=Shortcut installed " 37 | 38 | echo Checking if Visual C++ redistributable is installed... 39 | 40 | if %errorlevel%==0 ( 41 | for /f "tokens=2" %%i in ('reg query "HKLM\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64" /v Version ^| findstr /i "^[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*$"') do set installed_version=%%i 42 | echo Found installed version %installed_version% 43 | if "%installed_version%" geq "14.0.0.0" ( 44 | echo Visual C++ redistributable version is up to date. Skipping installation. 45 | goto end 46 | ) 47 | ) 48 | 49 | if %errorlevel%==0 ( 50 | echo Visual C++ redistributable version %REDIST_VERSION% is already installed. 51 | goto end 52 | ) 53 | 54 | echo Visual C++ redistributable version %REDIST_VERSION% is not installed. Downloading... 55 | 56 | %SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "Invoke-WebRequest '%REDIST_URL%' -OutFile '%REDIST_EXE%'" 57 | 58 | echo Installing Visual C++ redistributable version %REDIST_VERSION%... 59 | 60 | start /wait %REDIST_EXE% /quiet /norestart 61 | 62 | echo Visual C++ redistributable version %REDIST_VERSION% has been installed successfully. 63 | 64 | :end 65 | endlocal 66 | -------------------------------------------------------------------------------- /constructor/prepare_win.bat: -------------------------------------------------------------------------------- 1 | cd /D "%~dp0" 2 | 3 | robocopy ../src/abba_python abba_python /E 4 | 5 | tar -cvzf abba-pack-win.tar.gz abba_python img win Fiji.app -------------------------------------------------------------------------------- /constructor/unix/TODO.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NicoKiaru/ABBA-Python/1626654aaf370cd2619896195c7f88aeb7d16a7c/constructor/unix/TODO.txt -------------------------------------------------------------------------------- /constructor/win/README.txt: -------------------------------------------------------------------------------- 1 | TODO : You should unzip elastix-5.0.1 in this folder, windows version 2 | 3 | The folder hierarchy should be: 4 | constructor/win/elastix-5.0.1-win64 5 | and for instance the file 6 | constructor/win/elastix-5.0.1-win64/elastix.exe should exist -------------------------------------------------------------------------------- /constructor/win/run-abba.bat: -------------------------------------------------------------------------------- 1 | cd /D "%~dp0" & ..\condabin\activate.bat & ..\python.exe ..\abba_python\run-abba-local-fiji.py 2 | -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | # You really need to use mamba or this env will need a year to be created 2 | # Also : some dependencies explicit versions are kept, mostly these are obtained 3 | # by trimming down the deepslice envs examples: 4 | # https://github.com/PolarBean/DeepSlice/tree/master/conda_environments 5 | # and fixing issues as mentioned in the explicit versions below 6 | # it seems to work with for win64 machine 7 | name: abba 8 | channels: 9 | - conda-forge 10 | - defaults 11 | dependencies: 12 | - mkl 13 | - numpy 14 | - pandas 15 | - pip 16 | - protobuf 17 | - scikit-image 18 | - scikit-learn 19 | - scipy 20 | - tensorflow=1.14.0 # modif 1: other wise the predictions from DeepSlice are bad with nan values everywhere 21 | - tqdm 22 | - jupyterlab 23 | - pyimagej 24 | - python 25 | - xarray 26 | - h5py=2.10.0 # modif 2: seems required for deepslice, otherwise a keras decode utf8 error is raiser 27 | - bg-atlasapi 28 | - openssl=1.1.1q # modif 3: dll not loaded error with netcdf4 on windows 29 | - openjdk=8 # 8 or 11 should work, pyimagej not tested for version above 30 | - netcdf4 31 | 32 | -------------------------------------------------------------------------------- /src/0. Register And Save State.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "007bdd6f", 6 | "metadata": {}, 7 | "source": [ 8 | "# [Aligning Big Brains and Atlases](https://biop.github.io/ijp-imagetoatlas/) in Python\n", 9 | "\n", 10 | "This series of notebook demoes the use of ABBA with python.\n", 11 | "\n", 12 | "If you managed to create an environment with PyImageJ and DeepSlice, you will be able, by running this notebook, to perform a fully automated registration of demo mouse brain sections to the Adult Mouse Allen Brain atlas.\n", 13 | "\n", 14 | "For this notebook to run, an atlas will need to be downloaded, as well as some sample dataset.\n", 15 | "\n", 16 | "The dataset is downloaded from https://zenodo.org/record/6592478\n", 17 | "\n", 18 | "Multichannel registration works reasonably well in this notebook because the first channel of the atlas (NISSL, indexed 0), is ressembling the DAPI channel of the slices (indexed 0), and the second channel of the atlas (ARA, indexed 1), is ressembling the autofluorescence channel of the slices (indexed 1).\n", 19 | "\n", 20 | "NOTE : You need to set the elastix and transformix path for the elastix registration steps." 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "id": "5c4e9d2f", 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "# core dependencies\n", 31 | "import os\n", 32 | "import time\n", 33 | "from pathlib import Path\n", 34 | "\n", 35 | "from abba_python.Abba import Abba\n", 36 | "\n", 37 | "from bg_atlasapi import utils\n", 38 | "\n", 39 | "#from scijava_python_command.magic import cell_with_modal_ui" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": null, 45 | "id": "86a102df", 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "# Demo dataset for automated slices registration\n", 50 | "zenodo_demo_slices_url = 'https://zenodo.org/record/6592478/files/'\n", 51 | "\n", 52 | "\n", 53 | "# Only one section every five section is used for this demo\n", 54 | "demo_sections = [\n", 55 | " 'S00.tif',\n", 56 | " 'S05.tif',\n", 57 | " 'S10.tif',\n", 58 | " 'S15.tif',\n", 59 | " 'S20.tif',\n", 60 | " 'S25.tif',\n", 61 | " 'S30.tif',\n", 62 | " 'S35.tif',\n", 63 | " 'S40.tif',\n", 64 | " 'S45.tif',\n", 65 | " 'S50.tif',\n", 66 | " 'S55.tif',\n", 67 | " 'S60.tif',\n", 68 | " 'S65.tif',\n", 69 | " 'S70.tif',\n", 70 | " 'S75.tif',\n", 71 | " 'S80.tif']\n", 72 | "\n", 73 | "\n", 74 | "def download_if_necessary(base_path, section_name):\n", 75 | " output_path = Path(base_path + section_name)\n", 76 | " if not output_path.exists():\n", 77 | " utils.check_internet_connection()\n", 78 | " url = zenodo_demo_slices_url + section_name + '?download=1'\n", 79 | " utils.retrieve_over_http(url, output_path)\n", 80 | "\n", 81 | "\n", 82 | "def download_test_images(base_path):\n", 83 | " [download_if_necessary(base_path, section) for section in demo_sections]\n", 84 | "\n" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "id": "9dbd7118", 90 | "metadata": {}, 91 | "source": [ 92 | "## 1. Download test sections if necessary\n", 93 | "\n", 94 | " " 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": null, 100 | "id": "f68706c1", 101 | "metadata": {}, 102 | "outputs": [], 103 | "source": [ 104 | "basePath = os.getcwd() + '/images/'\n", 105 | "\n", 106 | "if not os.path.exists(basePath):\n", 107 | " os.makedirs(basePath)\n", 108 | " \n", 109 | "download_test_images(basePath)" 110 | ] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "id": "54979364", 115 | "metadata": {}, 116 | "source": [ 117 | "## 2. ABBA initialization" 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": null, 123 | "id": "98c03c88", 124 | "metadata": { 125 | "scrolled": true 126 | }, 127 | "outputs": [], 128 | "source": [ 129 | "\n", 130 | "\n", 131 | "headless = False\n", 132 | "\n", 133 | "# -- FOR DEBUGGING\n", 134 | "# import imagej.doctor\n", 135 | "# imagej.doctor.checkup()\n", 136 | "# imagej.doctor.debug_to_stderr()\n", 137 | "\n", 138 | "import logging\n", 139 | "# logging.basicConfig(level=logging.DEBUG)\n", 140 | "\n", 141 | "if headless:\n", 142 | " # -- HEADLESS\n", 143 | " # create a thread: the jupyter UI will not be responsive is the cell is not finished. \n", 144 | " # that's why it's needed to split the initialisation in two cells.\n", 145 | " abba = Abba('Adult Mouse Brain - Allen Brain Atlas V3p1', headless=True)\n", 146 | " \n", 147 | "else:\n", 148 | " # -- NOT HEADLESS\n", 149 | " abba = Abba('Adult Mouse Brain - Allen Brain Atlas V3p1')\n", 150 | " abba.show_bdv_ui() # creates and show a bdv view\n" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "id": "2f0ce139", 157 | "metadata": {}, 158 | "outputs": [], 159 | "source": [ 160 | "# Just make sure that elastix and transformix are correctly set -> Useless in headless mode, because the popup window is not displayed\n", 161 | "if not headless:\n", 162 | " # Maybe just run it once not in headless to set elastix and transformix path correctly. They will be remembered in headless mode (stored in java Prefs)\n", 163 | " abba.ij.command().run('ch.epfl.biop.wrappers.ij2command.BiopWrappersSet',True)" 164 | ] 165 | }, 166 | { 167 | "cell_type": "markdown", 168 | "id": "358e4e2c", 169 | "metadata": {}, 170 | "source": [ 171 | "## 3. Import sections into ABBA" 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": null, 177 | "id": "5c444a91", 178 | "metadata": {}, 179 | "outputs": [], 180 | "source": [ 181 | "# import sections into ABBA\n", 182 | "files = [basePath + section for section in demo_sections]\n", 183 | "abba.import_from_files(filepaths=files)\n", 184 | "\n", 185 | "# ALL REGISTRATIONS AND COMMANDS BELOW ARE PERFORMED ON THE SELECTED SLICES!!\n", 186 | "# since we want to register all of them, we select all of them\n", 187 | "# abba.select_all_slices()\n", 188 | "abba.deselect_all_slices()\n", 189 | "# abba.select_slices([0]) # only one for testing\n", 190 | "# abba.select_all_slices()\n" 191 | ] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "execution_count": null, 196 | "id": "96333598", 197 | "metadata": {}, 198 | "outputs": [], 199 | "source": [ 200 | "abba.select_all_slices()" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": null, 206 | "id": "66f97d0a", 207 | "metadata": {}, 208 | "outputs": [], 209 | "source": [ 210 | "# we want to avoid saturation in the display. This does not matter for\n", 211 | "# all registration methods EXCEPT for DeepSlice, which takes in rgb images\n", 212 | "abba.change_display_settings(0, 0, 500)\n", 213 | "abba.change_display_settings(1, 0, 1200)\n", 214 | "\n", 215 | "if not headless:\n", 216 | " # programmatic way to show (or hide) sections and channels\n", 217 | " abba.get_bdv_view().setSelectedSlicesVisibility(True)\n", 218 | " abba.get_bdv_view().setSelectedSlicesVisibility(0, True) # Channel 0\n", 219 | " abba.get_bdv_view().setSelectedSlicesVisibility(1, True) # Channel 1" 220 | ] 221 | }, 222 | { 223 | "cell_type": "markdown", 224 | "id": "3964abcb", 225 | "metadata": {}, 226 | "source": [ 227 | "## 4. DeepSlice Registration(s)" 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": null, 233 | "id": "e65db448", 234 | "metadata": {}, 235 | "outputs": [], 236 | "source": [ 237 | "# a first deepslice registration round : possible because it's the Allen CCF atlas, cut in coronal mode\n", 238 | "# what's assumed : the sections are already in the correct order\n", 239 | "abba.register_slices_deepslice(channels=[0, 1])\n", 240 | "\n", 241 | "# second deepslice registration: because the slices are resampled for the registration,\n", 242 | "# we usually get a slightly better positioning along z and cutting angle\n", 243 | "# also: it's fast, and the combination of two affine transforms is\n", 244 | "# an affine transform, so it's not like we are adding extra degrees of freedom\n", 245 | "# abba.register_slices_deepslice(channels=[0, 1])" 246 | ] 247 | }, 248 | { 249 | "cell_type": "markdown", 250 | "id": "83b8f828", 251 | "metadata": {}, 252 | "source": [ 253 | "## 5. Elastix affine registration" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": null, 259 | "id": "4d364363", 260 | "metadata": {}, 261 | "outputs": [], 262 | "source": [ 263 | "\n", 264 | "# a round of elastix registration, affine\n", 265 | "# the channel 0 of the dataset (DAPI) is registered with the Nissl Channel of the atlas (0)\n", 266 | "# and the channel 1 of the dataset (mainly autofluo) is registered with the autofluo channel of the atlas (1)\n", 267 | "# these two channels have equal weights in the registration process\n", 268 | "abba.register_slices_elastix_affine(channels_slice_csv='0,1',\n", 269 | " channels_atlas_csv='0,1',\n", 270 | " pixel_size_micrometer=40)" 271 | ] 272 | }, 273 | { 274 | "cell_type": "markdown", 275 | "id": "ee4cb12b", 276 | "metadata": {}, 277 | "source": [ 278 | "## 6. Elastix spline registration" 279 | ] 280 | }, 281 | { 282 | "cell_type": "code", 283 | "execution_count": null, 284 | "id": "f08093da", 285 | "metadata": {}, 286 | "outputs": [], 287 | "source": [ 288 | "# %%cell_with_modal_ui\n", 289 | "# optional: a round of elastix registration, spline\n", 290 | "# same channels as in the affine registration\n", 291 | "# 5 control points along x = very coarse spline (and thus maybe unnecessary)\n", 292 | "# abba.register_elastix_spline(\n", 293 | "# nb_control_points=5,\n", 294 | "# atlas_image_channels=[0, 1],\n", 295 | "# slice_image_channels=[0, 1],\n", 296 | "# pixel_size_micrometer=40).get()\n", 297 | "\n", 298 | "# a round of elastix registration, affine\n", 299 | "# same channels as in the affine registration \n", 300 | "# 16 control points = reasonable spline, which allows for local corrections, without deforming two much the section\n", 301 | "abba.register_slices_elastix_spline(channels_slice_csv='0,1',\n", 302 | " channels_atlas_csv='0,1',\n", 303 | " nb_control_points_x=16,\n", 304 | " pixel_size_micrometer=20)" 305 | ] 306 | }, 307 | { 308 | "cell_type": "markdown", 309 | "id": "57c522c1", 310 | "metadata": {}, 311 | "source": [ 312 | "## 7. Wait for end of all registrations" 313 | ] 314 | }, 315 | { 316 | "cell_type": "code", 317 | "execution_count": null, 318 | "id": "9d4a3a3c", 319 | "metadata": {}, 320 | "outputs": [], 321 | "source": [ 322 | "# all tasks/registrations are enqueued and executed asynchronously\n", 323 | "# if you need to wait before saving, then wait for all tasks to be finished:\n", 324 | "abba.wait_for_end_of_tasks()" 325 | ] 326 | }, 327 | { 328 | "cell_type": "markdown", 329 | "id": "b7508c96", 330 | "metadata": {}, 331 | "source": [ 332 | "## 8. Saving the result" 333 | ] 334 | }, 335 | { 336 | "cell_type": "code", 337 | "execution_count": null, 338 | "id": "27e6a478", 339 | "metadata": {}, 340 | "outputs": [], 341 | "source": [ 342 | "# abba.set_slices_thickness_match_neighbors() # not critical, but for 3d reconstruction it will allow for each slice to occupy the place available between its neighbors\n", 343 | "\n", 344 | "save_dir = os.path.join(os.getcwd(), 'temp', 'notebook0', 'state')\n", 345 | "\n", 346 | "if not os.path.exists(save_dir):\n", 347 | " os.makedirs(save_dir)\n", 348 | "\n", 349 | "\n", 350 | "abba.state_save(save_dir+\"/state.abba\") # full absolute path needed" 351 | ] 352 | } 353 | ], 354 | "metadata": { 355 | "kernelspec": { 356 | "display_name": "Python 3 (ipykernel)", 357 | "language": "python", 358 | "name": "python3" 359 | }, 360 | "language_info": { 361 | "codemirror_mode": { 362 | "name": "ipython", 363 | "version": 3 364 | }, 365 | "file_extension": ".py", 366 | "mimetype": "text/x-python", 367 | "name": "python", 368 | "nbconvert_exporter": "python", 369 | "pygments_lexer": "ipython3", 370 | "version": "3.7.12" 371 | } 372 | }, 373 | "nbformat": 4, 374 | "nbformat_minor": 5 375 | } 376 | -------------------------------------------------------------------------------- /src/1. Open State.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "007bdd6f", 6 | "metadata": {}, 7 | "source": [ 8 | "# [Aligning Big Brains and Atlases](https://biop.github.io/ijp-imagetoatlas/) in Python\n", 9 | "\n", 10 | "This series of notebook demoes the use of ABBA with python.\n", 11 | "\n", 12 | "If you have executed the previous notebook, you can re-open the saved state file.\n", 13 | "\n", 14 | "ABBA is not headless in this notebook, you can see use the GUI to act on the registration.\n" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "id": "5c4e9d2f", 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "# core dependencies\n", 25 | "import os\n", 26 | "import time\n", 27 | "from pathlib import Path\n", 28 | "\n", 29 | "\n", 30 | "from bg_atlasapi import show_atlases\n", 31 | "from bg_atlasapi import utils\n", 32 | "\n", 33 | "from abba_python.Abba import Abba" 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "id": "54979364", 39 | "metadata": {}, 40 | "source": [ 41 | "## 1. ABBA initialization" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "id": "98c03c88", 48 | "metadata": { 49 | "scrolled": true 50 | }, 51 | "outputs": [], 52 | "source": [ 53 | "# -- NOT HEADLESS\n", 54 | "abba = Abba('Adult Mouse Brain - Allen Brain Atlas V3p1') # You may have to click a window!\n", 55 | "abba.show_bdv_ui() # creates and show a bdv view" 56 | ] 57 | }, 58 | { 59 | "cell_type": "markdown", 60 | "id": "358e4e2c", 61 | "metadata": {}, 62 | "source": [ 63 | "## 2. Open state file" 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": null, 69 | "id": "5c444a91", 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "save_dir = os.path.join(os.getcwd(), 'temp', 'notebook0', 'state')\n", 74 | "\n", 75 | "abba.state_load(save_dir+\"/state.abba\") # full absolute path needed" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "id": "da60dcac", 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "# ALL COMMANDS ARE PERFORMED ON SELECTED SLICES!!\n", 86 | "abba.select_all_slices()\n", 87 | "\n", 88 | "# change display settings : channel index, min, max\n", 89 | "abba.change_display_settings(0, 0, 500)\n", 90 | "abba.change_display_settings(1, 0, 1200)\n", 91 | "\n", 92 | "abba.get_bdv_view().setSelectedSlicesVisibility(True)\n", 93 | "abba.get_bdv_view().setSelectedSlicesVisibility(0, True)" 94 | ] 95 | } 96 | ], 97 | "metadata": { 98 | "kernelspec": { 99 | "display_name": "Python 3 (ipykernel)", 100 | "language": "python", 101 | "name": "python3" 102 | }, 103 | "language_info": { 104 | "codemirror_mode": { 105 | "name": "ipython", 106 | "version": 3 107 | }, 108 | "file_extension": ".py", 109 | "mimetype": "text/x-python", 110 | "name": "python", 111 | "nbconvert_exporter": "python", 112 | "pygments_lexer": "ipython3", 113 | "version": "3.7.12" 114 | } 115 | }, 116 | "nbformat": 4, 117 | "nbformat_minor": 5 118 | } 119 | -------------------------------------------------------------------------------- /src/2. Register To BrainGlobe Atlas.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "007bdd6f", 6 | "metadata": {}, 7 | "source": [ 8 | "# [Aligning Big Brains and Atlases](https://biop.github.io/ijp-imagetoatlas/) in Python\n", 9 | "\n", 10 | "This series of notebook demoes the use of ABBA with python.\n", 11 | "\n", 12 | "If you managed to create an environment with PyImageJ and DeepSlice, you will be able, by running this notebook, to perform a partially automated registration of demo mouse brain sections to the a BrainGLobe atlas.\n", 13 | "\n", 14 | "For this notebook to run, an atlas will need to be downloaded, as well as some sample dataset.\n", 15 | "\n", 16 | "The dataset is downloaded from https://zenodo.org/record/6592478\n", 17 | "\n", 18 | "\n", 19 | "**THIS DOES NOT 'REALLY' WORK, I DO NOT HAVE A DATASET TO TEST WITH ONE OF THE BRAINGLOBE ATLASES.**\n", 20 | "\n", 21 | "Please share if you have one or if you know a nicely available public one." 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": null, 27 | "id": "5c4e9d2f", 28 | "metadata": {}, 29 | "outputs": [], 30 | "source": [ 31 | "# core dependencies\n", 32 | "import os\n", 33 | "import time\n", 34 | "from pathlib import Path\n", 35 | "\n", 36 | "from bg_atlasapi import show_atlases\n", 37 | "from bg_atlasapi import utils\n", 38 | "\n", 39 | "from abba_python.Abba import Abba" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": null, 45 | "id": "86a102df", 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "# Demo dataset for automated slices registration\n", 50 | "zenodo_demo_slices_url = 'https://zenodo.org/record/6592478/files/'\n", 51 | "\n", 52 | "\n", 53 | "# Only one section every five section is used for this demo\n", 54 | "demo_sections = [\n", 55 | " 'S00.tif',\n", 56 | " 'S05.tif',\n", 57 | " 'S10.tif',\n", 58 | " 'S15.tif',\n", 59 | " 'S20.tif',\n", 60 | " 'S25.tif',\n", 61 | " 'S30.tif',\n", 62 | " 'S35.tif',\n", 63 | " 'S40.tif',\n", 64 | " 'S45.tif',\n", 65 | " 'S50.tif',\n", 66 | " 'S55.tif',\n", 67 | " 'S60.tif',\n", 68 | " 'S65.tif',\n", 69 | " 'S70.tif',\n", 70 | " 'S75.tif',\n", 71 | " 'S80.tif']\n", 72 | "\n", 73 | "\n", 74 | "def download_if_necessary(base_path, section_name):\n", 75 | " output_path = Path(base_path + section_name)\n", 76 | " if not output_path.exists():\n", 77 | " utils.check_internet_connection()\n", 78 | " url = zenodo_demo_slices_url + section_name + '?download=1'\n", 79 | " utils.retrieve_over_http(url, output_path)\n", 80 | "\n", 81 | "\n", 82 | "def download_test_images(base_path):\n", 83 | " [download_if_necessary(base_path, section) for section in demo_sections]\n", 84 | "\n" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "id": "9dbd7118", 90 | "metadata": {}, 91 | "source": [ 92 | "## 1. Download test sections if necessary\n", 93 | "\n", 94 | " " 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": null, 100 | "id": "f68706c1", 101 | "metadata": {}, 102 | "outputs": [], 103 | "source": [ 104 | "\n", 105 | "basePath = os.getcwd() + '/images/'\n", 106 | "download_test_images(basePath)\n" 107 | ] 108 | }, 109 | { 110 | "cell_type": "markdown", 111 | "id": "fd26eb27", 112 | "metadata": {}, 113 | "source": [ 114 | "## 2. Choose a BrainGlobe Atlas" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "id": "6e64306b", 121 | "metadata": {}, 122 | "outputs": [], 123 | "source": [ 124 | "show_atlases()" 125 | ] 126 | }, 127 | { 128 | "cell_type": "markdown", 129 | "id": "54979364", 130 | "metadata": {}, 131 | "source": [ 132 | "## 3. ABBA initialization" 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": null, 138 | "id": "98c03c88", 139 | "metadata": { 140 | "scrolled": true 141 | }, 142 | "outputs": [], 143 | "source": [ 144 | "\n", 145 | "# -- FOR DEBUGGING\n", 146 | "# import imagej.doctor\n", 147 | "# imagej.doctor.checkup()\n", 148 | "# imagej.doctor.debug_to_stderr()\n", 149 | "\n", 150 | "abba = Abba('azba_zfish_4um') # Simply put the name of the BrainGlobe atlas\n", 151 | "abba.show_bdv_ui() # creates and show a bdv view\n", 152 | " \n", 153 | "# !! Warning : it takes time... first : downloading the atlas if not present\n", 154 | "# it can take up to a minute..." 155 | ] 156 | }, 157 | { 158 | "cell_type": "markdown", 159 | "id": "358e4e2c", 160 | "metadata": {}, 161 | "source": [ 162 | "## 4. Import sections into ABBA" 163 | ] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "execution_count": null, 168 | "id": "5c444a91", 169 | "metadata": {}, 170 | "outputs": [], 171 | "source": [ 172 | "# import sections into ABBA\n", 173 | "files = [basePath + section for section in demo_sections]\n", 174 | "abba.import_from_files(filepaths=files)\n", 175 | "\n", 176 | "# ALL REGISTRATIONS AND COMMANDS BELOW ARE PERFORMED ON THE SELECTED SLICES!!\n", 177 | "# since we want to register all of them, we select all of them\n", 178 | "abba.select_all_slices()" 179 | ] 180 | }, 181 | { 182 | "cell_type": "code", 183 | "execution_count": null, 184 | "id": "66f97d0a", 185 | "metadata": {}, 186 | "outputs": [], 187 | "source": [ 188 | "# we want to avoid saturation in the display. This does not matter for\n", 189 | "# all registration methods EXCEPT for DeepSlice, which takes in rgb images\n", 190 | "abba.change_display_settings(0, 0, 500)\n", 191 | "abba.change_display_settings(1, 0, 1200)\n", 192 | "\n", 193 | "# programmatic way to show (or hide) sections and channels\n", 194 | "abba.get_bdv_view().setSelectedSlicesVisibility(True)\n", 195 | "abba.get_bdv_view().setSelectedSlicesVisibility(0, True)\n", 196 | "\n", 197 | "# This data does not make a lot of sense... mouse sections with fish..." 198 | ] 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "id": "bb68f320", 203 | "metadata": {}, 204 | "source": [ 205 | "## 5. Position sections along the atlas axis" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "id": "23dd1376", 212 | "metadata": {}, 213 | "outputs": [], 214 | "source": [ 215 | "# Good luck with that, this can be done programmatically with a bit of pain now. \n", 216 | "# However in practice in absence of DeepSlice, you need to deal with that manually:\n", 217 | "# cf https://www.youtube.com/watch?v=sERGONVw4zE" 218 | ] 219 | }, 220 | { 221 | "cell_type": "markdown", 222 | "id": "83b8f828", 223 | "metadata": {}, 224 | "source": [ 225 | "## 5. Elastix affine registration" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": null, 231 | "id": "4d364363", 232 | "metadata": {}, 233 | "outputs": [], 234 | "source": [ 235 | "# a round of elastix registration, affine\n", 236 | "# the channel 0 of the dataset (DAPI) is registered with the Nissl Channel of the atlas (0)\n", 237 | "# and the channel 1 of the dataset (mainly autofluo) is registered with the autofluo channel of the atlas (1)\n", 238 | "# these two channels have equal weights in the registration process\n", 239 | "abba.register_slices_elastix_affine(channels_slice_csv='1',\n", 240 | " channels_atlas_csv='0',\n", 241 | " pixel_size_micrometer=40)" 242 | ] 243 | }, 244 | { 245 | "cell_type": "markdown", 246 | "id": "ee4cb12b", 247 | "metadata": {}, 248 | "source": [ 249 | "## 6. Elastix spline registration" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": null, 255 | "id": "f08093da", 256 | "metadata": {}, 257 | "outputs": [], 258 | "source": [ 259 | "# optional: a round of elastix registration, spline\n", 260 | "# same channels as in the affine registration\n", 261 | "# 5 control points along x = very coarse spline (and thus maybe unnecessary)\n", 262 | "# abba.register_elastix_spline(\n", 263 | "# nb_control_points=5,\n", 264 | "# atlas_image_channels=[0, 1],\n", 265 | "# slice_image_channels=[0, 1],\n", 266 | "# pixel_size_micrometer=40).get()\n", 267 | "\n", 268 | "# a round of elastix registration, affine\n", 269 | "# same channels as in the affine registration \n", 270 | "# 16 control points = reasonable spline, which allows for local corrections, without deforming two much the section\n", 271 | "abba.register_slices_elastix_spline(channels_slice_csv='1',\n", 272 | " channels_atlas_csv='0',\n", 273 | " nb_control_points_x=16,\n", 274 | " pixel_size_micrometer=20)" 275 | ] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "id": "57c522c1", 280 | "metadata": {}, 281 | "source": [ 282 | "## 7. Wait for end of all registrations" 283 | ] 284 | }, 285 | { 286 | "cell_type": "code", 287 | "execution_count": null, 288 | "id": "9d4a3a3c", 289 | "metadata": {}, 290 | "outputs": [], 291 | "source": [ 292 | "# all tasks/registrations are enqueued and executed asynchronously\n", 293 | "# if you need to wait before saving, then wait for all tasks to be finished:\n", 294 | "abba.wait_for_end_of_tasks()" 295 | ] 296 | }, 297 | { 298 | "cell_type": "markdown", 299 | "id": "b7508c96", 300 | "metadata": {}, 301 | "source": [ 302 | "## 8. Saving the result" 303 | ] 304 | }, 305 | { 306 | "cell_type": "code", 307 | "execution_count": null, 308 | "id": "27e6a478", 309 | "metadata": {}, 310 | "outputs": [], 311 | "source": [ 312 | "save_dir = os.path.join(os.getcwd(), 'temp', 'notebook1', 'state')\n", 313 | "\n", 314 | "if not os.path.exists(save_dir):\n", 315 | " os.makedirs(save_dir)\n", 316 | "\n", 317 | "\n", 318 | "abba.state_save(save_dir+\"/state.json\") # full absolute path needed" 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "execution_count": null, 324 | "id": "1391844f", 325 | "metadata": {}, 326 | "outputs": [], 327 | "source": [ 328 | "# EXTRA : manipulation of slices programmatically\n", 329 | "\n", 330 | "# slices selection and manipulation\n", 331 | "abba.mp.selectSlice(abba.mp.getSlices().get(2)) # select the last slice\n", 332 | "abba.mp.getReslicedAtlas().setRotateY(0.05) # Small correction in Y slicing of the atlas\n", 333 | "abba.mp.deselectSlice(abba.mp.getSlices()) # deselect all\n", 334 | "\n", 335 | "# The slices are always sorted from small z to high z. To keep track of who's who, reference them before moving them\n", 336 | "slice30 = abba.mp.getSlices().get(0) \n", 337 | "slice40 = abba.mp.getSlices().get(1)\n", 338 | "slice50 = abba.mp.getSlices().get(2)\n", 339 | "\n", 340 | "# move slices along the slicing axis\n", 341 | "abba.mp.moveSlice(slice50,9.5)\n", 342 | "abba.mp.moveSlice(slice40,8.2)\n", 343 | "abba.mp.moveSlice(slice30,7.5)\n", 344 | "\n", 345 | "# For a registration : let's select all slices\n", 346 | "abba.mp.selectSlice(abba.mp.getSlices()) # select all" 347 | ] 348 | } 349 | ], 350 | "metadata": { 351 | "kernelspec": { 352 | "display_name": "Python 3 (ipykernel)", 353 | "language": "python", 354 | "name": "python3" 355 | }, 356 | "language_info": { 357 | "codemirror_mode": { 358 | "name": "ipython", 359 | "version": 3 360 | }, 361 | "file_extension": ".py", 362 | "mimetype": "text/x-python", 363 | "name": "python", 364 | "nbconvert_exporter": "python", 365 | "pygments_lexer": "ipython3", 366 | "version": "3.7.12" 367 | } 368 | }, 369 | "nbformat": 4, 370 | "nbformat_minor": 5 371 | } 372 | -------------------------------------------------------------------------------- /src/3. Open State and Use Transforms.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "6aaf973e", 6 | "metadata": {}, 7 | "source": [ 8 | "# [Aligning Big Brains and Atlases](https://biop.github.io/ijp-imagetoatlas/) in Python\n", 9 | "\n", 10 | "This series of notebook demoes the use of ABBA with python.\n", 11 | "\n", 12 | "If you have executed the previous notebook, you can re-open the saved state file.\n", 13 | "\n", 14 | "This notebook shows how to convert the pixel position of a slice to its coordinates in the atlas (forth and back).\n" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "id": "62435da7", 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "# core dependencies\n", 25 | "import os\n", 26 | "import time\n", 27 | "from pathlib import Path\n", 28 | "\n", 29 | "\n", 30 | "from bg_atlasapi import show_atlases\n", 31 | "from bg_atlasapi import utils\n", 32 | "\n", 33 | "from abba_python.Abba import Abba" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "id": "99674331", 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "# -- NOT HEADLESS\n", 44 | "abba = Abba('Adult Mouse Brain - Allen Brain Atlas V3p1') # You may have to click a window!\n", 45 | "abba.show_bdv_ui() # creates and show a bdv view\n", 46 | "\n", 47 | "save_dir = os.path.join(os.getcwd(), 'temp', 'notebook0', 'state') # execute the first notebook to get this file!\n", 48 | "abba.state_load(save_dir+\"/state.abba\") # full absolute path needed\n", 49 | "\n", 50 | "# ALL COMMANDS ARE PERFORMED ON SELECTED SLICES!!\n", 51 | "# since we want to register all of them, we select all of them\n", 52 | "abba.select_all_slices()\n", 53 | "\n", 54 | "# change display settings : channel index, min, max\n", 55 | "abba.change_display_settings(0, 0, 500)\n", 56 | "abba.change_display_settings(1, 0, 1200)\n", 57 | "\n", 58 | "# YOU MAY NEED TO CLICK ON THE UI TO FINISH THE EXECUTION OF THIS CELL (angle change notification)" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "id": "0a056fa5", 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "# programmatic way to show (or hide) sections and channels\n", 69 | "abba.get_bdv_view().setSelectedSlicesVisibility(True)\n", 70 | "abba.get_bdv_view().setSelectedSlicesVisibility(0, True)" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": null, 76 | "id": "4c913344", 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "mp = abba.mp\n", 81 | "mp.selectSlice(mp.getSlices()) # select all slices" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": null, 87 | "id": "1d17f28e", 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "mp.deselectSlice(mp.getSlices()) # deselect all" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": null, 97 | "id": "d0cb63e0", 98 | "metadata": {}, 99 | "outputs": [], 100 | "source": [ 101 | "mp.selectSlice(mp.getSlices().get(2)) # select the third slice" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": null, 107 | "id": "e5b46eae", 108 | "metadata": {}, 109 | "outputs": [], 110 | "source": [ 111 | "# The slices are always sorted from small z to high z. To keep track of who's who, reference them before moving them\n", 112 | "slice_0 = mp.getSlices().get(0) \n", 113 | "slice_1 = mp.getSlices().get(1)\n", 114 | "slice_2 = mp.getSlices().get(2)" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "id": "93687822", 121 | "metadata": {}, 122 | "outputs": [], 123 | "source": [ 124 | "\n", 125 | "from jpype.types import JString, JArray, JDouble\n", 126 | "\n", 127 | "# Get transformation\n", 128 | "transform_pix_to_atlas = slice_0.getSlicePixToCCFRealTransform()\n", 129 | "\n", 130 | "DoubleArray = JArray(JDouble)\n", 131 | "\n", 132 | "coordInImage = DoubleArray(3)\n", 133 | "coordInCCF = DoubleArray(3)\n", 134 | "\n", 135 | "coordInImage[0] = 500 # X (pixel)\n", 136 | "coordInImage[1] = 500 # Y\n", 137 | "coordInImage[2] = 0 # Z\n", 138 | "\n", 139 | "transform_pix_to_atlas.inverse().apply(coordInImage,coordInCCF)\n", 140 | "\n", 141 | "print('CCF coord (mm):'+str(coordInCCF))\n" 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": null, 147 | "id": "b9f26097", 148 | "metadata": {}, 149 | "outputs": [], 150 | "source": [ 151 | "# We can also find the coordinates of the atlas into a slice\n", 152 | "# a coordinate in z far from 0, means that it's not in the slice, but far out\n", 153 | "# See https://forum.image.sc/t/coordinates-in-slice-to-atlas-using-abba-python/79513 \n", 154 | "\n", 155 | "coordInCCF = DoubleArray(3)\n", 156 | "coordInCCF[0] = 6.60 # X (pixel)\n", 157 | "coordInCCF[1] = 4.31 # Y\n", 158 | "coordInCCF[2] = 5.58 # Z\n", 159 | "\n", 160 | "coordInImage = DoubleArray(3)\n", 161 | "\n", 162 | "for idx in range(0,mp.getSlices().size()):\n", 163 | " # Get transformation\n", 164 | " transform_pix_to_atlas = mp.getSlices().get(idx).getSlicePixToCCFRealTransform()\n", 165 | " transform_pix_to_atlas.apply(coordInCCF, coordInImage)\n", 166 | " print('Slice['+str(idx)+'] coord (pixel):'+str(coordInImage))\n", 167 | " \n" 168 | ] 169 | }, 170 | { 171 | "cell_type": "code", 172 | "execution_count": null, 173 | "id": "4f1cb990", 174 | "metadata": {}, 175 | "outputs": [], 176 | "source": [ 177 | "# The slice indexed 6 should be the one which is the nearest to the atlas point.\n", 178 | "# Note that the values in Z are small because, in absence of 3D image, \n", 179 | "# each section is assumed to have a size of 1 mm" 180 | ] 181 | }, 182 | { 183 | "cell_type": "code", 184 | "execution_count": null, 185 | "id": "9b416a85", 186 | "metadata": {}, 187 | "outputs": [], 188 | "source": [ 189 | "# You can normalize the slices sections by expanding them to cover the space between neighboring slices, no more, no less\n", 190 | "abba.select_all_slices()\n", 191 | "abba.set_slices_thickness_match_neighbors() # not critical, but for 3d reconstruction it will allow for each slice to occupy the place available between its neighbors\n", 192 | "# The coordinates will be different in Z\n", 193 | "coordInImage = DoubleArray(3)\n", 194 | "\n", 195 | "for idx in range(0,mp.getSlices().size()):\n", 196 | " # Get transformation\n", 197 | " transform_pix_to_atlas = mp.getSlices().get(idx).getSlicePixToCCFRealTransform()\n", 198 | " transform_pix_to_atlas.apply(coordInCCF, coordInImage)\n", 199 | " print('Slice['+str(idx)+'] coord (pixel):'+str(coordInImage))" 200 | ] 201 | }, 202 | { 203 | "cell_type": "code", 204 | "execution_count": null, 205 | "id": "90bd8a3e", 206 | "metadata": {}, 207 | "outputs": [], 208 | "source": [] 209 | } 210 | ], 211 | "metadata": { 212 | "kernelspec": { 213 | "display_name": "Python 3 (ipykernel)", 214 | "language": "python", 215 | "name": "python3" 216 | }, 217 | "language_info": { 218 | "codemirror_mode": { 219 | "name": "ipython", 220 | "version": 3 221 | }, 222 | "file_extension": ".py", 223 | "mimetype": "text/x-python", 224 | "name": "python", 225 | "nbconvert_exporter": "python", 226 | "pygments_lexer": "ipython3", 227 | "version": "3.7.12" 228 | } 229 | }, 230 | "nbformat": 4, 231 | "nbformat_minor": 5 232 | } 233 | -------------------------------------------------------------------------------- /src/4. Register QuPath Project.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "007bdd6f", 6 | "metadata": {}, 7 | "source": [ 8 | "# [Aligning Big Brains and Atlases](https://biop.github.io/ijp-imagetoatlas/) in Python\n", 9 | "\n", 10 | "This series of notebook demoes the use of ABBA with python.\n", 11 | "\n", 12 | "If you managed to create an environment with PyImageJ and DeepSlice, you will be able, by running this notebook, to perform an automated registration of a qupath project containind mouse brain sections to the Adult Mouse Allen Brain atlas.\n", 13 | "\n", 14 | "Take care : in this notebook, the slices should be ordered, not flipped, orientated correctly, and you need to adjust the display settings for deepslice to work. Also, it's assumed that channel 0 is DAPI and channel 1 is autofluorescence.\n", 15 | "\n", 16 | "You may download and create a project out of this dataset: https://zenodo.org/record/6553641#.Yz6EHkxBxD8. Remove labels and overview in QuPath before running this notebook\n", 17 | "\n", 18 | "It's probably best not to run it headless to check the project before running the registration\n", 19 | "\n", 20 | "\n", 21 | "Multichannel registration works reasonably well in this notebook because the first channel of the atlas (NISSL, indexed 0), is ressembling the DAPI channel of the slices (indexed 0), and the second channel of the atlas (ARA, indexed 1), is ressembling the autofluorescence channel of the slices (indexed 1).\n", 22 | "\n", 23 | "NOTE : You need to set the elastix and transformix path for the elastix registration steps." 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": null, 29 | "id": "5c4e9d2f", 30 | "metadata": {}, 31 | "outputs": [], 32 | "source": [ 33 | "# core dependencies\n", 34 | "import os\n", 35 | "import time\n", 36 | "from pathlib import Path\n", 37 | "\n", 38 | "from bg_atlasapi import show_atlases\n", 39 | "from bg_atlasapi import utils\n", 40 | "\n", 41 | "from abba_python.Abba import Abba" 42 | ] 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "id": "54979364", 47 | "metadata": {}, 48 | "source": [ 49 | "## 1. ABBA initialization" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": null, 55 | "id": "6497144b", 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "headless = False\n", 60 | "\n", 61 | "# -- FOR DEBUGGING\n", 62 | "# import imagej.doctor\n", 63 | "# imagej.doctor.checkup()\n", 64 | "# imagej.doctor.debug_to_stderr()\n", 65 | "\n", 66 | "if headless:\n", 67 | " # -- HEADLESS\n", 68 | " abba = Abba('Adult Mouse Brain - Allen Brain Atlas V3p1', headless=True)\n", 69 | "else:\n", 70 | " # -- NOT HEADLESS\n", 71 | " abba = Abba('Adult Mouse Brain - Allen Brain Atlas V3p1')\n", 72 | " abba.show_bdv_ui() # creates and show a bdv view" 73 | ] 74 | }, 75 | { 76 | "cell_type": "markdown", 77 | "id": "5ffd9321", 78 | "metadata": {}, 79 | "source": [ 80 | "## 2. Loading QuPath project" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "id": "91eb6323", 87 | "metadata": {}, 88 | "outputs": [], 89 | "source": [ 90 | "abba.import_slices_from_qupath(slice_axis_initial_mm = 0.2,\n", 91 | " increment_between_slices_mm = 0.08,\n", 92 | " qupath_project= 'C:/Users/nico/Desktop/ABBA-Tutorial/tuto-abba/project.qpproj')" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "id": "63e9a7a2", 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "print('nSlices = '+str(abba.mp.getSlices().size()))\n", 103 | "# ALL REGISTRATIONS AND COMMANDS BELOW ARE PERFORMED ON THE SELECTED SLICES!!\n", 104 | "# since we want to register all of them, we select all of them\n", 105 | "abba.select_all_slices()" 106 | ] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "execution_count": null, 111 | "id": "66f97d0a", 112 | "metadata": {}, 113 | "outputs": [], 114 | "source": [ 115 | "# we want to avoid saturation in the display. This does not matter for\n", 116 | "# all registration methods EXCEPT for DeepSlice, which takes in rgb images\n", 117 | "abba.select_all_slices()\n", 118 | "abba.change_display_settings(0, 0, 800)\n", 119 | "#abba.change_display_settings(1, 0, 1200) # fails because some slices have no channel 1\n", 120 | "\n", 121 | "# programmatic way to show (or hide) sections and channels\n", 122 | "abba.get_bdv_view().setSelectedSlicesVisibility(True)\n", 123 | "abba.get_bdv_view().setSelectedSlicesVisibility(0, True)" 124 | ] 125 | }, 126 | { 127 | "cell_type": "markdown", 128 | "id": "3964abcb", 129 | "metadata": {}, 130 | "source": [ 131 | "## 4. DeepSlice Registration(s)" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": null, 137 | "id": "e65db448", 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [ 141 | "# REMOVE LABELS AND OVERVIEWS!!\n", 142 | "\n", 143 | "# a first deepslice registration round : possible because it's the Allen CCF atlas, cut in coronal mode\n", 144 | "# what's assumed : the sections are already in the correct order\n", 145 | "abba.register_slices_deepslice(channels=[0, 1])\n", 146 | "\n", 147 | "# second deepslice registration: because the slices are resampled for the registration,\n", 148 | "# we usually get a slightly better positioning along z and cutting angle\n", 149 | "# also: it's fast, and the combination of two affine transforms is\n", 150 | "# an affine transform, so it's not like we are adding extra degrees of freedom\n", 151 | "abba.register_slices_deepslice(channels=[0, 1])" 152 | ] 153 | }, 154 | { 155 | "cell_type": "raw", 156 | "id": "7f954791", 157 | "metadata": {}, 158 | "source": [ 159 | "## 5. Elastix affine registration" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "id": "4d364363", 166 | "metadata": {}, 167 | "outputs": [], 168 | "source": [ 169 | "# a round of elastix registration, affine\n", 170 | "# the channel 0 of the dataset (DAPI) is registered with the Nissl Channel of the atlas (0)\n", 171 | "# and the channel 1 of the dataset (mainly autofluo) is registered with the autofluo channel of the atlas (1)\n", 172 | "# these two channels have equal weights in the registration process\n", 173 | "abba.register_slices_elastix_affine(channels_slice_csv='0,1',\n", 174 | " channels_atlas_csv='0,1',\n", 175 | " pixel_size_micrometer=40)" 176 | ] 177 | }, 178 | { 179 | "cell_type": "markdown", 180 | "id": "ee4cb12b", 181 | "metadata": {}, 182 | "source": [ 183 | "## 6. Elastix spline registration" 184 | ] 185 | }, 186 | { 187 | "cell_type": "code", 188 | "execution_count": null, 189 | "id": "f08093da", 190 | "metadata": {}, 191 | "outputs": [], 192 | "source": [ 193 | "# optional: a round of elastix registration, spline\n", 194 | "# same channels as in the affine registration\n", 195 | "# 5 control points along x = very coarse spline (and thus maybe unnecessary)\n", 196 | "# abba.register_elastix_spline(\n", 197 | "# nb_control_points=5,\n", 198 | "# atlas_image_channels=[0, 1],\n", 199 | "# slice_image_channels=[0, 1],\n", 200 | "# pixel_size_micrometer=40).get()\n", 201 | "\n", 202 | "# a round of elastix registration, affine\n", 203 | "# same channels as in the affine registration \n", 204 | "# 16 control points = reasonable spline, which allows for local corrections, without deforming two much the section\n", 205 | "abba.register_slices_elastix_spline(channels_slice_csv='0,1',\n", 206 | " channels_atlas_csv='0,1',\n", 207 | " nb_control_points_x=16,\n", 208 | " pixel_size_micrometer=20)" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "id": "57c522c1", 214 | "metadata": {}, 215 | "source": [ 216 | "## 7. Wait for end of all registrations" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": null, 222 | "id": "9d4a3a3c", 223 | "metadata": {}, 224 | "outputs": [], 225 | "source": [ 226 | "# all tasks/registrations are enqueued and executed asynchronously\n", 227 | "# if you need to wait before saving, then wait for all tasks to be finished:\n", 228 | "abba.wait_for_end_of_tasks()" 229 | ] 230 | }, 231 | { 232 | "cell_type": "code", 233 | "execution_count": null, 234 | "id": "5bd54295", 235 | "metadata": {}, 236 | "outputs": [], 237 | "source": [ 238 | "abba.export_registration_to_qupath(erase_previous_file=True)" 239 | ] 240 | }, 241 | { 242 | "cell_type": "code", 243 | "execution_count": null, 244 | "id": "a21bb282", 245 | "metadata": {}, 246 | "outputs": [], 247 | "source": [ 248 | "# all tasks/registrations/exports are enqueued and executed asynchronously\n", 249 | "# if you need to wait before saving, then wait for all tasks to be finished:\n", 250 | "abba.wait_for_end_of_tasks()" 251 | ] 252 | }, 253 | { 254 | "cell_type": "markdown", 255 | "id": "b7508c96", 256 | "metadata": {}, 257 | "source": [ 258 | "## 8. Saving the result" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "execution_count": null, 264 | "id": "27e6a478", 265 | "metadata": {}, 266 | "outputs": [], 267 | "source": [ 268 | "save_dir = os.path.join(os.getcwd(), 'temp', 'notebook4', 'state')\n", 269 | "\n", 270 | "if not os.path.exists(save_dir):\n", 271 | " os.makedirs(save_dir)\n", 272 | "\n", 273 | "\n", 274 | "abba.state_save(save_dir+\"/state.abba\") # full absolute path needed" 275 | ] 276 | } 277 | ], 278 | "metadata": { 279 | "kernelspec": { 280 | "display_name": "Python 3 (ipykernel)", 281 | "language": "python", 282 | "name": "python3" 283 | }, 284 | "language_info": { 285 | "codemirror_mode": { 286 | "name": "ipython", 287 | "version": 3 288 | }, 289 | "file_extension": ".py", 290 | "mimetype": "text/x-python", 291 | "name": "python", 292 | "nbconvert_exporter": "python", 293 | "pygments_lexer": "ipython3", 294 | "version": "3.7.12" 295 | } 296 | }, 297 | "nbformat": 4, 298 | "nbformat_minor": 5 299 | } 300 | -------------------------------------------------------------------------------- /src/Playground - Adding a python registration method.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "id": "3d3bf6b0", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "import itk\n", 11 | "import imagej\n", 12 | "import time\n", 13 | "import numpy as np\n", 14 | "\n", 15 | "# core dependencies\n", 16 | "import os\n", 17 | "from pathlib import Path\n", 18 | "\n", 19 | "from abba import Abba\n", 20 | "# NOT FUNCTIONAL!!" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "id": "192f65c8", 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "# -- NOT HEADLESS\n", 31 | "abba = Abba('Adult Mouse Brain - Allen Brain Atlas V3')\n", 32 | "ij = abba.ij" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": null, 38 | "id": "c02d0bf1", 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "from abba.itk.abba_itk import add_abba_itk_registrations\n", 43 | "\n", 44 | "add_abba_itk_registrations(ij)" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": null, 50 | "id": "ea14c2fc", 51 | "metadata": {}, 52 | "outputs": [], 53 | "source": [ 54 | "abba.show_bdv_ui() # creates and show a bdv view" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": null, 60 | "id": "394c4a75", 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "ij.py.show(result_image)" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "id": "e58b6f77", 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [ 74 | "print(result_transform_parameters)" 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": null, 80 | "id": "4d2adc70", 81 | "metadata": {}, 82 | "outputs": [], 83 | "source": [ 84 | "print(result_transform_parameters.GetParameter(0, \"CompressResultImage\")[0])" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "id": "f5ce6d3b", 91 | "metadata": {}, 92 | "outputs": [], 93 | "source": [ 94 | "print(result_transform_parameters.GetParameter(0, \"ResampleInterpolator\"))" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": null, 100 | "id": "7e6ad3d4", 101 | "metadata": {}, 102 | "outputs": [], 103 | "source": [ 104 | "len(result_transform_parameters.GetParameter(0, \"ResampleInterpolator\"))" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": null, 110 | "id": "aeb46b5d", 111 | "metadata": {}, 112 | "outputs": [], 113 | "source": [ 114 | "from tempfile import TemporaryDirectory\n", 115 | "\n", 116 | "with TemporaryDirectory() as temp_dir:\n", 117 | " # ... do something with temp_dir\n", 118 | "# automatically cleaned up when context exited\n" 119 | ] 120 | } 121 | ], 122 | "metadata": { 123 | "kernelspec": { 124 | "display_name": "Python 3 (ipykernel)", 125 | "language": "python", 126 | "name": "python3" 127 | }, 128 | "language_info": { 129 | "codemirror_mode": { 130 | "name": "ipython", 131 | "version": 3 132 | }, 133 | "file_extension": ".py", 134 | "mimetype": "text/x-python", 135 | "name": "python", 136 | "nbconvert_exporter": "python", 137 | "pygments_lexer": "ipython3", 138 | "version": "3.7.12" 139 | } 140 | }, 141 | "nbformat": 4, 142 | "nbformat_minor": 5 143 | } 144 | -------------------------------------------------------------------------------- /src/abba_python/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = """nicolas_chiaruttini""" 2 | __version__ = "0.1.0-SNAPSHOT" 3 | 4 | from abba_python.Abba import Abba 5 | -------------------------------------------------------------------------------- /src/abba_python/abba_private/AbbaAtlas.py: -------------------------------------------------------------------------------- 1 | from bg_atlasapi import BrainGlobeAtlas 2 | from scyjava import jimport 3 | from jpype import JImplements, JOverride 4 | from jpype.types import JString 5 | from abba_python.abba_private.AbbaOntology import AbbaOntology 6 | from abba_python.abba_private.AbbaMap import AbbaMap 7 | 8 | ArrayList = jimport('java.util.ArrayList') 9 | Atlas = jimport('ch.epfl.biop.atlas.struct.Atlas') 10 | 11 | 12 | @JImplements(Atlas) 13 | class AbbaAtlas(object): 14 | """This python class is part of the translation mechanism between the underlying Java ABBA API: 15 | https://github.com/BIOP/ijp-atlas/tree/main/src/main/java/ch/epfl/biop/atlas/struct 16 | and the BrainGlobe API: 17 | https://github.com/brainglobe/bg-atlasapi/ 18 | 19 | Wrapper inner class that implements the following Java interface: 20 | https://github.com/BIOP/ijp-atlas/blob/main/src/main/java/ch/epfl/biop/atlas/struct/Atlas.java 21 | """ 22 | 23 | def __init__(self, bg_atlas: BrainGlobeAtlas, ij): 24 | self.atlas = bg_atlas 25 | self.ij = ij 26 | 27 | @JOverride 28 | def getMap(self): 29 | return self.bg_atlasmap 30 | 31 | @JOverride 32 | def getOntology(self): 33 | return self.bg_ontology 34 | 35 | @JOverride 36 | def initialize(self, mapURL, ontologyURL): 37 | self.bg_ontology = AbbaOntology(self.atlas) 38 | self.bg_ontology.initialize() 39 | self.bg_ontology.setNamingProperty(JString('acronym')) 40 | self.bg_atlasmap = AbbaMap(self.atlas, self.ij) 41 | self.bg_atlasmap.initialize(self.atlas.atlas_name) 42 | self.dois = ArrayList() 43 | self.dois.add(JString(self.atlas.metadata['citation'].split("doi.org/", 1)[1])) 44 | 45 | @JOverride 46 | def getDOIs(self): 47 | return self.dois 48 | 49 | @JOverride 50 | def getURL(self): 51 | return JString(self.atlas.metadata['atlas_link']) 52 | 53 | @JOverride 54 | def getName(self): 55 | return JString(self.atlas.atlas_name) 56 | 57 | @JOverride 58 | def toString(self): 59 | return self.getName() 60 | -------------------------------------------------------------------------------- /src/abba_python/abba_private/AbbaMap.py: -------------------------------------------------------------------------------- 1 | from scyjava import jimport 2 | from jpype import JImplements, JOverride 3 | from jpype.types import JString, JDouble, JInt 4 | 5 | import numpy as np 6 | 7 | AffineTransform3D = jimport('net.imglib2.realtransform.AffineTransform3D') 8 | ArrayList = jimport('java.util.ArrayList') 9 | AtlasHelper = jimport('ch.epfl.biop.atlas.struct.AtlasHelper') 10 | AtlasMap = jimport('ch.epfl.biop.atlas.struct.AtlasMap') 11 | BdvFunctions = jimport('bdv.util.BdvFunctions') 12 | BdvOptions = jimport('bdv.util.BdvOptions') 13 | SourceVoxelProcessor = jimport('ch.epfl.biop.sourceandconverter.SourceVoxelProcessor') 14 | 15 | RandomAccessibleIntervalSource = jimport('bdv.util.RandomAccessibleIntervalSource') 16 | Util = jimport('net.imglib2.util.Util') 17 | SourceAndConverterHelper = jimport('sc.fiji.bdvpg.sourceandconverter.SourceAndConverterHelper') 18 | def array_to_source(ij, array, name, transform=AffineTransform3D()): 19 | img = ij.py.to_java(array) 20 | name_java_str = JString(name) 21 | # we supposed it's of dimension 3 22 | pixel_type = Util.getTypeFromInterval(img); 23 | rai_source = RandomAccessibleIntervalSource(img, pixel_type, transform, name_java_str); 24 | return SourceAndConverterHelper.createSourceAndConverter(rai_source) 25 | 26 | 27 | @JImplements(AtlasMap) 28 | class AbbaMap(object): 29 | """This python class is part of the translation mechanism between the underlying Java ABBA API: 30 | https://github.com/BIOP/ijp-atlas/tree/main/src/main/java/ch/epfl/biop/atlas/struct 31 | and the BrainGlobe API: 32 | https://github.com/brainglobe/bg-atlasapi/ 33 | 34 | Wrapper inner class that implements the following Java interface: 35 | https://github.com/BIOP/ijp-atlas/blob/main/src/main/java/ch/epfl/biop/atlas/struct/AtlasMap.java 36 | """ 37 | 38 | def __init__(self, bg_atlas, ij): 39 | # this function is called way too many times if I put here the content 40 | # of initialize... and I don't know why 41 | # that's why there's this initialize function 42 | self.atlas = bg_atlas 43 | self.ij = ij 44 | 45 | @JOverride 46 | def setDataSource(self, dataSource): 47 | self.dataSource = dataSource 48 | 49 | @JOverride 50 | def initialize(self, atlasName): 51 | self.atlasName = str(atlasName) 52 | 53 | atlas_resolution_in__mm = JDouble(min(self.atlas.metadata['resolution']) / 1000.0) 54 | 55 | vox_x_mm = self.atlas.metadata['resolution'][0] / 1000.0 56 | vox_y_mm = self.atlas.metadata['resolution'][1] / 1000.0 57 | vox_z_mm = self.atlas.metadata['resolution'][2] / 1000.0 58 | 59 | affine_transform = AffineTransform3D() 60 | affine_transform.scale(JDouble(vox_x_mm), JDouble(vox_y_mm), JDouble(vox_z_mm)) 61 | 62 | # Convert 63 | reference_sac = array_to_source(self.ij, self.atlas.reference, 64 | name=self.atlas.atlas_name + '_reference', 65 | transform=affine_transform) 66 | 67 | left_right_sac = array_to_source(self.ij, self.atlas.hemispheres, 68 | name=self.atlas.atlas_name + '_hemispheres', 69 | transform=affine_transform) 70 | 71 | self.annotation_sac = array_to_source(self.ij, self.atlas.annotation, 72 | name=self.atlas.atlas_name + '_annotation', 73 | transform=affine_transform) 74 | 75 | image_keys = ArrayList() 76 | image_keys.add(JString('reference')) 77 | for extra_channel in self.atlas.metadata['additional_references']: 78 | image_keys.add(JString(extra_channel)) 79 | image_keys.add(JString('borders')) 80 | image_keys.add(JString('X')) 81 | image_keys.add(JString('Y')) 82 | image_keys.add(JString('Z')) 83 | image_keys.add(JString('Left Right')) 84 | 85 | structural_images = dict() 86 | self.maxValues = dict() 87 | structural_images['reference'] = reference_sac 88 | self.maxValues['reference'] = JDouble(np.max(self.atlas.reference) * 2) 89 | for extra_channel in self.atlas.metadata['additional_references']: 90 | structural_images[extra_channel] = array_to_source(self.ij, self.atlas.additional_references[extra_channel], 91 | name=self.atlas.atlas_name + '_' + extra_channel, 92 | transform=affine_transform) 93 | self.maxValues[extra_channel] = JDouble(np.max(self.atlas.additional_references[extra_channel]) * 2) 94 | structural_images['borders'] = SourceVoxelProcessor.getBorders(self.annotation_sac) 95 | self.maxValues['borders'] = 256 # we know this one. 96 | structural_images['X'] = AtlasHelper.getCoordinateSac(0, JString('X')) 97 | structural_images['Y'] = AtlasHelper.getCoordinateSac(1, JString('Y')) 98 | structural_images['Z'] = AtlasHelper.getCoordinateSac(2, JString('Z')) 99 | structural_images['Left Right'] = left_right_sac # return Map 100 | 101 | self.atlas_resolution_in__mm = atlas_resolution_in__mm 102 | self.affine_transform = affine_transform 103 | self.image_keys = image_keys 104 | self.structural_images = structural_images 105 | 106 | @JOverride 107 | def getDataSource(self): 108 | return self.dataSource # return URL 109 | 110 | @JOverride 111 | def getStructuralImages(self): 112 | return self.structural_images 113 | 114 | @JOverride 115 | def getImagesKeys(self): 116 | return self.image_keys 117 | 118 | @JOverride 119 | def getLabelImage(self): 120 | return self.annotation_sac # SourceAndConverter 121 | 122 | @JOverride 123 | def getAtlasPrecisionInMillimeter(self): 124 | return self.atlas_resolution_in__mm 125 | 126 | @JOverride 127 | def getCoronalTransform(self): 128 | return AffineTransform3D() 129 | 130 | @JOverride 131 | def getImageMax(self, key): 132 | return self.maxValues[key] 133 | 134 | @JOverride 135 | def labelRight(self): 136 | return JInt(1) 137 | 138 | @JOverride 139 | def labelLeft(self): 140 | return JInt(2) 141 | -------------------------------------------------------------------------------- /src/abba_python/abba_private/AbbaOntology.py: -------------------------------------------------------------------------------- 1 | from bg_atlasapi import BrainGlobeAtlas 2 | from bg_atlasapi.descriptors import STRUCTURES_FILENAME 3 | from scyjava import jimport 4 | from jpype import JImplements, JOverride 5 | from jpype.types import JString 6 | 7 | 8 | AtlasHelper = jimport('ch.epfl.biop.atlas.struct.AtlasHelper') 9 | AtlasOntology = jimport('ch.epfl.biop.atlas.struct.AtlasOntology') 10 | 11 | 12 | @JImplements(AtlasOntology) 13 | class AbbaOntology(object): 14 | """This python class is part of the translation mechanism between the underlying Java ABBA API: 15 | https://github.com/BIOP/ijp-atlas/tree/main/src/main/java/ch/epfl/biop/atlas/struct 16 | and the BrainGlobe API: 17 | https://github.com/brainglobe/bg-atlasapi/ 18 | 19 | Wrapper inner class that implements the following Java interface: 20 | https://github.com/BIOP/ijp-atlas/blob/main/src/main/java/ch/epfl/biop/atlas/struct/AtlasOntology.java 21 | """ 22 | 23 | def __init__(self, bg_atlas: BrainGlobeAtlas): 24 | self.atlas = bg_atlas 25 | # bg_atlas.root_dir. 26 | 27 | @JOverride 28 | def getName(self): 29 | return JString(self.atlas.atlas_name) 30 | 31 | @JOverride 32 | def initialize(self): 33 | BrainGlobeHelper = jimport('ch.epfl.biop.atlas.brainglobe.BrainGlobeHelper') 34 | print(str(self.atlas.root_dir / STRUCTURES_FILENAME)) 35 | print(BrainGlobeHelper) 36 | print(BrainGlobeHelper.buildTreeAndGetRoot) 37 | self.root_node = BrainGlobeHelper.buildTreeAndGetRoot(JString(str(self.atlas.root_dir / STRUCTURES_FILENAME))) # AbbaAtlasNode(self.atlas, self.atlas.structures.tree.root, None) 38 | self.idToAtlasNodeMap = AtlasHelper.buildIdToAtlasNodeMap(self.root_node) 39 | 40 | @JOverride 41 | def setDataSource(self, dataSource): 42 | self.dataSource = dataSource 43 | 44 | @JOverride 45 | def getDataSource(self): 46 | return self.dataSource # return URL 47 | 48 | @JOverride 49 | def getRoot(self): 50 | return self.root_node # return AtlasNode 51 | 52 | @JOverride 53 | def getNodeFromId(self, index): 54 | return self.idToAtlasNodeMap.get(index) # return AtlasNode 55 | 56 | @JOverride 57 | def getNamingProperty(self): 58 | return self.namingProperty 59 | 60 | @JOverride 61 | def setNamingProperty(self, namingProperty): 62 | self.namingProperty = namingProperty 63 | -------------------------------------------------------------------------------- /src/abba_python/abba_private/DeepSliceProcessor.py: -------------------------------------------------------------------------------- 1 | from scyjava import jimport 2 | from abba_python.deepslice.DeepSlice import DeepSlice 3 | from jpype import JImplements, JOverride 4 | from jpype.types import JString 5 | import os 6 | 7 | import urllib.request 8 | from tqdm import tqdm 9 | from abba_python.deepslice.DeepSlice import get_deepslice_path 10 | 11 | # Import deepslice and make the function for the ABBA command 12 | Function = jimport('java.util.function.Function') 13 | File = jimport('java.io.File') 14 | 15 | 16 | # ----- Download with progress bar, cf https://stackoverflow.com/questions/15644964/python-progress-bar-and-downloads 17 | class DownloadProgressBar(tqdm): 18 | def update_to(self, b=1, bsize=1, tsize=None): 19 | if tsize is not None: 20 | self.total = tsize 21 | self.update(b * bsize - self.n) 22 | 23 | 24 | def download_url(url, output_path): 25 | with DownloadProgressBar(unit='B', unit_scale=True, 26 | miniters=1, desc=url.split('/')[-1]) as t: 27 | urllib.request.urlretrieve(url, filename=output_path, reporthook=t.update_to) 28 | 29 | 30 | # ------------ 31 | 32 | def check_model_is_present(): 33 | path_to_model = get_deepslice_path() + "/NN_weights" 34 | if not os.path.isdir(path_to_model): 35 | print('DeepSlice model not present, 240 Mb will be downloaded ') 36 | os.makedirs(path_to_model) 37 | model_files = ['/Allen_Mixed_Best.h5', 38 | '/Synthetic_data_final.hdf5', 39 | '/xception_weights_tf_dim_ordering_tf_kernels.h5'] 40 | 41 | deepslice_model_url = 'https://github.com/PolarBean/DeepSlice/raw/master/NN_weights' 42 | 43 | for file in model_files: 44 | if not os.path.exists(path_to_model + file): 45 | target_url = deepslice_model_url + file 46 | print('Missing DeepSlice model file ' + file + '. Downloading (80Mb)...') 47 | download_url(target_url, path_to_model + file) 48 | 49 | 50 | @JImplements(Function) 51 | class DeepSliceProcessor: 52 | 53 | @JOverride 54 | def apply(self, folder): 55 | check_model_is_present() 56 | model = DeepSlice() 57 | model.Build() 58 | model.predict(image_dir=str(folder.getParent())) 59 | out = File(folder, JString('results')) 60 | model.Save_Results(out.getAbsolutePath()) 61 | return File(folder, JString('results.xml')) 62 | -------------------------------------------------------------------------------- /src/abba_python/abba_private/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = """Nicolas Chiaruttini""" 2 | __version__ = "0.1.0-SNAPSHOT" 3 | 4 | # Inner classes, do not access and use them directly 5 | # Used internally by the Abba package 6 | 7 | # from abba_python.abba_private.AbbaAtlasNode import AbbaAtlasNode 8 | -------------------------------------------------------------------------------- /src/abba_python/deepslice/DeepSlice.py: -------------------------------------------------------------------------------- 1 | ##very janky way to solve relative import problem 2 | import os 3 | from pathlib import Path 4 | # store ini paths 5 | ini_path = os.getcwd() 6 | ##set path to be the DeepSlice directory 7 | path = str(Path(__file__).parent) 8 | ##testing automated tests 9 | os.chdir(path) 10 | print(path) 11 | import warnings 12 | from tensorflow.keras.applications.xception import Xception 13 | from tensorflow.keras import Sequential 14 | from tensorflow.keras.layers import Dense 15 | from skimage import color 16 | from tensorflow.keras.preprocessing.image import ImageDataGenerator 17 | from abba_python.deepslice.utilities.QuickNII_functions import pd_to_quickNII, XML_to_csv 18 | from abba_python.deepslice.utilities import plane_alignment 19 | import pandas as pd 20 | import numpy as np 21 | from sklearn.linear_model import HuberRegressor 22 | import re 23 | import imghdr 24 | import struct 25 | 26 | # restore path 27 | os.chdir(ini_path) 28 | 29 | def get_image_size(fname): 30 | # https://stackoverflow.com/questions/8032642/how-to-obtain-image-size-using-standard-python-class-without-using-external-lib 31 | """Determine the image type of fhandle and return its size. 32 | from draco""" 33 | with open(fname, "rb") as fhandle: 34 | head = fhandle.read(24) 35 | if len(head) != 24: 36 | raise Exception("Invalid header") 37 | 38 | ext = imghdr.what(fname) 39 | if imghdr.what(fname) == "png": 40 | check = struct.unpack(">i", head[4:8])[0] 41 | if check != 0x0D0A1A0A: 42 | raise Exception("png checksum failed") 43 | width, height = struct.unpack(">ii", head[16:24]) 44 | elif imghdr.what(fname) == "gif": 45 | width, height = struct.unpack("H", fhandle.read(2))[0] - 2 57 | # We are at a SOFn block 58 | fhandle.seek(1, 1) # Skip `precision' byte. 59 | height, width = struct.unpack(">HH", fhandle.read(4)) 60 | else: 61 | raise Exception(f"Invalid filetype: {head}") 62 | return width, height 63 | 64 | 65 | def ideal_thickness(results, depth, detect_bad_sections=False): 66 | number_spacing = np.float64(results["section_ID"].values[1:]) - np.float64( 67 | results["section_ID"].values[:-1] 68 | ) 69 | depth_spacing = np.array(depth)[:-1] - np.array(depth)[1:] 70 | norm_depth = depth_spacing / number_spacing 71 | 72 | if detect_bad_sections == True: 73 | predicted_thickness = np.mean(norm_depth) 74 | thickness_variability = np.std(norm_depth) 75 | good_indexes = ( 76 | norm_depth < (predicted_thickness + (thickness_variability * 3)) 77 | ) & (norm_depth > (predicted_thickness - (thickness_variability * 3))) 78 | print( 79 | f"sections {results.Filenames[1:][~good_indexes]} appeared to be outliers and were not incorporated into the spacing analysis" 80 | ) 81 | norm_depth = norm_depth[good_indexes] 82 | predicted_thickness = np.mean(norm_depth) * 25 83 | thickness_variability = np.std(norm_depth) * 25 84 | 85 | print( 86 | "Your sections appear to be sectioned at {0:.4f} micron thickness".format( 87 | np.abs(predicted_thickness) 88 | ) 89 | ) 90 | print( 91 | "the variability of thickness is {0:.4f} microns".format(thickness_variability) 92 | ) 93 | return predicted_thickness 94 | 95 | 96 | def ideal_spacing( 97 | pred_oy, section_numbers, section_thickness_um, bad_section_indexes=None 98 | ): 99 | if bad_section_indexes is None: 100 | bad_section_indexes = np.array([False] * len(pred_oy)) 101 | 102 | pred_oy = np.float64(pred_oy[~bad_section_indexes]) 103 | section_numbers = np.float64(section_numbers.values) 104 | section_thickness_um = np.float64(section_thickness_um) 105 | pred_um = pred_oy * 25 106 | section_um = section_numbers * section_thickness_um 107 | print(f"section_um: {pred_um/25}") 108 | avg_dist = np.mean(pred_um - section_um[~bad_section_indexes]) 109 | print("ideal: ", (section_um + avg_dist) / 25) 110 | print("pred_UM: ") 111 | print(f"average distance: {avg_dist}") 112 | # print((pred_um-section_um) - avg_dist) 113 | return ((section_um + avg_dist)) / 25 114 | 115 | 116 | def calculate_brain_center_depth(section): 117 | cross, k = plane_alignment.find_plane_equation(section) 118 | translated_volume = np.array((456, 0, 320)) 119 | linear_point = ( 120 | ((translated_volume[0] / 2) * cross[0]) 121 | + ((translated_volume[2] / 2) * cross[2]) 122 | ) + k 123 | depth = -(linear_point / cross[1]) 124 | return depth 125 | 126 | def get_deepslice_path(): 127 | return path 128 | 129 | class DeepSlice: 130 | def __init__(self, web=False, folder_name=None): 131 | self.web = web 132 | self.folder_name = folder_name 133 | 134 | self.image_dir = None 135 | self.columns = ["ox", "oy", "oz", "ux", "uy", "uz", "vx", "vy", "vz"] 136 | 137 | def init_model(self, DS_weights, xception_weights): 138 | # Download Xception architecture with weights pretrained on imagenet 139 | DenseModel = Xception(include_top=True, weights=xception_weights) 140 | # remove the Dense Softmax layer and average pooling layer from the pretrained model 141 | DenseModel._layers.pop() 142 | DenseModel._layers.pop() 143 | # Build Deepslice 144 | model = Sequential() 145 | model.add(DenseModel) 146 | # we tested various sizes for these last two layers but consistently found that 256 performed best for some unknown reason. 147 | # theoretically larger layers should be better able to fit the training set but this is not what we saw. 148 | model.add(Dense(256, activation="relu")) 149 | model.add(Dense(256, activation="relu")) 150 | # as we are predicting continuous values, here we define 9 output neurons with linear activation functions, 151 | # each corresponding to one of the QuickNII alignment variables Oxyz, Uxyz, Vxyz. 152 | model.add(Dense(9, activation="linear")) 153 | if DS_weights != None: 154 | # load weights 155 | model.load_weights(DS_weights) 156 | return model 157 | 158 | def Build( 159 | self, 160 | DS_weights=path + "/NN_weights/Allen_Mixed_Best.h5", 161 | xception_weights=path 162 | + "/NN_weights/xception_weights_tf_dim_ordering_tf_kernels.h5", 163 | wise_weights=path + "/NN_weights/Synthetic_data_final.hdf5", 164 | species="mouse", 165 | ): 166 | self.wise_weights = wise_weights 167 | self.DS_weights = DS_weights 168 | self.rat_weights = path + "/NN_weights/rat_mixed_4056.h5" 169 | if species.lower() == "rat": 170 | self.model = self.init_model( 171 | DS_weights=self.rat_weights, xception_weights=xception_weights 172 | ) 173 | if species.lower() == "mouse": 174 | self.model = self.init_model( 175 | DS_weights=self.DS_weights, xception_weights=xception_weights 176 | ) 177 | self.species = species 178 | 179 | def gray_scale(self, img): 180 | # Downsamples images too 299 x 299 181 | # converts images to grayscale 182 | img = color.rgb2gray(img).reshape(299, 299, 1) 183 | return img 184 | 185 | def predict(self, image_dir, prop_angles=True, huber=False, wise=False): # input 186 | # define_image_generator 187 | self.Image_generator = ImageDataGenerator( 188 | preprocessing_function=self.gray_scale, samplewise_std_normalization=True 189 | ).flow_from_directory( 190 | image_dir, 191 | target_size=(299, 299), 192 | batch_size=1, 193 | color_mode="rgb", 194 | shuffle=False, 195 | ) 196 | self.image_dir = image_dir 197 | # reset the image generator to ensure it starts from the first image 198 | self.Image_generator.reset() 199 | # feed images to the model and store the predicted parameters 200 | preds = self.model.predict( 201 | self.Image_generator, 202 | steps=self.Image_generator.n // self.Image_generator.batch_size, 203 | verbose=1, 204 | ) 205 | # convert the parameter values to floating point digits 206 | preds = preds.astype(float) 207 | if wise: 208 | self.Image_generator.reset() 209 | self.model.load_weights(self.wise_weights) 210 | wise_preds = self.model.predict( 211 | self.Image_generator, 212 | steps=self.Image_generator.n // self.Image_generator.batch_size, 213 | verbose=1, 214 | ) 215 | 216 | preds = np.mean((preds, wise_preds), axis=0) 217 | self.model.load_weights(self.DS_weights) 218 | 219 | # define the column names 220 | # create a pandas DataFrame of the parameter values 221 | results = pd.DataFrame(preds, columns=self.columns) 222 | # insert the section filenames into the pandas DataFrame 223 | results["Filenames"] = self.Image_generator.filenames[: results.shape[0]] 224 | ordered_cols = ["Filenames"] + self.columns 225 | self.results = results[ordered_cols] # To get the same column order 226 | if prop_angles: 227 | self.propagate_angles(huber) 228 | 229 | def reorder_indexes(self, ascending): 230 | # reorders values so they are in the same order as the indexes with minimal swaps 231 | self.results.oy = self.results.oy.sort_values(ascending=ascending).values 232 | 233 | def even_spacing( 234 | self, 235 | section_thickness_um=None, 236 | no_correction=False, 237 | order_only=False, 238 | bad_sections=[], 239 | detect_bad_sections=False, 240 | ignore_final_chars=0, 241 | ): 242 | print( 243 | "Section Numbers must have been included as the last three digits of the Filename" 244 | ) 245 | ###This function takes a dataset with section numbers and spaces those sections based on their numbers 246 | section_numbers = [] 247 | depth = [] 248 | count = 1 249 | for Filename in ( 250 | self.results.Filenames.str.split("\\", expand=True).iloc[:, -1].values 251 | ): 252 | if ignore_final_chars > 0: 253 | temp_filename = Filename[:-ignore_final_chars] 254 | else: 255 | temp_filename = Filename 256 | ##this removes all non-numeric characters 257 | section_number = re.sub("[^0-9]", "", temp_filename) 258 | ###this gets the three numbers closest to the end 259 | section_number = section_number[-3:] 260 | ind = [Filename in i for i in self.results.Filenames.values] 261 | d = self.results[ind] 262 | d = calculate_brain_center_depth(d[self.columns].values[0]) 263 | # print(f"Filename: {Filename} section_number: {section_number} depth: {d}") 264 | 265 | ###find the first appearancex of the specified pattern 266 | ###remove non-numeric characters 267 | if len(section_number) < 3: 268 | warnings.warn( 269 | f'could not find three digit section number for file "{Filename}", it should be the last three digits of the filenames.' 270 | ) 271 | if len(section_number) == 0: 272 | warnings.warn( 273 | f'could not find any section number for file "{Filename}\, using {count} instead' 274 | ) 275 | section_numbers.append(count) 276 | count += 1 277 | section_numbers.append(section_number) 278 | 279 | self.results["section_ID"] = section_numbers 280 | 281 | self.results.section_ID = self.results.section_ID.astype(np.float64) 282 | self.results = self.results.sort_values( 283 | "section_ID", ascending=True 284 | ).reset_index(drop=True) 285 | 286 | print(self.results) 287 | 288 | depth = [] 289 | for section in self.results[self.columns].values: 290 | depth.append((calculate_brain_center_depth(section))) 291 | depth = np.array(depth) 292 | 293 | self.results["depth"] = pd.Series(depth) 294 | if len(bad_sections) > 0: 295 | bad_section_indexes = np.sum( 296 | [self.results.Filenames.str.contains(bs) for bs in bad_sections], 297 | axis=0, 298 | dtype=bool, 299 | ) 300 | print( 301 | f" we found {np.sum(bad_section_indexes)} out of {len(bad_sections)} bad sections" 302 | ) 303 | estimate_thickness = ideal_thickness( 304 | self.results[~bad_section_indexes], 305 | depth[~bad_section_indexes], 306 | detect_bad_sections=detect_bad_sections, 307 | ) 308 | else: 309 | estimate_thickness = ideal_thickness( 310 | self.results, depth, detect_bad_sections=detect_bad_sections 311 | ) 312 | 313 | print("\n", estimate_thickness, "\n") 314 | print("new version") 315 | 316 | if estimate_thickness > 0: 317 | print("the sections are numbered rostrocaudaly") 318 | self.reorder_indexes(ascending=False) 319 | 320 | else: 321 | print("the sections are not numbered rostrocaudaly") 322 | self.reorder_indexes(ascending=True) 323 | 324 | if section_thickness_um is not None: 325 | section_thickness_um *= -1 326 | 327 | if no_correction or order_only: 328 | return 329 | 330 | depth = [] 331 | for section in self.results[self.columns].values: 332 | depth.append((calculate_brain_center_depth(section))) 333 | depth = np.array(depth) 334 | 335 | if len(bad_sections) > 0: 336 | bad_section_indexes = np.sum( 337 | [self.results.Filenames.str.contains(bs) for bs in bad_sections], 338 | axis=0, 339 | dtype=bool, 340 | ) 341 | print( 342 | f" we found {np.sum(bad_section_indexes)} out of {len(bad_sections)} bad sections" 343 | ) 344 | estimate_thickness = ideal_thickness( 345 | self.results[~bad_section_indexes], 346 | depth[~bad_section_indexes], 347 | detect_bad_sections=detect_bad_sections, 348 | ) 349 | else: 350 | estimate_thickness = ideal_thickness( 351 | self.results, depth, detect_bad_sections=detect_bad_sections 352 | ) 353 | 354 | if section_thickness_um is None: 355 | section_thickness_um = -estimate_thickness 356 | print(len(depth)) 357 | if len(bad_sections) > 0: 358 | ideal = ideal_spacing( 359 | depth, 360 | self.results["section_ID"], 361 | section_thickness_um, 362 | bad_section_indexes=bad_section_indexes, 363 | ) 364 | else: 365 | ideal = ideal_spacing( 366 | depth, self.results["section_ID"], section_thickness_um 367 | ) 368 | 369 | self.results.oy -= depth - ideal 370 | depth = [] 371 | for section in self.results[self.columns].values: 372 | depth.append((calculate_brain_center_depth(section))) 373 | self.results.section_ID = np.abs(self.results.section_ID) 374 | 375 | def load_QuickNII(self, filename): 376 | self.results = XML_to_csv(filename) 377 | self.results[self.columns] = self.results[self.columns].astype(np.float64) 378 | 379 | def set_angles(self, DV=None, ML=None): 380 | rotated_sections = [] 381 | count = 0 382 | for section in self.results.iterrows(): 383 | m = section[1][ 384 | ["ox", "oy", "oz", "ux", "uy", "uz", "vx", "vy", "vz"] 385 | ].values.astype(np.float64) 386 | cross, k = plane_alignment.find_plane_equation(m) 387 | old_DV = plane_alignment.get_angle(m, cross, k, "DV") 388 | old_ML = plane_alignment.get_angle(m, cross, k, "ML") 389 | section = section[1][self.columns].values 390 | original_depth = calculate_brain_center_depth(section) 391 | for i in range(10): 392 | cross, k = plane_alignment.find_plane_equation(section) 393 | if DV is not None: 394 | section = plane_alignment.Section_adjust( 395 | section, mean=DV, direction="DV" 396 | ) 397 | else: 398 | section = plane_alignment.Section_adjust( 399 | section, mean=old_DV, direction="DV" 400 | ) 401 | if ML is not None: 402 | section = plane_alignment.Section_adjust( 403 | section, mean=ML, direction="ML" 404 | ) 405 | else: 406 | section = plane_alignment.Section_adjust( 407 | section, mean=old_ML, direction="DV" 408 | ) 409 | rotated_depth = calculate_brain_center_depth(section) 410 | movement = rotated_depth - original_depth 411 | # section[1] -= movement 412 | rotated_sections.append(section) 413 | cross, k = plane_alignment.find_plane_equation(section) 414 | final_depth = calculate_brain_center_depth(section) 415 | # print(" original: {} \n rotated {} \n corrected {} \n".format(original_depth, rotated_depth, final_depth)) 416 | 417 | count += 1 418 | self.results[self.columns] = rotated_sections 419 | # insert the section filenames into the pandas DataFrame 420 | 421 | def propagate_angles(self, huber=True): 422 | DV = [] 423 | ML = [] 424 | oy = [] 425 | for prediction in self.results.iterrows(): 426 | m = prediction[1][ 427 | ["ox", "oy", "oz", "ux", "uy", "uz", "vx", "vy", "vz"] 428 | ].values.astype(np.float64) 429 | oy.append(m[1]) 430 | cross, k = plane_alignment.find_plane_equation(m) 431 | DV.append(plane_alignment.get_angle(m, cross, k, "DV")) 432 | ML.append(plane_alignment.get_angle(m, cross, k, "ML")) 433 | if huber == True: 434 | oy = np.array(oy).reshape(-1, 1) 435 | # we use a huberised linear regressor as it is more robust to outliers 436 | huber_regressor = HuberRegressor().fit(oy, DV) 437 | # for our predictions we multiple the depth by the coefficient and add the y intercept 438 | prop_DV = (huber_regressor.coef_ * oy) + huber_regressor.intercept_ 439 | huber_regressor = HuberRegressor().fit(oy, ML) 440 | prop_ML = (huber_regressor.coef_ * oy) + huber_regressor.intercept_ 441 | else: 442 | length = len(DV) 443 | weights = plane_alignment.make_gaussian_weights(0, 528) 444 | oy = np.array(oy) 445 | oy[oy < 0] = 0 446 | oy[oy > 527] = 527 447 | weights = [weights[int(y)] for y in oy] 448 | # DV = sorted(DV, key=abs)[int(length*0.75):] 449 | # ML = sorted(ML, key=abs)[int(length*0.75):] 450 | print(weights) 451 | prop_DV = [np.average(DV, weights=np.array(weights))] * length 452 | prop_ML = [np.average(ML, weights=np.array(weights))] * length 453 | 454 | rotated_sections = [] 455 | count = 0 456 | for section in self.results.iterrows(): 457 | section = section[1][self.columns].values 458 | original_depth = calculate_brain_center_depth(section) 459 | for i in range(10): 460 | cross, k = plane_alignment.find_plane_equation(section) 461 | 462 | section = plane_alignment.Section_adjust( 463 | section, mean=prop_DV[count], direction="DV" 464 | ) 465 | 466 | section = plane_alignment.Section_adjust( 467 | section, mean=prop_ML[count], direction="ML" 468 | ) 469 | rotated_depth = calculate_brain_center_depth(section) 470 | movement = rotated_depth - original_depth 471 | # section[1] -= movement 472 | rotated_sections.append(section) 473 | cross, k = plane_alignment.find_plane_equation(section) 474 | final_depth = calculate_brain_center_depth(section) 475 | # print(" original: {} \n rotated {} \n corrected {} \n".format(original_depth, rotated_depth, final_depth)) 476 | 477 | count += 1 478 | results = pd.DataFrame(rotated_sections, columns=self.columns) 479 | # insert the section filenames into the pandas DataFrame 480 | results["Filenames"] = self.Image_generator.filenames[: results.shape[0]] 481 | ordered_cols = ["Filenames"] + self.columns 482 | self.results = results[ordered_cols] # To get the same column order 483 | 484 | def Save_Results(self, filename): 485 | if "section_ID" in self.results: 486 | section_numbers = np.abs(self.results["section_ID"]) 487 | else: 488 | section_numbers = None 489 | widths, heights = [], [] 490 | if self.image_dir is not None: 491 | for file in self.results.Filenames: 492 | width, height = get_image_size(self.image_dir + os.path.sep + file) 493 | widths.append(width) 494 | heights.append(height) 495 | else: 496 | for file in self.results.Filenames: 497 | width, height = get_image_size(file) 498 | widths.append(width) 499 | heights.append(height) 500 | self.results["width"] = widths 501 | self.results["height"] = heights 502 | pd_to_quickNII( 503 | results=self.results, 504 | orientation="coronal", 505 | filename=str(filename), 506 | web=self.web, 507 | folder_name=self.folder_name, 508 | aligner="DeepSlice_ver_3.0_python", 509 | ) 510 | 511 | -------------------------------------------------------------------------------- /src/abba_python/deepslice/LICENSE: -------------------------------------------------------------------------------- 1 | DeepSlice source code © [2022] Macquarie University patent pending in Australia, and contact Macquarie University for other countries. Macquarie University 2 | grants users a non-exclusive, non-transferable, non-sublicenseable licence to copy, reproduce and adapt DeepSlice only for use for non-commercial research 3 | purposes and not for other purposes without Macquarie University's prior written consent. DeepSlice is made available on the basis that it is released as a test 4 | version, 'as is', and should only be used for coronal images of the adult mouse brain, and may contain errors or produce results that are incorrect. DeepSlice 5 | or its derivatives should not be used or released for commercial use and cannot at present be reliably used to analyse brain images from species other than the 6 | mouse. Users agree that if they adapt DeepSlice, and make those adaptations available for others to use, they will release the adapted source code to GitHub on 7 | the same terms as this licence 8 | -------------------------------------------------------------------------------- /src/abba_python/deepslice/README.md: -------------------------------------------------------------------------------- 1 | 2 | ![Alt](docs/DeepSlice_github_banner.png "DeepSlice Banner") 3 | DeepSlice is a python library, published by [the McMullan Lab Group](https://researchers.mq.edu.au/en/persons/simon-mcmullan), which automatically aligns mouse histology with the allen brain atlas common coordinate framework. 4 | It is the Masters project of [Harry Carey](https://github.com/PolarBean/). The alignments are viewable, and refinable, using the [QuickNII](https://www.nitrc.org/projects/quicknii "QuickNII") software package. 5 | DeepSlice requires no preprocessing and works on any stain, however we have found it performs best on brightfield images. 6 | At present one limitation is that it only works on Coronally cut sections, we will release an update in the future for sagittal and horizontally cut histology. 7 | ![Alt](docs/process.PNG) 8 | DeepSlice automates the process of identifying exactly where in the brain a section lies, it can accomodate non-orthogonal cutting planes and will produce an image specific annotation for each section in your brain. 9 | ## Web Application 10 | If you would like to use DeepSlice but don't need your own personal installation, check out [**DeepSlice Flask**](https://www.DeepSlice.com.au), a fully functional web application which will allow you to upload your dataset and download the aligned results. The web interface was developed by [Michael Pegios](https://github.com/ThermoDev/). 11 | ## [Installation: How to install DeepSlice](docs/installation.md) 12 | 13 | ## [Usage: How to align using DeepSlice](docs/usage.md) 14 | For a quick example using google colab, view our notebook here! 15 | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/PolarBean/DeepSlice/blob/master/example_notebooks/DeepSlice_example.ipynb) 16 | 17 | **Happy Aligning :)** 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/abba_python/deepslice/__init__.py: -------------------------------------------------------------------------------- 1 | from abba_python.deepslice import DeepSlice -------------------------------------------------------------------------------- /src/abba_python/deepslice/utilities/QuickNII_functions.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import xml.etree.ElementTree as ET 3 | from tqdm import tqdm 4 | import re 5 | import numpy as np 6 | 7 | 8 | def indent(elem, level=0): 9 | i = "\n" + level * " " 10 | if len(elem): 11 | if not elem.text or not elem.text.strip(): 12 | elem.text = i + " " 13 | if not elem.tail or not elem.tail.strip(): 14 | elem.tail = i 15 | for elem in elem: 16 | indent(elem, level + 1) 17 | if not elem.tail or not elem.tail.strip(): 18 | elem.tail = i 19 | else: 20 | if level and (not elem.tail or not elem.tail.strip()): 21 | elem.tail = i 22 | 23 | 24 | # converts a pandas DataFrame to a quickNII compatible XML 25 | def pd_to_quickNII( 26 | results, 27 | orientation="coronal", 28 | filename="Download", 29 | web=False, 30 | folder_name=None, 31 | aligner=None, 32 | ): 33 | # Replace the subfolder present in results if we are running for the web 34 | if web and folder_name: 35 | results["Filenames"] = ( 36 | results["Filenames"] 37 | .str.replace(folder_name, "") 38 | .str.replace("\\", "") 39 | .str.replace("/", "") 40 | ) 41 | # Get the total number of sections 42 | num_of_sections = results.shape[0] 43 | 44 | if not "section_ID" in results: 45 | section_numbers = np.arange((num_of_sections)) + 1 46 | if orientation == "coronal": 47 | results = results.sort_values("oy") 48 | if orientation == "sagittal": 49 | results = results.sort_values("ox") 50 | if orientation == "horizontal": 51 | results = results.sort_values("oz") 52 | results["section_ID"] = section_numbers 53 | else: 54 | results = results.sort_values("section_ID") 55 | results = results[ 56 | [ 57 | "Filenames", 58 | "ox", 59 | "oy", 60 | "oz", 61 | "ux", 62 | "uy", 63 | "uz", 64 | "vx", 65 | "vy", 66 | "vz", 67 | "section_ID", 68 | "width", 69 | "height", 70 | ] 71 | ] 72 | # Create the XML structure 73 | root = ET.Element("series") 74 | root.attrib["first"] = str(results["section_ID"].values) 75 | root.attrib["last"] = str(results["section_ID"].values) 76 | root.attrib["aligner"] = str(aligner) 77 | # Explicitly confirm all filenames are Strings 78 | results["Filenames"] = results["Filenames"].astype(str) 79 | # for each section append Oxyz, Uxyz and Vxyz parameters to the XML 80 | for i in range(num_of_sections): 81 | child = ET.SubElement(root, "slice") 82 | # this is the filename in our results file 83 | child.attrib["filename"] = results.iloc[i, 0] 84 | root.attrib["name"] = results.iloc[i, 0] # so is this 85 | # Organise our coordinates 86 | ox, oy, oz, ux, uy, uz, vx, vy, vz = results.iloc[i, 1:10] 87 | # these next two values are the original file size of the image, i need to fix this later. 88 | child.attrib["height"] = results.iloc[ 89 | i, 90 | ] 91 | child.attrib["width"] = "-999" 92 | # Section number 93 | child.attrib["nr"] = str(results.iloc[i, 10]) 94 | child.attrib["width"] = str(results.iloc[i, 11]) 95 | child.attrib["height"] = str(results.iloc[i, 12]) 96 | # writes Oxyz, Uxyz and Vxyz parameters to the XML in the correct format 97 | child.attrib["anchoring"] = ( 98 | "ox=" 99 | + str(ox) 100 | + "&oy=" 101 | + str(oy) 102 | + "&oz=" 103 | + str(oz) 104 | + "&ux=" 105 | + str(ux) 106 | + "&uy=" 107 | + str(uy) 108 | + "&uz=" 109 | + str(uz) 110 | + "&vx=" 111 | + str(vx) 112 | + "&vy=" 113 | + str(vy) 114 | + "&vz=" 115 | + str(vz) 116 | ) 117 | indent(root) 118 | ET.ElementTree(root).write("{}.xml".format(filename)) 119 | results.to_csv("{}.csv".format(filename)) 120 | 121 | 122 | # a useful script that converts a Quicknii XML to a csv file 123 | # handy for training on human-aligned QuickNII files. 124 | 125 | 126 | def XML_to_csv(xml): 127 | tree = ET.parse(str(xml)) 128 | root = tree.getroot() 129 | count = 0 130 | df = pd.DataFrame() 131 | for i in root.findall("slice"): 132 | try: 133 | stringdata = str(i.attrib["anchoring"]) 134 | except KeyError: 135 | continue 136 | df.loc[count, "Filenames"] = i.attrib["filename"] 137 | df.loc[count, "ox"] = re.search("ox=(.+?)&oy", stringdata).group(1) 138 | df.loc[count, "oy"] = re.search("oy=(.+?)&oz", stringdata).group(1) 139 | df.loc[count, "oz"] = re.search("oz=(.+?)&ux", stringdata).group(1) 140 | df.loc[count, "ux"] = re.search("ux=(.+?)&uy", stringdata).group(1) 141 | df.loc[count, "uy"] = re.search("uy=(.+?)&uz", stringdata).group(1) 142 | df.loc[count, "uz"] = re.search("uz=(.+?)&vx", stringdata).group(1) 143 | df.loc[count, "vx"] = re.search("vx=(.+?)&vy", stringdata).group(1) 144 | df.loc[count, "vy"] = re.search("vy=(.+?)&vz", stringdata).group(1) 145 | df.loc[count, "vz"] = re.search("vz=(.+?)$", stringdata).group(1) 146 | count += 1 147 | return df 148 | -------------------------------------------------------------------------------- /src/abba_python/deepslice/utilities/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NicoKiaru/ABBA-Python/1626654aaf370cd2619896195c7f88aeb7d16a7c/src/abba_python/deepslice/utilities/__init__.py -------------------------------------------------------------------------------- /src/abba_python/deepslice/utilities/neuron_tools.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from abba_python.deepslice.utilities import QuickNII_functions 3 | import glob 4 | import pandas as pd 5 | def points_to_3d(points, plane): 6 | resolution = points[['width', 'height']].values.astype(np.float64)[0] 7 | points = points[['X', 'Y']].values.astype(np.float64) 8 | ## Scale points by the resolution (numbers will now be between 0 and 1 9 | points/=resolution 10 | O_plane = plane[['ox','oy','oz']].values.astype(np.float64) 11 | X_plane = plane[['ux','uy','uz']].values.astype(np.float64) 12 | Y_plane = plane[['vx','vy','vz']].values.astype(np.float64) 13 | ## Since we have the vectors U&V and the fractional cell coordinates 14 | ## We can convert these onto the points on the plane 15 | ## Should probably be vectorised 16 | X_dim = [X_plane * points[i, 0] for i in range(len(points))] 17 | Y_dim = [Y_plane * points[i, 1] for i in range(len(points))] 18 | points = np.sum((X_dim,Y_dim), axis=0) 19 | ##Now we add the origin to these coordinates to transform them into our alignment space 20 | points += O_plane 21 | points = points.reshape((len(points), 3)) 22 | return points 23 | 24 | def analyse_slice(point_name, plane): 25 | image_name = point_name.split('/')[-1][:-4] 26 | raw_names = [name[0].split('/')[-1] for name in plane["Filenames"].str.split('.')] 27 | index = [i==image_name for i in raw_names] 28 | plane = plane[index] 29 | points = pd.read_csv(point_name) 30 | points = points_to_3d(points, plane) 31 | return points 32 | 33 | def analyse_brain(plane_file, points_folder = 'points/', save_csv=False): 34 | plane = QuickNII_functions.XML_to_csv(plane_file) 35 | cells = np.empty((0,3)) 36 | for points in glob.glob(points_folder+'/*.csv'): 37 | cells = np.vstack((cells, analyse_slice(points, plane))) 38 | cells = pd.DataFrame(cells, columns = ['X', 'Y', 'Z']) 39 | cells.to_hdf(plane_file[:-4]+'Whole_Brain_Cell_Count.h5') 40 | if save_csv: 41 | cells.to_csv(plane_file[:-4]+'Whole_Brain_Cell_Count.csv') 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/abba_python/deepslice/utilities/plane_alignment.py: -------------------------------------------------------------------------------- 1 | import random 2 | from statistics import mean 3 | import numpy as np 4 | import math 5 | from PIL import Image 6 | import glob 7 | image_list = [] 8 | # a 2-dimensional plane can be fully describable if you know any three points that lie on its surface 9 | 10 | 11 | def find_plane_equation(plane): 12 | ''' 13 | Finds the plane equation of a plane 14 | :param plane: the plane to find the equation of 15 | :type plane: :any:`numpy.ndarray` 16 | :returns: the normal vector of the plane and the constant k 17 | :rtype: :any:`numpy.ndarray`, float 18 | ''' 19 | a, b, c = np.array(plane[0:3], dtype=np.float64), np.array(plane[3:6], dtype=np.float64), np.array(plane[6:9], 20 | dtype=np.float64) 21 | cross = np.cross(b, c) 22 | cross /= 9 23 | k = -((a[0] * cross[0]) + (a[1] * cross[1]) + (a[2] * cross[2])) 24 | return (cross, k) 25 | 26 | def get_angle(inp, cross, k, direction): 27 | # inp is the input plane, represented by 3 xzy sets 28 | # cross and k is the normal vector of the plane 29 | # Direction defines whether we want the mediolateral or dorsaventral angle 30 | section = inp.copy() 31 | # transform vector into absolute coordinates 32 | for i in range(3): 33 | section[i + 3] += section[i] 34 | section[i + 6] += section[i] 35 | if direction == 'ML': 36 | # original xzy point 37 | a = section[0:2] 38 | # calculate a point which differs from this point only in the x dimension 39 | # to do this we use the plane equation which tells us the position of every point on the plane 40 | linear_point = (((section[0] - 100) * cross[0] 41 | ) + ((section[2]) * cross[2])) + k 42 | # this tells us the depth of that point which differs in x dimension but lies on the same plane 43 | depth = -(linear_point / cross[1]) 44 | b = np.array((section[0] - 100, depth)) 45 | c = b + [100, 0] 46 | 47 | 48 | if direction == 'DV': 49 | a = section[1:3] 50 | linear_point = (((section[0]) * cross[0]) + 51 | ((section[2] - 100) * cross[2])) + k 52 | depth = -(linear_point / cross[1]) 53 | b = np.array((depth, section[2] - 100)) 54 | c = b + [0, 100] 55 | ba = a - b 56 | bc = c - b 57 | cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc)) 58 | # This looks redundant, needs to be tested 59 | angle = np.arccos(cosine_angle) 60 | angle = np.degrees(angle) 61 | if direction == 'ML': 62 | if b[1] > a[1]: 63 | angle *= -1 64 | if direction == 'DV': 65 | if b[0] < a[0]: 66 | angle *= -1 67 | return (angle) 68 | 69 | 70 | def rotation_around_axis(axis, angle): 71 | ''' 72 | Generates a 3x3 rotation matrix using the Euler-Rodrigues formula 73 | following the definition here: 74 | https://en.wikipedia.org/wiki/Euler%E2%80%93Rodrigues_formula. 75 | :param axis: the axis around which to rotate as a vector of length 3 76 | (no normalisation required) 77 | :type axis: array like 78 | :param angle: the angle in radians to rotate 79 | :type angle: float 80 | :returns: the rotation matrix 81 | :rtype: a 3x3 :any:`numpy.ndarray` 82 | ''' 83 | angle = np.radians(angle) 84 | axis = axis / np.linalg.norm(axis) 85 | 86 | a = math.cos(angle / 2.0) 87 | b, c, d = axis * math.sin(angle / 2.0) 88 | aa, bb, cc, dd = a * a, b * b, c * c, d * d 89 | bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d 90 | 91 | return np.array([[aa + bb - cc - dd, 2 * (bc - ad), 2 * (bd + ac)], 92 | [2 * (bc + ad), aa + cc - bb - dd, 2 * (cd - ab)], 93 | [2 * (bd - ac), 2 * (cd + ab), aa + dd - bb - cc]]) 94 | 95 | 96 | def make_gaussian_weights(mini, maxi): 97 | ''' 98 | Generates a list of weights for a gaussian distribution 99 | :param mini: the minimum value of the distribution 100 | :type mini: float 101 | :param maxi: the maximum value of the distribution 102 | :type maxi: float 103 | :returns: a list of weights 104 | :rtype: list 105 | ''' 106 | weights = [] 107 | center = mean((mini, maxi)) 108 | quartile = (maxi-mini)/4 109 | while len(weights) < ((maxi-mini)/2): 110 | weights.append(random.gauss(center, quartile)) 111 | weights = [max(x, mini) for x in weights] 112 | weights = [min(x, maxi) for x in weights] 113 | weights = [x-center if x > center else x for x in weights] 114 | weights = sorted(weights) 115 | weights_rev = sorted(weights, reverse=True) 116 | weights.extend(weights_rev) 117 | return [x/max(weights) for x in weights] 118 | 119 | 120 | def get_axis(m, translation_vector, direction, plane_of_section=None, atlas='AMBA'): 121 | ''' 122 | :param m: the matrix to rotate 123 | :type m: 3x3 :any:`numpy.ndarray` 124 | :param translation_vector: the translation vector to apply 125 | :type translation_vector: 3x1 :any:`numpy.ndarray` 126 | :param direction: the direction of the rotation 127 | :type direction: string 128 | :param plane: the plane to rotate around 129 | :type plane: string 130 | :returns: the axis of rotation 131 | :rtype: 3x1 :any:`numpy.ndarray` 132 | ''' 133 | # find the plane equation for a set of QuickNII coordinates 134 | cross, k = find_plane_equation(m) 135 | if atlas == 'AMBA': 136 | volume = np.array((528, 320, 456)) 137 | posx, posy, posz = volume/2 138 | 139 | if atlas == 'WHS': 140 | volume = np.array((512, 1024, 512)) 141 | posx, posy, posz = 256, 512, 256 142 | 143 | translated_volume = volume - translation_vector 144 | 145 | cor_linear_point = ( 146 | (((translated_volume[0] / 2)) * cross[0]) + ((translated_volume[2] / 2) * cross[2])) + k 147 | cor_Y = -(cor_linear_point / cross[1]) 148 | # cor_axis = ((translated_volume[0] / 2, depth, translated_volume[2] / 2)) 149 | 150 | sag_linear_point = ( 151 | ((translated_volume[1] / 2) * cross[1]) + ((translated_volume[2] / 2) * cross[2])) + k 152 | sag_X = -(sag_linear_point / cross[0]) 153 | # sag_axis = ((translated_volume[1] / 2, depth, translated_volume[2] / 2)) 154 | 155 | horz_linear_point = ( 156 | ((translated_volume[0] / 2) * cross[0]) + ((translated_volume[1] / 2) * cross[1])) + k 157 | horz_Z = -(horz_linear_point / cross[2]) 158 | if plane_of_section is None: 159 | plane_of_section = np.argmin(np.abs((cor_Y - posy, sag_X - posx, horz_Z - posz))) 160 | choices = {'x': sag_X, ' y': cor_Y,' z': horz_Z } 161 | 162 | if plane_of_section == 0: 163 | axis = ((translated_volume[0] / 2, cor_Y, translated_volume[2] / 2)) 164 | print(f'cor: {axis + translation_vector}') 165 | 166 | if direction == 'DV': 167 | linear_point = ( 168 | ((translated_volume[0]) * cross[0]) + ((translated_volume[2] / 2) * cross[2])) + k 169 | Ypred = -(linear_point / cross[1]) 170 | ##the way QNII rotates is but i prefer my way 171 | # axis2 = ((translated_volume[0], cor_Y, translated_volume[2] / 2)) 172 | axis2 = ((translated_volume[0], Ypred, translated_volume[2] / 2)) 173 | 174 | ##this gives me the depth of a point directly beside the coronal center point 175 | if direction == 'ML': 176 | linear_point = (((translated_volume[0] / 2) * cross[0]) + ((translated_volume[2]) * cross[2])) + k 177 | Ypred = -(linear_point / cross[1]) 178 | axis2 = ((translated_volume[0] / 2, Ypred, translated_volume[2])) 179 | 180 | 181 | 182 | 183 | if plane_of_section==1: 184 | axis = ((sag_X, translated_volume[1] / 2, translated_volume[2] / 2)) 185 | print(f'sag: {axis + translation_vector}') 186 | 187 | if direction == 'DV': 188 | linear_point = ( 189 | ((translated_volume[1]) * cross[1]) + ((translated_volume[2] / 2) * cross[2])) + k 190 | Xpred = -(linear_point / cross[0]) 191 | axis2 = ((Xpred, translated_volume[1], translated_volume[2] / 2)) 192 | if direction == 'ML': 193 | linear_point = ( 194 | ((translated_volume[1] / 2) * cross[1]) + ((translated_volume[2]) * cross[2])) + k 195 | Xpred = -(linear_point / cross[0]) 196 | axis2 = ((Xpred, translated_volume[1] / 2, translated_volume[2])) 197 | 198 | 199 | if plane_of_section==2: 200 | axis = ((translated_volume[0] / 2, translated_volume[1] / 2, horz_Z)) 201 | print(f'horz: {axis + translation_vector}') 202 | if direction == 'DV': 203 | linear_point = ( 204 | ((translated_volume[0]) * cross[0]) + ((translated_volume[1] / 2) * cross[1])) + k 205 | Zpred = -(linear_point / cross[2]) 206 | axis2 = ((translated_volume[0], translated_volume[1] / 2, Zpred)) 207 | 208 | 209 | if direction == 'ML': 210 | linear_point = ( 211 | ((translated_volume[0] / 2) * cross[0]) + ((translated_volume[1]) * cross[1])) + k 212 | Zpred = -(linear_point / cross[2]) 213 | axis2 = ((translated_volume[0] / 2, translated_volume[1], Zpred)) 214 | axis_vector = np.array(axis) - np.array(axis2) 215 | return (axis_vector) 216 | 217 | 218 | 219 | def rotate_section(section, degrees, direction, plane_of_section=None, atlas = 'AMBA'): 220 | ''' 221 | Rotates a section 222 | :param section: the section to rotate 223 | :type section: :any:`numpy.ndarray` 224 | :param degrees: the degrees to rotate the section 225 | :type degrees: float 226 | :param direction: the direction of the rotation 227 | :type direction: string 228 | :param plane: the plane to rotate around 229 | :type plane: string 230 | :returns: the rotated section 231 | :rtype: :any:`numpy.ndarray` 232 | ''' 233 | 234 | cross, k = find_plane_equation(section) 235 | 236 | # this looks redundant 237 | # if direction==ML: 238 | # ML=get_angle(section.reshape(9),cross,k,direction=direction) 239 | section_points = section.copy() 240 | for i in range(3): 241 | section_points[i + 3] += section_points[i] 242 | section_points[i + 6] += section_points[i] 243 | 244 | points = section_points.reshape(3, 3) 245 | if atlas == 'WHS': 246 | translated_volume = np.array((489, 1024, 590)) 247 | posx, posy, posz = 256, 512, 256 248 | if atlas == 'AMBA': 249 | translated_volume = np.array((528, 320, 456)) 250 | posx, posy, posz = translated_volume/2 251 | 252 | cor_linear_point = ( 253 | (((translated_volume[0] / 2)) * cross[0]) + ((translated_volume[2] / 2) * cross[2])) + k 254 | cor_Y = -(cor_linear_point / cross[1]) 255 | # cor_axis = ((translated_volume[0] / 2, depth, translated_volume[2] / 2)) 256 | 257 | sag_linear_point = ( 258 | ((translated_volume[1] / 2) * cross[1]) + ((translated_volume[2] / 2) * cross[2])) + k 259 | sag_X = -(sag_linear_point / cross[0]) 260 | # sag_axis = ((translated_volume[1] / 2, depth, translated_volume[2] / 2)) 261 | 262 | horz_linear_point = ( 263 | ((translated_volume[0] / 2) * cross[0]) + ((translated_volume[1] / 2) * cross[1])) + k 264 | horz_Z = -(horz_linear_point / cross[2]) 265 | if plane_of_section is None: 266 | plane_of_section = np.argmin(np.abs((cor_Y - posy, sag_X - posx, horz_Z - posz))) 267 | # midpoint = translated_volume/2 268 | # x = symbols('x') 269 | # expr = sum((x * cross + midpoint) * cross) - k 270 | # m = solve(expr) 271 | # translation_vector = np.array((m * cross + midpoint), dtype=np.float) 272 | if plane_of_section==0: 273 | 274 | translation_vector = ( 275 | (translated_volume[0] / 2, cor_Y, translated_volume[2] / 2)) 276 | 277 | if plane_of_section==1: 278 | translation_vector = ( 279 | (sag_X, translated_volume[1] / 2, translated_volume[2] / 2)) 280 | 281 | if plane_of_section==2: 282 | translation_vector = ( 283 | (translated_volume[0] / 2, translated_volume[1] / 2, horz_Z)) 284 | 285 | translated_points = points - translation_vector 286 | axis = get_axis(section, translation_vector, direction=direction, plane_of_section=plane_of_section) 287 | print(axis) 288 | rot_matrix = rotation_around_axis(axis, degrees) 289 | # perform rotation, centred on (0,0,0) 290 | rotated_translated_points = np.dot(translated_points, rot_matrix) 291 | # translate back to original geometric centre. 292 | rotated_points = rotated_translated_points + translation_vector 293 | rotated_points = rotated_points.reshape(9) 294 | for i in range(3): 295 | rotated_points[i + 3] -= rotated_points[i] 296 | rotated_points[i + 6] -= rotated_points[i] 297 | return (rotated_points) 298 | 299 | 300 | 301 | def Section_adjust(section, direction, mean): 302 | cross, k = find_plane_equation(section) 303 | angle = get_angle(section, cross, k, direction) 304 | dif = angle-mean 305 | rot = (rotate_section(section, -dif, direction)) 306 | return(rot) 307 | -------------------------------------------------------------------------------- /src/abba_python/deepslice/utilities/plane_alignment_rat.py: -------------------------------------------------------------------------------- 1 | import random 2 | from statistics import mean 3 | import numpy as np 4 | import math 5 | from PIL import Image 6 | import glob 7 | image_list = [] 8 | # a 2-dimensional plane can be fully describable if you know any three points that lie on its surface 9 | 10 | 11 | def find_plane_equation(plane): 12 | ''' 13 | Finds the plane equation of a plane 14 | :param plane: the plane to find the equation of 15 | :type plane: :any:`numpy.ndarray` 16 | :returns: the normal vector of the plane and the constant k 17 | :rtype: :any:`numpy.ndarray`, float 18 | ''' 19 | a, b, c = np.array(plane[0:3], dtype=np.float64), np.array(plane[3:6], dtype=np.float64), np.array(plane[6:9], 20 | dtype=np.float64) 21 | cross = np.cross(b, c) 22 | cross /= 9 23 | k = -((a[0] * cross[0]) + (a[1] * cross[1]) + (a[2] * cross[2])) 24 | return (cross, k) 25 | 26 | 27 | def get_angle(inp, cross, k, direction): 28 | # inp is the input plane, represented by 3 xzy sets 29 | # cross and k is the normal vector of the plane 30 | # Direction defines whether we want the mediolateral or dorsaventral angle 31 | section = inp.copy() 32 | # transform vector into absolute coordinates 33 | for i in range(3): 34 | section[i + 3] += section[i] 35 | section[i + 6] += section[i] 36 | if direction == 'ML': 37 | # original xzy point 38 | a = section[0:2] 39 | # calculate a point which differs from this point only in the x dimension 40 | # to do this we use the plane equation which tells us the position of every point on the plane 41 | linear_point = (((section[0] - 100) * cross[0] 42 | ) + ((section[2]) * cross[2])) + k 43 | # this tells us the depth of that point which differs in x dimension but lies on the same plane 44 | depth = -(linear_point / cross[1]) 45 | b = np.array((section[0] - 100, depth)) 46 | c = b + [100, 0] 47 | 48 | 49 | if direction == 'DV': 50 | a = section[1:3] 51 | linear_point = (((section[0]) * cross[0]) + 52 | ((section[2] - 100) * cross[2])) + k 53 | depth = -(linear_point / cross[1]) 54 | b = np.array((depth, section[2] - 100)) 55 | c = b + [0, 100] 56 | ba = a - b 57 | bc = c - b 58 | cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc)) 59 | # This looks redundant, needs to be tested 60 | angle = np.arccos(cosine_angle) 61 | angle = np.degrees(angle) 62 | if direction == 'ML': 63 | if b[1] > a[1]: 64 | angle *= -1 65 | if direction == 'DV': 66 | if b[0] < a[0]: 67 | angle *= -1 68 | return (angle) 69 | 70 | 71 | def rotation_around_axis(axis, angle): 72 | ''' 73 | Generates a 3x3 rotation matrix using the Euler-Rodrigues formula 74 | following the definition here: 75 | https://en.wikipedia.org/wiki/Euler%E2%80%93Rodrigues_formula. 76 | :param axis: the axis around which to rotate as a vector of length 3 77 | (no normalisation required) 78 | :type axis: array like 79 | :param angle: the angle in radians to rotate 80 | :type angle: float 81 | :returns: the rotation matrix 82 | :rtype: a 3x3 :any:`numpy.ndarray` 83 | ''' 84 | angle = np.radians(angle) 85 | axis = axis / np.linalg.norm(axis) 86 | 87 | a = math.cos(angle / 2.0) 88 | b, c, d = axis * math.sin(angle / 2.0) 89 | aa, bb, cc, dd = a * a, b * b, c * c, d * d 90 | bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d 91 | 92 | return np.array([[aa + bb - cc - dd, 2 * (bc - ad), 2 * (bd + ac)], 93 | [2 * (bc + ad), aa + cc - bb - dd, 2 * (cd - ab)], 94 | [2 * (bd - ac), 2 * (cd + ab), aa + dd - bb - cc]]) 95 | 96 | 97 | def make_gaussian_weights(mini, maxi): 98 | ''' 99 | Generates a list of weights for a gaussian distribution 100 | :param mini: the minimum value of the distribution 101 | :type mini: float 102 | :param maxi: the maximum value of the distribution 103 | :type maxi: float 104 | :returns: a list of weights 105 | :rtype: list 106 | ''' 107 | weights = [] 108 | center = mean((mini, maxi)) 109 | quartile = (maxi-mini)/4 110 | while len(weights) < ((maxi-mini)/2): 111 | weights.append(random.gauss(center, quartile)) 112 | weights = [max(x, mini) for x in weights] 113 | weights = [min(x, maxi) for x in weights] 114 | weights = [x-center if x > center else x for x in weights] 115 | weights = sorted(weights) 116 | weights_rev = sorted(weights, reverse=True) 117 | weights.extend(weights_rev) 118 | return [x/max(weights) for x in weights] 119 | 120 | 121 | def get_axis(m, translation_vector, direction, plane_of_section=None): 122 | ''' 123 | :param m: the matrix to rotate 124 | :type m: 3x3 :any:`numpy.ndarray` 125 | :param translation_vector: the translation vector to apply 126 | :type translation_vector: 3x1 :any:`numpy.ndarray` 127 | :param direction: the direction of the rotation 128 | :type direction: string 129 | :param plane: the plane to rotate around 130 | :type plane: string 131 | :returns: the axis of rotation 132 | :rtype: 3x1 :any:`numpy.ndarray` 133 | ''' 134 | # find the plane equation for a set of QuickNII coordinates 135 | cross, k = find_plane_equation(m) 136 | volume = np.array((512, 1024, 512)) 137 | translated_volume = volume - translation_vector 138 | print(f'axis_tvol: {translated_volume}') 139 | print(f'axis_tvec: {translation_vector}') 140 | 141 | # translated_volume = volume 142 | midpoint = volume/2 143 | 144 | cor_linear_point = ( 145 | (((translated_volume[0] / 2)) * cross[0]) + ((translated_volume[2] / 2) * cross[2])) + k 146 | cor_Y = -(cor_linear_point / cross[1]) 147 | # cor_axis = ((translated_volume[0] / 2, depth, translated_volume[2] / 2)) 148 | 149 | sag_linear_point = ( 150 | ((translated_volume[1] / 2) * cross[1]) + ((translated_volume[2] / 2) * cross[2])) + k 151 | sag_X = -(sag_linear_point / cross[0]) 152 | # sag_axis = ((translated_volume[1] / 2, depth, translated_volume[2] / 2)) 153 | 154 | horz_linear_point = ( 155 | ((translated_volume[0] / 2) * cross[0]) + ((translated_volume[1] / 2) * cross[1])) + k 156 | horz_Z = -(horz_linear_point / cross[2]) 157 | if plane_of_section is None: 158 | plane_of_section = np.argmin(np.abs((cor_Y - 512, sag_X - 256, horz_Z - 256))) 159 | choices = {'x': sag_X - 256, ' y': cor_Y-512,' z': horz_Z - 256 } 160 | choices = {'x': sag_X, ' y': cor_Y,' z': horz_Z } 161 | 162 | if plane_of_section == 0: 163 | axis = ((translated_volume[0] / 2, cor_Y, translated_volume[2] / 2)) 164 | print(f'cor: {axis + translation_vector}') 165 | 166 | if direction == 'DV': 167 | linear_point = ( 168 | ((translated_volume[0]) * cross[0]) + ((translated_volume[2] / 2) * cross[2])) + k 169 | Ypred = -(linear_point / cross[1]) 170 | ##the way QNII rotates is but i prefer my way 171 | # axis2 = ((translated_volume[0], cor_Y, translated_volume[2] / 2)) 172 | axis2 = ((translated_volume[0], Ypred, translated_volume[2] / 2)) 173 | 174 | ##this gives me the depth of a point directly beside the coronal center point 175 | if direction == 'ML': 176 | linear_point = (((translated_volume[0] / 2) * cross[0]) + ((translated_volume[2]) * cross[2])) + k 177 | Ypred = -(linear_point / cross[1]) 178 | axis2 = ((translated_volume[0] / 2, Ypred, translated_volume[2])) 179 | 180 | 181 | 182 | 183 | if plane_of_section==1: 184 | axis = ((sag_X, translated_volume[1] / 2, translated_volume[2] / 2)) 185 | print(f'sag: {axis + translation_vector}') 186 | 187 | if direction == 'DV': 188 | linear_point = ( 189 | ((translated_volume[1]) * cross[1]) + ((translated_volume[2] / 2) * cross[2])) + k 190 | Xpred = -(linear_point / cross[0]) 191 | axis2 = ((Xpred, translated_volume[1], translated_volume[2] / 2)) 192 | if direction == 'ML': 193 | linear_point = ( 194 | ((translated_volume[1] / 2) * cross[1]) + ((translated_volume[2]) * cross[2])) + k 195 | Xpred = -(linear_point / cross[0]) 196 | axis2 = ((Xpred, translated_volume[1] / 2, translated_volume[2])) 197 | 198 | 199 | if plane_of_section==2: 200 | axis = ((translated_volume[0] / 2, translated_volume[1] / 2, horz_Z)) 201 | print(f'horz: {axis + translation_vector}') 202 | if direction == 'DV': 203 | linear_point = ( 204 | ((translated_volume[0]) * cross[0]) + ((translated_volume[1] / 2) * cross[1])) + k 205 | Zpred = -(linear_point / cross[2]) 206 | axis2 = ((translated_volume[0], translated_volume[1] / 2, Zpred)) 207 | 208 | 209 | if direction == 'ML': 210 | linear_point = ( 211 | ((translated_volume[0] / 2) * cross[0]) + ((translated_volume[1]) * cross[1])) + k 212 | Zpred = -(linear_point / cross[2]) 213 | axis2 = ((translated_volume[0] / 2, translated_volume[1], Zpred)) 214 | 215 | 216 | 217 | 218 | # axis = ((translated_volume[0] / 2, depth, translated_volume[1] / 2)) 219 | 220 | 221 | # expr = sum((x * cross + midpoint) * cross) - k 222 | # m = solve(expr) 223 | # axis = np.array((m * cross + midpoint), dtype=np.float) 224 | ##this gives me the depth of a point directly beneath the coronal center point 225 | ##the axis needs to be set 226 | print(r'-------------------------------------------------------------------') 227 | 228 | axis_vector = np.array(axis) - np.array(axis2) 229 | return (axis_vector) 230 | 231 | def rotate_section(section, degrees, direction, plane_of_section=None): 232 | ''' 233 | Rotates a section 234 | :param section: the section to rotate 235 | :type section: :any:`numpy.ndarray` 236 | :param degrees: the degrees to rotate the section 237 | :type degrees: float 238 | :param direction: the direction of the rotation 239 | :type direction: string 240 | :param plane: the plane to rotate around 241 | :type plane: string 242 | :returns: the rotated section 243 | :rtype: :any:`numpy.ndarray` 244 | ''' 245 | cross, k = find_plane_equation(section) 246 | 247 | # this looks redundant 248 | # if direction==ML: 249 | # ML=get_angle(section.reshape(9),cross,k,direction=direction) 250 | section_points = section.copy() 251 | for i in range(3): 252 | section_points[i + 3] += section_points[i] 253 | section_points[i + 6] += section_points[i] 254 | 255 | points = section_points.reshape(3, 3) 256 | translated_volume = np.array((489, 1024, 590)) 257 | 258 | cor_linear_point = ( 259 | (((translated_volume[0] / 2)) * cross[0]) + ((translated_volume[2] / 2) * cross[2])) + k 260 | cor_Y = -(cor_linear_point / cross[1]) 261 | # cor_axis = ((translated_volume[0] / 2, depth, translated_volume[2] / 2)) 262 | 263 | sag_linear_point = ( 264 | ((translated_volume[1] / 2) * cross[1]) + ((translated_volume[2] / 2) * cross[2])) + k 265 | sag_X = -(sag_linear_point / cross[0]) 266 | # sag_axis = ((translated_volume[1] / 2, depth, translated_volume[2] / 2)) 267 | 268 | horz_linear_point = ( 269 | ((translated_volume[0] / 2) * cross[0]) + ((translated_volume[1] / 2) * cross[1])) + k 270 | horz_Z = -(horz_linear_point / cross[2]) 271 | if plane_of_section is None: 272 | plane_of_section = np.argmin(np.abs((cor_Y - 512, sag_X - 256, horz_Z - 256))) 273 | # midpoint = translated_volume/2 274 | # x = symbols('x') 275 | # expr = sum((x * cross + midpoint) * cross) - k 276 | # m = solve(expr) 277 | # translation_vector = np.array((m * cross + midpoint), dtype=np.float) 278 | if plane_of_section==0: 279 | 280 | translation_vector = ( 281 | (translated_volume[0] / 2, cor_Y, translated_volume[2] / 2)) 282 | 283 | if plane_of_section==1: 284 | translation_vector = ( 285 | (sag_X, translated_volume[1] / 2, translated_volume[2] / 2)) 286 | 287 | if plane_of_section==2: 288 | translation_vector = ( 289 | (translated_volume[0] / 2, translated_volume[1] / 2, horz_Z)) 290 | print('tv: ', translation_vector) 291 | 292 | translated_points = points - translation_vector 293 | axis = get_axis(section, translation_vector, direction=direction, plane_of_section=plane_of_section) 294 | rot_matrix = rotation_around_axis(axis, degrees) 295 | # perform rotation, centred on (0,0,0) 296 | rotated_translated_points = np.dot(translated_points, rot_matrix) 297 | # translate back to original geometric centre. 298 | rotated_points = rotated_translated_points + translation_vector 299 | rotated_points = rotated_points.reshape(9) 300 | for i in range(3): 301 | rotated_points[i + 3] -= rotated_points[i] 302 | rotated_points[i + 6] -= rotated_points[i] 303 | return (rotated_points) 304 | 305 | 306 | 307 | 308 | def Section_adjust(section, direction, mean, plane='Coronal'): 309 | ''' 310 | Adjusts a section 311 | :param section: the section to adjust 312 | :type section: :any:`numpy.ndarray` 313 | :param direction: the direction of the adjustment 314 | :type direction: string 315 | :param mean: the target angle to adjust to 316 | :type mean: float 317 | :param plane: whether the section is coronal, sagittal, horizontal 318 | :type plane: string 319 | :returns: the adjusted section 320 | :rtype: :any:`numpy.ndarray` 321 | ''' 322 | cross, k = find_plane_equation(section) 323 | angle = get_angle(section, cross, k, direction) 324 | dif = angle-mean 325 | rot = (rotate_section(section, -dif, direction, plane)) 326 | return(rot) 327 | -------------------------------------------------------------------------------- /src/abba_python/deepslice/utilities/render_tools.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NicoKiaru/ABBA-Python/1626654aaf370cd2619896195c7f88aeb7d16a7c/src/abba_python/deepslice/utilities/render_tools.py -------------------------------------------------------------------------------- /src/abba_python/itk/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = """Nicolas Chiaruttini""" 2 | __version__ = "0.1.0-SNAPSHOT" 3 | 4 | # Inner classes, do not access and use them directly 5 | # Used internally by the Abba package 6 | 7 | -------------------------------------------------------------------------------- /src/abba_python/itk/abba_itk.py: -------------------------------------------------------------------------------- 1 | from scyjava import jimport 2 | from jpype import JImplements, JOverride 3 | from jpype.types import JString, JDouble, JInt 4 | import os 5 | 6 | from abba_python.scijava_python_command import ScijavaCommand, ScijavaInput 7 | import itk 8 | import numpy as np 9 | import tempfile 10 | 11 | ExternalABBARegistrationPlugin = jimport('ch.epfl.biop.atlas.aligner.plugin.ExternalABBARegistrationPlugin') 12 | AffineTransform3D = jimport('net.imglib2.realtransform.AffineTransform3D') 13 | MultiSlicePositioner = jimport('ch.epfl.biop.atlas.aligner.MultiSlicePositioner') 14 | 15 | Supplier = jimport('java.util.function.Supplier') 16 | 17 | Command = jimport('org.scijava.command.Command') 18 | JPlugin = jimport('org.scijava.plugin.Plugin') 19 | Parameter = jimport('org.scijava.plugin.Parameter') 20 | ImagePlus = jimport('ij.ImagePlus') 21 | 22 | SimpleABBARegistrationPlugin = jimport('ch.epfl.biop.atlas.aligner.plugin.SimpleABBARegistrationPlugin') 23 | 24 | ElastixTransform = jimport('itc.transforms.elastix.ElastixTransform') 25 | ElastixEuler2DToAffineTransform3D = jimport('itc.converters.ElastixEuler2DToAffineTransform3D') 26 | File = jimport('java.io.File') 27 | 28 | SourcesChannelsSelect = jimport('ch.epfl.biop.sourceandconverter.processor.SourcesChannelsSelect') 29 | HashMap = jimport('java.util.HashMap') 30 | SimpleRegistrationWrapper = jimport('ch.epfl.biop.atlas.aligner.plugin.SimpleRegistrationWrapper') 31 | 32 | 33 | @JImplements(SimpleABBARegistrationPlugin) 34 | class ITKRigidRegistration(object): 35 | 36 | def __init__(self, ij): 37 | print('init SimpleRotateAffineRegistration') 38 | self.ij = ij 39 | pass 40 | 41 | # @return Sampling required for the registration, in micrometer (double) 42 | # 43 | @JOverride 44 | def getVoxelSizeInMicron(self): 45 | return JDouble(40) 46 | 47 | # Is called before registration to pass any extra registration parameter 48 | # argument. Passed as a dictionary of String to preserve serialization 49 | # capability. 50 | # param parameters dictionary of parameters (Map) 51 | @JOverride 52 | def setRegistrationParameters(self, parameters): 53 | self.parameters = parameters 54 | 55 | # param fixed image (ImagePlus) 56 | # param moving image (ImagePlus) 57 | # param fixed mask (ImagePlus) 58 | # param moving mask (ImagePlus) 59 | # return the transform, result of the registration, (InvertibleRealTransform) 60 | # going from fixed to moving coordinates, in pixels 61 | @JOverride 62 | def register(self, fixed, moving, fixedMask, movingMask): 63 | # fixed.show() 64 | # moving.show() 65 | # ij.py.show(fixed) 66 | # ij.py.show(moving) 67 | 68 | # global parameter_object 69 | parameter_object = itk.ParameterObject.New() 70 | default_rigid_parameter_map = parameter_object.GetDefaultParameterMap('rigid') 71 | parameter_object.AddParameterMap(default_rigid_parameter_map) 72 | 73 | # global fixed_py 74 | # global moving_py 75 | fixed_py = self.ij.py.from_java(fixed) 76 | moving_py = self.ij.py.from_java(moving) 77 | fixed_py = fixed_py.to_numpy().astype(np.float32) 78 | moving_py = moving_py.to_numpy().astype(np.float32) 79 | 80 | # Call registration function 81 | with tempfile.TemporaryDirectory() as temp_dir: 82 | # ... do something with temp_dir 83 | itk.elastix_registration_method( 84 | fixed_py, moving_py, 85 | output_directory=temp_dir, 86 | parameter_object=parameter_object, 87 | log_to_console=False) 88 | output_path = os.path.join(temp_dir, 'TransformParameters.0.txt') 89 | et = ElastixTransform.load(File(output_path)) 90 | transform = ElastixEuler2DToAffineTransform3D.convert(et) 91 | 92 | # temp dir automatically cleaned up when context exited 93 | return transform 94 | 95 | 96 | @JImplements(Supplier) 97 | class ITKRigidRegistrationSupplier(object): 98 | 99 | def __init__(self, ij): 100 | self.ij = ij 101 | pass 102 | 103 | @JOverride 104 | def get(self): 105 | return SimpleRegistrationWrapper(JString('ITKRigidRegistration'), 106 | ITKRigidRegistration(self.ij)) 107 | 108 | 109 | def add_abba_itk_registrations(ij): 110 | MultiSlicePositioner.registerRegistrationPlugin('ITKRigidRegistration', 111 | ITKRigidRegistrationSupplier(ij)) 112 | 113 | @ScijavaCommand(context=ij.context(), # ij context needed 114 | name='ITK - Rigid Registration') 115 | @ScijavaInput('fixed_channel', JInt, 116 | label='Atlas channel index:', description='') 117 | @ScijavaInput('moving_channel', JInt, 118 | label='Section channel index', description='') 119 | @ScijavaInput('mp', MultiSlicePositioner, 120 | label='Section channel index', description='') 121 | class SimpleRotateAffineRegistrationCommand: 122 | def run(self): 123 | params = HashMap() 124 | self.mp.registerSelectedSlices('ITKRigidRegistration', 125 | SourcesChannelsSelect(self.fixed_channel), 126 | SourcesChannelsSelect(self.moving_channel), 127 | params) 128 | 129 | MultiSlicePositioner.registerRegistrationPluginUI('ITKRigidRegistration', 130 | 'ITK - Rigid Registration'); 131 | -------------------------------------------------------------------------------- /src/abba_python/run-abba-local-fiji.py: -------------------------------------------------------------------------------- 1 | # core dependencies 2 | import time 3 | 4 | from abba_python.Abba import enable_python_hooks, add_brainglobe_atlases 5 | # in order to wait for a jvm shutdown 6 | import jpype 7 | import imagej 8 | 9 | import os 10 | 11 | # THIS FILE SETS MANY PATHS EXPLICITLY WHEN ABBA IS INSTALLED FROM THE INSTALLER! 12 | # IF YOU WANT TO RUN ABBA FROM PYTHON, TRY run-abba.py first! 13 | 14 | if __name__ == '__main__': 15 | os.path.dirname(os.getcwd()) 16 | # In ABBA PYthon, Fiji.app is in the parent directory of this script 17 | fiji_app_path = str(os.path.join(os.path.dirname(os.getcwd()), 'Fiji.app')) 18 | ij = imagej.init(fiji_app_path, mode="interactive") 19 | 20 | ij.ui().showUI() 21 | enable_python_hooks(ij) 22 | add_brainglobe_atlases(ij) 23 | 24 | # Set Elastix Path: 25 | # File ch.epfl.biop.wrappers.elastix.Elastix exePath 26 | # File ch.epfl.biop.wrappers.transformix.Transformix exePath 27 | from scyjava import jimport 28 | from jpype.types import JString 29 | 30 | # Java class imports 31 | 32 | DebugTools = jimport('loci.common.DebugTools') 33 | File = jimport('java.io.File') 34 | # DebugTools.enableLogging('OFF') 35 | DebugTools.enableLogging("INFO"); 36 | # DebugTools.enableLogging("DEBUG"); 37 | 38 | import platform 39 | if platform.system() == 'Windows': 40 | elastixPath = str(os.path.join(os.path.dirname(os.getcwd()), 'win', 'elastix-5.0.1-win64', 'elastix.exe')) 41 | transformixPath = str(os.path.join(os.path.dirname(os.getcwd()), 'win', 'elastix-5.0.1-win64', 'transformix.exe')) 42 | 43 | Elastix = jimport('ch.epfl.biop.wrappers.elastix.Elastix') 44 | Elastix.exePath = JString(str(elastixPath)) 45 | Elastix.setExePath(File(JString(str(elastixPath)))) 46 | Transformix = jimport('ch.epfl.biop.wrappers.transformix.Transformix') 47 | Transformix.exePath = JString(str(transformixPath)) 48 | Transformix.setExePath(File(JString(str(transformixPath)))) 49 | 50 | # Now let's set the atlas folder location in a folder that all users can access 51 | 52 | AtlasLocationHelper = jimport('ch.epfl.biop.atlas.AtlasLocationHelper') 53 | directory = os.path.join(os.environ['ProgramData'], 'abba-atlas') 54 | 55 | # create the directory with write access for all users 56 | try: 57 | print('Attempt to set ABBA Atlas cache directory to ' + directory) 58 | # //os.mkdir(directory) 59 | os.makedirs(directory, exist_ok=True) 60 | atlasPath = str(directory) 61 | AtlasLocationHelper.defaultCacheDir = File(JString(atlasPath)) 62 | print('ABBA Atlas cache directory set to ' + directory) 63 | except OSError: 64 | print('ERROR! Could not set ABBA Atlas cache dir') 65 | # directory already exists ? 66 | pass 67 | else: 68 | print('ERROR! '+platform.system()+' OS not supported yet.') 69 | 70 | # -- 71 | 72 | # Wait for the JVM to shut down 73 | while jpype.isJVMStarted(): 74 | time.sleep(1) 75 | 76 | print("JVM has shut down") 77 | -------------------------------------------------------------------------------- /src/abba_python/run-abba.py: -------------------------------------------------------------------------------- 1 | # core dependencies 2 | import time 3 | 4 | from abba_python.Abba import enable_python_hooks, get_java_dependencies, add_brainglobe_atlases 5 | # in order to wait for a jvm shutdown 6 | import jpype 7 | import imagej 8 | 9 | import os 10 | 11 | 12 | if __name__ == '__main__': 13 | 14 | # MAC ISSUE 15 | # https: // github.com / imagej / pyimagej / issues / 23 16 | # -- FOR DEBUGGING 17 | # import imagej.doctor 18 | # imagej.doctor.checkup() 19 | # imagej.doctor.debug_to_stderr() 20 | # -- Atlas 21 | # Any brainglobe atlas can be used 22 | # show_atlases() 23 | # abba_python = Abba("azba_zfish_4um", slicing_mode='sagittal', headless=True) # or any other brainglobe atlas 24 | 25 | # -- HEADLESS 26 | # abba_python = Abba('Adult Mouse Brain - Allen Brain Atlas V3', headless=True) # or any other brainglobe atlas 27 | # -- 28 | 29 | # -- NOT HEADLESS 30 | # abba = Abba('Adult Mouse Brain - Allen Brain Atlas V3') 31 | # abba.show_bdv_ui() # creates and show a bdv view 32 | ij = imagej.init(get_java_dependencies(), mode="interactive") 33 | ij.ui().showUI() 34 | enable_python_hooks(ij) 35 | add_brainglobe_atlases(ij) 36 | 37 | from scyjava import jimport 38 | from jpype.types import JString 39 | 40 | # loci.common.DebugTools.enableLogging("OFF"); 41 | DebugTools = jimport('loci.common.DebugTools') 42 | # DebugTools.enableLogging('OFF') 43 | DebugTools.enableLogging("INFO"); 44 | # DebugTools.enableLogging("DEBUG"); 45 | 46 | import platform 47 | if platform.system() == 'Windows': 48 | File = jimport('java.io.File') 49 | # Now let's set the atlas folder location in a folder with all users access 50 | 51 | AtlasLocationHelper = jimport('ch.epfl.biop.atlas.AtlasLocationHelper') 52 | directory = os.path.join(os.environ['ProgramData'], 'abba-atlas') 53 | 54 | # create the directory with write access for all users 55 | try: 56 | print('Attempt to set ABBA Atlas cache directory to ' + directory) 57 | os.makedirs(directory, exist_ok=True) 58 | atlasPath = str(directory) 59 | AtlasLocationHelper.defaultCacheDir = File(JString(atlasPath)) 60 | print('ABBA Atlas cache directory set to ' + directory) 61 | except OSError: 62 | print('ERROR! Could not set ABBA Atlas cache dir') 63 | # directory already exists ? 64 | pass 65 | else: 66 | print('ERROR! '+platform.system()+' OS not supported yet.') 67 | 68 | # -- 69 | 70 | # Wait for the JVM to shut down 71 | while jpype.isJVMStarted(): 72 | time.sleep(1) 73 | 74 | print("JVM has shut down") 75 | -------------------------------------------------------------------------------- /src/abba_python/scijava_python_command/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = """nicolas_chiaruttini""" 2 | __version__ = "0.1.0-SNAPSHOT" 3 | 4 | #from scijava_python_command.MagicJupyter import run_in_another_thread 5 | #from scijava_python_command.ScijavaJupyterUI import enable_jupyter_ui 6 | #from scijava_python_command.ScijavaCommand import ScijavaCommand, ScijavaInput, ScijavaOutput 7 | -------------------------------------------------------------------------------- /src/abba_python/scijava_python_command/command.py: -------------------------------------------------------------------------------- 1 | from scyjava import jimport 2 | from jpype.types import JObject, JClass 3 | 4 | import logging 5 | 6 | PyCommandBuilder = jimport('org.scijava.command.PyCommandBuilder') 7 | PyParameterBuilder = jimport('org.scijava.command.PyParameterBuilder') 8 | 9 | # Decorator that registers a python CLASS containing a method named "run" as a Scijava Command 10 | # 11 | # This uses PyCommandBuilder which is in the java repo ch.epfl.biop:pyimagej-scijava-command 12 | # PyCommandBuilder allows to build a Command fully programmatically without using any 13 | # java annotation as java annotations are needed for 'easy' Scijava Commands definition 14 | # but these are not completely supported in JPype: 15 | # cf https://github.com/jpype-project/jpype/issues/940 16 | # 17 | # Example of registering a Scijava Command via the @ScijavaCommand decorator: 18 | # ------------------------------------------ 19 | # @ScijavaCommand(context=ij.context(), # ij context needed 20 | # name='pyCommand.HelloCommand') 21 | # @ScijavaInput('name', JString, 22 | # label='Name :', description='Please enter your name') 23 | # @ScijavaInput('familiar', JBoolean, 24 | # label='Familiar :', description='Hi or Hello ?') 25 | # @ScijavaOutput('greetings', JString) 26 | # class HelloCommand: 27 | # 28 | # def run(self): 29 | # if (self.familiar): 30 | # self.greetings = 'Hi ' + str(self.name) + '!' 31 | # else: 32 | # self.greetings = 'Hello my dear ' + str(self.name) + '.' 33 | # print(self.greetings) 34 | # ------------------------------------------ 35 | # 36 | # Note: this way of defining a command is probably not ideal if this has to be used from the python side also 37 | # 38 | # Because it's a preliminary work, this decorator prints a lot of stuff in the process 39 | # 40 | # TODO: functools ?? 41 | 42 | logger = logging.getLogger('ScijavaCommand') 43 | 44 | def ScijavaCommand(name, context): 45 | logger.info("- Registering scijava command " + name) 46 | 47 | def registerCommand(func): 48 | 49 | # This class will be registered as a SciJava Command 50 | builder = PyCommandBuilder() # Java PyCommandBuilder 51 | 52 | # The name of the command - to avoid name conflicts, consider a 'virtual' class name with its package 53 | builder = builder.name(name).label(name) 54 | 55 | # Register all inputs 56 | if hasattr(func, 'scijava_inputs'): 57 | logger.debug('- Inputs') 58 | for scijava_input_name, scijava_input_properties in func.scijava_inputs.items(): 59 | logger.debug('\t'+ scijava_input_name+ ' : '+ str(scijava_input_properties['scijava_class'])) 60 | builder = builder.input(scijava_input_name, 61 | scijava_input_properties['scijava_class'], 62 | scijava_input_properties['scijava_parameter']) 63 | setattr(func, scijava_input_name, None) # declares empty input field 64 | logger.debug('Inputs registered') 65 | else: 66 | logger.debug('- No input') 67 | 68 | # Register all outputs 69 | if hasattr(func, 'scijava_outputs'): 70 | logger.debug('- Outputs') 71 | for scijava_output_name, scijava_output_properties in func.scijava_outputs.items(): 72 | logger.debug('\t'+ scijava_output_name+ ' : '+ str(scijava_output_properties['scijava_class'])) 73 | builder = builder.output(scijava_output_name, 74 | scijava_output_properties['scijava_class'], 75 | scijava_output_properties['scijava_parameter']) 76 | setattr(func, scijava_output_name, None) # declares empty input field 77 | logger.debug('Outputs registered') 78 | else: 79 | logger.debug('- No Output') 80 | 81 | # Wraps the run function - takes kwargs as input, returns outputs 82 | def wrapped_run(inner_kwargs): 83 | inner_object = func() 84 | logger.debug('Settings inputs...') 85 | if hasattr(func, 'scijava_inputs'): 86 | for input_name in func.scijava_inputs.keys(): 87 | setattr(inner_object, input_name, inner_kwargs[input_name]) 88 | logger.debug('Inputs set.') 89 | logger.debug('Running scijava command: ' + name) 90 | inner_object.run() 91 | logger.debug(name + ' command execution done.') 92 | logger.debug('Fetching outputs...') 93 | outputs = {} 94 | if hasattr(func, 'scijava_outputs'): 95 | for output_name in func.scijava_outputs.keys(): 96 | outputs[output_name] = getattr(inner_object, output_name) # gets outputs 97 | logger.debug('Outputs set.') 98 | return JObject(outputs, JClass('java.util.Map')) # Returns output as a java HashMap 99 | 100 | # Sets the function in PyCommandBuilder: 101 | # Function, Map> command 102 | builder = builder.function(wrapped_run) 103 | 104 | # Effectively registers this command to the ij context 105 | builder.create(context) 106 | return func 107 | 108 | return registerCommand 109 | 110 | 111 | def ScijavaInput(scijava_input_name, scijava_class, **kwargs): 112 | logger.debug("- Registering scijava input "+scijava_input_name) 113 | def registerInput(func): 114 | 115 | if not hasattr(func, 'scijava_inputs'): 116 | setattr(func, 'scijava_inputs', dict()) 117 | 118 | if scijava_input_name in func.scijava_inputs: 119 | raise Exception("Error, two inputs have the same name " + str(scijava_input_name)) 120 | 121 | scijava_parameter = PyParameterBuilder.input() 122 | 123 | for key, value in kwargs.items(): 124 | getattr(scijava_parameter, key)(value) # builder pattern powa! 125 | 126 | func.scijava_inputs[scijava_input_name] = \ 127 | {'scijava_class': scijava_class, 128 | 'scijava_parameter': scijava_parameter.get()} 129 | 130 | return func 131 | 132 | return registerInput 133 | 134 | 135 | def ScijavaOutput(scijava_output_name, scijava_class, **kwargs): 136 | logger.debug("- Registering scijava output "+scijava_output_name) 137 | 138 | def registerOutput(func): 139 | 140 | if not hasattr(func, 'scijava_outputs'): 141 | setattr(func, 'scijava_outputs', dict()) 142 | 143 | if scijava_output_name in func.scijava_outputs: 144 | raise Exception("Error, two outputs have the same name " + str(scijava_output_name)) 145 | 146 | scijava_parameter = PyParameterBuilder.output() 147 | 148 | for key, value in kwargs.items(): 149 | getattr(scijava_parameter, key)(value) # builder pattern powa! 150 | 151 | func.scijava_outputs[scijava_output_name] = \ 152 | {'scijava_class': scijava_class, 153 | 'scijava_parameter': scijava_parameter.get()} 154 | 155 | return func 156 | 157 | return registerOutput 158 | -------------------------------------------------------------------------------- /src/abba_python/scijava_python_command/jupyter_ui.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import ipywidgets as widgets 3 | from IPython.display import display 4 | from scyjava import jimport 5 | from jpype import JImplements, JOverride 6 | from jpype.types import JString, JBoolean, JDouble, JInt, JFloat 7 | 8 | from ipyfilechooser import FileChooser 9 | import logging 10 | 11 | logger = logging.getLogger('ScijavaJupyterUI') 12 | 13 | Consumer = jimport('java.util.function.Consumer') 14 | Supplier = jimport('java.util.function.Supplier') 15 | JFile = jimport('java.io.File') 16 | PyPreprocessor = jimport('org.scijava.processor.PyPreprocessor') 17 | 18 | 19 | def enable_jupyter_ui(): 20 | PyPreprocessor = jimport('org.scijava.processor.PyPreprocessor') 21 | PyPreprocessor.register(IPyWidgetCommandPreprocessorSupplier()) 22 | print('Scijava jupyter ui enabled') 23 | 24 | 25 | @JImplements(Consumer) 26 | class IPyWidgetCommandPreprocessor(object): 27 | 28 | @JOverride 29 | def accept(self, module): 30 | self.module = module 31 | inputs = module.getInputs() 32 | self.all_widgets = dict() 33 | logger.debug('Jupyter pre-processing, module ' + str(module)) 34 | for input_key in inputs.keySet(): 35 | if not module.isInputResolved(input_key): 36 | logger.debug('Unresolved input: ' + str(input_key)) 37 | current_widget = get_jupyter_widget(module, input_key) 38 | if current_widget is not None: 39 | logger.debug('Widget acquired for input ' + str(input_key)) 40 | self.all_widgets[input_key] = current_widget 41 | else: 42 | # maybe log something or put a warning 43 | logger.debug('Widget not found for input ' + str(input_key)) 44 | pass 45 | 46 | if len(self.all_widgets) != 0: 47 | list_of_widgets = [x.get_widget() for key, x in self.all_widgets.items()] 48 | 49 | # Creates an OK button, and its associated event 50 | user_has_clicked = threading.Event() 51 | ok_button = widgets.Button(description='OK') 52 | ok_button.on_click(lambda _: user_has_clicked.set()) 53 | list_of_widgets.append(ok_button) 54 | logger.debug('Display widgets module ' + str(module)) 55 | display(widgets.VBox(list_of_widgets)) 56 | logger.debug('Waiting for click') 57 | 58 | # Wait for button click 59 | user_has_clicked.wait() 60 | logger.debug('button clicked') 61 | 62 | # the user has clicked 63 | # retrieve contents of all widgets: 64 | for key, w in self.all_widgets.items(): 65 | logger.debug('Resolving input ' + str(key)) 66 | module.setInput(key, w.get_value()) 67 | module.resolveInput(key) 68 | logger.debug('Input ' + str(key) + " resolved") 69 | 70 | 71 | @JImplements(Supplier) 72 | class IPyWidgetCommandPreprocessorSupplier(object): 73 | @JOverride 74 | def get(self): 75 | return IPyWidgetCommandPreprocessor() 76 | 77 | 78 | booleanClasses = ['class java.lang.Boolean', 'boolean'] 79 | intClasses = ['class java.lang.Integer', 'int'] 80 | floatClasses = ['class java.lang.Float', 'float'] 81 | doubleClasses = ['class java.lang.Double', 'double'] 82 | 83 | 84 | def getLabel(module, input_key): 85 | label = module.getInfo().getInput(input_key).getLabel() 86 | if (label is None) or (label == ''): 87 | label = str(input_key) 88 | else: 89 | label = str(label) 90 | return label 91 | 92 | 93 | def get_jupyter_widget(module, input_key): 94 | if str(module.getInfo().getInput(input_key).getType()) == 'class java.lang.String': 95 | return JupyterTextWidget(module, input_key) 96 | 97 | if str(module.getInfo().getInput(input_key).getType()) in booleanClasses: 98 | return JupyterToggleWidget(module, input_key) 99 | 100 | if str(module.getInfo().getInput(input_key).getType()) in intClasses: 101 | return JupyterIntWidget(module, input_key) 102 | 103 | if str(module.getInfo().getInput(input_key).getType()) in floatClasses: 104 | return JupyterFloatWidget(module, input_key) 105 | 106 | if str(module.getInfo().getInput(input_key).getType()) in doubleClasses: 107 | return JupyterDoubleWidget(module, input_key) 108 | 109 | if str(module.getInfo().getInput(input_key).getType()) == 'class java.io.File': 110 | return JupyterFileWidget(module, input_key) 111 | 112 | print("Unsupported widget for type " + str(module.getInfo().getInput(input_key).getType())) 113 | 114 | return None 115 | 116 | 117 | class JupyterInputWidget: 118 | def __init__(self, module, input_key): 119 | pass 120 | 121 | def get_widget(self): 122 | return self.widget 123 | 124 | def get_value(self): 125 | return None 126 | 127 | 128 | class JupyterTextWidget(JupyterInputWidget): 129 | def __init__(self, module, input_key): 130 | self.widget = widgets.Text( 131 | value=str(module.getInput(input_key)), 132 | placeholder=str(module.getInfo().getInput(input_key).getDescription()), 133 | description=getLabel(module, input_key), 134 | disabled=False 135 | ) 136 | 137 | def get_value(self): 138 | return JString(self.widget.value) 139 | 140 | 141 | class JupyterToggleWidget(JupyterInputWidget): 142 | def __init__(self, module, input_key): 143 | self.widget = widgets.Checkbox( 144 | value=bool(module.getInput(input_key)), 145 | description=getLabel(module, input_key), 146 | disabled=False, 147 | indent=True 148 | ) 149 | 150 | def get_value(self): 151 | return JBoolean(self.widget.value) 152 | 153 | 154 | class JupyterIntWidget(JupyterInputWidget): 155 | def __init__(self, module, input_key): 156 | min_value = module.getInfo().getInput(input_key).getMinimumValue() 157 | max_value = module.getInfo().getInput(input_key).getMaximumValue() 158 | step_size = module.getInfo().getInput(input_key).getStepSize() 159 | 160 | if (min_value is not None) and (max_value is not None): 161 | 162 | if step_size is None: 163 | step_size = 1 164 | else: 165 | step_size = step_size.intValue() 166 | 167 | self.widget = widgets.BoundedIntText( 168 | value=int(module.getInput(input_key)), 169 | min=int(min_value), 170 | max=int(max_value), 171 | step=int(step_size), 172 | description=getLabel(module, input_key), 173 | disabled=False 174 | ) 175 | else: 176 | self.widget = widgets.IntText( 177 | value=int(module.getInput(input_key)), 178 | description=getLabel(module, input_key), 179 | disabled=False 180 | ) 181 | 182 | def get_value(self): 183 | return JInt(self.widget.value) 184 | 185 | 186 | class JupyterFloatWidget(JupyterInputWidget): 187 | def __init__(self, module, input_key): 188 | 189 | min_value = module.getInfo().getInput(input_key).getMinimumValue() 190 | max_value = module.getInfo().getInput(input_key).getMaximumValue() 191 | step_size = module.getInfo().getInput(input_key).getStepSize() 192 | 193 | if (min_value is not None) and (max_value is not None): 194 | if step_size is None: 195 | step_size = 1 196 | else: 197 | step_size = step_size.intValue() 198 | 199 | self.widget = widgets.FloatText( 200 | value=float(module.getInput(input_key)), 201 | min=float(min_value), 202 | max=float(max_value), 203 | step=float(step_size), 204 | description=getLabel(module, input_key), 205 | disabled=False 206 | ) 207 | else: 208 | self.widget = widgets.BoundedFloatText( 209 | value=float(module.getInput(input_key)), 210 | description=getLabel(module, input_key), 211 | disabled=False 212 | ) 213 | 214 | def get_value(self): 215 | return JFloat(self.widget.value) 216 | 217 | 218 | class JupyterDoubleWidget(JupyterFloatWidget): 219 | def __init__(self, module, input_key): 220 | JupyterFloatWidget.__init__(self, module, input_key) 221 | 222 | def get_value(self): 223 | return JDouble(self.widget.value) 224 | 225 | 226 | class JupyterFileWidget(JupyterInputWidget): 227 | def __init__(self, module, input_key): 228 | 229 | styles = module.getInfo().getInput(input_key).getWidgetStyle().replace(" ", "").split(',') 230 | 231 | if 'save' in styles: 232 | self.save = True 233 | self.widget = widgets.Text( 234 | value=str(module.getInput(input_key)), 235 | placeholder=str(module.getInfo().getInput(input_key).getDescription()), 236 | description=getLabel(module, input_key), 237 | disabled=False 238 | ) 239 | 240 | else: 241 | self.save = False 242 | 243 | # Create and display a FileChooser widget 244 | fc = FileChooser(select_default=True) 245 | # Change the title 246 | fc.title = getLabel(module, input_key) 247 | 248 | if 'directory' in styles: 249 | # Switch to folder-only mode 250 | fc.show_only_dirs = True 251 | if module.getInput(input_key) is not None: 252 | fc.default_path = str(module.getInput(input_key)) 253 | fc.reset() 254 | else: 255 | if module.getInput(input_key) is not None: 256 | fc.default_path = str(module.getInput(input_key).getParent()) 257 | fc.default_filename = str(module.getInput(input_key).getName()) 258 | fc.reset() 259 | 260 | matching_extensions = [s for s in styles if 'extensions:' in s] 261 | if len(matching_extensions) == 1: 262 | all_extensions = matching_extensions[0].split(":")[1].split("/") 263 | # Set multiple file filter patterns (uses https://docs.python.org/3/library/fnmatch.html) 264 | fc.filter_pattern = ['*.' + str(ext) for ext in all_extensions] 265 | 266 | self.widget = fc 267 | 268 | def get_value(self): 269 | if self.save: 270 | return JFile(JString(self.widget.value)) 271 | else: 272 | return JFile(JString(self.widget.selected)) # TODO : fix casting 273 | -------------------------------------------------------------------------------- /src/abba_python/scijava_python_command/magic.py: -------------------------------------------------------------------------------- 1 | from IPython.core.magic import register_cell_magic 2 | from jupyter_ui_poll import ui_events 3 | from threading import Thread 4 | from IPython.core.interactiveshell import InteractiveShell 5 | import time 6 | 7 | 8 | @register_cell_magic('cell_with_modal_ui') 9 | def cell_with_modal_ui(line, cell): 10 | shell = InteractiveShell.instance() 11 | 12 | def f(): 13 | shell.run_cell(cell) 14 | 15 | cell_runner = Thread(target=f) 16 | cell_runner.start() 17 | with ui_events() as poll: 18 | while cell_runner.is_alive(): 19 | poll(10) # React to UI events (upto 10 at a time) 20 | time.sleep(0.1) 21 | --------------------------------------------------------------------------------